diff --git a/src/ComputeSharp.SourceGeneration/Extensions/ISymbolExtensions.cs b/src/ComputeSharp.SourceGeneration/Extensions/ISymbolExtensions.cs index a7c58ed1..612b5fb7 100644 --- a/src/ComputeSharp.SourceGeneration/Extensions/ISymbolExtensions.cs +++ b/src/ComputeSharp.SourceGeneration/Extensions/ISymbolExtensions.cs @@ -1,4 +1,5 @@ using System.Diagnostics.CodeAnalysis; +using System.Threading; using Microsoft.CodeAnalysis; namespace ComputeSharp.SourceGeneration.Extensions; @@ -117,4 +118,31 @@ internal static class ISymbolExtensions return false; } + + /// + /// Tries to get a syntax node with a given type from an input symbol. + /// + /// The type of syntax node to look for. + /// The input instance to get the syntax node for. + /// The used to cancel the operation, if needed. + /// The resulting syntax node, if found. + /// Whether or not a syntax node of type was retrieved successfully. + public static bool TryGetSyntaxNode(this ISymbol symbol, CancellationToken token, [NotNullWhen(true)] out T? syntaxNode) + where T : SyntaxNode + { + // If there are no syntax references, there is nothing to do + if (symbol.DeclaringSyntaxReferences is not [SyntaxReference syntaxReference, ..]) + { + syntaxNode = null; + + return false; + } + + // Get the target node, and check that it's of the desired type + T? candidateNode = syntaxReference.GetSyntax(token) as T; + + syntaxNode = candidateNode; + + return candidateNode is not null; + } } \ No newline at end of file