using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Text; using ComputeSharp.__Internals; using ComputeSharp.SourceGeneration.Extensions; using ComputeSharp.SourceGeneration.Helpers; using ComputeSharp.SourceGeneration.Models; using ComputeSharp.SourceGeneration.SyntaxRewriters; using ComputeSharp.SourceGenerators.Models; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using static ComputeSharp.SourceGenerators.Helpers.SyntaxFactoryHelper; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; #pragma warning disable CS0618 namespace ComputeSharp.SourceGenerators; /// /// A source generator for processing static methods referenced from compute shaders. /// [Generator(LanguageNames.CSharp)] public sealed partial class ShaderMethodSourceGenerator : IIncrementalGenerator { /// public void Initialize(IncrementalGeneratorInitializationContext context) { // Get all declared methods (including global function declarations) with the [ShaderMethod] attribute, and their info IncrementalValuesProvider methodInfoWithErrors = context.SyntaxProvider .ForAttributeWithMetadataName( typeof(ShaderMethodAttribute).FullName, static (node, _) => node is MethodDeclarationSyntax { AttributeLists.Count: > 0 } or LocalFunctionStatementSyntax { Parent: GlobalStatementSyntax { Parent: CompilationUnitSyntax } }, static (context, token) => { HlslMethodSourceInfo hlslMethodSourceInfo = Execute.GetData( context.SemanticModel.Compilation, (CSharpSyntaxNode)context.TargetNode, (IMethodSymbol)context.TargetSymbol, out ImmutableArray diagnostics); return new ShaderMethodInfo(hlslMethodSourceInfo, diagnostics); }); // Output the diagnostics, if any context.ReportDiagnostics( methodInfoWithErrors .Select(static (item, _) => item.Diagnostcs) .WithComparer(EqualityComparer.Default.ForImmutableArray())); // Generate the [ShaderMethodSource] attributes context.RegisterSourceOutput(methodInfoWithErrors, static (context, item) => { CompilationUnitSyntax compilationUnit = Execute.GetSyntax(item.HlslMethodSource); string filename = item.HlslMethodSource.MetadataName.Replace('`', '-').Replace('+', '.'); context.AddSource($"{filename}.g.cs", compilationUnit.GetText(Encoding.UTF8)); }); } /// /// A helper with all logic to generate the attribute declarations. /// private static class Execute { /// /// Processes a given target method. /// /// The input object currently in use. /// The or node to process. /// The instance for the current method. /// The resulting diagnostics from the processing operation. public static HlslMethodSourceInfo GetData( Compilation compilation, CSharpSyntaxNode methodDeclaration, IMethodSymbol methodSymbol, out ImmutableArray diagnostics) { using ImmutableArrayBuilder builder = ImmutableArrayBuilder.Rent(); // We need to sets to track all discovered custom types and static methods HashSet discoveredTypes = new(SymbolEqualityComparer.Default); Dictionary constantDefinitions = new(SymbolEqualityComparer.Default); Dictionary instanceMethods = new(SymbolEqualityComparer.Default); // Unused in this generator // Explore the syntax tree and extract the processed info SemanticModelProvider semanticModel = new(compilation); (string entryPoint, ImmutableArray<(string Signature, string Definition)> dependentMethods) = GetProcessedMethods(builder, methodDeclaration, semanticModel, discoveredTypes, constantDefinitions); ImmutableArray<(string Name, string Definition)> definedTypes = IShaderGenerator.BuildHlslSource.GetDeclaredTypes(builder, methodSymbol, discoveredTypes, instanceMethods); ImmutableArray<(string Name, string Value)> definedConstants = IShaderGenerator.BuildHlslSource.GetDefinedConstants(constantDefinitions); diagnostics = builder.ToImmutable(); return new( methodSymbol.GetFullMetadataName(includeParameters: true), entryPoint, definedTypes, definedConstants, dependentMethods); } /// /// Gets a sequence of processed methods from a target method declaration. /// /// The collection of produced instances. /// The or instance for the current method. /// The instance for the method to process. /// The collection of currently discovered types. /// The collection of discovered constant definitions. /// A sequence of processed methods in (main method and all captured methods). private static (string TargetMethod, ImmutableArray<(string Signature, string Definition)> DependentMethods) GetProcessedMethods( ImmutableArrayBuilder diagnostics, CSharpSyntaxNode methodDeclaration, SemanticModelProvider semanticModel, ICollection discoveredTypes, IDictionary constantDefinitions) { Dictionary staticMethods = new(SymbolEqualityComparer.Default); Dictionary instanceMethods = new(SymbolEqualityComparer.Default); ShaderSourceRewriter shaderSourceRewriter = new(semanticModel, discoveredTypes, staticMethods, instanceMethods, constantDefinitions, diagnostics); // Process the possible syntax nodes SyntaxNode visitedMethod = methodDeclaration switch { MethodDeclarationSyntax methodDeclarationSyntax => shaderSourceRewriter.Visit(methodDeclarationSyntax)!.WithIdentifier(Identifier(ShaderMethodSourceAttribute.InvokeMethodIdentifier)), LocalFunctionStatementSyntax functionStatementSyntax => shaderSourceRewriter.Visit(functionStatementSyntax)!.WithIdentifier(Identifier(ShaderMethodSourceAttribute.InvokeMethodIdentifier)), _ => throw new ArgumentException("Invalid method declaration syntax node type.") }; // Rewrite the method syntax tree string targetMethod = visitedMethod .WithoutTrivia() .NormalizeWhitespace(eol: "\n") .ToFullString(); using ImmutableArrayBuilder<(string, string)> methods = ImmutableArrayBuilder<(string, string)>.Rent(); // Emit the extracted local functions foreach (KeyValuePair localFunction in shaderSourceRewriter.LocalFunctions) { methods.Add(( localFunction.Value.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(), localFunction.Value.NormalizeWhitespace(eol: "\n").ToFullString())); } // Emit the discovered static methods foreach (MethodDeclarationSyntax staticMethod in staticMethods.Values) { methods.Add(( staticMethod.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(), staticMethod.NormalizeWhitespace(eol: "\n").ToFullString())); } return (targetMethod, methods.ToImmutable()); } /// /// Creates a instance with the processed attribute. /// /// The input instance to use. public static CompilationUnitSyntax GetSyntax(HlslMethodSourceInfo methodSourceInfo) { // This produces an assembly attribute declaration as follows: // // // // #pragma warning disable // [assembly: global::ComputeSharp.ShaderMethodSourceAttribute()] return CompilationUnit().AddAttributeLists( AttributeList(SingletonSeparatedList( Attribute(IdentifierName($"global::{typeof(ShaderMethodSourceAttribute).FullName}")).AddArgumentListArguments( AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(methodSourceInfo.MetadataName))), AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(methodSourceInfo.EntryPoint))), AttributeArgument(NestedArrayExpression(methodSourceInfo.DefinedTypes)), AttributeArgument(NestedArrayExpression(methodSourceInfo.DependentMethods)), AttributeArgument(NestedArrayExpression(methodSourceInfo.DefinedConstants))))) .WithOpenBracketToken(Token(TriviaList(Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), SyntaxKind.OpenBracketToken, TriviaList())) .WithOpenBracketToken(Token(TriviaList( Comment("// "), Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), SyntaxKind.OpenBracketToken, TriviaList())) .WithTarget(AttributeTargetSpecifier(Token(SyntaxKind.AssemblyKeyword)))) .NormalizeWhitespace(eol: "\n"); } } }