diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateBuildHlslSourceMethod.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateBuildHlslSourceMethod.cs index 0cef3803..4b3ee9b2 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateBuildHlslSourceMethod.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateBuildHlslSourceMethod.cs @@ -52,6 +52,7 @@ partial class ID2D1ShaderGenerator // We need to sets to track all discovered custom types and static methods HashSet discoveredTypes = new(SymbolEqualityComparer.Default); Dictionary staticMethods = new(SymbolEqualityComparer.Default); + Dictionary instanceMethods = new(SymbolEqualityComparer.Default); Dictionary constantDefinitions = new(SymbolEqualityComparer.Default); // Extract information on all captured fields @@ -64,11 +65,11 @@ partial class ID2D1ShaderGenerator // Explore the syntax tree and extract the processed info var semanticModelProvider = new SemanticModelProvider(compilation); - var (entryPoint, processedMethods) = GetProcessedMethods(diagnostics, structDeclaration, structDeclarationSymbol, semanticModelProvider, discoveredTypes, staticMethods, constantDefinitions, out bool methodsNeedD2D1RequiresScenePosition); + var (entryPoint, processedMethods) = GetProcessedMethods(diagnostics, structDeclaration, structDeclarationSymbol, semanticModelProvider, discoveredTypes, staticMethods, instanceMethods, constantDefinitions, out bool methodsNeedD2D1RequiresScenePosition); var staticFields = GetStaticFields(diagnostics, semanticModelProvider, structDeclaration, structDeclarationSymbol, discoveredTypes, constantDefinitions, out bool fieldsNeedD2D1RequiresScenePosition); // Process the discovered types and constants - var declaredTypes = GetDeclaredTypes(diagnostics, structDeclarationSymbol, discoveredTypes); + var declaredTypes = GetDeclaredTypes(diagnostics, structDeclarationSymbol, discoveredTypes, instanceMethods); var definedConstants = GetDefinedConstants(constantDefinitions); // Check whether the scene position is required @@ -258,6 +259,7 @@ partial class ID2D1ShaderGenerator /// The instance for the type to process. /// The collection of currently discovered types. /// The set of discovered and processed static methods. + /// The collection of discovered instance methods for custom struct types. /// The collection of discovered constant definitions. /// Whether or not the shader needs the [D2DRequiresScenePosition] annotation. /// A sequence of processed methods in , and the entry point. @@ -268,6 +270,7 @@ partial class ID2D1ShaderGenerator SemanticModelProvider semanticModel, ICollection discoveredTypes, IDictionary staticMethods, + IDictionary instanceMethods, IDictionary constantDefinitions, out bool needsD2D1RequiresScenePosition) { @@ -303,6 +306,7 @@ partial class ID2D1ShaderGenerator semanticModel, discoveredTypes, staticMethods, + instanceMethods, constantDefinitions, diagnostics, isShaderEntryPoint); @@ -374,11 +378,13 @@ partial class ID2D1ShaderGenerator /// The collection of produced instances. /// The type symbol for the shader type. /// The sequence of discovered custom types. + /// The collection of discovered instance methods for custom struct types. /// A sequence of custom type definitions to add to the shader source. private static ImmutableArray<(string Name, string Definition)> GetDeclaredTypes( ImmutableArray.Builder diagnostics, INamedTypeSymbol structDeclarationSymbol, - IEnumerable types) + IEnumerable types, + IReadOnlyDictionary instanceMethods) { ImmutableArray<(string, string)>.Builder builder = ImmutableArray.CreateBuilder<(string, string)>(); IReadOnlyCollection invalidTypes; @@ -414,6 +420,12 @@ partial class ID2D1ShaderGenerator VariableDeclarator(Identifier(mappedName!))))); } + // Declare the methods of the current type + foreach (var method in instanceMethods.Where(pair => SymbolEqualityComparer.Default.Equals(pair.Key.ContainingType, type))) + { + structDeclaration = structDeclaration.AddMembers(method.Value); + } + // Insert the trailing ; right after the closing bracket (after normalization) builder.Add(( structType, diff --git a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/ShaderSourceRewriter.cs b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/ShaderSourceRewriter.cs index c32f24ef..92aca433 100644 --- a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/ShaderSourceRewriter.cs +++ b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/ShaderSourceRewriter.cs @@ -31,6 +31,11 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter /// private readonly IDictionary staticMethods; + /// + /// The collection of discovered instance methods for custom struct types. + /// + private readonly IDictionary instanceMethods; + /// /// The collection of processed local functions in the current tree. /// @@ -63,6 +68,7 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter /// The instance for the target syntax tree. /// The set of discovered custom types. /// The set of discovered and processed static methods. + /// The collection of discovered instance methods for custom struct types. /// The collection of discovered constant definitions. /// The collection of produced instances. /// Whether or not the current instance is processing a shader entry point. @@ -71,6 +77,7 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter SemanticModelProvider semanticModel, ICollection discoveredTypes, IDictionary staticMethods, + IDictionary instanceMethods, IDictionary constantDefinitions, ImmutableArray.Builder diagnostics, bool isEntryPoint) @@ -78,6 +85,7 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter { this.shaderType = shaderType; this.staticMethods = staticMethods; + this.instanceMethods = instanceMethods; this.localFunctions = new(); this.implicitVariables = new(); this.isEntryPoint = isEntryPoint; @@ -89,17 +97,20 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter /// The instance for the target syntax tree. /// The set of discovered custom types. /// The set of discovered and processed static methods. + /// The collection of discovered instance methods for custom struct types. /// The collection of discovered constant definitions. /// The collection of produced instances. public ShaderSourceRewriter( SemanticModelProvider semanticModel, ICollection discoveredTypes, IDictionary staticMethods, + IDictionary instanceMethods, IDictionary constantDefinitions, ImmutableArray.Builder diagnostics) : base(semanticModel, discoveredTypes, constantDefinitions, diagnostics) { this.staticMethods = staticMethods; + this.instanceMethods = instanceMethods; this.implicitVariables = new(); this.localFunctions = new(); } @@ -459,7 +470,7 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter return updatedNode; } - ShaderSourceRewriter shaderSourceRewriter = new(SemanticModel, DiscoveredTypes, this.staticMethods, ConstantDefinitions, Diagnostics); + ShaderSourceRewriter shaderSourceRewriter = new(SemanticModel, DiscoveredTypes, this.staticMethods, this.instanceMethods, ConstantDefinitions, Diagnostics); MethodDeclarationSyntax processedMethod = shaderSourceRewriter.Visit(methodNode)!.NormalizeWhitespace(eol: "\n").WithoutTrivia(); this.staticMethods.Add(method, processedMethod.WithIdentifier(Identifier(methodIdentifier))); @@ -472,6 +483,7 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter { string metadataName = method.GetFullMetadataName(includeParameters: true); + // Check whether this is a Sample(...) call on a normalized texture type if (HlslKnownMethods.TryGetMappedResourceSamplerAccessType(metadataName, out string? mapping)) { // Get the syntax for the argument syntax transformation (adding the vector type constructor if needed) @@ -484,6 +496,32 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter // Rewrite texture resource sampled accesses, if needed return RewriteSampledTextureAccess(operation, updatedNode.Expression, coordinateSyntax); } + + // If the instance is a struct type that is available in source, rewrite the instance method + if (operation.TargetMethod.ContainingType is { TypeKind: TypeKind.Struct } structTypeSymbol) + { + DiscoveredTypes.Add(structTypeSymbol); + + var methodIdentifier = method.GetFullMetadataName().ToHlslIdentifierName(); + + // Same as for static methods, ensure the method is available in source, and process it if so + if (!this.instanceMethods.ContainsKey(method)) + { + if (method.DeclaringSyntaxReferences.FirstOrDefault()?.GetSyntax() is not MethodDeclarationSyntax methodNode) + { + Diagnostics.Add(InvalidMethodCall, node, method); + + return updatedNode; + } + + ShaderSourceRewriter shaderSourceRewriter = new(SemanticModel, DiscoveredTypes, this.instanceMethods, this.instanceMethods, ConstantDefinitions, Diagnostics); + MethodDeclarationSyntax processedMethod = shaderSourceRewriter.Visit(methodNode)!.NormalizeWhitespace(eol: "\n").WithoutTrivia(); + + this.instanceMethods.Add(method, processedMethod.WithIdentifier(Identifier(methodIdentifier))); + } + + return updatedNode.WithExpression(((MemberAccessExpressionSyntax)updatedNode.Expression).WithName(IdentifierName(methodIdentifier))); + } } } diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.cs index a4b31e9c..703cf89f 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.cs @@ -48,6 +48,7 @@ partial class IShaderGenerator // We need to sets to track all discovered custom types and static methods HashSet discoveredTypes = new(SymbolEqualityComparer.Default); Dictionary staticMethods = new(SymbolEqualityComparer.Default); + Dictionary instanceMethods = new(SymbolEqualityComparer.Default); Dictionary constantDefinitions = new(SymbolEqualityComparer.Default); // A given type can only represent a single shader type @@ -64,12 +65,12 @@ partial class IShaderGenerator var (resourceFields, valueFields) = GetInstanceFields(diagnostics, structDeclarationSymbol, discoveredTypes, isComputeShader); var delegateInstanceFields = GetDispatchId.GetInfo(structDeclarationSymbol); var sharedBuffers = GetSharedBuffers(diagnostics, structDeclarationSymbol, discoveredTypes); - var (entryPoint, processedMethods, isSamplerUsed) = GetProcessedMethods(diagnostics, structDeclaration, structDeclarationSymbol, semanticModelProvider, discoveredTypes, staticMethods, constantDefinitions, isComputeShader); + var (entryPoint, processedMethods, isSamplerUsed) = GetProcessedMethods(diagnostics, structDeclaration, structDeclarationSymbol, semanticModelProvider, discoveredTypes, staticMethods, instanceMethods, constantDefinitions, isComputeShader); var implicitSamplerField = isSamplerUsed ? ("SamplerState", "__sampler") : default((string, string)?); var staticFields = GetStaticFields(diagnostics, semanticModelProvider, structDeclaration, structDeclarationSymbol, discoveredTypes, constantDefinitions); // Process the discovered types and constants - var declaredTypes = GetDeclaredTypes(diagnostics, structDeclarationSymbol, discoveredTypes); + var declaredTypes = GetDeclaredTypes(diagnostics, structDeclarationSymbol, discoveredTypes, instanceMethods); var definedConstants = GetDefinedConstants(constantDefinitions); // Get the HLSL source data with the intermediate info @@ -315,6 +316,7 @@ partial class IShaderGenerator /// The instance for the type to process. /// The collection of currently discovered types. /// The set of discovered and processed static methods. + /// The collection of discovered instance methods for custom struct types. /// The collection of discovered constant definitions. /// Indicates whether or not represents a compute shader. /// A sequence of processed methods in , and the entry point. @@ -325,6 +327,7 @@ partial class IShaderGenerator SemanticModelProvider semanticModel, ICollection discoveredTypes, IDictionary staticMethods, + IDictionary instanceMethods, IDictionary constantDefinitions, bool isComputeShader) { @@ -365,6 +368,7 @@ partial class IShaderGenerator semanticModel, discoveredTypes, staticMethods, + instanceMethods, constantDefinitions, diagnostics, isShaderEntryPoint); @@ -436,14 +440,16 @@ partial class IShaderGenerator /// /// Gets the sequence of processed discovered custom types. /// - /// The sequence of discovered custom types. - /// The symbol for the current object being processed. /// The collection of produced instances. + /// The symbol for the current object being processed. + /// The sequence of discovered custom types. + /// The collection of discovered instance methods for custom struct types. /// A sequence of custom type definitions to add to the shader source. internal static ImmutableArray<(string Name, string Definition)> GetDeclaredTypes( ImmutableArray.Builder diagnostics, ISymbol sourceSymbol, - IEnumerable types) + IEnumerable types, + IReadOnlyDictionary instanceMethods) { ImmutableArray<(string, string)>.Builder builder = ImmutableArray.CreateBuilder<(string, string)>(); IReadOnlyCollection invalidTypes; @@ -479,6 +485,12 @@ partial class IShaderGenerator VariableDeclarator(Identifier(mappedName!))))); } + // Declare the methods of the current type + foreach (var method in instanceMethods.Where(pair => SymbolEqualityComparer.Default.Equals(pair.Key.ContainingType, type))) + { + structDeclaration = structDeclaration.AddMembers(method.Value); + } + // Insert the trailing ; right after the closing bracket (after normalization) builder.Add(( structType, diff --git a/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs b/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs index dd06162d..7985bf26 100644 --- a/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs @@ -84,11 +84,12 @@ public sealed partial class ShaderMethodSourceGenerator : IIncrementalGenerator // 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 var semanticModel = new SemanticModelProvider(compilation); var (entryPoint, dependentMethods) = GetProcessedMethods(builder, methodDeclaration, semanticModel, discoveredTypes, constantDefinitions); - var definedTypes = IShaderGenerator.BuildHlslSource.GetDeclaredTypes(builder, methodSymbol, discoveredTypes); + var definedTypes = IShaderGenerator.BuildHlslSource.GetDeclaredTypes(builder, methodSymbol, discoveredTypes, instanceMethods); var definedConstants = IShaderGenerator.BuildHlslSource.GetDefinedConstants(constantDefinitions); diagnostics = builder.ToImmutable(); @@ -118,8 +119,9 @@ public sealed partial class ShaderMethodSourceGenerator : IIncrementalGenerator IDictionary constantDefinitions) { Dictionary staticMethods = new(SymbolEqualityComparer.Default); + Dictionary instanceMethods = new(SymbolEqualityComparer.Default); - ShaderSourceRewriter shaderSourceRewriter = new(semanticModel, discoveredTypes, staticMethods, constantDefinitions, diagnostics); + ShaderSourceRewriter shaderSourceRewriter = new(semanticModel, discoveredTypes, staticMethods, instanceMethods, constantDefinitions, diagnostics); // Process the possible syntax nodes SyntaxNode visitedMethod = methodDeclaration switch