|
| 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.Collections.Immutable; |
| 6 | +using System.Composition; |
| 7 | +using System.Threading.Tasks; |
| 8 | +using CommunityToolkit.Mvvm.SourceGenerators; |
| 9 | +using Microsoft.CodeAnalysis; |
| 10 | +using Microsoft.CodeAnalysis.CodeActions; |
| 11 | +using Microsoft.CodeAnalysis.CodeFixes; |
| 12 | +using Microsoft.CodeAnalysis.CSharp.Syntax; |
| 13 | +using Microsoft.CodeAnalysis.Editing; |
| 14 | +using Microsoft.CodeAnalysis.Text; |
| 15 | +using static CommunityToolkit.Mvvm.SourceGenerators.Diagnostics.DiagnosticDescriptors; |
| 16 | +using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; |
| 17 | + |
| 18 | +namespace CommunityToolkit.Mvvm.CodeFixers; |
| 19 | + |
| 20 | +/// <summary> |
| 21 | +/// A code fixer that automatically updates types using <c>[ObservableObject]</c> or <c>[INotifyPropertyChanged]</c> |
| 22 | +/// that have no base type to inherit from <c>ObservableObject</c> instead. |
| 23 | +/// </summary> |
| 24 | +[ExportCodeFixProvider(LanguageNames.CSharp)] |
| 25 | +[Shared] |
| 26 | +public sealed class ClassUsingAttributeInsteadOfInheritanceCodeFixer : CodeFixProvider |
| 27 | +{ |
| 28 | + /// <inheritdoc/> |
| 29 | + public override ImmutableArray<string> FixableDiagnosticIds { get; } = ImmutableArray.Create( |
| 30 | + InheritFromObservableObjectInsteadOfUsingINotifyPropertyChangedAttributeId, |
| 31 | + InheritFromObservableObjectInsteadOfUsingObservableObjectAttributeId); |
| 32 | + |
| 33 | + /// <inheritdoc/> |
| 34 | + public override FixAllProvider? GetFixAllProvider() |
| 35 | + { |
| 36 | + return WellKnownFixAllProviders.BatchFixer; |
| 37 | + } |
| 38 | + |
| 39 | + /// <inheritdoc/> |
| 40 | + public override async Task RegisterCodeFixesAsync(CodeFixContext context) |
| 41 | + { |
| 42 | + Diagnostic diagnostic = context.Diagnostics[0]; |
| 43 | + TextSpan diagnosticSpan = diagnostic.Location.SourceSpan; |
| 44 | + |
| 45 | + // Retrieve the property passed by the analyzer |
| 46 | + if (diagnostic.Properties[ClassUsingAttributeInsteadOfInheritanceAnalyzer.TypeNameKey] is not string typeName || |
| 47 | + diagnostic.Properties[ClassUsingAttributeInsteadOfInheritanceAnalyzer.AttributeTypeNameKey] is not string attributeTypeName) |
| 48 | + { |
| 49 | + return; |
| 50 | + } |
| 51 | + |
| 52 | + SyntaxNode? root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); |
| 53 | + |
| 54 | + // Get the class declaration from the target diagnostic |
| 55 | + if (root!.FindNode(diagnosticSpan) is ClassDeclarationSyntax { Identifier.Text: string identifierName } classDeclaration && |
| 56 | + identifierName == typeName) |
| 57 | + { |
| 58 | + // Register the code fix to update the class declaration to inherit from ObservableObject instead |
| 59 | + context.RegisterCodeFix( |
| 60 | + CodeAction.Create( |
| 61 | + title: "Inherit from ObservableObject", |
| 62 | + createChangedDocument: token => UpdateReference(context.Document, root, classDeclaration, attributeTypeName), |
| 63 | + equivalenceKey: "Inherit from ObservableObject"), |
| 64 | + diagnostic); |
| 65 | + |
| 66 | + return; |
| 67 | + } |
| 68 | + } |
| 69 | + |
| 70 | + /// <summary> |
| 71 | + /// Applies the code fix to a target class declaration and returns an updated document. |
| 72 | + /// </summary> |
| 73 | + /// <param name="document">The original document being fixed.</param> |
| 74 | + /// <param name="root">The original tree root belonging to the current document.</param> |
| 75 | + /// <param name="classDeclaration">The <see cref="ClassDeclarationSyntax"/> to update.</param> |
| 76 | + /// <param name="attributeTypeName">The name of the attribute that should be removed.</param> |
| 77 | + /// <returns>An updated document with the applied code fix, and <paramref name="classDeclaration"/> inheriting from <c>ObservableObject</c>.</returns> |
| 78 | + private static Task<Document> UpdateReference(Document document, SyntaxNode root, ClassDeclarationSyntax classDeclaration, string attributeTypeName) |
| 79 | + { |
| 80 | + // Insert ObservableObject always in first position in the base list. The type might have |
| 81 | + // some interfaces in the base list, so we just copy them back after ObservableObject. |
| 82 | + SyntaxGenerator generator = SyntaxGenerator.GetGenerator(document); |
| 83 | + ClassDeclarationSyntax updatedClassDeclaration = (ClassDeclarationSyntax)generator.AddBaseType(classDeclaration, IdentifierName("ObservableObject")); |
| 84 | + |
| 85 | + // Find the attribute list and attribute to remove |
| 86 | + foreach (AttributeListSyntax attributeList in updatedClassDeclaration.AttributeLists) |
| 87 | + { |
| 88 | + foreach (AttributeSyntax attribute in attributeList.Attributes) |
| 89 | + { |
| 90 | + if (attribute.Name is IdentifierNameSyntax { Identifier.Text: string identifierName } && |
| 91 | + (identifierName == attributeTypeName || (identifierName + "Attribute") == attributeTypeName)) |
| 92 | + { |
| 93 | + // We found the attribute to remove and the list to update |
| 94 | + updatedClassDeclaration = (ClassDeclarationSyntax)generator.RemoveNode(updatedClassDeclaration, attribute); |
| 95 | + |
| 96 | + break; |
| 97 | + } |
| 98 | + } |
| 99 | + } |
| 100 | + |
| 101 | + return Task.FromResult(document.WithSyntaxRoot(root.ReplaceNode(classDeclaration, updatedClassDeclaration))); |
| 102 | + } |
| 103 | +} |
0 commit comments