|
| 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.Generic; |
| 6 | +using System.Diagnostics.Contracts; |
| 7 | +using System.Linq; |
| 8 | +using System.Text; |
| 9 | +using Microsoft.CodeAnalysis; |
| 10 | +using Microsoft.CodeAnalysis.CSharp; |
| 11 | +using Microsoft.CodeAnalysis.CSharp.Syntax; |
| 12 | +using Microsoft.CodeAnalysis.Text; |
| 13 | +using Microsoft.Toolkit.Mvvm.ComponentModel; |
| 14 | +using Microsoft.Toolkit.Mvvm.SourceGenerators.Extensions; |
| 15 | +using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; |
| 16 | +using static Microsoft.CodeAnalysis.SymbolDisplayTypeQualificationStyle; |
| 17 | + |
| 18 | +namespace Microsoft.Toolkit.Mvvm.SourceGenerators |
| 19 | +{ |
| 20 | + /// <summary> |
| 21 | + /// A source generator for the <see cref="ObservablePropertyAttribute"/> type. |
| 22 | + /// </summary> |
| 23 | + [Generator] |
| 24 | + public sealed partial class ObservablePropertyGenerator : ISourceGenerator |
| 25 | + { |
| 26 | + /// <inheritdoc/> |
| 27 | + public void Initialize(GeneratorInitializationContext context) |
| 28 | + { |
| 29 | + context.RegisterForSyntaxNotifications(static () => new SyntaxReceiver()); |
| 30 | + } |
| 31 | + |
| 32 | + /// <inheritdoc/> |
| 33 | + public void Execute(GeneratorExecutionContext context) |
| 34 | + { |
| 35 | + // Get the syntax receiver with the candidate nodes |
| 36 | + if (context.SyntaxContextReceiver is not SyntaxReceiver syntaxReceiver || |
| 37 | + syntaxReceiver.GatheredInfo.Count == 0) |
| 38 | + { |
| 39 | + return; |
| 40 | + } |
| 41 | + |
| 42 | + foreach (var items in syntaxReceiver.GatheredInfo.GroupBy<SyntaxReceiver.Item, INamedTypeSymbol>(static item => item.FieldSymbol.ContainingType, SymbolEqualityComparer.Default)) |
| 43 | + { |
| 44 | + if (items.Key.DeclaringSyntaxReferences.Length > 0 && |
| 45 | + items.Key.DeclaringSyntaxReferences.First().GetSyntax() is ClassDeclarationSyntax classDeclaration) |
| 46 | + { |
| 47 | + OnExecute(context, classDeclaration, items.Key, items); |
| 48 | + } |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + /// <summary> |
| 53 | + /// Processes a given target type. |
| 54 | + /// </summary> |
| 55 | + /// <param name="context">The input <see cref="GeneratorExecutionContext"/> instance to use.</param> |
| 56 | + /// <param name="classDeclaration">The <see cref="ClassDeclarationSyntax"/> node to process.</param> |
| 57 | + /// <param name="classDeclarationSymbol">The <see cref="INamedTypeSymbol"/> for <paramref name="classDeclaration"/>.</param> |
| 58 | + /// <param name="items">The sequence of fields to process.</param> |
| 59 | + private static void OnExecute( |
| 60 | + GeneratorExecutionContext context, |
| 61 | + ClassDeclarationSyntax classDeclaration, |
| 62 | + INamedTypeSymbol classDeclarationSymbol, |
| 63 | + IEnumerable<SyntaxReceiver.Item> items) |
| 64 | + { |
| 65 | + // Create the class declaration for the user type. This will produce a tree as follows: |
| 66 | + // |
| 67 | + // <MODIFIERS> <CLASS_NAME> |
| 68 | + // { |
| 69 | + // <MEMBERS> |
| 70 | + // } |
| 71 | + var classDeclarationSyntax = |
| 72 | + ClassDeclaration(classDeclarationSymbol.Name) |
| 73 | + .WithModifiers(classDeclaration.Modifiers) |
| 74 | + .AddMembers(items.Select(static item => CreatePropertyDeclaration(item.FieldSymbol)).ToArray()); |
| 75 | + |
| 76 | + TypeDeclarationSyntax typeDeclarationSyntax = classDeclarationSyntax; |
| 77 | + |
| 78 | + // Add all parent types in ascending order, if any |
| 79 | + foreach (var parentType in classDeclaration.Ancestors().OfType<TypeDeclarationSyntax>()) |
| 80 | + { |
| 81 | + typeDeclarationSyntax = parentType |
| 82 | + .WithMembers(SingletonList<MemberDeclarationSyntax>(typeDeclarationSyntax)) |
| 83 | + .WithConstraintClauses(List<TypeParameterConstraintClauseSyntax>()) |
| 84 | + .WithBaseList(null) |
| 85 | + .WithAttributeLists(List<AttributeListSyntax>()) |
| 86 | + .WithoutTrivia(); |
| 87 | + } |
| 88 | + |
| 89 | + // Create the compilation unit with the namespace and target member. |
| 90 | + // From this, we can finally generate the source code to output. |
| 91 | + var namespaceName = classDeclarationSymbol.ContainingNamespace.ToDisplayString(new(typeQualificationStyle: NameAndContainingTypesAndNamespaces)); |
| 92 | + |
| 93 | + // Create the final compilation unit to generate (with leading trivia) |
| 94 | + var source = |
| 95 | + CompilationUnit().AddUsings( |
| 96 | + UsingDirective(IdentifierName("System.Collections.Generic")).WithLeadingTrivia(TriviaList( |
| 97 | + Comment("// Licensed to the .NET Foundation under one or more agreements."), |
| 98 | + Comment("// The .NET Foundation licenses this file to you under the MIT license."), |
| 99 | + Comment("// See the LICENSE file in the project root for more information."), |
| 100 | + Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true)))), |
| 101 | + UsingDirective(IdentifierName("System.Diagnostics")), |
| 102 | + UsingDirective(IdentifierName("System.Diagnostics.CodeAnalysis"))).AddMembers( |
| 103 | + NamespaceDeclaration(IdentifierName(namespaceName)) |
| 104 | + .AddMembers(typeDeclarationSyntax)) |
| 105 | + .NormalizeWhitespace() |
| 106 | + .ToFullString(); |
| 107 | + |
| 108 | + // Add the partial type |
| 109 | + context.AddSource($"[{typeof(ObservablePropertyAttribute).Name}]_[{classDeclarationSymbol.GetFullMetadataNameForFileName()}].cs", SourceText.From(source, Encoding.UTF8)); |
| 110 | + } |
| 111 | + |
| 112 | + /// <summary> |
| 113 | + /// Creates a <see cref="PropertyDeclarationSyntax"/> instance for a specified field. |
| 114 | + /// </summary> |
| 115 | + /// <param name="fieldSymbol">The input <see cref="IFieldSymbol"/> instance to process.</param> |
| 116 | + /// <returns>A generated <see cref="PropertyDeclarationSyntax"/> instance for the input field.</returns> |
| 117 | + [Pure] |
| 118 | + private static PropertyDeclarationSyntax CreatePropertyDeclaration(IFieldSymbol fieldSymbol) |
| 119 | + { |
| 120 | + // Get the field type and the target property name |
| 121 | + string |
| 122 | + typeName = fieldSymbol.Type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat), |
| 123 | + propertyName = fieldSymbol.Name; |
| 124 | + |
| 125 | + if (propertyName.StartsWith("m_")) |
| 126 | + { |
| 127 | + propertyName = propertyName.Substring(2); |
| 128 | + } |
| 129 | + else if (propertyName.StartsWith("_")) |
| 130 | + { |
| 131 | + propertyName = propertyName.TrimStart('_'); |
| 132 | + } |
| 133 | + |
| 134 | + propertyName = $"{char.ToUpper(propertyName[0])}{propertyName.Substring(1)}"; |
| 135 | + |
| 136 | + BlockSyntax setter = Block(); |
| 137 | + |
| 138 | + // Add the OnPropertyChanging() call if necessary |
| 139 | + setter = setter.AddStatements(ExpressionStatement(InvocationExpression(IdentifierName("OnPropertyChanging")))); |
| 140 | + |
| 141 | + // Add the following statements: |
| 142 | + // |
| 143 | + // <FIELD_NAME> = value; |
| 144 | + // OnPropertyChanged(); |
| 145 | + setter = setter.AddStatements( |
| 146 | + ExpressionStatement( |
| 147 | + AssignmentExpression( |
| 148 | + SyntaxKind.SimpleAssignmentExpression, |
| 149 | + IdentifierName(fieldSymbol.Name), |
| 150 | + IdentifierName("value"))), |
| 151 | + ExpressionStatement(InvocationExpression(IdentifierName("OnPropertyChanged")))); |
| 152 | + |
| 153 | + // Construct the generated property as follows: |
| 154 | + // |
| 155 | + // [DebuggerNonUserCode] |
| 156 | + // [ExcludeFromCodeCoverage] |
| 157 | + // public <FIELD_TYPE> <PROPERTY_NAME> |
| 158 | + // { |
| 159 | + // get => <FIELD_NAME>; |
| 160 | + // set |
| 161 | + // { |
| 162 | + // if (!EqualityComparer<<FIELD_TYPE>>.Default.Equals(<FIELD_NAME>, value)) |
| 163 | + // { |
| 164 | + // OnPropertyChanging(); // Optional |
| 165 | + // <FIELD_NAME> = value; |
| 166 | + // OnPropertyChanged(); |
| 167 | + // } |
| 168 | + // } |
| 169 | + // } |
| 170 | + return |
| 171 | + PropertyDeclaration(IdentifierName(typeName), Identifier(propertyName)) |
| 172 | + .AddAttributeLists( |
| 173 | + AttributeList(SingletonSeparatedList(Attribute(IdentifierName("DebuggerNonUserCode")))), |
| 174 | + AttributeList(SingletonSeparatedList(Attribute(IdentifierName("ExcludeFromCodeCoverage"))))) |
| 175 | + .AddModifiers(Token(SyntaxKind.PublicKeyword)) |
| 176 | + .AddAccessorListAccessors( |
| 177 | + AccessorDeclaration(SyntaxKind.GetAccessorDeclaration) |
| 178 | + .WithExpressionBody(ArrowExpressionClause(IdentifierName(fieldSymbol.Name))) |
| 179 | + .WithSemicolonToken(Token(SyntaxKind.SemicolonToken)), |
| 180 | + AccessorDeclaration(SyntaxKind.SetAccessorDeclaration) |
| 181 | + .AddBodyStatements( |
| 182 | + IfStatement( |
| 183 | + PrefixUnaryExpression( |
| 184 | + SyntaxKind.LogicalNotExpression, |
| 185 | + InvocationExpression( |
| 186 | + MemberAccessExpression( |
| 187 | + SyntaxKind.SimpleMemberAccessExpression, |
| 188 | + MemberAccessExpression( |
| 189 | + SyntaxKind.SimpleMemberAccessExpression, |
| 190 | + GenericName(Identifier("EqualityComparer")) |
| 191 | + .AddTypeArgumentListArguments(IdentifierName(typeName)), |
| 192 | + IdentifierName("Default")), |
| 193 | + IdentifierName("Equals"))) |
| 194 | + .AddArgumentListArguments( |
| 195 | + Argument(IdentifierName(fieldSymbol.Name)), |
| 196 | + Argument(IdentifierName("value")))), |
| 197 | + setter))); |
| 198 | + } |
| 199 | + } |
| 200 | +} |
0 commit comments