using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis; namespace ComputeSharp.SourceGeneration.Extensions; /// /// Extension methods for the type. /// internal static class SymbolInfoExtensions { /// /// Tries to get the resolved attribute type symbol from a given value. /// /// The value to check. /// The resulting attribute type symbol, if correctly resolved. /// Whether is resolved to a symbol. /// /// This can be used to ensure users haven't eg. spelled names incorrecty or missed a using directive. Normally, code would just /// not compile if that was the case, but that doesn't apply for attributes using invalid targets. In that case, Roslyn will ignore /// any errors, meaning the generator has to validate the type symbols are correctly resolved on its own. /// public static bool TryGetAttributeTypeSymbol(this SymbolInfo symbolInfo, [NotNullWhen(true)] out INamedTypeSymbol? typeSymbol) { ISymbol? attributeSymbol = symbolInfo.Symbol; // If no symbol is selected and there is a single candidate symbol, use that if (attributeSymbol is null && symbolInfo.CandidateSymbols is [ISymbol candidateSymbol]) { attributeSymbol = candidateSymbol; } // Extract the symbol from either the current one or the containing type if ((attributeSymbol as INamedTypeSymbol ?? attributeSymbol?.ContainingType) is not INamedTypeSymbol resultingSymbol) { typeSymbol = null; return false; } typeSymbol = resultingSymbol; return true; } }