diff --git a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.HlslSource.cs b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.HlslSource.cs index fcf1994d..fb6abca8 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.HlslSource.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.HlslSource.cs @@ -12,7 +12,6 @@ using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors; -using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; namespace ComputeSharp.D2D1.SourceGenerators; @@ -44,8 +43,8 @@ partial class D2DPixelShaderDescriptorGenerator ImmutableArray inputSimpleIndices, ImmutableArray inputComplexIndices) { - // Properties are not supported - DetectAndReportInvalidPropertyDeclarations(diagnostics, structDeclarationSymbol); + // Detect any invalid properties + HlslDefinitionsSyntaxProcessor.DetectAndReportInvalidPropertyDeclarations(diagnostics, structDeclarationSymbol); // We need to sets to track all discovered custom types and static methods HashSet discoveredTypes = new(SymbolEqualityComparer.Default); @@ -67,8 +66,8 @@ partial class D2DPixelShaderDescriptorGenerator ImmutableArray<(string Name, string TypeDeclaration, string? Assignment)> staticFields = GetStaticFields(diagnostics, semanticModelProvider, structDeclaration, structDeclarationSymbol, discoveredTypes, constantDefinitions, out bool fieldsNeedD2D1RequiresScenePosition); // Process the discovered types and constants - ImmutableArray<(string Name, string Definition)> declaredTypes = GetDeclaredTypes(diagnostics, structDeclarationSymbol, discoveredTypes, instanceMethods); - ImmutableArray<(string Name, string Value)> definedConstants = GetDefinedConstants(constantDefinitions); + ImmutableArray<(string Name, string Definition)> declaredTypes = HlslDefinitionsSyntaxProcessor.GetDeclaredTypes(diagnostics, structDeclarationSymbol, discoveredTypes, instanceMethods); + ImmutableArray<(string Name, string Value)> definedConstants = HlslDefinitionsSyntaxProcessor.GetDefinedConstants(constantDefinitions); // Check whether the scene position is required bool requiresScenePosition = GetD2DRequiresScenePositionInfo(structDeclarationSymbol); @@ -358,132 +357,6 @@ partial class D2DPixelShaderDescriptorGenerator return (entryPoint!, methods.ToImmutable()); } - /// - /// Gets a sequence of discovered constants. - /// - /// The collection of discovered constant definitions. - /// A sequence of discovered constants to declare in the shader. - private static ImmutableArray<(string Name, string Value)> GetDefinedConstants(IReadOnlyDictionary constantDefinitions) - { - using ImmutableArrayBuilder<(string, string)> builder = new(); - - foreach (KeyValuePair constant in constantDefinitions) - { - string ownerTypeName = ((INamedTypeSymbol)constant.Key.ContainingSymbol).ToDisplayString().ToHlslIdentifierName(); - string constantName = $"__{ownerTypeName}__{constant.Key.Name}"; - - builder.Add((constantName, constant.Value)); - } - - return builder.ToImmutable(); - } - - /// - /// Gets the sequence of processed discovered custom types. - /// - /// 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( - ImmutableArrayBuilder diagnostics, - INamedTypeSymbol structDeclarationSymbol, - IEnumerable types, - IReadOnlyDictionary instanceMethods) - { - using ImmutableArrayBuilder<(string, string)> builder = new(); - - IReadOnlyCollection invalidTypes; - - // Process the discovered types - foreach (INamedTypeSymbol type in HlslKnownTypes.GetCustomTypes(types, out invalidTypes)) - { - string structType = type.GetFullyQualifiedMetadataName().ToHlslIdentifierName(); - StructDeclarationSyntax structDeclaration = StructDeclaration(structType); - - // Declare the fields of the current type - foreach (ISymbol memberSymbol in type.GetMembers()) - { - // Once again, skip constants and staticv fields - if (memberSymbol is not IFieldSymbol { IsConst: false, IsStatic: false } fieldSymbol) - { - continue; - } - - // Try to get the actual field name - if (!ConstantBufferSyntaxProcessor.TryGetFieldAccessorName(fieldSymbol, out string? fieldName, out _)) - { - continue; - } - - INamedTypeSymbol fieldType = (INamedTypeSymbol)fieldSymbol.Type; - - // Convert the name to the fully qualified HLSL version - if (!HlslKnownTypes.TryGetMappedName(fieldType.GetFullyQualifiedMetadataName(), out string? mappedType)) - { - mappedType = fieldType.GetFullyQualifiedMetadataName().ToHlslIdentifierName(); - } - - // Get the field name as a valid HLSL identifier - if (!HlslKnownKeywords.TryGetMappedName(fieldName, out string? mappedName)) - { - mappedName = fieldName; - } - - structDeclaration = structDeclaration.AddMembers( - FieldDeclaration(VariableDeclaration( - IdentifierName(mappedType!)).AddVariables( - VariableDeclarator(Identifier(mappedName!))))); - } - - // Declare the methods of the current type - foreach (KeyValuePair 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, - structDeclaration - .NormalizeWhitespace(eol: "\n") - .WithSemicolonToken(Token(SyntaxKind.SemicolonToken)) - .ToFullString())); - } - - // Process the invalid types - foreach (INamedTypeSymbol invalidType in invalidTypes) - { - diagnostics.Add(InvalidDiscoveredType, structDeclarationSymbol, structDeclarationSymbol, invalidType); - } - - return builder.ToImmutable(); - } - - /// - /// Finds and reports all invalid declared properties in a shader. - /// - /// The collection of produced instances. - /// The input instance to process. - private static void DetectAndReportInvalidPropertyDeclarations(ImmutableArrayBuilder diagnostics, INamedTypeSymbol structDeclarationSymbol) - { - foreach (ISymbol memberSymbol in structDeclarationSymbol.GetMembers()) - { - // Detect properties that are not explicit interface implementations - if (memberSymbol is IPropertySymbol { ExplicitInterfaceImplementations.IsEmpty: true }) - { - diagnostics.Add(InvalidPropertyDeclaration, memberSymbol, structDeclarationSymbol, memberSymbol); - } - - // Detect properties causing a field to be generated - if (memberSymbol is IFieldSymbol { AssociatedSymbol: IPropertySymbol associatedProperty }) - { - diagnostics.Add(InvalidPropertyDeclaration, associatedProperty, structDeclarationSymbol, associatedProperty); - } - } - } - /// /// Reports diagnostics for invalid uses of [D2DRequiresScenePosition] in a shader. /// diff --git a/src/ComputeSharp.SourceGeneration.Hlsl/ComputeSharp.SourceGeneration.Hlsl.projitems b/src/ComputeSharp.SourceGeneration.Hlsl/ComputeSharp.SourceGeneration.Hlsl.projitems index ed307b28..377f6561 100644 --- a/src/ComputeSharp.SourceGeneration.Hlsl/ComputeSharp.SourceGeneration.Hlsl.projitems +++ b/src/ComputeSharp.SourceGeneration.Hlsl/ComputeSharp.SourceGeneration.Hlsl.projitems @@ -29,6 +29,7 @@ + diff --git a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxProcessors/HlslDefinitionsSyntaxProcessor.cs b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxProcessors/HlslDefinitionsSyntaxProcessor.cs new file mode 100644 index 00000000..74bb3aa0 --- /dev/null +++ b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxProcessors/HlslDefinitionsSyntaxProcessor.cs @@ -0,0 +1,147 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using ComputeSharp.SourceGeneration.Extensions; +using ComputeSharp.SourceGeneration.Helpers; +using ComputeSharp.SourceGeneration.Mappings; +using ComputeSharp.SourceGeneration.Models; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors; +using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; + +namespace ComputeSharp.SourceGeneration.SyntaxProcessors; + +/// +/// A processor responsible for extracting definitions from shader types +/// +internal static class HlslDefinitionsSyntaxProcessor +{ + /// + /// Gets a sequence of discovered constants. + /// + /// The collection of discovered constant definitions. + /// A sequence of discovered constants to declare in the shader. + public static ImmutableArray<(string Name, string Value)> GetDefinedConstants(IReadOnlyDictionary constantDefinitions) + { + using ImmutableArrayBuilder<(string, string)> builder = new(); + + foreach (KeyValuePair constant in constantDefinitions) + { + string ownerTypeName = ((INamedTypeSymbol)constant.Key.ContainingSymbol).ToDisplayString().ToHlslIdentifierName(); + string constantName = $"__{ownerTypeName}__{constant.Key.Name}"; + + builder.Add((constantName, constant.Value)); + } + + return builder.ToImmutable(); + } + + /// + /// Gets the sequence of processed discovered custom types. + /// + /// 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. + public static ImmutableArray<(string Name, string Definition)> GetDeclaredTypes( + ImmutableArrayBuilder diagnostics, + INamedTypeSymbol structDeclarationSymbol, + IEnumerable types, + IReadOnlyDictionary instanceMethods) + { + using ImmutableArrayBuilder<(string, string)> builder = new(); + + IReadOnlyCollection invalidTypes; + + // Process the discovered types + foreach (INamedTypeSymbol type in HlslKnownTypes.GetCustomTypes(types, out invalidTypes)) + { + string structType = type.GetFullyQualifiedMetadataName().ToHlslIdentifierName(); + StructDeclarationSyntax structDeclaration = StructDeclaration(structType); + + // Declare the fields of the current type + foreach (ISymbol memberSymbol in type.GetMembers()) + { + // Once again, skip constants and static fields + if (memberSymbol is not IFieldSymbol { IsConst: false, IsStatic: false } fieldSymbol) + { + continue; + } + + // Try to get the actual field name + if (!ConstantBufferSyntaxProcessor.TryGetFieldAccessorName(fieldSymbol, out string? fieldName, out _)) + { + continue; + } + + INamedTypeSymbol fieldType = (INamedTypeSymbol)fieldSymbol.Type; + + // Convert the name to the fully qualified HLSL version + if (!HlslKnownTypes.TryGetMappedName(fieldType.GetFullyQualifiedMetadataName(), out string? mappedType)) + { + mappedType = fieldType.GetFullyQualifiedMetadataName().ToHlslIdentifierName(); + } + + // Get the field name as a valid HLSL identifier + if (!HlslKnownKeywords.TryGetMappedName(fieldName, out string? mappedName)) + { + mappedName = fieldName; + } + + structDeclaration = structDeclaration.AddMembers( + FieldDeclaration(VariableDeclaration( + IdentifierName(mappedType!)).AddVariables( + VariableDeclarator(Identifier(mappedName!))))); + } + + // Declare the methods of the current type + foreach (KeyValuePair 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, + structDeclaration + .NormalizeWhitespace(eol: "\n") + .WithSemicolonToken(Token(SyntaxKind.SemicolonToken)) + .ToFullString())); + } + + // Process the invalid types + foreach (INamedTypeSymbol invalidType in invalidTypes) + { + diagnostics.Add(InvalidDiscoveredType, structDeclarationSymbol, structDeclarationSymbol, invalidType); + } + + return builder.ToImmutable(); + } + + /// + /// Finds and reports all invalid declared properties in a shader. + /// + /// The collection of produced instances. + /// The input instance to process. + public static void DetectAndReportInvalidPropertyDeclarations(ImmutableArrayBuilder diagnostics, INamedTypeSymbol structDeclarationSymbol) + { + foreach (ISymbol memberSymbol in structDeclarationSymbol.GetMembers()) + { + // Detect properties that are not explicit interface implementations + if (memberSymbol is IPropertySymbol { ExplicitInterfaceImplementations.IsEmpty: true }) + { + diagnostics.Add(InvalidPropertyDeclaration, memberSymbol, structDeclarationSymbol, memberSymbol); + } + + // Detect properties causing a field to be generated + if (memberSymbol is IFieldSymbol { AssociatedSymbol: IPropertySymbol associatedProperty }) + { + diagnostics.Add(InvalidPropertyDeclaration, associatedProperty, structDeclarationSymbol, associatedProperty); + } + } + } +} diff --git a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.HlslSource.cs b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.HlslSource.cs index e02941d4..8bf4add2 100644 --- a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.HlslSource.cs +++ b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.HlslSource.cs @@ -13,7 +13,6 @@ using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors; -using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; namespace ComputeSharp.SourceGenerators; @@ -50,8 +49,8 @@ partial class ComputeShaderDescriptorGenerator out bool isSamplerUsed, out string hlslSource) { - // Detect invalid properties - DetectAndReportInvalidPropertyDeclarations(diagnostics, structDeclarationSymbol); + // Detect any invalid properties + HlslDefinitionsSyntaxProcessor.DetectAndReportInvalidPropertyDeclarations(diagnostics, structDeclarationSymbol); // We need to sets to track all discovered custom types and static methods HashSet discoveredTypes = new(SymbolEqualityComparer.Default); @@ -77,8 +76,8 @@ partial class ComputeShaderDescriptorGenerator ImmutableArray<(string Name, string TypeDeclaration, string? Assignment)> staticFields = GetStaticFields(diagnostics, semanticModelProvider, structDeclaration, structDeclarationSymbol, discoveredTypes, constantDefinitions); // Process the discovered types and constants - ImmutableArray<(string Name, string Definition)> declaredTypes = GetDeclaredTypes(diagnostics, structDeclarationSymbol, discoveredTypes, instanceMethods); - ImmutableArray<(string Name, string Value)> definedConstants = GetDefinedConstants(constantDefinitions); + ImmutableArray<(string Name, string Definition)> declaredTypes = HlslDefinitionsSyntaxProcessor.GetDeclaredTypes(diagnostics, structDeclarationSymbol, discoveredTypes, instanceMethods); + ImmutableArray<(string Name, string Value)> definedConstants = HlslDefinitionsSyntaxProcessor.GetDefinedConstants(constantDefinitions); // Check whether an implicit texture is used in the shader isImplicitTextureUsed = implicitTextureType is not null; @@ -420,125 +419,6 @@ partial class ComputeShaderDescriptorGenerator return (entryPoint!, methods.ToImmutable(), isSamplerUsed); } - /// - /// Gets a sequence of discovered constants. - /// - /// The collection of discovered constant definitions. - /// A sequence of discovered constants to declare in the shader. - private static ImmutableArray<(string Name, string Value)> GetDefinedConstants(IReadOnlyDictionary constantDefinitions) - { - using ImmutableArrayBuilder<(string, string)> builder = new(); - - foreach (KeyValuePair constant in constantDefinitions) - { - string ownerTypeName = ((INamedTypeSymbol)constant.Key.ContainingSymbol).ToDisplayString().ToHlslIdentifierName(); - string constantName = $"__{ownerTypeName}__{constant.Key.Name}"; - - builder.Add((constantName, constant.Value)); - } - - return builder.ToImmutable(); - } - - /// - /// Gets the sequence of processed discovered custom types. - /// - /// 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. - private static ImmutableArray<(string Name, string Definition)> GetDeclaredTypes( - ImmutableArrayBuilder diagnostics, - ISymbol sourceSymbol, - IEnumerable types, - IReadOnlyDictionary instanceMethods) - { - using ImmutableArrayBuilder<(string, string)> builder = new(); - - IReadOnlyCollection invalidTypes; - - // Process the discovered types - foreach (INamedTypeSymbol type in HlslKnownTypes.GetCustomTypes(types, out invalidTypes)) - { - string structType = type.GetFullyQualifiedMetadataName().ToHlslIdentifierName(); - StructDeclarationSyntax structDeclaration = StructDeclaration(structType); - - // Declare the fields of the current type - foreach (IFieldSymbol field in type.GetMembers().OfType()) - { - if (field.IsStatic) - { - continue; - } - - INamedTypeSymbol fieldType = (INamedTypeSymbol)field.Type; - - // Convert the name to the fully qualified HLSL version - if (!HlslKnownTypes.TryGetMappedName(fieldType.GetFullyQualifiedMetadataName(), out string? mappedType)) - { - mappedType = fieldType.GetFullyQualifiedMetadataName().ToHlslIdentifierName(); - } - - // Get the field name as a valid HLSL identifier - if (!HlslKnownKeywords.TryGetMappedName(field.Name, out string? mappedName)) - { - mappedName = field.Name; - } - - structDeclaration = structDeclaration.AddMembers( - FieldDeclaration(VariableDeclaration( - IdentifierName(mappedType!)).AddVariables( - VariableDeclarator(Identifier(mappedName!))))); - } - - // Declare the methods of the current type - foreach (KeyValuePair 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, - structDeclaration - .NormalizeWhitespace(eol: "\n") - .WithSemicolonToken(Token(SyntaxKind.SemicolonToken)) - .ToFullString())); - } - - // Process the invalid types - foreach (INamedTypeSymbol invalidType in invalidTypes) - { - diagnostics.Add(InvalidDiscoveredType, sourceSymbol, sourceSymbol, invalidType); - } - - return builder.ToImmutable(); - } - - /// - /// Finds and reports all invalid declared properties in a shader. - /// - /// The collection of produced instances. - /// The input instance to process. - private static void DetectAndReportInvalidPropertyDeclarations(ImmutableArrayBuilder diagnostics, INamedTypeSymbol structDeclarationSymbol) - { - foreach (ISymbol memberSymbol in structDeclarationSymbol.GetMembers()) - { - // Detect properties that are not explicit interface implementations - if (memberSymbol is IPropertySymbol { ExplicitInterfaceImplementations.IsEmpty: true }) - { - diagnostics.Add(InvalidPropertyDeclaration, memberSymbol, structDeclarationSymbol, memberSymbol); - } - - // Detect properties causing a field to be generated - if (memberSymbol is IFieldSymbol { AssociatedSymbol: IPropertySymbol associatedProperty }) - { - diagnostics.Add(InvalidPropertyDeclaration, associatedProperty, structDeclarationSymbol, associatedProperty); - } - } - } - /// /// Produces the series of statements to build the current HLSL source. ///