|
| 1 | +using System.Collections.Immutable; |
| 2 | +using System.Composition; |
| 3 | +using Microsoft.CodeAnalysis; |
| 4 | +using Microsoft.CodeAnalysis.CodeActions; |
| 5 | +using Microsoft.CodeAnalysis.CodeFixes; |
| 6 | +using Microsoft.CodeAnalysis.CSharp; |
| 7 | +using Microsoft.CodeAnalysis.CSharp.Syntax; |
| 8 | + |
| 9 | +namespace Architect.DomainModeling.CodeFixProviders; |
| 10 | + |
| 11 | +/// <summary> |
| 12 | +/// Provides a code fix for migrating from Entity<TId, TPrimitive> to EntityAttribute<TId, TIdUnderlying>. |
| 13 | +/// </summary> |
| 14 | +[Shared] |
| 15 | +[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(EntityBaseClassWithIdTypeGenerationCodeFixProvider))] |
| 16 | +public sealed class EntityBaseClassWithIdTypeGenerationCodeFixProvider : CodeFixProvider |
| 17 | +{ |
| 18 | + private static readonly ImmutableArray<string> FixableDiagnosticIdConstant = ["EntityBaseClassWithIdTypeGeneration"]; |
| 19 | + |
| 20 | + public sealed override ImmutableArray<string> FixableDiagnosticIds => FixableDiagnosticIdConstant; |
| 21 | + |
| 22 | + public sealed override FixAllProvider GetFixAllProvider() |
| 23 | + { |
| 24 | + return WellKnownFixAllProviders.BatchFixer; |
| 25 | + } |
| 26 | + |
| 27 | + public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) |
| 28 | + { |
| 29 | + var diagnostic = context.Diagnostics.First(diagnostic => diagnostic.Id == FixableDiagnosticIdConstant[0]); |
| 30 | + var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); |
| 31 | + if (root is null) |
| 32 | + return; |
| 33 | + |
| 34 | + if (root.FindNode(diagnostic.Location.SourceSpan) is not BaseTypeSyntax baseTypeSyntax) |
| 35 | + return; |
| 36 | + |
| 37 | + var tds = baseTypeSyntax.Ancestors().OfType<TypeDeclarationSyntax>().FirstOrDefault(); |
| 38 | + if (tds is null) |
| 39 | + return; |
| 40 | + |
| 41 | + // Do not offer the fix for abstract types |
| 42 | + if (tds.Modifiers.Any(SyntaxKind.AbstractKeyword)) |
| 43 | + return; |
| 44 | + |
| 45 | + // Do not offer the fix if the inheritance is indirect |
| 46 | + if (baseTypeSyntax.Type is not GenericNameSyntax { Arity: 2, TypeArgumentList.Arguments.Count: 2, } entityBaseTypeSyntax) |
| 47 | + return; |
| 48 | + var semanticModel = await context.Document.GetSemanticModelAsync(context.CancellationToken).ConfigureAwait(false); |
| 49 | + if (semanticModel.GetTypeInfo(baseTypeSyntax.Type, context.CancellationToken).Type is not |
| 50 | + INamedTypeSymbol { Arity: 2, Name: "Entity", ContainingNamespace: { Name: "DomainModeling", ContainingNamespace: { Name: "Architect", ContainingNamespace.IsGlobalNamespace: true, } } } entityBaseType) |
| 51 | + return; |
| 52 | + |
| 53 | + var action = CodeAction.Create( |
| 54 | + title: "Move type parameter for ID's underlying type into EntityAttribute", |
| 55 | + createChangedDocument: ct => ConvertToAttributeAsync(context.Document, root, tds, entityBaseTypeSyntax), |
| 56 | + equivalenceKey: "MoveIdTypeGenerationFromBaseToAttribute"); |
| 57 | + context.RegisterCodeFix(action, diagnostic); |
| 58 | + } |
| 59 | + |
| 60 | + private static Task<Document> ConvertToAttributeAsync( |
| 61 | + Document document, |
| 62 | + SyntaxNode root, |
| 63 | + TypeDeclarationSyntax tds, |
| 64 | + GenericNameSyntax baseTypeSyntax) |
| 65 | + { |
| 66 | + var idTypeToGenerate = baseTypeSyntax.TypeArgumentList.Arguments[0]; |
| 67 | + var idUnderlyingType = baseTypeSyntax.TypeArgumentList.Arguments[1]; |
| 68 | + |
| 69 | + // Create Entity<TId, TIdUnderlying> attribute |
| 70 | + var attributeArguments = SyntaxFactory.SeparatedList([idTypeToGenerate, idUnderlyingType,]); |
| 71 | + var entityAttribute = |
| 72 | + SyntaxFactory.Attribute( |
| 73 | + SyntaxFactory.GenericName(SyntaxFactory.Identifier("Entity")) |
| 74 | + .WithTypeArgumentList(SyntaxFactory.TypeArgumentList(attributeArguments))); |
| 75 | + |
| 76 | + // Check if Entity attribute already exists |
| 77 | + var existingEntityAttribute = tds.AttributeLists |
| 78 | + .SelectMany(list => list.Attributes) |
| 79 | + .FirstOrDefault(attribute => attribute.Name is IdentifierNameSyntax { Identifier.Text: "Entity" or "EntityAttribute" } or QualifiedNameSyntax { Right.Identifier.Text: "Entity" or "EntityAttribute" }); |
| 80 | + |
| 81 | + // Replace or add the Entity attribute |
| 82 | + TypeDeclarationSyntax newTds; |
| 83 | + if (existingEntityAttribute is { Parent: AttributeListSyntax oldAttributeList }) |
| 84 | + { |
| 85 | + var newAttributes = oldAttributeList.Attributes.Replace(existingEntityAttribute, entityAttribute); |
| 86 | + var newAttributeList = oldAttributeList |
| 87 | + .WithAttributes(newAttributes) |
| 88 | + .WithLeadingTrivia(oldAttributeList.GetLeadingTrivia()) |
| 89 | + .WithTrailingTrivia(oldAttributeList.GetTrailingTrivia()); |
| 90 | + newTds = tds.ReplaceNode(oldAttributeList, newAttributeList); |
| 91 | + } |
| 92 | + else |
| 93 | + { |
| 94 | + // This requires some gymnastics to keep the trivia intact |
| 95 | + |
| 96 | + // No existing attributes - move the type's leading trivia onto the new attribute |
| 97 | + if (tds.AttributeLists.Count == 0) |
| 98 | + { |
| 99 | + var attributeList = SyntaxFactory.AttributeList(SyntaxFactory.SingletonSeparatedList(entityAttribute)) |
| 100 | + .WithLeadingTrivia(tds.GetLeadingTrivia()); |
| 101 | + var newAttributeLists = tds.AttributeLists.Add(attributeList); |
| 102 | + newTds = tds |
| 103 | + .WithoutLeadingTrivia() |
| 104 | + .WithAttributeLists(newAttributeLists); |
| 105 | + } |
| 106 | + // Existing attributes - carefully preserve keep the leading trivia on the first attribute |
| 107 | + else |
| 108 | + { |
| 109 | + var attributeList = SyntaxFactory.AttributeList(SyntaxFactory.SingletonSeparatedList(entityAttribute)); |
| 110 | + var newAttributeLists = tds.AttributeLists |
| 111 | + .Replace(tds.AttributeLists[0], tds.AttributeLists[0].WithLeadingTrivia(tds.AttributeLists[0].GetLeadingTrivia())) |
| 112 | + .Add(attributeList); |
| 113 | + newTds = tds.WithAttributeLists(newAttributeLists); |
| 114 | + } |
| 115 | + } |
| 116 | + |
| 117 | + // Replace the base type |
| 118 | + if (newTds.BaseList is { Types: { Count: > 0 } baseTypes } && baseTypes[0].Type is GenericNameSyntax { Arity: 2, TypeArgumentList.Arguments: { Count: 2 } typeArgs, } genericBaseType) |
| 119 | + { |
| 120 | + var newTypeArgs = SyntaxFactory.TypeArgumentList( |
| 121 | + SyntaxFactory.SingletonSeparatedList(typeArgs[0])); |
| 122 | + var newGenericBaseType = genericBaseType.WithTypeArgumentList(newTypeArgs); |
| 123 | + var newBaseType = baseTypes[0] |
| 124 | + .WithType(newGenericBaseType) |
| 125 | + .WithLeadingTrivia(baseTypes[0].GetLeadingTrivia()) |
| 126 | + .WithTrailingTrivia(baseTypes[0].GetTrailingTrivia()); |
| 127 | + newTds = newTds.ReplaceNode(baseTypes[0], newBaseType); |
| 128 | + } |
| 129 | + |
| 130 | + var newRoot = root.ReplaceNode(tds, newTds); |
| 131 | + return Task.FromResult(document.WithSyntaxRoot(newRoot)); |
| 132 | + } |
| 133 | +} |
0 commit comments