SyntaxExtensions
Extension methods for working with syntax nodes.
internal static class SyntaxExtensionsExamples
Section titled “Examples”The following example finds a field declaration from a syntax node and resolves attribute symbols.
using System;using System.Linq;using Hertzole.SourceGen;using Microsoft.CodeAnalysis;using Microsoft.CodeAnalysis.CSharp.Syntax;
public static class SyntaxInspector{ public static void Inspect(SyntaxNode node, SemanticModel semanticModel) { // Finds the field declaration that contains the node or one of its ancestors. if (node.TryGetFieldDeclaration(out FieldDeclarationSyntax? field)) { Console.WriteLine(field); }
foreach (AttributeSyntax attribute in node.DescendantNodes().OfType<AttributeSyntax>()) { // Resolves the attribute syntax to its type symbol. INamedTypeSymbol? attributeSymbol = attribute.GetAttributeSymbol(semanticModel); Console.WriteLine(attributeSymbol); } }}Methods
Section titled “Methods”GetAttributeSymbol(AttributeSyntax, SemanticModel, CancellationToken)
Section titled “GetAttributeSymbol(AttributeSyntax, SemanticModel, CancellationToken)”Gets the INamedTypeSymbol for the specified attribute syntax.
public static INamedTypeSymbol? GetAttributeSymbol(this AttributeSyntax syntax, SemanticModel semanticModel, CancellationToken cancellationToken = default);syntax
Section titled “syntax”The attribute syntax node.
semanticModel
Section titled “semanticModel”The semantic model for the syntax tree.
cancellationToken
Section titled “cancellationToken”A cancellation token.
Returns
Section titled “Returns”The INamedTypeSymbol for the attribute, or null if not found.
TryGetFieldDeclaration(SyntaxNode, out FieldDeclarationSyntax?, CancellationToken)
Section titled “TryGetFieldDeclaration(SyntaxNode, out FieldDeclarationSyntax?, CancellationToken)”Attempts to find a FieldDeclarationSyntax from the specified node or its ancestors.
public static bool TryGetFieldDeclaration(this SyntaxNode node, out FieldDeclarationSyntax? fieldDeclaration, CancellationToken cancellationToken = default);The syntax node to search from.
fieldDeclaration
Section titled “fieldDeclaration”When this method returns, contains the field declaration if found; otherwise, null.
cancellationToken
Section titled “cancellationToken”A cancellation token.
Returns
Section titled “Returns”true if a field declaration was found; otherwise false.