-
-
Notifications
You must be signed in to change notification settings - Fork 17
Implémentation de la règle RCS1242: Do not pass non-read-only struct … #91
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
Merged
Changes from all commits
Commits
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
119 changes: 119 additions & 0 deletions
119
src/Creedengo.Core/Analyzers/GCIACV.NonReadOnlyStruct.Fixer.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,119 @@ | ||
| namespace Creedengo.Core.Analyzers; | ||
|
|
||
| /// <summary>GCIACV fixer: Do not pass non-read-only struct by read-only reference.</summary> | ||
| [ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(NonReadOnlyStructFixer)), Shared] | ||
| public sealed class NonReadOnlyStructFixer : CodeFixProvider | ||
| { | ||
| /// <inheritdoc/> | ||
| public override ImmutableArray<string> FixableDiagnosticIds => _fixableDiagnosticIds; | ||
| private static readonly ImmutableArray<string> _fixableDiagnosticIds = [NonReadOnlyStruct.Descriptor.Id]; | ||
|
|
||
| /// <inheritdoc/> | ||
| [ExcludeFromCodeCoverage] | ||
| public override FixAllProvider GetFixAllProvider() => WellKnownFixAllProviders.BatchFixer; | ||
|
|
||
| /// <inheritdoc/> | ||
| public override async Task RegisterCodeFixesAsync(CodeFixContext context) | ||
| { | ||
| if (context.Diagnostics.Length == 0) return; | ||
|
|
||
| var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); | ||
| if (root == null) return; | ||
|
|
||
| var diagnostic = context.Diagnostics.First(); | ||
| var nodeSpan = diagnostic.Location.SourceSpan; | ||
| var parameter = root.FindToken(nodeSpan.Start) | ||
| .Parent? | ||
| .AncestorsAndSelf() | ||
| .OfType<ParameterSyntax>() | ||
| .FirstOrDefault(); | ||
|
|
||
| if (parameter == null) return; | ||
|
|
||
| // Check if it's an 'in' parameter or 'ref readonly' parameter | ||
| if (parameter.Modifiers.Any(SyntaxKind.InKeyword)) | ||
| { | ||
| context.RegisterCodeFix( | ||
| CodeAction.Create( | ||
| title: "Remove 'in' modifier", | ||
| c => RemoveInModifierAsync(context.Document, parameter, c), | ||
| equivalenceKey: "Remove 'in' modifier"), | ||
| diagnostic); | ||
| } | ||
| else if (parameter.Modifiers.Any(SyntaxKind.RefKeyword) && parameter.Modifiers.Any(SyntaxKind.ReadOnlyKeyword)) | ||
| { | ||
| context.RegisterCodeFix( | ||
| CodeAction.Create( | ||
| title: "Remove 'readonly' modifier (keep 'ref')", | ||
| c => RemoveReadOnlyModifierAsync(context.Document, parameter, c), | ||
| equivalenceKey: "Remove 'readonly' modifier"), | ||
| diagnostic); | ||
|
|
||
| context.RegisterCodeFix( | ||
| CodeAction.Create( | ||
| title: "Remove 'ref readonly' modifiers", | ||
| c => RemoveRefReadOnlyModifiersAsync(context.Document, parameter, c), | ||
| equivalenceKey: "Remove 'ref readonly' modifiers"), | ||
| diagnostic); | ||
| } | ||
| } | ||
|
|
||
| private static async Task<Document> RemoveInModifierAsync( | ||
| Document document, | ||
| ParameterSyntax parameter, | ||
| CancellationToken cancellationToken) | ||
| { | ||
| var editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false); | ||
|
|
||
| // Get the 'in' modifier | ||
| var inModifier = parameter.Modifiers.First(m => m.IsKind(SyntaxKind.InKeyword)); | ||
|
|
||
| // Create new parameter without the 'in' modifier | ||
| var newParameter = parameter.WithModifiers(parameter.Modifiers.Remove(inModifier)); | ||
|
|
||
| // Replace the parameter | ||
| editor.ReplaceNode(parameter, newParameter); | ||
|
|
||
| return editor.GetChangedDocument(); | ||
| } | ||
|
|
||
| private static async Task<Document> RemoveReadOnlyModifierAsync( | ||
| Document document, | ||
| ParameterSyntax parameter, | ||
| CancellationToken cancellationToken) | ||
| { | ||
| var editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false); | ||
|
|
||
| // Get the 'readonly' modifier | ||
| var readOnlyModifier = parameter.Modifiers.First(m => m.IsKind(SyntaxKind.ReadOnlyKeyword)); | ||
|
|
||
| // Create new parameter without the 'readonly' modifier | ||
| var newParameter = parameter.WithModifiers(parameter.Modifiers.Remove(readOnlyModifier)); | ||
|
|
||
| // Replace the parameter | ||
| editor.ReplaceNode(parameter, newParameter); | ||
|
|
||
| return editor.GetChangedDocument(); | ||
| } | ||
|
|
||
| private static async Task<Document> RemoveRefReadOnlyModifiersAsync( | ||
| Document document, | ||
| ParameterSyntax parameter, | ||
| CancellationToken cancellationToken) | ||
| { | ||
| var editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false); | ||
|
|
||
| // Get the 'ref' and 'readonly' modifiers | ||
| var refModifier = parameter.Modifiers.First(m => m.IsKind(SyntaxKind.RefKeyword)); | ||
| var readOnlyModifier = parameter.Modifiers.First(m => m.IsKind(SyntaxKind.ReadOnlyKeyword)); | ||
|
|
||
| // Create new parameter without both modifiers | ||
| var newParameter = parameter.WithModifiers( | ||
| parameter.Modifiers.Remove(refModifier).Remove(readOnlyModifier)); | ||
|
|
||
| // Replace the parameter | ||
| editor.ReplaceNode(parameter, newParameter); | ||
|
|
||
| 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,64 @@ | ||
| namespace Creedengo.Core.Analyzers; | ||
|
|
||
| /// <summary>GCIACV: Do not pass non-read-only struct by read-only reference.</summary> | ||
| [DiagnosticAnalyzer(LanguageNames.CSharp)] | ||
| public sealed class NonReadOnlyStruct : DiagnosticAnalyzer | ||
| { | ||
| private static readonly ImmutableArray<SyntaxKind> MethodDeclarations = [SyntaxKind.MethodDeclaration]; | ||
|
|
||
| /// <summary>The diagnostic descriptor.</summary> | ||
| public static DiagnosticDescriptor Descriptor { get; } = Rule.CreateDescriptor( | ||
| id: Rule.Ids.GCIACV_NonReadOnlyStruct, | ||
| title: "Do not pass non-read-only struct by read-only reference", | ||
| message: "Non-read-only struct should not be passed by read-only reference.", | ||
| category: Rule.Categories.Performance, | ||
| severity: DiagnosticSeverity.Warning, | ||
| description: "Using 'in' or 'ref readonly' parameter modifier for non-readonly struct types can lead to defensive copies, causing performance degradation."); | ||
|
|
||
| /// <inheritdoc/> | ||
| public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => _supportedDiagnostics; | ||
| private static readonly ImmutableArray<DiagnosticDescriptor> _supportedDiagnostics = [Descriptor]; | ||
|
|
||
| /// <inheritdoc/> | ||
| public override void Initialize(AnalysisContext context) | ||
| { | ||
| context.EnableConcurrentExecution(); | ||
| context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); | ||
| context.RegisterSyntaxNodeAction(static context => AnalyzeSyntaxNode(context), MethodDeclarations); | ||
| } | ||
|
|
||
| private static void AnalyzeSyntaxNode(SyntaxNodeAnalysisContext context) | ||
| { | ||
| var methodDeclaration = (MethodDeclarationSyntax)context.Node; | ||
| var semanticModel = context.SemanticModel; | ||
| var compilation = context.Compilation; // Analyze each parameter in the method declaration | ||
| foreach (var parameter in methodDeclaration.ParameterList.Parameters) | ||
| { | ||
| // Check if the parameter has either 'in' keyword or 'ref readonly' modifiers | ||
| bool isReadOnlyReference = parameter.Modifiers.Any(SyntaxKind.InKeyword) || | ||
| (parameter.Modifiers.Any(SyntaxKind.RefKeyword) && parameter.Modifiers.Any(SyntaxKind.ReadOnlyKeyword)); | ||
|
|
||
| if (isReadOnlyReference && | ||
| parameter.Type != null && | ||
| ModelExtensions.GetTypeInfo(semanticModel, parameter.Type).Type is { } parameterTypeSymbol && | ||
| parameterTypeSymbol.IsValueType && | ||
| parameterTypeSymbol is INamedTypeSymbol namedTypeSymbol) | ||
| { | ||
| // For nested struct types or any other struct, check if it's readonly | ||
| if (!namedTypeSymbol.IsReadOnly) | ||
| { | ||
| // Report diagnostic on the type identifier part of the parameter | ||
| var diagnosticLocation = parameter.Type.GetLocation(); | ||
| if (diagnosticLocation == null) | ||
| diagnosticLocation = parameter.GetLocation(); | ||
|
|
||
| context.ReportDiagnostic( | ||
| Diagnostic.Create( | ||
| Descriptor, | ||
| diagnosticLocation, | ||
| parameter.Identifier.ValueText)); | ||
| } | ||
| } | ||
| } | ||
| } | ||
| } | ||
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
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.