From 3392dbea4984a0cc395a510391ff41b4dd249669 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 29 Jan 2023 19:47:44 +0100 Subject: [PATCH 1/2] Remove code duplication in object creation rewriting --- .../SyntaxRewriters/HlslSourceRewriter.cs | 68 +++++++------------ 1 file changed, 26 insertions(+), 42 deletions(-) diff --git a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/HlslSourceRewriter.cs b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/HlslSourceRewriter.cs index 52452865..c70804ba 100644 --- a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/HlslSourceRewriter.cs +++ b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/HlslSourceRewriter.cs @@ -97,20 +97,40 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter { ObjectCreationExpressionSyntax updatedNode = (ObjectCreationExpressionSyntax)base.VisitObjectCreationExpression(node)!; + updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.Type, node, SemanticModel.For(node), DiscoveredTypes); + + return VisitObjectCreationExpression(node, updatedNode, updatedNode.Type); + } + + /// + public override SyntaxNode VisitImplicitObjectCreationExpression(ImplicitObjectCreationExpressionSyntax node) + { + ImplicitObjectCreationExpressionSyntax updatedNode = (ImplicitObjectCreationExpressionSyntax)base.VisitImplicitObjectCreationExpression(node)!; + TypeSyntax explicitType = IdentifierName("").ReplaceAndTrackType(node, SemanticModel.For(node), DiscoveredTypes); + + return VisitObjectCreationExpression(node, updatedNode, explicitType); + } + + /// + /// The original input instance. + /// The updated instance with tweaked syntax. + /// The for the object being created. + /// The rewritten for the object creation expression. + private SyntaxNode VisitObjectCreationExpression(BaseObjectCreationExpressionSyntax node, BaseObjectCreationExpressionSyntax updatedNode, TypeSyntax targetType) + { + // Emit a diagnostic if the object being created is not valid (ie. it's a managed type) if (SemanticModel.For(node).GetTypeInfo(node).Type is ITypeSymbol { IsUnmanagedType: false } type) { Diagnostics.Add(InvalidObjectCreationExpression, node, type); } - updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.Type, node, SemanticModel.For(node), DiscoveredTypes); - - // New objects use the default HLSL cast syntax, eg. (float4)0 + // Mutate the syntax like with explicit object creation expressions if (updatedNode.ArgumentList!.Arguments.Count == 0) { - return CastExpression(updatedNode.Type, LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0))); + return CastExpression(targetType, LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0))); } - // Add explicit casts for matrix constructors to help the overload resolution + // Add explicit casts like with the explicit object creation expressions above if (SemanticModel.For(node).GetTypeInfo(node).Type is ITypeSymbol matrixType && HlslKnownTypes.IsMatrixType(matrixType.GetFullyQualifiedMetadataName())) { @@ -125,43 +145,7 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter } } - return InvocationExpression(updatedNode.Type, updatedNode.ArgumentList!); - } - - /// - public override SyntaxNode VisitImplicitObjectCreationExpression(ImplicitObjectCreationExpressionSyntax node) - { - ImplicitObjectCreationExpressionSyntax updatedNode = (ImplicitObjectCreationExpressionSyntax)base.VisitImplicitObjectCreationExpression(node)!; - - if (SemanticModel.For(node).GetTypeInfo(node).Type is ITypeSymbol { IsUnmanagedType: false } type) - { - Diagnostics.Add(InvalidObjectCreationExpression, node, type); - } - - TypeSyntax explicitType = IdentifierName("").ReplaceAndTrackType(node, SemanticModel.For(node), DiscoveredTypes); - - // Mutate the syntax like with explicit object creation expressions - if (updatedNode.ArgumentList!.Arguments.Count == 0) - { - return CastExpression(explicitType, LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0))); - } - - // Add explicit casts like with the explicit object creation expressions above - if (SemanticModel.For(node).GetTypeInfo(node).Type is ITypeSymbol matrixType && - HlslKnownTypes.IsMatrixType(matrixType.GetFullyQualifiedMetadataName())) - { - for (int i = 0; i < node.ArgumentList.Arguments.Count; i++) - { - IArgumentOperation argumentOperation = (IArgumentOperation)SemanticModel.For(node).GetOperation(node.ArgumentList.Arguments[i])!; - INamedTypeSymbol elementType = (INamedTypeSymbol)argumentOperation.Parameter!.Type; - - updatedNode = updatedNode.ReplaceNode( - updatedNode.ArgumentList.Arguments[i].Expression, - CastExpression(IdentifierName(HlslKnownTypes.GetMappedName(elementType)), updatedNode.ArgumentList.Arguments[i].Expression)); - } - } - - return InvocationExpression(explicitType, updatedNode.ArgumentList); + return InvocationExpression(targetType, updatedNode.ArgumentList!); } /// From b49bb27f8e8fb475ca2c7c418b4a4c398429e477 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Fri, 24 Nov 2023 15:08:40 +0100 Subject: [PATCH 2/2] Move shared code to HlslDefinitionsSyntaxProcessor --- ...xelShaderDescriptorGenerator.HlslSource.cs | 135 +--------------- ...mputeSharp.SourceGeneration.Hlsl.projitems | 1 + .../HlslDefinitionsSyntaxProcessor.cs | 147 ++++++++++++++++++ ...uteShaderDescriptorGenerator.HlslSource.cs | 128 +-------------- 4 files changed, 156 insertions(+), 255 deletions(-) create mode 100644 src/ComputeSharp.SourceGeneration.Hlsl/SyntaxProcessors/HlslDefinitionsSyntaxProcessor.cs 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. ///