-
-
Notifications
You must be signed in to change notification settings - Fork 61
Add Roslyn analyzer for multiline XML comments #908
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
meziantou
merged 14 commits into
main
from
copilot/add-roslyn-analyzer-multiline-xml-comments
Nov 1, 2025
Merged
Changes from all commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
8503d66
Initial plan
Copilot ffd9c1e
Add MA0177 analyzer for XML comments with single-line content
Copilot 9a976da
Changes before error encountered
Copilot 07df1bd
Address code review feedback: remove tag filtering, fix line comparis…
Copilot 42d15af
Change terminology from 'inline' to 'single-line' XML comment
Copilot 965a7f5
Add max_line_length check to avoid exceeding line length limits
Copilot 0952e4d
Merge branch 'main' into copilot/add-roslyn-analyzer-multiline-xml-co…
meziantou 16ec8c1
Fix analyzer to skip CDATA sections and nested elements
Copilot 4e46bc2
Update documentation for MA0177 analyzer
Copilot 499e313
Add comprehensive documentation for MA0177 rule
Copilot 78f8038
Merge branch 'main' into copilot/add-roslyn-analyzer-multiline-xml-co…
meziantou d13559e
Merge branch 'main' into copilot/add-roslyn-analyzer-multiline-xml-co…
meziantou e8c15f9
Merge branch 'main' into copilot/add-roslyn-analyzer-multiline-xml-co…
meziantou 6571218
Rerun documentation generator to fix formatting
Copilot File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,74 @@ | ||
| # MA0177 - Use single-line XML comment syntax when possible | ||
|
|
||
| This rule reports XML documentation comments that span multiple lines but contain only single-line content. Such comments can be more concisely written on a single line for better readability. | ||
|
|
||
| ````csharp | ||
| /// <summary> | ||
| /// This is a description | ||
| /// </summary> | ||
| public class Sample { } | ||
|
|
||
| // Should be | ||
| /// <summary>This is a description</summary> | ||
| public class Sample { } | ||
| ```` | ||
|
|
||
| ## When to use single-line format | ||
|
|
||
| The analyzer will suggest converting to single-line format when: | ||
| - The XML element spans multiple lines | ||
| - The element contains only a single line of actual text content (ignoring whitespace) | ||
| - The resulting single-line comment would fit within the `max_line_length` configuration (if set) | ||
|
|
||
| ## When NOT to use single-line format | ||
|
|
||
| The analyzer will NOT suggest converting when: | ||
| - The element already uses single-line format | ||
| - The element contains multiple lines of text content | ||
| - The element contains CDATA sections | ||
| - The element contains nested XML elements (like `<c>`, `<see>`, etc.) | ||
| - The single-line version would exceed the `max_line_length` setting | ||
|
|
||
| ## Configuration | ||
|
|
||
| The analyzer respects the `max_line_length` setting from your `.editorconfig` file: | ||
|
|
||
| ````editorconfig | ||
| [*.cs] | ||
| max_line_length = 120 | ||
| ```` | ||
|
|
||
| If the single-line version of the XML comment would exceed this limit, the analyzer will not report a diagnostic. | ||
|
|
||
| ## Examples | ||
|
|
||
| ````csharp | ||
| // Non-compliant: Single-line content on multiple lines | ||
| /// <summary> | ||
| /// Returns the sum of two numbers | ||
| /// </summary> | ||
| public int Add(int a, int b) => a + b; | ||
|
|
||
| // Compliant: Single line | ||
| /// <summary>Returns the sum of two numbers</summary> | ||
| public int Add(int a, int b) => a + b; | ||
|
|
||
| // Compliant: Multiple lines of actual content | ||
| /// <summary> | ||
| /// Returns the sum of two numbers. | ||
| /// This method handles integer overflow. | ||
| /// </summary> | ||
| public int Add(int a, int b) => a + b; | ||
|
|
||
| // Compliant: Contains nested XML element | ||
| /// <summary> | ||
| /// Returns the sum using <see cref="Add"/> method | ||
| /// </summary> | ||
| public int Calculate(int a, int b) => Add(a, b); | ||
|
|
||
| // Compliant: Contains CDATA section | ||
| /// <summary><![CDATA[ | ||
| /// Special content with <markup> | ||
| /// ]]></summary> | ||
| public void Process() { } | ||
| ```` |
78 changes: 78 additions & 0 deletions
78
src/Meziantou.Analyzer.CodeFixers/Rules/UseInlineXmlCommentSyntaxWhenPossibleFixer.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,78 @@ | ||
| using System.Collections.Immutable; | ||
| using System.Composition; | ||
| using System.Text; | ||
| using Microsoft.CodeAnalysis; | ||
| using Microsoft.CodeAnalysis.CodeActions; | ||
| using Microsoft.CodeAnalysis.CodeFixes; | ||
| using Microsoft.CodeAnalysis.CSharp; | ||
| using Microsoft.CodeAnalysis.CSharp.Syntax; | ||
| using Microsoft.CodeAnalysis.Editing; | ||
| using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; | ||
|
|
||
| namespace Meziantou.Analyzer.Rules; | ||
|
|
||
| [ExportCodeFixProvider(LanguageNames.CSharp), Shared] | ||
| public sealed class UseInlineXmlCommentSyntaxWhenPossibleFixer : CodeFixProvider | ||
| { | ||
| public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(RuleIdentifiers.UseSingleLineXmlCommentSyntaxWhenPossible); | ||
|
|
||
| public override FixAllProvider GetFixAllProvider() => WellKnownFixAllProviders.BatchFixer; | ||
|
|
||
| public override async Task RegisterCodeFixesAsync(CodeFixContext context) | ||
| { | ||
| var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); | ||
| var nodeToFix = root?.FindNode(context.Span, getInnermostNodeForTie: true, findInsideTrivia: true); | ||
| if (nodeToFix is not XmlElementSyntax elementSyntax) | ||
| return; | ||
|
|
||
| var title = "Use single-line XML comment syntax"; | ||
| var codeAction = CodeAction.Create( | ||
| title, | ||
| cancellationToken => Fix(context.Document, elementSyntax, cancellationToken), | ||
| equivalenceKey: title); | ||
|
|
||
| context.RegisterCodeFix(codeAction, context.Diagnostics); | ||
| } | ||
|
|
||
| private static async Task<Document> Fix(Document document, XmlElementSyntax elementSyntax, CancellationToken cancellationToken) | ||
| { | ||
| var editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false); | ||
|
|
||
| // Extract the text content | ||
| var contentText = new StringBuilder(); | ||
| foreach (var content in elementSyntax.Content) | ||
| { | ||
| if (content is XmlTextSyntax textSyntax) | ||
| { | ||
| foreach (var token in textSyntax.TextTokens) | ||
| { | ||
| // Skip newline tokens | ||
| if (token.IsKind(SyntaxKind.XmlTextLiteralNewLineToken)) | ||
| continue; | ||
|
|
||
| var text = token.Text.Trim(); | ||
| if (!string.IsNullOrWhiteSpace(text)) | ||
| { | ||
| if (contentText.Length > 0) | ||
| contentText.Append(' '); | ||
| contentText.Append(text); | ||
| } | ||
| } | ||
| } | ||
| } | ||
|
|
||
| // Create single-line syntax | ||
| var elementName = elementSyntax.StartTag.Name; | ||
| var attributes = elementSyntax.StartTag.Attributes; | ||
|
|
||
| var newNode = XmlElement( | ||
| XmlElementStartTag(elementName, attributes), | ||
| SingletonList<XmlNodeSyntax>(XmlText(contentText.ToString())), | ||
| XmlElementEndTag(elementName)) | ||
| .WithLeadingTrivia(elementSyntax.GetLeadingTrivia()) | ||
| .WithTrailingTrivia(elementSyntax.GetTrailingTrivia()); | ||
|
|
||
| editor.ReplaceNode(elementSyntax, newNode); | ||
| return editor.GetChangedDocument(); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
175 changes: 175 additions & 0 deletions
175
src/Meziantou.Analyzer/Rules/UseInlineXmlCommentSyntaxWhenPossibleAnalyzer.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,175 @@ | ||
| using System.Collections.Immutable; | ||
| using Microsoft.CodeAnalysis; | ||
| using Microsoft.CodeAnalysis.CSharp.Syntax; | ||
| using Microsoft.CodeAnalysis.Diagnostics; | ||
|
|
||
| namespace Meziantou.Analyzer.Rules; | ||
|
|
||
| [DiagnosticAnalyzer(LanguageNames.CSharp)] | ||
| public sealed class UseInlineXmlCommentSyntaxWhenPossibleAnalyzer : DiagnosticAnalyzer | ||
| { | ||
| private static readonly DiagnosticDescriptor Rule = new( | ||
| RuleIdentifiers.UseSingleLineXmlCommentSyntaxWhenPossible, | ||
| title: "Use single-line XML comment syntax when possible", | ||
| messageFormat: "Use single-line XML comment syntax when possible", | ||
| RuleCategories.Style, | ||
| DiagnosticSeverity.Info, | ||
| isEnabledByDefault: false, | ||
| description: "", | ||
| helpLinkUri: RuleIdentifiers.GetHelpUri(RuleIdentifiers.UseSingleLineXmlCommentSyntaxWhenPossible)); | ||
|
|
||
| public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule); | ||
|
|
||
| public override void Initialize(AnalysisContext context) | ||
| { | ||
| context.EnableConcurrentExecution(); | ||
| context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); | ||
|
|
||
| context.RegisterSymbolAction(AnalyzeSymbol, SymbolKind.NamedType, SymbolKind.Method, SymbolKind.Field, SymbolKind.Event, SymbolKind.Property); | ||
| } | ||
|
|
||
| private static void AnalyzeSymbol(SymbolAnalysisContext context) | ||
| { | ||
| var symbol = context.Symbol; | ||
| if (symbol.IsImplicitlyDeclared) | ||
| return; | ||
|
|
||
| if (symbol is INamedTypeSymbol namedTypeSymbol && (namedTypeSymbol.IsImplicitClass || symbol.Name.Contains('$', StringComparison.Ordinal))) | ||
| return; | ||
|
|
||
| foreach (var syntaxReference in symbol.DeclaringSyntaxReferences) | ||
| { | ||
| var syntax = syntaxReference.GetSyntax(context.CancellationToken); | ||
| if (!syntax.HasStructuredTrivia) | ||
| continue; | ||
|
|
||
| foreach (var trivia in syntax.GetLeadingTrivia()) | ||
| { | ||
| var structure = trivia.GetStructure(); | ||
| if (structure is null) | ||
| continue; | ||
|
|
||
| if (structure is not DocumentationCommentTriviaSyntax documentation) | ||
| continue; | ||
|
|
||
| foreach (var childNode in documentation.ChildNodes()) | ||
| { | ||
| if (childNode is XmlElementSyntax elementSyntax) | ||
| { | ||
| // Check if element spans multiple lines | ||
| var startLine = elementSyntax.StartTag.GetLocation().GetLineSpan().StartLinePosition.Line; | ||
| var endLine = elementSyntax.EndTag.GetLocation().GetLineSpan().EndLinePosition.Line; | ||
|
|
||
| if (endLine == startLine) | ||
| continue; // Single line, no issue | ||
|
|
||
| // Check if content is single-line (ignoring whitespace) | ||
| // Skip if content contains CDATA sections or other non-text elements | ||
| var hasCDataOrOtherElements = false; | ||
| var meaningfulTextTokenCount = 0; | ||
| foreach (var content in elementSyntax.Content) | ||
| { | ||
| if (content is XmlTextSyntax textSyntax) | ||
| { | ||
| foreach (var token in textSyntax.TextTokens) | ||
| { | ||
| // Skip whitespace-only tokens and newline tokens | ||
| if (token.IsKind(Microsoft.CodeAnalysis.CSharp.SyntaxKind.XmlTextLiteralNewLineToken)) | ||
| continue; | ||
|
|
||
| var text = token.Text.Trim(); | ||
| if (!string.IsNullOrWhiteSpace(text)) | ||
| { | ||
| meaningfulTextTokenCount++; | ||
| } | ||
| } | ||
| } | ||
| else if (content is XmlCDataSectionSyntax || content is XmlElementSyntax) | ||
| { | ||
| // Skip elements with CDATA sections or nested elements | ||
| hasCDataOrOtherElements = true; | ||
| break; | ||
| } | ||
| } | ||
|
|
||
| // Report diagnostic if content is effectively single-line (0 or 1 meaningful text tokens) | ||
| // and doesn't contain CDATA or other nested elements | ||
| if (!hasCDataOrOtherElements && meaningfulTextTokenCount <= 1) | ||
| { | ||
| // Check if the single-line version would fit within max_line_length | ||
| if (WouldFitInMaxLineLength(context, elementSyntax)) | ||
| { | ||
| context.ReportDiagnostic(Diagnostic.Create(Rule, elementSyntax.GetLocation())); | ||
| } | ||
| } | ||
| } | ||
| } | ||
| } | ||
| } | ||
| } | ||
|
|
||
| private static bool WouldFitInMaxLineLength(SymbolAnalysisContext context, XmlElementSyntax elementSyntax) | ||
| { | ||
| // Get max_line_length from .editorconfig | ||
| var options = context.Options.AnalyzerConfigOptionsProvider.GetOptions(elementSyntax.SyntaxTree); | ||
| if (!options.TryGetValue("max_line_length", out var maxLineLengthValue)) | ||
| return true; // No limit configured, allow the change | ||
|
|
||
| if (!int.TryParse(maxLineLengthValue, System.Globalization.NumberStyles.None, System.Globalization.CultureInfo.InvariantCulture, out var maxLineLength) || maxLineLength <= 0) | ||
| return true; // Invalid or no limit, allow the change | ||
|
|
||
| // Get the indentation of the current line | ||
| var lineSpan = elementSyntax.GetLocation().GetLineSpan(); | ||
| var sourceText = elementSyntax.SyntaxTree.GetText(); | ||
| var line = sourceText.Lines[lineSpan.StartLinePosition.Line]; | ||
| var lineText = line.ToString(); | ||
| var indentation = lineText.Length - lineText.TrimStart().Length; | ||
|
|
||
| // Build the single-line content | ||
| var contentLength = indentation; | ||
| var elementName = elementSyntax.StartTag.Name.LocalName.Text; | ||
| var attributes = elementSyntax.StartTag.Attributes; | ||
|
|
||
| // Calculate: "/// <elementName" + attributes + ">" + content + "</elementName>" | ||
| contentLength += 4; // "/// " | ||
| contentLength += 1; // "<" | ||
| contentLength += elementName.Length; | ||
|
|
||
| // Add attribute lengths | ||
| foreach (var attribute in attributes) | ||
| { | ||
| contentLength += attribute.Span.Length + 1; // +1 for space before attribute | ||
| } | ||
|
|
||
| contentLength += 1; // ">" | ||
|
|
||
| // Add text content | ||
| var hasContent = false; | ||
| foreach (var content in elementSyntax.Content) | ||
| { | ||
| if (content is XmlTextSyntax textSyntax) | ||
| { | ||
| foreach (var token in textSyntax.TextTokens) | ||
| { | ||
| if (token.IsKind(Microsoft.CodeAnalysis.CSharp.SyntaxKind.XmlTextLiteralNewLineToken)) | ||
| continue; | ||
|
|
||
| var text = token.Text.Trim(); | ||
| if (!string.IsNullOrWhiteSpace(text)) | ||
| { | ||
| if (hasContent) | ||
| contentLength += 1; // space separator between multiple text tokens | ||
| contentLength += text.Length; | ||
| hasContent = true; | ||
| } | ||
| } | ||
| } | ||
| } | ||
|
|
||
| contentLength += 2; // "</" | ||
| contentLength += elementName.Length; | ||
| contentLength += 1; // ">" | ||
|
|
||
| return contentLength <= maxLineLength; | ||
| } | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.