diff --git a/build/Directory.Build.props b/build/Directory.Build.props index ca6d499f..6545de68 100644 --- a/build/Directory.Build.props +++ b/build/Directory.Build.props @@ -186,11 +186,13 @@ false - true + true diff --git a/src/ComputeSharp.D2D1.UI.CodeFixers/ComputeSharp.D2D1.UI.CodeFixers.projitems b/src/ComputeSharp.D2D1.UI.CodeFixers/ComputeSharp.D2D1.UI.CodeFixers.projitems index ef3f3898..7f9be695 100644 --- a/src/ComputeSharp.D2D1.UI.CodeFixers/ComputeSharp.D2D1.UI.CodeFixers.projitems +++ b/src/ComputeSharp.D2D1.UI.CodeFixers/ComputeSharp.D2D1.UI.CodeFixers.projitems @@ -9,5 +9,6 @@ ComputeSharp.D2D1.UI.CodeFixers + - + \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.UI.CodeFixers/UseGeneratedCanvasEffectPropertyOnSemiAutoPropertyCodeFixer.cs b/src/ComputeSharp.D2D1.UI.CodeFixers/UseGeneratedCanvasEffectPropertyOnSemiAutoPropertyCodeFixer.cs new file mode 100644 index 00000000..2f95c021 --- /dev/null +++ b/src/ComputeSharp.D2D1.UI.CodeFixers/UseGeneratedCanvasEffectPropertyOnSemiAutoPropertyCodeFixer.cs @@ -0,0 +1,297 @@ +using System.Collections.Immutable; +using System.Composition; +using System.Diagnostics.CodeAnalysis; +using System.Threading.Tasks; +#if WINDOWS_UWP +using ComputeSharp.D2D1.Uwp.SourceGenerators.Constants; +#else +using ComputeSharp.D2D1.WinUI.SourceGenerators.Constants; +#endif +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 Microsoft.CodeAnalysis.Formatting; +using Microsoft.CodeAnalysis.Simplification; +using Microsoft.CodeAnalysis.Text; +#if WINDOWS_UWP +using static ComputeSharp.D2D1.Uwp.SourceGenerators.DiagnosticDescriptors; +#else +using static ComputeSharp.D2D1.WinUI.SourceGenerators.DiagnosticDescriptors; +#endif +using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; + +#if WINDOWS_UWP +namespace ComputeSharp.D2D1.Uwp.SourceGenerators; +#else +namespace ComputeSharp.D2D1.WinUI.SourceGenerators; +#endif + +/// +/// A code fixer that converts manual properties into partial properties using [GeneratedCanvasEffectProperty]. +/// +[ExportCodeFixProvider(LanguageNames.CSharp)] +[Shared] +public sealed class UseGeneratedCanvasEffectPropertyOnSemiAutoPropertyCodeFixer : CodeFixProvider +{ + /// + public override ImmutableArray FixableDiagnosticIds { get; } = [UseGeneratedCanvasEffectPropertyOnSemiAutoPropertyId]; + + /// + public override Microsoft.CodeAnalysis.CodeFixes.FixAllProvider? GetFixAllProvider() + { + return new FixAllProvider(); + } + + /// + public override async Task RegisterCodeFixesAsync(CodeFixContext context) + { + Diagnostic diagnostic = context.Diagnostics[0]; + TextSpan diagnosticSpan = context.Span; + + // This code fixer needs the semantic model, so check that first + if (!context.Document.SupportsSemanticModel) + { + return; + } + + // Retrieve the properties passed by the analyzer + if (!int.TryParse(diagnostic.Properties[UseGeneratedCanvasEffectPropertyOnSemiAutoPropertyAnalyzer.InvalidationModePropertyName], out int invalidationMode)) + { + return; + } + + SyntaxNode? root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); + + // Get the property declaration from the target diagnostic + if (root!.FindNode(diagnosticSpan) is PropertyDeclarationSyntax propertyDeclaration) + { + // Get the semantic model, as we need to resolve symbols + SemanticModel semanticModel = (await context.Document.GetSemanticModelAsync(context.CancellationToken).ConfigureAwait(false))!; + + // Register the code fix to update the semi-auto property to a partial property with [GeneratedCanvasEffectProperty] + context.RegisterCodeFix( + CodeAction.Create( + title: "Use [GeneratedCanvasEffectProperty]", + createChangedDocument: token => ConvertToPartialProperty( + context.Document, + semanticModel, + root, + propertyDeclaration, + invalidationMode), + equivalenceKey: "Use [GeneratedCanvasEffectProperty]"), + diagnostic); + } + } + + /// + /// Tries to get an for the [GeneratedCanvasEffectProperty] attribute. + /// + /// The original document being fixed. + /// The instance for the current compilation. + /// The resulting attribute list, if successfully retrieved. + /// Whether could be retrieved successfully. + private static bool TryGetGeneratedCanvasEffectPropertyAttributeList( + Document document, + SemanticModel semanticModel, + [NotNullWhen(true)] out AttributeListSyntax? generatedCanvasEffectPropertyAttributeList) + { + // Make sure we can resolve the '[GeneratedCanvasEffectProperty]' attribute + if (semanticModel.Compilation.GetTypeByMetadataName(WellKnownTypeNames.GeneratedCanvasEffectPropertyAttribute) is not INamedTypeSymbol attributeSymbol) + { + generatedCanvasEffectPropertyAttributeList = null; + + return false; + } + + SyntaxGenerator syntaxGenerator = SyntaxGenerator.GetGenerator(document); + + // Create the attribute syntax for the new '[GeneratedCanvasEffectProperty]' attribute here too + SyntaxNode attributeTypeSyntax = syntaxGenerator.TypeExpression(attributeSymbol).WithAdditionalAnnotations(Simplifier.AddImportsAnnotation); + + generatedCanvasEffectPropertyAttributeList = (AttributeListSyntax)syntaxGenerator.Attribute(attributeTypeSyntax); + + return true; + } + + /// + /// Applies the code fix to a target identifier and returns an updated document. + /// + /// The original document being fixed. + /// The instance for the current compilation. + /// The original tree root belonging to the current document. + /// The for the property being updated. + /// The invalidation mode to use. + /// An updated document with the applied code fix, and being replaced with a partial property. + private static async Task ConvertToPartialProperty( + Document document, + SemanticModel semanticModel, + SyntaxNode root, + PropertyDeclarationSyntax propertyDeclaration, + int invalidationMode) + { + await Task.CompletedTask; + + // If we can't generate the new attribute list, bail (this should never happen) + if (!TryGetGeneratedCanvasEffectPropertyAttributeList(document, semanticModel, out AttributeListSyntax? generatedCanvasEffectPropertyAttributeList)) + { + return document; + } + + // Create an editor to perform all mutations + SyntaxEditor syntaxEditor = new(root, document.Project.Solution.Workspace.Services); + + ConvertToPartialProperty( + propertyDeclaration, + generatedCanvasEffectPropertyAttributeList, + syntaxEditor, + invalidationMode); + + // Create the new document with the single change + return document.WithSyntaxRoot(syntaxEditor.GetChangedRoot()); + } + + /// + /// Applies the code fix to a target identifier and returns an updated document. + /// + /// The for the property being updated. + /// The with the attribute to add. + /// The instance to use. + /// The invalidation mode to use. + /// An updated document with the applied code fix, and being replaced with a partial property. + private static void ConvertToPartialProperty( + PropertyDeclarationSyntax propertyDeclaration, + AttributeListSyntax generatedCanvasEffectPropertyAttributeList, + SyntaxEditor syntaxEditor, + int invalidationMode) + { + // If the invalidation mode is not the default, set it in the attribute. + // We extract the generated attribute so we can add the new argument. + // It's important to reuse it, as it has the "add usings" annotation. + if (invalidationMode == 1) + { + generatedCanvasEffectPropertyAttributeList = + AttributeList(SingletonSeparatedList( + generatedCanvasEffectPropertyAttributeList.Attributes[0] + .AddArgumentListArguments( + AttributeArgument(ParseExpression($"global::{WellKnownTypeNames.CanvasEffectInvalidationType}.Update")) + .WithNameEquals(NameEquals(IdentifierName("InvalidationMode")))))); + } + + // Start setting up the updated attribute lists + SyntaxList attributeLists = propertyDeclaration.AttributeLists; + + if (attributeLists is [AttributeListSyntax firstAttributeListSyntax, ..]) + { + // Remove the trivia from the original first attribute + attributeLists = attributeLists.Replace( + nodeInList: firstAttributeListSyntax, + newNode: firstAttributeListSyntax.WithoutTrivia()); + + // If the property has at least an attribute list, move the trivia from it to the new attribute + generatedCanvasEffectPropertyAttributeList = generatedCanvasEffectPropertyAttributeList.WithTriviaFrom(firstAttributeListSyntax); + + // Insert the new attribute + attributeLists = attributeLists.Insert(0, generatedCanvasEffectPropertyAttributeList); + } + else + { + // Otherwise (there are no attribute lists), transfer the trivia to the new (only) attribute list + generatedCanvasEffectPropertyAttributeList = generatedCanvasEffectPropertyAttributeList.WithTriviaFrom(propertyDeclaration); + + // Save the new attribute list + attributeLists = attributeLists.Add(generatedCanvasEffectPropertyAttributeList); + } + + // Get a new property that is partial and with semicolon token accessors + PropertyDeclarationSyntax updatedPropertyDeclaration = + propertyDeclaration + .AddModifiers(Token(SyntaxKind.PartialKeyword)) + .WithoutLeadingTrivia() + .WithAttributeLists(attributeLists) + .WithAdditionalAnnotations(Formatter.Annotation) + .WithAccessorList(AccessorList(List( + [ + // Keep the accessors (so we can easily keep all trivia, modifiers, attributes, etc.) but make them semicolon only + propertyDeclaration.AccessorList!.Accessors[0] + .WithBody(null) + .WithExpressionBody(null) + .WithSemicolonToken(Token(SyntaxKind.SemicolonToken)) + .WithAdditionalAnnotations(Formatter.Annotation), + propertyDeclaration.AccessorList!.Accessors[1] + .WithBody(null) + .WithExpressionBody(null) + .WithSemicolonToken(Token(SyntaxKind.SemicolonToken)) + .WithTrailingTrivia(propertyDeclaration.AccessorList.Accessors[1].GetTrailingTrivia()) + .WithAdditionalAnnotations(Formatter.Annotation) + ])).WithTrailingTrivia(propertyDeclaration.AccessorList.GetTrailingTrivia())); + + syntaxEditor.ReplaceNode(propertyDeclaration, updatedPropertyDeclaration); + + // Find the parent type for the property + TypeDeclarationSyntax typeDeclaration = propertyDeclaration.FirstAncestorOrSelf()!; + + // Make sure it's partial (we create the updated node in the function to preserve the updated property declaration). + // If we created it separately and replaced it, the whole tree would also be replaced, and we'd lose the new property. + if (!typeDeclaration.Modifiers.Any(SyntaxKind.PartialKeyword)) + { + syntaxEditor.ReplaceNode(typeDeclaration, static (node, generator) => generator.WithModifiers(node, generator.GetModifiers(node).WithPartial(true))); + } + } + + /// + /// A custom with the logic from . + /// + private sealed class FixAllProvider : DocumentBasedFixAllProvider + { + /// + protected override async Task FixAllAsync(FixAllContext fixAllContext, Document document, ImmutableArray diagnostics) + { + // Get the semantic model, as we need to resolve symbols + if (await document.GetSemanticModelAsync(fixAllContext.CancellationToken).ConfigureAwait(false) is not SemanticModel semanticModel) + { + return document; + } + + // Get the document root (this should always succeed) + if (await document.GetSyntaxRootAsync(fixAllContext.CancellationToken).ConfigureAwait(false) is not SyntaxNode root) + { + return document; + } + + // If we can't generate the new attribute list, bail (this should never happen) + if (!TryGetGeneratedCanvasEffectPropertyAttributeList(document, semanticModel, out AttributeListSyntax? generatedCanvasEffectPropertyAttributeList)) + { + return document; + } + + // Create an editor to perform all mutations (across all edits in the file) + SyntaxEditor syntaxEditor = new(root, fixAllContext.Solution.Services); + + foreach (Diagnostic diagnostic in diagnostics) + { + // Get the current property declaration for the diagnostic + if (root.FindNode(diagnostic.Location.SourceSpan) is not PropertyDeclarationSyntax propertyDeclaration) + { + continue; + } + + // Retrieve the properties passed by the analyzer + if (!int.TryParse(diagnostic.Properties[UseGeneratedCanvasEffectPropertyOnSemiAutoPropertyAnalyzer.InvalidationModePropertyName], out int invalidationMode)) + { + continue; + } + + ConvertToPartialProperty( + propertyDeclaration, + generatedCanvasEffectPropertyAttributeList, + syntaxEditor, + invalidationMode); + } + + return document.WithSyntaxRoot(syntaxEditor.GetChangedRoot()); + } + } +} \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.UI.SourceGenerators/ComputeSharp.D2D1.UI.SourceGenerators.projitems b/src/ComputeSharp.D2D1.UI.SourceGenerators/ComputeSharp.D2D1.UI.SourceGenerators.projitems index 2c250331..02d5da44 100644 --- a/src/ComputeSharp.D2D1.UI.SourceGenerators/ComputeSharp.D2D1.UI.SourceGenerators.projitems +++ b/src/ComputeSharp.D2D1.UI.SourceGenerators/ComputeSharp.D2D1.UI.SourceGenerators.projitems @@ -16,7 +16,7 @@ - + diff --git a/src/ComputeSharp.D2D1.UI.SourceGenerators/Constants/WellKnownTypeNames.cs b/src/ComputeSharp.D2D1.UI.SourceGenerators/Constants/WellKnownTypeNames.cs index 4abbee9d..d79fbb56 100644 --- a/src/ComputeSharp.D2D1.UI.SourceGenerators/Constants/WellKnownTypeNames.cs +++ b/src/ComputeSharp.D2D1.UI.SourceGenerators/Constants/WellKnownTypeNames.cs @@ -10,7 +10,7 @@ namespace ComputeSharp.D2D1.WinUI.SourceGenerators.Constants; internal static class WellKnownTypeNames { /// - /// The fully qualified type name for the [GeneratedCanvasEffectPropertyAttribute] type. + /// The fully qualified type name for the [GeneratedCanvasEffectProperty] type. /// public const string GeneratedCanvasEffectPropertyAttribute = #if WINDOWS_UWP diff --git a/src/ComputeSharp.D2D1.UI.SourceGenerators/Diagnostics/Analyzers/UseCanvasEffectPropertyOnSemiAutoPropertyAnalyzer.cs b/src/ComputeSharp.D2D1.UI.SourceGenerators/Diagnostics/Analyzers/UseGeneratedCanvasEffectPropertyOnSemiAutoPropertyAnalyzer.cs similarity index 95% rename from src/ComputeSharp.D2D1.UI.SourceGenerators/Diagnostics/Analyzers/UseCanvasEffectPropertyOnSemiAutoPropertyAnalyzer.cs rename to src/ComputeSharp.D2D1.UI.SourceGenerators/Diagnostics/Analyzers/UseGeneratedCanvasEffectPropertyOnSemiAutoPropertyAnalyzer.cs index 749eef70..d2b360b8 100644 --- a/src/ComputeSharp.D2D1.UI.SourceGenerators/Diagnostics/Analyzers/UseCanvasEffectPropertyOnSemiAutoPropertyAnalyzer.cs +++ b/src/ComputeSharp.D2D1.UI.SourceGenerators/Diagnostics/Analyzers/UseGeneratedCanvasEffectPropertyOnSemiAutoPropertyAnalyzer.cs @@ -28,10 +28,10 @@ namespace ComputeSharp.D2D1.WinUI.SourceGenerators; #endif /// -/// A diagnostic analyzer that generates a suggestion whenever [CanvasEffectProperty] is used on a semi-auto property when a partial property could be used instead. +/// A diagnostic analyzer that generates a suggestion whenever [GeneratedCanvasEffectProperty] is used on a semi-auto property when a partial property could be used instead. /// [DiagnosticAnalyzer(LanguageNames.CSharp)] -public sealed class UseCanvasEffectPropertyOnSemiAutoPropertyAnalyzer : DiagnosticAnalyzer +public sealed class UseGeneratedCanvasEffectPropertyOnSemiAutoPropertyAnalyzer : DiagnosticAnalyzer { /// /// The number of pooled flags per stack (ie. how many properties we expect on average per type). @@ -55,7 +55,7 @@ public sealed class UseCanvasEffectPropertyOnSemiAutoPropertyAnalyzer : Diagnost public const string InvalidationModePropertyName = "InvalidationMode"; /// - public override ImmutableArray SupportedDiagnostics { get; } = [UseCanvasEffectPropertyOnSemiAutoProperty]; + public override ImmutableArray SupportedDiagnostics { get; } = [UseGeneratedCanvasEffectPropertyOnSemiAutoProperty]; /// public override void Initialize(AnalysisContext context) @@ -282,10 +282,14 @@ public sealed class UseCanvasEffectPropertyOnSemiAutoPropertyAnalyzer : Diagnost { if (pair.Value is [1, 1 or 2]) { + // Shift back the index to match the actual enum values, to simplify the code fixer. Here we're adding 1 to + // signal "the setter is valid", but we want to hide this implementation detail to downstream consumers. + int invalidationType = pair.Value[1] - 1; + context.ReportDiagnostic(Diagnostic.Create( - UseCanvasEffectPropertyOnSemiAutoProperty, + UseGeneratedCanvasEffectPropertyOnSemiAutoProperty, pair.Key.Locations.FirstOrDefault(), - ImmutableDictionary.Create().Add(InvalidationModePropertyName, pair.Value[1].ToString()), + ImmutableDictionary.Create().Add(InvalidationModePropertyName, invalidationType.ToString()), pair.Key)); } } diff --git a/src/ComputeSharp.D2D1.UI.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs b/src/ComputeSharp.D2D1.UI.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs index f087363c..8c062332 100644 --- a/src/ComputeSharp.D2D1.UI.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs +++ b/src/ComputeSharp.D2D1.UI.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs @@ -32,9 +32,9 @@ internal static class DiagnosticDescriptors #endif /// - /// The diagnostic id for . + /// The diagnostic id for . /// - public const string UseCanvasEffectPropertyOnSemiAutoPropertyId = $"{DiagnosticIdPrefix}0008"; + public const string UseGeneratedCanvasEffectPropertyOnSemiAutoPropertyId = $"{DiagnosticIdPrefix}0008"; /// /// Gets a for an invalid CanvasEffect property. @@ -149,18 +149,18 @@ internal static class DiagnosticDescriptors helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); /// - /// Gets a for when a semi-auto property can be converted to use [CanvasEffectProperty] instead. + /// Gets a for when a semi-auto property can be converted to use [GeneratedCanvasEffectProperty] instead. /// - /// Format: "The semi-auto property "{0}" can be converted to a partial property using [CanvasEffectProperty], which is recommended (doing so makes the code less verbose and results in more optimized code)". + /// Format: "The semi-auto property "{0}" can be converted to a partial property using [GeneratedCanvasEffectProperty], which is recommended (doing so makes the code less verbose and results in more optimized code)". /// /// - public static readonly DiagnosticDescriptor UseCanvasEffectPropertyOnSemiAutoProperty = new( - id: UseCanvasEffectPropertyOnSemiAutoPropertyId, - title: "Prefer using [CanvasEffectProperty] over semi-auto properties", - messageFormat: """The semi-auto property "{0}" can be converted to a partial property using [CanvasEffectProperty], which is recommended (doing so makes the code less verbose and results in more optimized code)""", + public static readonly DiagnosticDescriptor UseGeneratedCanvasEffectPropertyOnSemiAutoProperty = new( + id: UseGeneratedCanvasEffectPropertyOnSemiAutoPropertyId, + title: "Prefer using [GeneratedCanvasEffectProperty] over semi-auto properties", + messageFormat: """The semi-auto property "{0}" can be converted to a partial property using [GeneratedCanvasEffectProperty], which is recommended (doing so makes the code less verbose and results in more optimized code)""", category: DiagnosticCategory, defaultSeverity: DiagnosticSeverity.Info, isEnabledByDefault: true, - description: "Semi-auto properties should be converted to partial properties using [CanvasEffectProperty] when possible, which is recommended (doing so makes the code less verbose and results in more optimized code).", + description: "Semi-auto properties should be converted to partial properties using [GeneratedCanvasEffectProperty] when possible, which is recommended (doing so makes the code less verbose and results in more optimized code).", helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); } \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.Uwp.CodeFixers/ComputeSharp.D2D1.Uwp.CodeFixers.csproj b/src/ComputeSharp.D2D1.Uwp.CodeFixers/ComputeSharp.D2D1.Uwp.CodeFixers.csproj index e5e14eb2..725f187a 100644 --- a/src/ComputeSharp.D2D1.Uwp.CodeFixers/ComputeSharp.D2D1.Uwp.CodeFixers.csproj +++ b/src/ComputeSharp.D2D1.Uwp.CodeFixers/ComputeSharp.D2D1.Uwp.CodeFixers.csproj @@ -1,6 +1,7 @@ netstandard2.0 + $(DefineConstants);WINDOWS_UWP;D2D1_UI_SOURCE_GENERATOR diff --git a/src/ComputeSharp.D2D1.Uwp.SourceGenerators/ComputeSharp.D2D1.Uwp.SourceGenerators.csproj b/src/ComputeSharp.D2D1.Uwp.SourceGenerators/ComputeSharp.D2D1.Uwp.SourceGenerators.csproj index 2500e683..6407c6de 100644 --- a/src/ComputeSharp.D2D1.Uwp.SourceGenerators/ComputeSharp.D2D1.Uwp.SourceGenerators.csproj +++ b/src/ComputeSharp.D2D1.Uwp.SourceGenerators/ComputeSharp.D2D1.Uwp.SourceGenerators.csproj @@ -18,4 +18,9 @@ + + + + + diff --git a/src/ComputeSharp.D2D1.WinUI.CodeFixers/ComputeSharp.D2D1.WinUI.CodeFixers.csproj b/src/ComputeSharp.D2D1.WinUI.CodeFixers/ComputeSharp.D2D1.WinUI.CodeFixers.csproj index 632c8969..f305ea87 100644 --- a/src/ComputeSharp.D2D1.WinUI.CodeFixers/ComputeSharp.D2D1.WinUI.CodeFixers.csproj +++ b/src/ComputeSharp.D2D1.WinUI.CodeFixers/ComputeSharp.D2D1.WinUI.CodeFixers.csproj @@ -1,6 +1,7 @@ netstandard2.0 + $(DefineConstants);D2D1_UI_SOURCE_GENERATOR diff --git a/src/ComputeSharp.D2D1.WinUI.SourceGenerators/ComputeSharp.D2D1.WinUI.SourceGenerators.csproj b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/ComputeSharp.D2D1.WinUI.SourceGenerators.csproj index 1781f0d7..56822c94 100644 --- a/src/ComputeSharp.D2D1.WinUI.SourceGenerators/ComputeSharp.D2D1.WinUI.SourceGenerators.csproj +++ b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/ComputeSharp.D2D1.WinUI.SourceGenerators.csproj @@ -18,4 +18,9 @@ + + + + +