-
-
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 4 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
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.UseInlineXmlCommentSyntaxWhenPossible); | ||
|
|
||
| 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 inline 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 inline 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
98 changes: 98 additions & 0 deletions
98
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,98 @@ | ||
| 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.UseInlineXmlCommentSyntaxWhenPossible, | ||
| title: "Use inline XML comment syntax when possible", | ||
| messageFormat: "Use inline XML comment syntax when possible", | ||
| RuleCategories.Style, | ||
| DiagnosticSeverity.Info, | ||
| isEnabledByDefault: false, | ||
| description: "", | ||
| helpLinkUri: RuleIdentifiers.GetHelpUri(RuleIdentifiers.UseInlineXmlCommentSyntaxWhenPossible)); | ||
|
|
||
| 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) | ||
meziantou marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| // Count the number of text tokens that have meaningful content | ||
| 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++; | ||
| } | ||
| } | ||
| } | ||
| } | ||
|
|
||
| // Report diagnostic if content is effectively single-line (0 or 1 meaningful text tokens) | ||
| if (meaningfulTextTokenCount <= 1) | ||
| { | ||
| context.ReportDiagnostic(Diagnostic.Create(Rule, elementSyntax.GetLocation())); | ||
| } | ||
| } | ||
| } | ||
| } | ||
| } | ||
| } | ||
| } | ||
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.