Skip to content

SyntaxExtensions

Extension methods for working with syntax nodes.

C# Signature
internal static class SyntaxExtensions

The following example finds a field declaration from a syntax node and resolves attribute symbols.

C#
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);
}
}
}

GetAttributeSymbol(AttributeSyntax, SemanticModel, CancellationToken)

Section titled “GetAttributeSymbol(AttributeSyntax, SemanticModel, CancellationToken)”

Gets the INamedTypeSymbol for the specified attribute syntax.

C# Signature
public static INamedTypeSymbol? GetAttributeSymbol(this AttributeSyntax syntax, SemanticModel semanticModel, CancellationToken cancellationToken = default);

The attribute syntax node.

The semantic model for the syntax tree.

A cancellation token.

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.

C# Signature
public static bool TryGetFieldDeclaration(this SyntaxNode node, out FieldDeclarationSyntax? fieldDeclaration, CancellationToken cancellationToken = default);

The syntax node to search from.

When this method returns, contains the field declaration if found; otherwise, null.

A cancellation token.

true if a field declaration was found; otherwise false.