// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace CommunityToolkit.Mvvm.SourceGenerators; /// public sealed partial class ObservablePropertyGenerator { /// /// An that selects candidate nodes to process. /// private sealed class SyntaxReceiver : ISyntaxContextReceiver { /// /// The list of info gathered during exploration. /// private readonly List gatheredInfo = new(); /// /// Gets the collection of gathered info to process. /// public IReadOnlyCollection GatheredInfo => this.gatheredInfo; /// public void OnVisitSyntaxNode(GeneratorSyntaxContext context) { if (context.Node is FieldDeclarationSyntax { AttributeLists: { Count: > 0 } } fieldDeclaration && context.SemanticModel.Compilation.GetTypeByMetadataName("CommunityToolkit.Mvvm.ComponentModel.ObservablePropertyAttribute") is INamedTypeSymbol attributeSymbol) { SyntaxTriviaList leadingTrivia = fieldDeclaration.GetLeadingTrivia(); foreach (VariableDeclaratorSyntax variableDeclarator in fieldDeclaration.Declaration.Variables) { if (context.SemanticModel.GetDeclaredSymbol(variableDeclarator) is IFieldSymbol fieldSymbol && fieldSymbol.GetAttributes().Any(a => SymbolEqualityComparer.Default.Equals(a.AttributeClass, attributeSymbol))) { this.gatheredInfo.Add(new Item(leadingTrivia, fieldSymbol)); } } } } /// /// A model for a group of item representing a discovered type to process. /// /// The leading trivia for the field declaration. /// The instance for the target field. public sealed record Item(SyntaxTriviaList LeadingTrivia, IFieldSymbol FieldSymbol); } }