[英]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.