如何在LINQ表达式组中捕获标识符的语法节点…到

问题描述 投票:0回答:1

我想用我的自定义代码分析器处理代码中的所有标识符。我在这样的表达式中捕获了所有这些,除了标识符y

var z = from x in new int[] { }
        group x by x into y
        select new { };

有最少的分析器源代码示例:

[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class IdentifierAnalyzer : DiagnosticAnalyzer
{
    private static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor("Id", "", "", "Naming", DiagnosticSeverity.Warning, true, null);
    public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule);
    public override void Initialize(AnalysisContext context)
    {
        context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics);
        context.EnableConcurrentExecution();
        context.RegisterSyntaxNodeAction(AnalyzeNode, SyntaxKinds);
    }

    private static readonly SyntaxKind[] SyntaxKinds = new[] {
                                                           SyntaxKind.JoinIntoClause,
                                                           //TODO: LINQ group...into <identifier>
                                                       };

    private static void AnalyzeNode(SyntaxNodeAnalysisContext context)
    {
        switch (context.Node)
        {
            case JoinIntoClauseSyntax joinIntoClause:
                if (IsNotValid(joinIntoClause.Identifier.Text))
                    context.ReportDiagnostic(Diagnostic.Create(Rule, joinIntoClause.Identifier.GetLocation(), joinIntoClause.Identifier.Text));
                break;
            //TODO: LINQ group...into <identifier>
        }
    }

    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    private static bool IsNotValid(string text)
    {            
        return true;
    }
}

我想用我的自定义代码分析器处理代码中的所有标识符。我在这样的表达式中捕获了除标识符y以外的所有这些变量:var z = from new int [] {} group中的x by x into y ...

c# linq roslyn roslyn-code-analysis
1个回答
0
投票
switch (context.Node)
        {
            case JoinIntoClauseSyntax joinIntoClause:
                if (IsNotValid(joinIntoClause.Identifier.Text))
                    context.ReportDiagnostic(Diagnostic.Create(Rule, joinIntoClause.Identifier.GetLocation(), joinIntoClause.Identifier.Text));
                break;
            case QueryContinuationSyntax continuationSyntax:
                if (IsNotValid(continuationSyntax.Identifier.Text))
                    context.ReportDiagnostic(Diagnostic.Create(Rule, continuationSyntax.Identifier.GetLocation(), continuationSyntax.Identifier.Text));
                break;
        }
© www.soinside.com 2019 - 2024. All rights reserved.