diff --git a/ComputeSharp.sln b/ComputeSharp.sln index 778f57a2..2c8e64eb 100644 --- a/ComputeSharp.sln +++ b/ComputeSharp.sln @@ -469,6 +469,7 @@ Global src\ComputeSharp.Win32.D2D1\ComputeSharp.Win32.D2D1.projitems*{4d7d9ba8-a821-4b1c-9ee2-cbcf5849906e}*SharedItemsImports = 5 src\ComputeSharp.Win32.D3D12\ComputeSharp.Win32.D3D12.projitems*{514ff00e-bbf0-4d55-a47c-eeeb6208adce}*SharedItemsImports = 13 src\ComputeSharp.SourceGeneration\ComputeSharp.SourceGeneration.projitems*{51d5a422-d3a5-4c4d-8a6d-a048940bf279}*SharedItemsImports = 13 + src\ComputeSharp.CodeFixing\ComputeSharp.CodeFixing.projitems*{54654960-54b5-4e19-b3ed-993591ca39e5}*SharedItemsImports = 5 samples\ComputeSharp.SwapChain.Shaders.D2D1.Shared\ComputeSharp.SwapChain.Shaders.D2D1.Shared.projitems*{73c32d0f-64db-4674-84e9-8fcc41228474}*SharedItemsImports = 5 src\ComputeSharp.SourceGeneration.Hlsl\ComputeSharp.SourceGeneration.Hlsl.projitems*{9ac496a3-bbf0-4c8f-a50d-a20bf01c5e05}*SharedItemsImports = 13 src\ComputeSharp.Win32.D2D1\ComputeSharp.Win32.D2D1.projitems*{9da1da9f-f8b2-4b25-be80-c21f773029e3}*SharedItemsImports = 13 diff --git a/src/ComputeSharp.CodeFixing/ComputeSharp.CodeFixing.projitems b/src/ComputeSharp.CodeFixing/ComputeSharp.CodeFixing.projitems index 98ea93eb..bf418a95 100644 --- a/src/ComputeSharp.CodeFixing/ComputeSharp.CodeFixing.projitems +++ b/src/ComputeSharp.CodeFixing/ComputeSharp.CodeFixing.projitems @@ -9,5 +9,6 @@ ComputeSharp.CodeFixing + - + \ No newline at end of file diff --git a/src/ComputeSharp.CodeFixing/MissingAttributeCodeFixer.cs b/src/ComputeSharp.CodeFixing/MissingAttributeCodeFixer.cs new file mode 100644 index 00000000..bc33a9b2 --- /dev/null +++ b/src/ComputeSharp.CodeFixing/MissingAttributeCodeFixer.cs @@ -0,0 +1,235 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Threading; +using System.Threading.Tasks; +using ComputeSharp.SourceGeneration.Extensions; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CodeActions; +using Microsoft.CodeAnalysis.CodeFixes; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Editing; +using Microsoft.CodeAnalysis.Simplification; +using Microsoft.CodeAnalysis.Text; + +namespace ComputeSharp.CodeFixing; + +/// +/// A code fixer that adds an attribute that is missing on a type that requires it. +/// +public abstract class MissingAttributeCodeFixer : CodeFixProvider +{ + /// + /// The title to display for the code fixer. + /// + private readonly string codeActionTitle; + + /// + /// The fully qualified type name of the attribute to add. + /// + private readonly string attributeFullyQualifiedMetadataName; + + /// + /// The fully qualified type names of leading attributes to skip. + /// + private readonly IEnumerable leadingAttributeFullyQualifiedMetadataNames; + + /// + /// Creates a new instance with the specified parameters. + /// + /// The diagnostic id to trigger the code fixer. + /// The title to display for the code fixer. + /// The fully qualified type name of the attribute to add. + /// The fully qualified type names of leading attributes to skip. + protected MissingAttributeCodeFixer( + string diagnosticId, + string codeActionTitle, + string attributeFullyQualifiedMetadataName, + IEnumerable leadingAttributeFullyQualifiedMetadataNames) + { + this.codeActionTitle = codeActionTitle; + this.attributeFullyQualifiedMetadataName = attributeFullyQualifiedMetadataName; + this.leadingAttributeFullyQualifiedMetadataNames = leadingAttributeFullyQualifiedMetadataNames; + + FixableDiagnosticIds = ImmutableArray.Create(diagnosticId); + } + + /// + public override ImmutableArray FixableDiagnosticIds { get; } + + /// + public override Microsoft.CodeAnalysis.CodeFixes.FixAllProvider? GetFixAllProvider() + { + return new FixAllProvider(this); + } + + /// + public override async Task RegisterCodeFixesAsync(CodeFixContext context) + { + Diagnostic diagnostic = context.Diagnostics[0]; + TextSpan diagnosticSpan = context.Span; + + SyntaxNode? root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); + + // Get the struct declaration from the target diagnostic + if (root?.FindNode(diagnosticSpan) is StructDeclarationSyntax structDeclaration) + { + // Register the code fix to update the return type to be Task instead + context.RegisterCodeFix( + CodeAction.Create( + title: this.codeActionTitle, + createChangedDocument: token => AddMissingAttribute(context.Document, root, structDeclaration, token), + equivalenceKey: this.codeActionTitle), + diagnostic); + } + } + + /// + /// Applies the code fix to add the missing attribute to a target type. + /// + /// The original document being fixed. + /// The original tree root belonging to the current document. + /// The to update. + /// The cancellation token for the operation. + /// An updated document with the applied code fix, and the return type of the method being . + private async Task AddMissingAttribute( + Document document, + SyntaxNode root, + StructDeclarationSyntax structDeclaration, + CancellationToken cancellationToken) + { + // Get the new struct declaration + SyntaxNode updatedStructDeclaration = await AddMissingAttribute( + document, + structDeclaration, + cancellationToken); + + // Replace the node in the document tree + return document.WithSyntaxRoot(root.ReplaceNode(structDeclaration, updatedStructDeclaration)); + } + + /// + /// Applies the code fix to add the missing attribute to a target type. + /// + /// The original document being fixed. + /// The to update. + /// The cancellation token for the operation. + /// An updated document with the applied code fix, and the return type of the method being . + private async Task AddMissingAttribute( + Document document, + StructDeclarationSyntax structDeclaration, + CancellationToken cancellationToken) + { + // Get the semantic model (bail if it's not available) + if (await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false) is not SemanticModel semanticModel) + { + return structDeclaration; + } + + // Build the map of attributes to look for + if (!semanticModel.Compilation.TryBuildNamedTypeSymbolSet(this.leadingAttributeFullyQualifiedMetadataNames, out ImmutableHashSet? leadingAttributeTypeSymbols)) + { + return structDeclaration; + } + + // Also bail if we can't resolve the target attribute symbol (this should really never happen) + if (semanticModel.Compilation.GetTypeByMetadataName(this.attributeFullyQualifiedMetadataName) is not INamedTypeSymbol attributeSymbol) + { + return structDeclaration; + } + + int index = 0; + + // Find the index to use to insert the attribute. We want to make it so that if the struct declaration + // has a bunch of leading attributes, the new one will be inserted right after that. This way the final list + // will be nicely sorted, instead of having attributes interleaving other unrelated attributes, if any. + foreach (AttributeListSyntax attributeList in structDeclaration.AttributeLists) + { + // Make sure we have an attribute to check + if (attributeList.Attributes is not [AttributeSyntax attribute, ..]) + { + continue; + } + + // Resolve the symbol for the attribute (stop here if this failed for whatever reason) + if (!semanticModel.GetSymbolInfo(attribute, cancellationToken).TryGetAttributeTypeSymbol(out INamedTypeSymbol? attributeTypeSymbol)) + { + break; + } + + // If the attribute is a leading one, increment the index and continue + if (leadingAttributeTypeSymbols.Contains(attributeTypeSymbol)) + { + index++; + } + else + { + // Otherwise, stop here, we reached the end of the sequence + break; + } + } + + SyntaxGenerator syntaxGenerator = SyntaxGenerator.GetGenerator(document); + + // Create the attribute syntax for the new attribute. Also annotate it + // to automatically add using directives to the document, if needed. + // Then create the attribute syntax and insert it at the right position. + SyntaxNode attributeTypeSyntax = syntaxGenerator.TypeExpression(attributeSymbol).WithAdditionalAnnotations(Simplifier.AddImportsAnnotation); + SyntaxNode attributeSyntax = syntaxGenerator.Attribute(attributeTypeSyntax); + SyntaxNode updatedStructDeclarationSyntax = syntaxGenerator.InsertAttributes(structDeclaration, index, attributeSyntax); + + // Replace the node in the syntax tree + return updatedStructDeclarationSyntax; + } + + /// + /// A custom with the logic from . + /// + private sealed class FixAllProvider : DocumentBasedFixAllProvider + { + /// + /// The owning instance. + /// + private readonly MissingAttributeCodeFixer codeFixer; + + /// + /// Creates a new instance with the specified parameters. + /// + /// The owning instance. + public FixAllProvider(MissingAttributeCodeFixer codeFixer) + { + this.codeFixer = codeFixer; + } + + /// + protected override async Task FixAllAsync(FixAllContext fixAllContext, Document document, ImmutableArray diagnostics) + { + // Get the document root (this should always succeed) + if (await document.GetSyntaxRootAsync(fixAllContext.CancellationToken).ConfigureAwait(false) is not SyntaxNode root) + { + return document; + } + + SyntaxEditor syntaxEditor = new(root, fixAllContext.Solution.Services); + + foreach (Diagnostic diagnostic in diagnostics) + { + // Get the current struct declaration for the diagnostic + if (root.FindNode(diagnostic.Location.SourceSpan) is not StructDeclarationSyntax structDeclaration) + { + continue; + } + + // Get the syntax node with the updated declaration + SyntaxNode updatedStructDeclaration = await this.codeFixer.AddMissingAttribute( + document, + structDeclaration, + fixAllContext.CancellationToken); + + // Replace the node via the editor + syntaxEditor.ReplaceNode(structDeclaration, updatedStructDeclaration); + } + + return document.WithSyntaxRoot(syntaxEditor.GetChangedRoot()); + } + } +} diff --git a/src/ComputeSharp.D2D1.CodeFixers/ComputeSharp.D2D1.CodeFixers.csproj b/src/ComputeSharp.D2D1.CodeFixers/ComputeSharp.D2D1.CodeFixers.csproj index 41ca05c4..14fb87c2 100644 --- a/src/ComputeSharp.D2D1.CodeFixers/ComputeSharp.D2D1.CodeFixers.csproj +++ b/src/ComputeSharp.D2D1.CodeFixers/ComputeSharp.D2D1.CodeFixers.csproj @@ -10,4 +10,6 @@ + +