From d1fabb6fedce058970a83b948f7f23b36749aa2a Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 7 Dec 2021 13:32:48 +0100 Subject: [PATCH] Switch [ShaderMethod] generator to incremental --- ...ator.CreateBuildHlslStringMethod.Syntax.cs | 8 +- ...erGenerator.CreateBuildHlslStringMethod.cs | 8 +- .../IShaderGenerator.cs | 14 +- .../Models/HlslMethodSourceInfo.cs | 73 +++++ ...lSourceInfo.cs => HlslShaderSourceInfo.cs} | 10 +- ...derMethodSourceGenerator.SyntaxReceiver.cs | 46 ---- .../ShaderMethodSourceGenerator.cs | 250 ++++++++++-------- 7 files changed, 236 insertions(+), 173 deletions(-) create mode 100644 src/ComputeSharp.SourceGenerators/Models/HlslMethodSourceInfo.cs rename src/ComputeSharp.SourceGenerators/Models/{HlslSourceInfo.cs => HlslShaderSourceInfo.cs} (93%) delete mode 100644 src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.SyntaxReceiver.cs diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.Syntax.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.Syntax.cs index 8ecc9d28..5b4e860a 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.Syntax.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.Syntax.cs @@ -20,9 +20,9 @@ public sealed partial class IShaderGenerator /// /// Creates a instance for the BuildHlslString method. /// - /// The input instance to use. + /// The input instance to use. /// The resulting instance for the BuildHlslString method. - public static MethodDeclarationSyntax GetSyntax(HlslSourceInfo hlslSourceInfo) + public static MethodDeclarationSyntax GetSyntax(HlslShaderSourceInfo hlslSourceInfo) { ImmutableArray bodyStatements = GenerateRenderMethodBody(hlslSourceInfo); @@ -49,9 +49,9 @@ public sealed partial class IShaderGenerator /// /// Produces the series of statements to build the current HLSL source. /// - /// The input instance to use. + /// The input instance to use. /// The series of statements to build the HLSL source to compile to execute the current shader. - private static ImmutableArray GenerateRenderMethodBody(HlslSourceInfo hlslSourceInfo) + private static ImmutableArray GenerateRenderMethodBody(HlslShaderSourceInfo hlslSourceInfo) { ImmutableArray.Builder statements = ImmutableArray.CreateBuilder(); StringBuilder textBuilder = new(); diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs index 58b2c3fc..d329491e 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs @@ -36,7 +36,7 @@ public sealed partial class IShaderGenerator /// The for . /// The resulting diagnostics from the processing operation. /// The resulting info on the processed shader. - public static HlslSourceInfo GetInfo( + public static HlslShaderSourceInfo GetInfo( Compilation compilation, StructDeclarationSyntax structDeclaration, INamedTypeSymbol structDeclarationSymbol, @@ -508,7 +508,7 @@ public sealed partial class IShaderGenerator /// Whether the static sampler is used by the shader. /// The body of the entry point of the shader. /// The series of statements to build the HLSL source to compile to execute the current shader. - private static HlslSourceInfo GetHlslSourceInfo( + private static HlslShaderSourceInfo GetHlslSourceInfo( ImmutableArray<(string Name, string Value)> definedConstants, ImmutableArray<(string Name, string Definition)> declaredTypes, ImmutableArray<(string MetadataName, string Name, string HlslType)> resourceFields, @@ -731,9 +731,9 @@ public sealed partial class IShaderGenerator /// /// Produces the non dynamic HLSL source (concatenating all generated HLSL source chunks). /// - /// The input instance to use. + /// The input instance to use. /// The non dynamic HLSL source code. - public static string GetNonDynamicHlslSource(HlslSourceInfo hlslSourceInfo) + public static string GetNonDynamicHlslSource(HlslShaderSourceInfo hlslSourceInfo) { return hlslSourceInfo.HeaderAndThreadsX + "" + diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs index 3e887061..50af3d93 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs @@ -71,7 +71,7 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator // Get the dispatch data, HLSL source and embedded bytecode info. This info is computed on the // same step as parts are shared in following sub-branches in the incremental generator pipeline. - IncrementalValuesProvider<(Result Dispatch, Result Hlsl, Result ThreadIds)> shaderInfoWithErrors = + IncrementalValuesProvider<(Result Dispatch, Result Hlsl, Result ThreadIds)> shaderInfoWithErrors = shaderDeclarations .Combine(context.CompilationProvider) .Select(static (item, token) => @@ -93,7 +93,7 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator dispatchDataDiagnostics); // BuildHlslString() info - HlslSourceInfo hlslSourceInfo = BuildHlslString.GetInfo( + HlslShaderSourceInfo hlslSourceInfo = BuildHlslString.GetInfo( item.Right, item.Left.Syntax, item.Left.Symbol, @@ -107,7 +107,7 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator return ( dispatchDataInfo, - new Result(hlslSourceInfo, hlslSourceDiagnostics), + new Result(hlslSourceInfo, hlslSourceDiagnostics), new Result(threadIds, threadIdsDiagnostics)); }); @@ -117,10 +117,10 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator context.ReportDiagnostics(shaderInfoWithErrors.Select(static (item, token) => item.ThreadIds.Errors)); // Filter all items to enable caching at a coarse level, and remove diagnostics - IncrementalValuesProvider<(DispatchDataInfo Dispatch, HlslSourceInfo Hlsl, ThreadIdsInfo ThreadIds)> shaderInfo = + IncrementalValuesProvider<(DispatchDataInfo Dispatch, HlslShaderSourceInfo Hlsl, ThreadIdsInfo ThreadIds)> shaderInfo = shaderInfoWithErrors .Select(static (item, token) => (item.Dispatch.Value, item.Hlsl.Value, item.ThreadIds.Value)) - .WithComparers(DispatchDataInfo.Comparer.Default, HlslSourceInfo.Comparer.Default, ThreadIdsInfo.Comparer.Default); + .WithComparers(DispatchDataInfo.Comparer.Default, HlslShaderSourceInfo.Comparer.Default, ThreadIdsInfo.Comparer.Default); // Get a filtered sequence to enable caching IncrementalValuesProvider dispatchDataInfo = @@ -142,10 +142,10 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator }); // Get the filtered sequence to enable caching - IncrementalValuesProvider<(HierarchyInfo Hierarchy, HlslSourceInfo SourceInfo)> hlslSourceInfo = + IncrementalValuesProvider<(HierarchyInfo Hierarchy, HlslShaderSourceInfo SourceInfo)> hlslSourceInfo = shaderInfo .Select(static (item, token) => (item.Dispatch.Hierarchy, item.Hlsl)) - .WithComparers(HierarchyInfo.Comparer.Default, HlslSourceInfo.Comparer.Default); + .WithComparers(HierarchyInfo.Comparer.Default, HlslShaderSourceInfo.Comparer.Default); // Generate the BuildHlslString() methods context.RegisterSourceOutput(hlslSourceInfo.Combine(canUseSkipLocalsInit), static (context, item) => diff --git a/src/ComputeSharp.SourceGenerators/Models/HlslMethodSourceInfo.cs b/src/ComputeSharp.SourceGenerators/Models/HlslMethodSourceInfo.cs new file mode 100644 index 00000000..40788938 --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/Models/HlslMethodSourceInfo.cs @@ -0,0 +1,73 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using ComputeSharp.SourceGenerators.Extensions; + +namespace ComputeSharp.SourceGenerators.Models; + +/// +/// A model for extracted info on a processed HLSL method. +/// +/// The metadata name for the method. +/// The meethod entry point. +/// The discovered declared types. +/// The discovered defined constants. +/// The dependent captured methods. +internal sealed record HlslMethodSourceInfo( + string MetadataName, + string EntryPoint, + ImmutableArray<(string Name, string Definition)> DefinedTypes, + ImmutableArray<(string Name, string Value)> DefinedConstants, + ImmutableArray<(string Signature, string Definition)> DependentMethods) +{ + /// + /// An implementation for . + /// + public sealed class Comparer : IEqualityComparer + { + /// + /// The singleton instance. + /// + public static Comparer Default { get; } = new(); + + /// + public bool Equals(HlslMethodSourceInfo? x, HlslMethodSourceInfo? y) + { + if (x is null && y is null) + { + return true; + } + + if (x is null || y is null) + { + return false; + } + + if (ReferenceEquals(x, y)) + { + return true; + } + + return + x.MetadataName == y.MetadataName && + x.EntryPoint == y.EntryPoint && + x.DefinedTypes.SequenceEqual(y.DefinedTypes) && + x.DefinedConstants.SequenceEqual(y.DefinedConstants) && + x.DependentMethods.SequenceEqual(y.DependentMethods); + } + + /// + public int GetHashCode(HlslMethodSourceInfo obj) + { + HashCode hashCode = default; + + hashCode.Add(obj.MetadataName); + hashCode.Add(obj.EntryPoint); + hashCode.AddRange(obj.DefinedTypes); + hashCode.AddRange(obj.DefinedConstants); + hashCode.AddRange(obj.DependentMethods); + + return hashCode.ToHashCode(); + } + } +} diff --git a/src/ComputeSharp.SourceGenerators/Models/HlslSourceInfo.cs b/src/ComputeSharp.SourceGenerators/Models/HlslShaderSourceInfo.cs similarity index 93% rename from src/ComputeSharp.SourceGenerators/Models/HlslSourceInfo.cs rename to src/ComputeSharp.SourceGenerators/Models/HlslShaderSourceInfo.cs index 630884e2..82067efa 100644 --- a/src/ComputeSharp.SourceGenerators/Models/HlslSourceInfo.cs +++ b/src/ComputeSharp.SourceGenerators/Models/HlslShaderSourceInfo.cs @@ -22,7 +22,7 @@ namespace ComputeSharp.SourceGenerators.Models; /// The names of defined constants. /// The signatures for captured methods. /// The list of delegate fields. -internal sealed record HlslSourceInfo( +internal sealed record HlslShaderSourceInfo( string HeaderAndThreadsX, string ThreadsY, string ThreadsZ, @@ -39,9 +39,9 @@ internal sealed record HlslSourceInfo( ImmutableArray Delegates) { /// - /// An implementation for . + /// An implementation for . /// - public sealed class Comparer : IEqualityComparer + public sealed class Comparer : IEqualityComparer { /// /// The singleton instance. @@ -49,7 +49,7 @@ internal sealed record HlslSourceInfo( public static Comparer Default { get; } = new(); /// - public bool Equals(HlslSourceInfo? x, HlslSourceInfo? y) + public bool Equals(HlslShaderSourceInfo? x, HlslShaderSourceInfo? y) { if (x is null && y is null) { @@ -84,7 +84,7 @@ internal sealed record HlslSourceInfo( } /// - public int GetHashCode(HlslSourceInfo obj) + public int GetHashCode(HlslShaderSourceInfo obj) { HashCode hashCode = default; diff --git a/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.SyntaxReceiver.cs b/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.SyntaxReceiver.cs deleted file mode 100644 index 8349eb3f..00000000 --- a/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.SyntaxReceiver.cs +++ /dev/null @@ -1,46 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Syntax; - -namespace ComputeSharp.SourceGenerators; - -/// -public sealed partial class ShaderMethodSourceGenerator -{ - /// - /// An that selects candidate nodes to process. - /// - private sealed class SyntaxReceiver : ISyntaxContextReceiver - { - /// - /// The list of info gathered during exploration. - /// - private readonly List gatheredInfo = new(); - - /// - /// Gets the collection of gathered info to process. - /// - public IReadOnlyCollection GatheredInfo => this.gatheredInfo; - - /// - public void OnVisitSyntaxNode(GeneratorSyntaxContext context) - { - if (context.Node is MethodDeclarationSyntax { AttributeLists: { Count: > 0 } } methodDeclaration && - context.SemanticModel.GetDeclaredSymbol(methodDeclaration) is IMethodSymbol methodSymbol && - context.SemanticModel.Compilation.GetTypeByMetadataName(typeof(ShaderMethodAttribute).FullName) is INamedTypeSymbol attributeSymbol && - methodSymbol.GetAttributes().Any(a => SymbolEqualityComparer.Default.Equals(a.AttributeClass, attributeSymbol))) - { - this.gatheredInfo.Add(new Item(methodDeclaration, methodSymbol)); - } - } - - /// - /// A model for a group of item representing a discovered method to process. - /// - /// The instance for the target method declaration. - /// The instance for . - public sealed record Item(MethodDeclarationSyntax MethodDeclaration, IMethodSymbol MethodSymbol); - } -} diff --git a/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs b/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs index 4d569fa0..ad462f9a 100644 --- a/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs @@ -1,17 +1,18 @@ using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics.Contracts; +using System.Linq; using System.Text; using ComputeSharp.__Internals; using ComputeSharp.SourceGenerators.Diagnostics; using ComputeSharp.SourceGenerators.Extensions; using ComputeSharp.SourceGenerators.Helpers; +using ComputeSharp.SourceGenerators.Models; using ComputeSharp.SourceGenerators.SyntaxRewriters; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; -using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors; using static ComputeSharp.SourceGenerators.Helpers.SyntaxFactoryHelper; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; @@ -22,129 +23,164 @@ namespace ComputeSharp.SourceGenerators; /// /// A source generator for processing static methods referenced from compute shaders. /// -[Generator] -public sealed partial class ShaderMethodSourceGenerator : ISourceGenerator +[Generator(LanguageNames.CSharp)] +public sealed partial class ShaderMethodSourceGenerator : IIncrementalGenerator { /// - public void Initialize(GeneratorInitializationContext context) + public void Initialize(IncrementalGeneratorInitializationContext context) { - context.RegisterForSyntaxNotifications(static () => new SyntaxReceiver()); - } + // Get all declared methods with the [ShaderMethod] attribute + IncrementalValuesProvider<(MethodDeclarationSyntax Syntax, IMethodSymbol Symbol)> structDeclarations = + context.SyntaxProvider + .CreateSyntaxProvider( + static (node, token) => node is MethodDeclarationSyntax { AttributeLists.Count: > 0 } methodDeclaration, + static (context, token) => ( + Syntax: (MethodDeclarationSyntax)context.Node, + Symbol: (IMethodSymbol?)context.SemanticModel.GetDeclaredSymbol(context.Node, token))) + .Where(static item => item.Symbol is not null && + item.Symbol.GetAttributes().Any(static a => a.AttributeClass?.ToDisplayString() == typeof(ShaderMethodAttribute).FullName))!; - /// - public void Execute(GeneratorExecutionContext context) - { - // Get the syntax receiver with the candidate nodes - if (context.SyntaxContextReceiver is not SyntaxReceiver syntaxReceiver) - { - return; - } - - foreach (SyntaxReceiver.Item item in syntaxReceiver.GatheredInfo) - { - SemanticModelProvider semanticModel = new(context.Compilation); - - try + // Get the source info for each method + IncrementalValuesProvider> methodSourceInfoWithErrors = + structDeclarations + .Combine(context.CompilationProvider) + .Select(static (item, token) => { - OnExecute(context, item.MethodDeclaration, semanticModel, item.MethodSymbol); - } - catch - { - context.ReportDiagnostic(ShaderMethodSourceGeneratorError, item.MethodDeclaration, item.MethodSymbol); - } - } + HlslMethodSourceInfo sourceInfo = Execute.GetData( + item.Right, + item.Left.Syntax, + item.Left.Symbol, + out ImmutableArray diagnostics); + + return new Result(sourceInfo, diagnostics); + }); + + // Output the diagnostics + context.ReportDiagnostics(methodSourceInfoWithErrors.Select(static (item, token) => item.Errors)); + + // Get the filtered sequence to enable caching + IncrementalValuesProvider methodSourceInfo = + methodSourceInfoWithErrors + .Select(static (item, token) => item.Value) + .WithComparer(HlslMethodSourceInfo.Comparer.Default); + + // Generate the [ShaderMethodSource] attributes + context.RegisterSourceOutput(methodSourceInfo, static (context, item) => + { + CompilationUnitSyntax compilationUnit = Execute.GetSyntax(item); + string filename = item.MetadataName.Replace('`', '-').Replace('+', '.'); + + context.AddSource(filename, SourceText.From(compilationUnit.ToFullString(), Encoding.UTF8)); + }); } /// - /// Processes a given target method. + /// A helper with all logic to generate the attribute declarations. /// - /// The input instance to use. - /// The node to process. - /// The with metadata on the types being processed. - /// The for . - private static void OnExecute(GeneratorExecutionContext context, MethodDeclarationSyntax methodDeclaration, SemanticModelProvider semanticModel, IMethodSymbol methodDeclarationSymbol) + private static class Execute { - // We need to sets to track all discovered custom types and static methods - HashSet discoveredTypes = new(SymbolEqualityComparer.Default); - Dictionary constantDefinitions = new(SymbolEqualityComparer.Default); - - // Explore the syntax tree and extract the processed info - var (invokeMethod, processedMethods) = GetProcessedMethods(context, methodDeclaration, semanticModel, discoveredTypes, constantDefinitions); - var processedTypes = IShaderGenerator.BuildHlslString.GetDeclaredTypes(discoveredTypes); - var processedConstants = IShaderGenerator.BuildHlslString.GetDefinedConstants(constantDefinitions); - - // Create the compilation unit with the source attribute - var source = - CompilationUnit().AddAttributeLists( - AttributeList(SingletonSeparatedList( - Attribute(IdentifierName($"global::{typeof(ShaderMethodSourceAttribute).FullName}")).AddArgumentListArguments( - AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(methodDeclarationSymbol.GetFullMetadataName(true)))), - AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(invokeMethod))), - AttributeArgument(NestedArrayExpression(processedTypes)), - AttributeArgument(NestedArrayExpression(processedMethods)), - AttributeArgument(NestedArrayExpression(processedConstants))))) - .WithOpenBracketToken(Token(TriviaList(Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), SyntaxKind.OpenBracketToken, TriviaList())) - .WithTarget(AttributeTargetSpecifier(Token(SyntaxKind.AssemblyKeyword)))) - .NormalizeWhitespace(eol: "\n") - .ToFullString(); - - // Add the method source attribute - context.AddSource(methodDeclarationSymbol.GetGeneratedFileName(), SourceText.From(source, Encoding.UTF8)); - } - - /// - /// Gets a sequence of processed methods from a target method declaration. - /// - /// The current generator context in use. - /// The 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). - [Pure] - private static (string TargetMethod, IEnumerable<(string Signature, string Definition)> ProcessedMethods) GetProcessedMethods( - GeneratorExecutionContext context, - MethodDeclarationSyntax methodDeclaration, - SemanticModelProvider semanticModel, - ICollection discoveredTypes, - IDictionary constantDefinitions) - { - Dictionary staticMethods = new(SymbolEqualityComparer.Default); - ImmutableArray.Builder diagnostics = ImmutableArray.CreateBuilder(); - - ShaderSourceRewriter shaderSourceRewriter = new(semanticModel, discoveredTypes, staticMethods, constantDefinitions, diagnostics); - - foreach (Diagnostic diagnostic in diagnostics.ToImmutable()) + /// + /// Processes a given target method. + /// + /// The input object currently in use. + /// The node to process. + /// The instance for the current method. + /// The resulting diagnostics from the processing operation. + public static HlslMethodSourceInfo GetData( + Compilation compilation, + MethodDeclarationSyntax methodDeclaration, + IMethodSymbol methodSymbol, + out ImmutableArray diagnostics) { - context.ReportDiagnostic(diagnostic); + // We need to sets to track all discovered custom types and static methods + HashSet discoveredTypes = new(SymbolEqualityComparer.Default); + Dictionary constantDefinitions = new(SymbolEqualityComparer.Default); + + // Explore the syntax tree and extract the processed info + var semanticModel = new SemanticModelProvider(compilation); + var (entryPoint, dependentMethods) = GetProcessedMethods(methodDeclaration, semanticModel, discoveredTypes, constantDefinitions, out diagnostics); + var definedTypes = IShaderGenerator.BuildHlslString.GetDeclaredTypes(discoveredTypes); + var definedConstants = IShaderGenerator.BuildHlslString.GetDefinedConstants(constantDefinitions); + + return new( + methodSymbol.GetFullMetadataName(includeParameters: true), + entryPoint, + definedTypes, + definedConstants, + dependentMethods); } - // Rewrite the method syntax tree - var targetMethod = shaderSourceRewriter - .Visit(methodDeclaration)! - .WithIdentifier(Identifier(ShaderMethodSourceAttribute.InvokeMethodIdentifier)) - .WithoutTrivia() - .NormalizeWhitespace(eol: "\n") - .ToFullString(); - - List<(string, string)> processedMethods = new(shaderSourceRewriter.LocalFunctions.Count); - - // Emit the extracted local functions - foreach (var localFunction in shaderSourceRewriter.LocalFunctions) + /// + /// Gets a sequence of processed methods from a target method declaration. + /// + /// The instance for the current method. + /// The instance for the method to process. + /// The collection of currently discovered types. + /// The collection of discovered constant definitions. + /// The resulting diagnostics from the processing operation. + /// A sequence of processed methods in (main method and all captured methods). + [Pure] + private static (string TargetMethod, ImmutableArray<(string Signature, string Definition)> DependentMethods) GetProcessedMethods( + MethodDeclarationSyntax methodDeclaration, + SemanticModelProvider semanticModel, + ICollection discoveredTypes, + IDictionary constantDefinitions, + out ImmutableArray diagnostics) { - processedMethods.Add(( - localFunction.Value.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(), - localFunction.Value.NormalizeWhitespace(eol: "\n").ToFullString())); + Dictionary staticMethods = new(SymbolEqualityComparer.Default); + ImmutableArray.Builder builder = ImmutableArray.CreateBuilder(); + + ShaderSourceRewriter shaderSourceRewriter = new(semanticModel, discoveredTypes, staticMethods, constantDefinitions, builder); + + diagnostics = builder.ToImmutable(); + + // Rewrite the method syntax tree + var targetMethod = shaderSourceRewriter + .Visit(methodDeclaration)! + .WithIdentifier(Identifier(ShaderMethodSourceAttribute.InvokeMethodIdentifier)) + .WithoutTrivia() + .NormalizeWhitespace(eol: "\n") + .ToFullString(); + + ImmutableArray<(string, string)>.Builder methods = ImmutableArray.CreateBuilder<(string, string)>(shaderSourceRewriter.LocalFunctions.Count); + + // Emit the extracted local functions + foreach (var 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 (var staticMethod in staticMethods.Values) + { + methods.Add(( + staticMethod.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(), + staticMethod.NormalizeWhitespace(eol: "\n").ToFullString())); + } + + return (targetMethod, methods.ToImmutable()); } - // Emit the discovered static methods - foreach (var staticMethod in staticMethods.Values) + /// + /// Creates a instance with the processed attribute. + /// + /// The input instance to use. + public static CompilationUnitSyntax GetSyntax(HlslMethodSourceInfo methodSourceInfo) { - processedMethods.Add(( - staticMethod.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(), - staticMethod.NormalizeWhitespace(eol: "\n").ToFullString())); + 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())) + .WithTarget(AttributeTargetSpecifier(Token(SyntaxKind.AssemblyKeyword)))) + .NormalizeWhitespace(eol: "\n"); } - - return (targetMethod, processedMethods); } }