Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
119 changes: 119 additions & 0 deletions src/Creedengo.Core/Analyzers/GCIACV.NonReadOnlyStruct.Fixer.cs
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();
}
}
64 changes: 64 additions & 0 deletions src/Creedengo.Core/Analyzers/GCIACV.NonReadOnlyStruct.cs
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));
}
}
}
}
}
1 change: 1 addition & 0 deletions src/Creedengo.Core/Models/Rule.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ public static class Ids
public const string GCI91_UseWhereBeforeOrderBy = "GCI91";
public const string GCI92_UseStringEmptyLength = "GCI92";
public const string GCI93_ReturnTaskDirectly = "GCI93";
public const string GCIACV_NonReadOnlyStruct = "GCIACV";
public const string GCI95_UseIsOperatorInsteadOfAsOperator = "GCI95";
}

Expand Down
Loading