Получение диагностики ошибок csharpcompilation, несмотря на то, что, по -видимому, имея все правильные настройкиC#

Место общения программистов C#
Ответить
Anonymous
 Получение диагностики ошибок csharpcompilation, несмотря на то, что, по -видимому, имея все правильные настройки

Сообщение Anonymous »

Вот мой код: < /p>

Код: Выделить всё

var compilation = CSharpCompilation.Create(asmProps.AssemblyName, syntaxTrees, references,
new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary,
assemblyIdentityComparer: DesktopAssemblyIdentityComparer.Default,
generalDiagnosticOption: ReportDiagnostic.Error,
specificDiagnosticOptions: s_specificDiagnosticOptions,
usings: implicitUsings));

if (m_enableDiagnostics)
{
var diagnostics = compilation
.GetDiagnostics()
.Where(o => o.Id is not "CS8301" and not "CS1705")
.ToList();
if (diagnostics.Count > 0)
{
var found = compilation.GetTypeByMetadataName("System.Diagnostics.CodeAnalysis.SetsRequiredMembersAttribute");
if (found.GetType().Name != "NonErrorNamedTypeSymbol")
{
throw new ApplicationException("Code Bug");
}
Debugger.Launch();
syntaxTrees
.Select(o => o.FilePath)
.Where(s => s.IndexOf("PolySharp") >= 0)
.ForEach(Console.WriteLine);
Console.WriteLine("-----");
Console.WriteLine(syntaxTrees
.First(o => o.FilePath.IndexOf("SetsRequiredMembersAttribute") >= 0)
.ToString());
...
< /code>
Последовательная ошибка диагностики такова: < /p>

src\wfm\grosspayenginedataprovider\laborcostengine.cs(35,10): Ошибка CS0246: Необычное. или ссылка на сборку?)using CoreCommon.Logging.Implementation;
using CoreCommon.Logging.Interfaces;
using CoreCommon.Session.Interfaces;
using DataAccessModels.Enums;
using xyz.Data.Core;
using GrossPayEngine.SegmentAggregator;
using GrossPayEngineDataProvider.Interface;
using GrossPayEngineDataProvider.Models;
using GrossPayEngineDataProvider.Utilities;
using SharpTop.Platform.Logging;
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Threading.Tasks;

namespace GrossPayEngineDataProvider
{
[PartCreationPolicy(CreationPolicy.NonShared)]
public class LaborCostEngine : ILaborCostEngine
{
[ImportMany]
public required ILaborCostEngineExecutor[] _executors { private get; init; }

[ImportingConstructor]
[SetsRequiredMembers] // DO NOT COPY/PASTE. We abuse this attribute here to facilitate MEF to Autofac migration.
public LaborCostEngine(ILaborCacheResultDAL cacheDAL, ILaborCostEngineEmployeeDAL employeeDAL, ILaborCostEngineDAL employeeResultDAL,
ILaborCostEngineConfigurationProvider configProvider)
{
this.employeeDAL = employeeDAL;
this.cacheDAL = cacheDAL;
this.employeeResultDAL = employeeResultDAL;
this.configProvider = configProvider;
}

...
}
}
Обратите внимание, что этот файл не имеет использования system.diagnostics.codeanalysis . Тем не менее, все проекты импортируют следующий файл props msbuild: < /p>

Код: Выделить всё


true



all
runtime; build; native; contentfiles; analyzers; buildtransitive




< /code>
Вышеупомянутый фрагмент Roslyn является частью инструмента, который я использую для анализа нашего исходного кода, который отлично построен в командной строке с использованием MSBuild. Он также работал нормально до того, как я внедрил PolySharp в кодовую базу.
Способ я имею дело с Polysharp при создании объекта компиляции Roslyn: 

[*] Добавить Pregenerated Polyfills к Syntaxtres 
.
. /> Фрагмент выше печатает имена всех полифиллов Polysharp, а также сбрасывает исходный код для атрибута SetSrequiredMembersattribute < /code>, и все выглядит правильно: < / p > < b r / > < c o d e > P o l y S h a r p . S o u r c e G e n e r a t o r s \ P o l y S h a r p . S o urceGenerators.PolyfillsGenerator\System.Diagnostics.CodeAnalysis.AllowNullAttribute.g.cs
PolySharp.SourceGenerators\PolySharp.SourceGenerators.PolyfillsGenerator\System.Diagnostics.CodeAnalysis.ConstantExpectedAttribute.g.cs
PolySharp.SourceGenerators\PolySharp.SourceGenerators.PolyfillsGenerator\System.Diagnostics.CodeAnalysis.DisallowNullAttribute.g.cs
PolySharp.SourceGenerators\PolySharp.SourceGenerators.PolyfillsGenerator\System.Diagnostics.CodeAnalysis.DoesNotReturnAttribute.g.cs
PolySharp.SourceGenerators\PolySharp.SourceGenerators.PolyfillsGenerator\System.Diagnostics.CodeAnalysis.DoesNotReturnIfAttribute.g.cs
PolySharp.SourceGenerators\PolySharp.SourceGenerators.PolyfillsGenerator\System.Diagnostics.CodeAnalysis.ExperimentalAttribute.g.cs
PolySharp.SourceGenerators\PolySharp.SourceGenerators.PolyfillsGenerator\System.Diagnostics.CodeAnalysis.MaybeNullAttribute.g.cs
PolySharp.SourceGenerators\PolySharp.SourceGenerators.PolyfillsGenerator\System.Diagnostics.CodeAnalysis.MaybeNullWhenAttribute.g.cs
PolySharp.SourceGenerators\PolySharp.SourceGenerators.PolyfillsGenerator\System.Diagnostics.CodeAnalysis.MemberNotNullAttribute.g.cs
PolySharp.SourceGenerators\PolySharp.SourceGenerators.PolyfillsGenerator\System.Diagnostics.CodeAnalysis.MemberNotNullWhenAttribute.g.cs
PolySharp.SourceGenerators\PolySharp.SourceGenerators.PolyfillsGenerator\System.Diagnostics.CodeAnalysis.NotNullAttribute.g.cs
PolySharp.SourceGenerators\PolySharp.SourceGenerators.PolyfillsGenerator\System.Diagnostics.CodeAnalysis.NotNullIfNotNullAttribute.g.cs
PolySharp.SourceGenerators\PolySharp.SourceGenerators.PolyfillsGenerator\System.Diagnostics.CodeAnalysis.NotNullWhenAttribute.g.cs
PolySharp.SourceGenerators\PolySharp.SourceGenerators.PolyfillsGenerator\System.Diagnostics.CodeAnalysis.SetsRequiredMembersAttribute.g.cs
PolySharp.SourceGenerators\PolySharp.SourceGenerators.PolyfillsGenerator\System.Diagnostics.CodeAnalysis.StringSyntaxAttribute.g.cs
PolySharp.SourceGenerators\PolySharp.SourceGenerators.PolyfillsGenerator\System.Diagnostics.CodeAnalysis.UnscopedRefAttribute.g.cs
PolySharp.SourceGenerators\PolySharp.SourceGenerators.PolyfillsGenerator\System.Index.g.cs
PolySharp.SourceGenerators\PolySharp.SourceGenerators.PolyfillsGenerator\System.Range.g.cs
PolySharp.SourceGenerators\PolySharp.SourceGenerators.PolyfillsGenerator\System.Runtime.CompilerServices.AsyncMethodBuilderAttribute.g.cs
PolySharp.SourceGenerators\PolySharp.SourceGenerators.PolyfillsGenerator\System.Runtime.CompilerServices.CallerArgumentExpressionAttribute.g.cs
PolySharp.SourceGenerators\PolySharp.SourceGenerators.PolyfillsGenerator\System.Runtime.CompilerServices.CollectionBuilderAttribute.g.cs
PolySharp.SourceGenerators\PolySharp.SourceGenerators.PolyfillsGenerator\System.Runtime.CompilerServices.CompilerFeatureRequiredAttribute.g.cs
PolySharp.SourceGenerators\PolySharp.SourceGenerators.PolyfillsGenerator\System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute.g.cs
PolySharp.SourceGenerators\PolySharp.SourceGenerators.PolyfillsGenerator\System.Runtime.CompilerServices.InterpolatedStringHandlerAttribute.g.cs
PolySharp.SourceGenerators\PolySharp.SourceGenerators.PolyfillsGenerator\System.Runtime.CompilerServices.IsExternalInit.g.cs
PolySharp.SourceGenerators\PolySharp.SourceGenerators.PolyfillsGenerator\System.Runtime.CompilerServices.ModuleInitializerAttribute.g.cs
PolySharp.SourceGenerators\PolySharp.SourceGenerators.PolyfillsGenerator\System.Runtime.CompilerServices.OverloadResolutionPriorityAttribute.g.cs
PolySharp.SourceGenerators\PolySharp.SourceGenerators.PolyfillsGenerator\System.Runtime.CompilerServices.ParamCollectionAttribute.g.cs
PolySharp.SourceGenerators\PolySharp.SourceGenerators.PolyfillsGenerator\System.Runtime.CompilerServices.RequiredMemberAttribute.g.cs
PolySharp.SourceGenerators\PolySharp.SourceGenerators.PolyfillsGenerator\System.Runtime.CompilerServices.RequiresLocationAttribute.g.cs
PolySharp.SourceGenerators\PolySharp.SourceGenerators.PolyfillsGenerator\System.Runtime.CompilerServices.SkipLocalsInitAttribute.g.cs
PolySharp.SourceGenerators\PolySharp.SourceGenerators.PolyfillsGenerator\System.Runtime.Versioning.RequiresPreviewFeaturesAttribute.g.cs
-----
//
#pragma warning disable
#nullable enable annotations

// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

namespace System.Diagnostics.CodeAnalysis
{
///
/// Specifies that this constructor sets all required members for the current type,
/// and callers do not need to set any required members themselves.
///
[global::System.AttributeUsage(global::System.AttributeTargets.Constructor, AllowMultiple = false, Inherited = false)]
[global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
internal sealed class SetsRequiredMembersAttribute : global::System.Attribute
{
}
}

Кроме того, код не выбрасывает исключение «кода», поэтому System.diagnostics.codeanalysis.setsrequiredmembersattribute Тип был успешно извлечен, а его тип - nonerrornamedtypesymbol . Таким образом, тип найден? Что происходит?

Код: Выделить всё

Console.WriteLine("-----");
var semanticModel = compilation.GetSemanticModel(diagnostics[0].Location.SourceTree, true);
var attrNode = diagnostics[0].Location.SourceTree
.GetCompilationUnitRoot()
.DescendantNodes()
.OfType()
.FirstOrDefault(a => a.Name.ToString() == "SetsRequiredMembers");
var ctorNode = (ConstructorDeclarationSyntax)attrNode.Parent.Parent;
var ctorSymbol = semanticModel.GetDeclaredSymbol(ctorNode);
var attrSymbol = ctorSymbol.GetAttributes().FirstOrDefault(a => a.AttributeClass.ToString().IndexOf("SetsRequiredMembers") >= 0);
Console.WriteLine($"{attrSymbol.AttributeClass} : {attrSymbol.AttributeClass.GetType().Name}");
и он выводит setsrequiredmembers: errortypesymbol . Для другого атрибута на том же конструкторе данные символа верны. < /P>
Таким образом, проблема реальна. Но почему это происходит?

Подробнее здесь: https://stackoverflow.com/questions/797 ... ll-the-rig
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «C#»