using System.Collections.Immutable; using System.Composition; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp; namespace Brutal.Strings.Analyzers; [ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(SpanToStringFixProvider)), Shared] public class SpanToStringFixProvider : CodeFixProvider { // Specify the diagnostic IDs of analyzers that are expected to be linked. public sealed override ImmutableArray FixableDiagnosticIds { get; } = [Resources.BrutalCore0001.Id]; // If you don't need the 'fix all' behaviour, return null. public override FixAllProvider? GetFixAllProvider() => null; public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) { // We link only one diagnostic and assume there is only one diagnostic in the context. var diagnostic = context.Diagnostics.Single(); // 'SourceSpan' of 'Location' is the highlighted area. We're going to use this area to find the 'SyntaxNode' to rename. var diagnosticSpan = diagnostic.Location.SourceSpan; // Get the root of Syntax Tree that contains the highlighted diagnostic. var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); // Find SyntaxNode corresponding to the diagnostic. var diagnosticNode = root?.FindNode(diagnosticSpan)!; // Register a code action that will invoke the fix. context.RegisterCodeFix( CodeAction.Create( title: Resources.BrutalCore0001Suggestion, createChangedSolution: c => FixToStringAsync(context.Document, diagnosticNode, c), equivalenceKey: nameof(Resources.BrutalCore0001.Id) ), diagnostic ); } /// /// Executed on the quick fix action raised by the user. /// /// Affected source file. /// The syntax node that we found in 'RegisterCodeFixesAsync'. /// Any fix is cancellable by the user, so we should support the cancellation token. /// Clone of the solution with updates: renamed class. private static async Task FixToStringAsync( Document document, SyntaxNode methodName, CancellationToken cancellationToken ) { // change from "ReadOnlySpan.ToString()" to "ReadOnlySpan.ToString16()" var root = await document.GetSyntaxRootAsync(cancellationToken); if (root == null) return document.Project.Solution; var newName = SyntaxFactory.IdentifierName("ToString16"); var newRoot = root.ReplaceNode(methodName, newName); var newDocument = document.WithSyntaxRoot(newRoot); return newDocument.Project.Solution; } }