|
| 1 | +// Licensed to the .NET Foundation under one or more agreements. |
| 2 | +// The .NET Foundation licenses this file to you under the MIT license. |
| 3 | +// See the LICENSE file in the project root for more information. |
| 4 | + |
| 5 | +using System; |
| 6 | +using System.Collections.Immutable; |
| 7 | +using System.Composition; |
| 8 | +using System.Linq; |
| 9 | +using System.Threading; |
| 10 | +using System.Threading.Tasks; |
| 11 | +using CommunityToolkit.Mvvm.SourceGenerators; |
| 12 | +using Microsoft.CodeAnalysis; |
| 13 | +using Microsoft.CodeAnalysis.CodeActions; |
| 14 | +using Microsoft.CodeAnalysis.CodeFixes; |
| 15 | +using Microsoft.CodeAnalysis.CSharp.Syntax; |
| 16 | +using Microsoft.CodeAnalysis.Text; |
| 17 | +using static CommunityToolkit.Mvvm.SourceGenerators.Diagnostics.DiagnosticDescriptors; |
| 18 | +using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; |
| 19 | + |
| 20 | +namespace CommunityToolkit.Mvvm.CodeFixers; |
| 21 | + |
| 22 | +/// <summary> |
| 23 | +/// A code fixer that automatically updates types using <c>[ObservableObject]</c> or <c>[INotifyPropertyChanged]</c> |
| 24 | +/// that have no base type to inherit from <c>ObservableObject</c> instead. |
| 25 | +/// </summary> |
| 26 | +[ExportCodeFixProvider(LanguageNames.CSharp)] |
| 27 | +[Shared] |
| 28 | +public sealed class ClassUsingAttributeInsteadOfInheritanceCodeFixer : CodeFixProvider |
| 29 | +{ |
| 30 | + /// <inheritdoc/> |
| 31 | + public override ImmutableArray<string> FixableDiagnosticIds { get; } = ImmutableArray.Create( |
| 32 | + InheritFromObservableObjectInsteadOfUsingINotifyPropertyChangedAttributeId, |
| 33 | + InheritFromObservableObjectInsteadOfUsingObservableObjectAttributeId); |
| 34 | + |
| 35 | + /// <inheritdoc/> |
| 36 | + public override FixAllProvider? GetFixAllProvider() |
| 37 | + { |
| 38 | + return WellKnownFixAllProviders.BatchFixer; |
| 39 | + } |
| 40 | + |
| 41 | + /// <inheritdoc/> |
| 42 | + public override async Task RegisterCodeFixesAsync(CodeFixContext context) |
| 43 | + { |
| 44 | + Diagnostic diagnostic = context.Diagnostics[0]; |
| 45 | + TextSpan diagnosticSpan = diagnostic.Location.SourceSpan; |
| 46 | + |
| 47 | + // Retrieve the property passed by the analyzer |
| 48 | + if (diagnostic.Properties[ClassUsingAttributeInsteadOfInheritanceAnalyzer.TypeNameKey] is not string typeName || |
| 49 | + diagnostic.Properties[ClassUsingAttributeInsteadOfInheritanceAnalyzer.AttributeTypeNameKey] is not string attributeTypeName) |
| 50 | + { |
| 51 | + return; |
| 52 | + } |
| 53 | + |
| 54 | + SyntaxNode? root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); |
| 55 | + |
| 56 | + foreach (SyntaxNode syntaxNode in root!.FindNode(diagnosticSpan).DescendantNodesAndSelf()) |
| 57 | + { |
| 58 | + // Find the first descendant node from the source of the diagnostic that is a class declaration with the target name |
| 59 | + if (syntaxNode is ClassDeclarationSyntax { Identifier.Text: string identifierName } classDeclaration && |
| 60 | + identifierName == typeName) |
| 61 | + { |
| 62 | + // Register the code fix to update the class declaration to inherit from ObservableObject instead |
| 63 | + context.RegisterCodeFix( |
| 64 | + CodeAction.Create( |
| 65 | + title: "Inherit from ObservableObject", |
| 66 | + createChangedDocument: token => UpdateReference(context.Document, classDeclaration, attributeTypeName, token), |
| 67 | + equivalenceKey: "Inherit from ObservableObject"), |
| 68 | + diagnostic); |
| 69 | + |
| 70 | + return; |
| 71 | + } |
| 72 | + } |
| 73 | + } |
| 74 | + |
| 75 | + /// <summary> |
| 76 | + /// Applies the code fix to a target class declaration and returns an updated document. |
| 77 | + /// </summary> |
| 78 | + /// <param name="document">The original document being fixed.</param> |
| 79 | + /// <param name="classDeclaration">The <see cref="ClassDeclarationSyntax"/> to update.</param> |
| 80 | + /// <param name="attributeTypeName">The name of the attribute that should be removed.</param> |
| 81 | + /// <param name="cancellationToken">The cancellation token for the operation.</param> |
| 82 | + /// <returns>An updated document with the applied code fix, and <paramref name="classDeclaration"/> inheriting from <c>ObservableObject</c>.</returns> |
| 83 | + private static async Task<Document> UpdateReference(Document document, ClassDeclarationSyntax classDeclaration, string attributeTypeName, CancellationToken cancellationToken) |
| 84 | + { |
| 85 | + // Insert ObservableObject always in first position in the base list. The type might have |
| 86 | + // some interfaces in the base list, so we just copy them back after ObservableObject. |
| 87 | + ClassDeclarationSyntax updatedClassDeclaration = |
| 88 | + classDeclaration.WithBaseList(BaseList(SingletonSeparatedList( |
| 89 | + (BaseTypeSyntax)SimpleBaseType(IdentifierName("ObservableObject")))) |
| 90 | + .AddTypes(classDeclaration.BaseList?.Types.ToArray() ?? Array.Empty<BaseTypeSyntax>())); |
| 91 | + |
| 92 | + AttributeListSyntax? targetAttributeList = null; |
| 93 | + AttributeSyntax? targetAttribute = null; |
| 94 | + |
| 95 | + // Find the attribute list and attribute to remove |
| 96 | + foreach (AttributeListSyntax attributeList in updatedClassDeclaration.AttributeLists) |
| 97 | + { |
| 98 | + foreach (AttributeSyntax attribute in attributeList.Attributes) |
| 99 | + { |
| 100 | + if (attribute.Name is IdentifierNameSyntax { Identifier.Text: string identifierName } && |
| 101 | + identifierName == attributeTypeName) |
| 102 | + { |
| 103 | + // We found the attribute to remove and the list to update |
| 104 | + targetAttributeList = attributeList; |
| 105 | + targetAttribute = attribute; |
| 106 | + |
| 107 | + break; |
| 108 | + } |
| 109 | + } |
| 110 | + } |
| 111 | + |
| 112 | + // If we found an attribute to remove, do that |
| 113 | + if (targetAttribute is not null) |
| 114 | + { |
| 115 | + // If the target list has more than one attribute, keep it and just remove the target one |
| 116 | + if (targetAttributeList!.Attributes.Count > 1) |
| 117 | + { |
| 118 | + updatedClassDeclaration = |
| 119 | + updatedClassDeclaration.ReplaceNode( |
| 120 | + targetAttributeList, |
| 121 | + targetAttributeList.RemoveNode(targetAttribute, SyntaxRemoveOptions.KeepNoTrivia)!); |
| 122 | + } |
| 123 | + else |
| 124 | + { |
| 125 | + // Otherwise, remove the entire attribute list |
| 126 | + updatedClassDeclaration = updatedClassDeclaration.RemoveNode(targetAttributeList, SyntaxRemoveOptions.KeepExteriorTrivia)!; |
| 127 | + } |
| 128 | + } |
| 129 | + |
| 130 | + SyntaxNode originalRoot = await classDeclaration.SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false); |
| 131 | + SyntaxTree updatedTree = originalRoot.ReplaceNode(classDeclaration, updatedClassDeclaration).SyntaxTree; |
| 132 | + |
| 133 | + return document.WithSyntaxRoot(await updatedTree.GetRootAsync(cancellationToken).ConfigureAwait(false)); |
| 134 | + } |
| 135 | +} |
0 commit comments