简体   繁体   English

使用 Roslyn Analyzer 检查源代码行是否超过行长的最佳方法是什么?

[英]What's the best way to check source code lines for exceeding line length with Roslyn Analyzer?

I'd like to enforce some hard limits to code line length.我想对代码行长度实施一些硬性限制。

What Roslyn's API should I use for it?我应该使用什么 Roslyn 的 API?

Registering action for every syntax node and checking node's location seems to be not the most efficient approach.为每个语法节点注册动作并检查节点的位置似乎不是最有效的方法。

An easy approach might be to register for syntax trees, but then immediately just call GetText() on the syntax tree;一种简单的方法可能是注册语法树,然后立即在语法树上调用 GetText(); from there you can look at the lines of the text directly and at least find "long" lines since you can directly get line spans and lengths that way.从那里您可以直接查看文本行,并且至少找到“长”行,因为您可以通过这种方式直接获取行跨度和长度。 You'll still potentially need to filter out things though like long string literals or something.您仍然可能需要过滤掉诸如长字符串文字之类的东西。

Not perfect solution:不完美的解决方案:

[DiagnosticAnalyzer(LanguageNames.CSharp)]
public sealed class LineMaxLengthAnalyzer : DiagnosticAnalyzer
{
    public const int LineMaxLength = 150;
    public const string DiagnosticId = nameof(LineMaxLengthAnalyzer);

    private static readonly LocalizableString Title = new LocalizableResourceString(
        nameof(Resources.LineMaxLengthAnalyzerTitle), Resources.ResourceManager, typeof(Resources));
    private static readonly LocalizableString MessageFormat = new LocalizableResourceString(
        nameof(Resources.LineMaxLengthAnalyzerMessageFormat), Resources.ResourceManager, typeof(Resources));
    private static readonly LocalizableString Description = new LocalizableResourceString(
        nameof(Resources.LineMaxLengthAnalyzerDescription), Resources.ResourceManager, typeof(Resources));
    private const string Category = "Readability";

    private static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor(
        DiagnosticId, Title, MessageFormat, Category, DiagnosticSeverity.Error, isEnabledByDefault: true, description: Description);

    public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = ImmutableArray.Create(Rule);

    public override void Initialize(AnalysisContext context)
    {
        context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
        context.EnableConcurrentExecution();

        var nodeTypes = Enum.GetValues(typeof(SyntaxKind)).Cast<SyntaxKind>().ToArray();
        context.RegisterSyntaxTreeAction(VerifyLines);
    }

    private void VerifyLines(SyntaxTreeAnalysisContext context)
    {
        var text = context.Tree.GetText();
        text.Lines.Where(line => line.End - line.Start + 1 > LineMaxLength).ToList()
            .ForEach(line =>
            {
                var location = Location.Create(context.Tree, line.Span);
                var diagnostic = Diagnostic.Create(Rule, location, LineMaxLength);
                context.ReportDiagnostic(diagnostic);
            });
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在C#中,在多条源代码行之间散布单行字符串文字的最佳方法是什么? - In C#, what's the best way to spread a single-line string literal across multiple source lines? 在 Roslyn 分析器中检查表达式类型的正确方法? - Correct way to check the type of an expression in Roslyn analyzer? 使用Roslyn突出显示C#语法的最佳方法是什么? - What's the best way to highlight C# syntax using Roslyn? 创建一条从另一条线上的点开始并以给定角度延伸给定长度的线的最佳方法是什么? - What's the best way to create a line that starts at a point on another line and extends at a given angle for a given length? 在同一解决方案中使用Roslyn代码分析器 - Use Roslyn code analyzer in same solution 在 Roslyn 分析器中分析后预处理器代码 - Analyze post-preprocessor code in Roslyn analyzer 有没有办法在Roslyn的分析器和代码修复提供程序之间传递数据(除了通过属性包)? - Is there a way to pass data (other than through the property bag) between an analyzer and a code fix provider in Roslyn? 分离此代码的问题的最佳方法是什么? - What's the best way to separate concerns for this code? 如果我支持VS2015,我的分析器可以定位的Roslyn的最新版本是什么? - What's the latest version of Roslyn my analyzer can target if I support VS2015? 如何在Roslyn中没有源代码的情况下浏览程序集的内容 - How to browse an assembly's content without source code in Roslyn
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM