From baffb8fccb2d9ae145ef52d2f9e43e54974a5991 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 9 Aug 2022 12:54:14 +0200 Subject: [PATCH] Move HlslSourceRewriter to shared file --- .../SyntaxRewriters/HlslSourceRewriter.cs | 356 +---------------- ...mputeSharp.SourceGeneration.Hlsl.projitems | 1 + .../HlslSourceRewriter.Diagnostics.cs | 3 +- .../SyntaxRewriters/HlslSourceRewriter.cs | 343 +++++++++++++++++ .../SyntaxRewriters/HlslSourceRewriter.cs | 361 ++---------------- 5 files changed, 387 insertions(+), 677 deletions(-) create mode 100644 src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/HlslSourceRewriter.cs diff --git a/src/ComputeSharp.D2D1.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.cs b/src/ComputeSharp.D2D1.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.cs index 01dbe00c..d33cd576 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.cs @@ -1,353 +1,37 @@ -using System; -using System.Collections.Generic; -using System.Collections.Immutable; -using System.Globalization; -using System.Linq; -using ComputeSharp.SourceGeneration.Extensions; -using ComputeSharp.SourceGeneration.Helpers; -using ComputeSharp.SourceGeneration.Mappings; +using ComputeSharp.SourceGeneration.Mappings; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Operations; -using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; namespace ComputeSharp.SourceGeneration.SyntaxRewriters; -/// -/// A base type that processes C# source to convert to HLSL compliant code. -/// This class contains only the shared logic for all derived HLSL source rewriters. -/// -internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter +/// +partial class HlslSourceRewriter { - /// - /// An array with the '.' and 'E' characters. - /// - private static readonly char[] FloatLiteralSpecialCharacters = { '.', 'E' }; - - /// - /// The instance with semantic info on the target syntax tree. - /// - protected readonly SemanticModelProvider SemanticModel; - - /// - /// The collection of discovered custom types. - /// - protected readonly ICollection DiscoveredTypes; - - /// - /// The collection of discovered constant definitions. - /// - protected readonly IDictionary ConstantDefinitions; - - /// - /// The collection of produced instances. - /// - protected readonly ImmutableArray.Builder Diagnostics; - - /// - /// Creates a new instance with the specified parameters. - /// - /// The instance for the target syntax tree. - /// The set of discovered custom types. - /// The collection of discovered constant definitions. - /// The collection of produced instances. - protected HlslSourceRewriter( - SemanticModelProvider semanticModel, - ICollection discoveredTypes, - IDictionary constantDefinitions, - ImmutableArray.Builder diagnostics) - { - SemanticModel = semanticModel; - DiscoveredTypes = discoveredTypes; - ConstantDefinitions = constantDefinitions; - Diagnostics = diagnostics; - } - /// - public override SyntaxNode VisitCastExpression(CastExpressionSyntax node) + private partial SyntaxNode RewriteSampledTextureAccess(IPropertyReferenceOperation operation, ElementAccessExpressionSyntax node, string? mappedType) { - var updatedNode = (CastExpressionSyntax)base.VisitCastExpression(node)!; - - return updatedNode.ReplaceAndTrackType(updatedNode.Type, node.Type, SemanticModel.For(node), DiscoveredTypes); - } - - /// - public override SyntaxNode? VisitVariableDeclaration(VariableDeclarationSyntax node) - { - var updatedNode = (VariableDeclarationSyntax)base.VisitVariableDeclaration(node)!; - - if (SemanticModel.For(node).GetTypeInfo(node.Type).Type is ITypeSymbol { IsUnmanagedType: false } type) + // Get the syntax for the argument syntax transformation as described above + ArgumentSyntax coordinateSyntax = mappedType switch { - Diagnostics.Add(InvalidObjectDeclaration, node, type); - } + not null => Argument(InvocationExpression(IdentifierName(mappedType!), ArgumentList(node.ArgumentList.Arguments))), + null => node.ArgumentList.Arguments[0] + }; - // If var is used, replace it with the explicit type - if (updatedNode.Type is IdentifierNameSyntax { IsVar: true }) - { - updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.Type, node.Type, SemanticModel.For(node), DiscoveredTypes); - } + string fieldName = (operation.Instance as IFieldReferenceOperation)?.Member.Name ?? ""; - return updatedNode; - } + _ = HlslKnownKeywords.TryGetMappedName(fieldName, out string? mapped); - /// - public override SyntaxNode VisitObjectCreationExpression(ObjectCreationExpressionSyntax node) - { - var updatedNode = (ObjectCreationExpressionSyntax)base.VisitObjectCreationExpression(node)!; - - 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 - if (updatedNode.ArgumentList!.Arguments.Count == 0) - { - return CastExpression(updatedNode.Type, LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0))); - } - - // Add explicit casts for matrix constructors to help the overload resolution - if (SemanticModel.For(node).GetTypeInfo(node).Type is ITypeSymbol matrixType && - HlslKnownTypes.IsMatrixType(matrixType.GetFullMetadataName())) - { - 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(updatedNode.Type, updatedNode.ArgumentList!); - } - - /// - public override SyntaxNode VisitImplicitObjectCreationExpression(ImplicitObjectCreationExpressionSyntax node) - { - var 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.GetFullMetadataName())) - { - 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); - } - - /// - public override SyntaxNode VisitDefaultExpression(DefaultExpressionSyntax node) - { - var updatedNode = (DefaultExpressionSyntax)base.VisitDefaultExpression(node)!; - - updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.Type, node.Type, SemanticModel.For(node), DiscoveredTypes); - - // A default expression becomes (T)0 in HLSL - return CastExpression(updatedNode.Type, LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0))); - } - - /// - public override SyntaxNode? VisitLiteralExpression(LiteralExpressionSyntax node) - { - var updatedNode = (LiteralExpressionSyntax)base.VisitLiteralExpression(node)!; - - if (updatedNode.IsKind(SyntaxKind.DefaultLiteralExpression)) - { - TypeSyntax type = node.TrackType(SemanticModel.For(node), DiscoveredTypes); - - // Same HLSL-style expression in the form (T)0 - return CastExpression(type, LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0))); - } - else if (updatedNode.IsKind(SyntaxKind.NumericLiteralExpression) && - SemanticModel.For(node).GetOperation(node) is ILiteralOperation operation && - operation.Type is INamedTypeSymbol type) - { - // If the expression is a literal floating point value, we need to ensure the proper suffixes are - // used in the HLSL representation. Floating point values accept either f or F, but they don't work - // when the literal doesn't contain a decimal point. Since 32 bit floating point values are the default - // in HLSL, we can remove the suffix entirely. As for 64 bit values, we simply use the 'L' suffix. - if (type.SpecialType == SpecialType.System_Single) - { - string literal = updatedNode.Token.ValueText; - - // If the numeric literal is neither a decimal nor an exponential, add the ".0" suffix - if (literal.IndexOfAny(FloatLiteralSpecialCharacters) == -1) - { - literal += ".0"; - } - - return updatedNode.WithToken(Literal(literal, 0f)); - } - else if (type.SpecialType == SpecialType.System_Double) - { - string literal = updatedNode.Token.ValueText; - - // If the numeric literal is neither a decimal nor an exponential, add the ".0L" suffix. - // This is necessary because otherwise integer literals would actually be of type long. - if (literal.IndexOfAny(FloatLiteralSpecialCharacters) == -1) - { - literal += ".0L"; - } - else - { - literal += "L"; - } - - return updatedNode.WithToken(Literal(literal, 0d)); - } - } - else if (updatedNode.IsKind(SyntaxKind.StringLiteralExpression)) - { - Diagnostics.Add(StringLiteralExpression, node); - } - - return updatedNode; - } - - /// - public override SyntaxNode? VisitElementAccessExpression(ElementAccessExpressionSyntax node) - { - var updatedNode = (ElementAccessExpressionSyntax)base.VisitElementAccessExpression(node)!; - - if (SemanticModel.For(node).GetOperation(node) is IPropertyReferenceOperation operation) - { - string propertyName = operation.Property.GetFullMetadataName(); - - // Rewrite texture resource indices taking individual indices a vector argument, as per HLSL spec. - // For instance: texture[ThreadIds.X, ThreadIds.Y] will be rewritten as texture[int2(ThreadIds.X, ThreadIds.Y)]. - if (HlslKnownProperties.TryGetMappedResourceIndexerTypeName(propertyName, out string? mapping)) - { - var index = InvocationExpression(IdentifierName(mapping!), ArgumentList(updatedNode.ArgumentList.Arguments)); - - return updatedNode.WithArgumentList(BracketedArgumentList(SingletonSeparatedList(Argument(index)))); - } - - // Rewrite texture resource sampled accesses, if needed - if (HlslKnownProperties.TryGetMappedResourceSamplerAccessType(propertyName, out mapping)) - { - // Get the syntax for the argument syntax transformation as described above - ArgumentSyntax coordinateSyntax = mapping switch - { - not null => Argument(InvocationExpression(IdentifierName(mapping!), ArgumentList(updatedNode.ArgumentList.Arguments))), - null => updatedNode.ArgumentList.Arguments[0] - }; - - string fieldName = (operation.Instance as IFieldReferenceOperation)?.Member.Name ?? ""; - - _ = HlslKnownKeywords.TryGetMappedName(fieldName, out string? mapped); - - // Transform an indexer syntax into a sampling call with the implicit static linear sampler. - // For instance: texture[uv] will be rewritten as texture.Sample(__sampler__texture, uv). - return - InvocationExpression( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - updatedNode.Expression, - IdentifierName("Sample"))) - .AddArgumentListArguments(Argument(IdentifierName($"__sampler__{mapped ?? fieldName}")), coordinateSyntax); - } - - // If the current property is a swizzled matrix indexer, ensure all the arguments are constants, and rewrite - // the property access to the corresponding HLSL syntax. For instance, m[M11, M12] will become m._m00_m01. - if (HlslKnownProperties.IsKnownMatrixIndexer(propertyName)) - { - bool isValid = true; - - // Validate the arguments - foreach (ArgumentSyntax argument in node.ArgumentList.Arguments) - { - if (SemanticModel.For(node).GetOperation(argument.Expression) is not IFieldReferenceOperation fieldReference || - !HlslKnownProperties.IsKnownMatrixIndex(fieldReference.Field.GetFullMetadataName())) - { - Diagnostics.Add(NonConstantMatrixSwizzledIndex, argument); - - isValid = false; - } - } - - if (isValid) - { - // Rewrite the indexer as a property access - string hlslPropertyName = string.Join("", - from argument in node.ArgumentList.Arguments - let fieldReference = (IFieldReferenceOperation)SemanticModel.For(node).GetOperation(argument.Expression)! - let fieldName = fieldReference.Field.Name - let row = (char)(fieldName[1] - 1) - let column = (char)(fieldName[2] - 1) - select $"_m{row}{column}"); - - return MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - updatedNode.Expression, - IdentifierName(hlslPropertyName)); - } - } - } - - return updatedNode; - } - - /// - public override SyntaxNode? VisitIdentifierName(IdentifierNameSyntax node) - { - var updatedNode = (IdentifierNameSyntax)base.VisitIdentifierName(node)!; - - if (SemanticModel.For(node).GetOperation(node) is IFieldReferenceOperation operation && - operation.Field.IsConst && - operation.Type!.TypeKind != TypeKind.Enum) - { - ConstantDefinitions[operation.Field] = ((IFormattable)operation.Field.ConstantValue!).ToString(null, CultureInfo.InvariantCulture); - - var ownerTypeName = ((INamedTypeSymbol)operation.Field.ContainingSymbol).ToDisplayString().ToHlslIdentifierName(); - var constantName = $"__{ownerTypeName}__{operation.Field.Name}"; - - return IdentifierName(constantName); - } - - return updatedNode; - } - - /// - public override SyntaxToken VisitToken(SyntaxToken token) - { - SyntaxToken updatedToken = base.VisitToken(token); - - // Replace all identifier tokens when needed, to avoid colliding with HLSL keywords - if (updatedToken.IsKind(SyntaxKind.IdentifierToken) && - HlslKnownKeywords.TryGetMappedName(updatedToken.Text, out string? mapped)) - { - return ParseToken(mapped!); - } - - return updatedToken.WithoutTrivia(); + // Transform an indexer syntax into a sampling call with the implicit static linear sampler. + // For instance: texture[uv] will be rewritten as texture.Sample(__sampler__texture, uv). + return + InvocationExpression( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + node.Expression, + IdentifierName("Sample"))) + .AddArgumentListArguments(Argument(IdentifierName($"__sampler__{mapped ?? fieldName}")), coordinateSyntax); } } diff --git a/src/ComputeSharp.SourceGeneration.Hlsl/ComputeSharp.SourceGeneration.Hlsl.projitems b/src/ComputeSharp.SourceGeneration.Hlsl/ComputeSharp.SourceGeneration.Hlsl.projitems index 02755448..21f36c97 100644 --- a/src/ComputeSharp.SourceGeneration.Hlsl/ComputeSharp.SourceGeneration.Hlsl.projitems +++ b/src/ComputeSharp.SourceGeneration.Hlsl/ComputeSharp.SourceGeneration.Hlsl.projitems @@ -18,6 +18,7 @@ + \ No newline at end of file diff --git a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/HlslSourceRewriter.Diagnostics.cs b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/HlslSourceRewriter.Diagnostics.cs index 8e562c08..e308f084 100644 --- a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/HlslSourceRewriter.Diagnostics.cs +++ b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/HlslSourceRewriter.Diagnostics.cs @@ -1,13 +1,12 @@ using ComputeSharp.SourceGeneration.Extensions; using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors; namespace ComputeSharp.SourceGeneration.SyntaxRewriters; /// -partial class HlslSourceRewriter : CSharpSyntaxRewriter +partial class HlslSourceRewriter { /// public override SyntaxNode? VisitAnonymousObjectCreationExpression(AnonymousObjectCreationExpressionSyntax node) diff --git a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/HlslSourceRewriter.cs b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/HlslSourceRewriter.cs new file mode 100644 index 00000000..abd9e52f --- /dev/null +++ b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/HlslSourceRewriter.cs @@ -0,0 +1,343 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Globalization; +using System.Linq; +using ComputeSharp.SourceGeneration.Extensions; +using ComputeSharp.SourceGeneration.Helpers; +using ComputeSharp.SourceGeneration.Mappings; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Operations; +using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors; +using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; + +namespace ComputeSharp.SourceGeneration.SyntaxRewriters; + +/// +/// A base type that processes C# source to convert to HLSL compliant code. +/// This class contains only the shared logic for all derived HLSL source rewriters. +/// +internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter +{ + /// + /// An array with the '.' and 'E' characters. + /// + private static readonly char[] FloatLiteralSpecialCharacters = { '.', 'E' }; + + /// + /// The instance with semantic info on the target syntax tree. + /// + protected readonly SemanticModelProvider SemanticModel; + + /// + /// The collection of discovered custom types. + /// + protected readonly ICollection DiscoveredTypes; + + /// + /// The collection of discovered constant definitions. + /// + protected readonly IDictionary ConstantDefinitions; + + /// + /// The collection of produced instances. + /// + protected readonly ImmutableArray.Builder Diagnostics; + + /// + /// Creates a new instance with the specified parameters. + /// + /// The instance for the target syntax tree. + /// The set of discovered custom types. + /// The collection of discovered constant definitions. + /// The collection of produced instances. + protected HlslSourceRewriter( + SemanticModelProvider semanticModel, + ICollection discoveredTypes, + IDictionary constantDefinitions, + ImmutableArray.Builder diagnostics) + { + SemanticModel = semanticModel; + DiscoveredTypes = discoveredTypes; + ConstantDefinitions = constantDefinitions; + Diagnostics = diagnostics; + } + + /// + public override SyntaxNode VisitCastExpression(CastExpressionSyntax node) + { + var updatedNode = (CastExpressionSyntax)base.VisitCastExpression(node)!; + + return updatedNode.ReplaceAndTrackType(updatedNode.Type, node.Type, SemanticModel.For(node), DiscoveredTypes); + } + + /// + public override SyntaxNode? VisitVariableDeclaration(VariableDeclarationSyntax node) + { + var updatedNode = (VariableDeclarationSyntax)base.VisitVariableDeclaration(node)!; + + if (SemanticModel.For(node).GetTypeInfo(node.Type).Type is ITypeSymbol { IsUnmanagedType: false } type) + { + Diagnostics.Add(InvalidObjectDeclaration, node, type); + } + + // If var is used, replace it with the explicit type + if (updatedNode.Type is IdentifierNameSyntax { IsVar: true }) + { + updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.Type, node.Type, SemanticModel.For(node), DiscoveredTypes); + } + + return updatedNode; + } + + /// + public override SyntaxNode VisitObjectCreationExpression(ObjectCreationExpressionSyntax node) + { + var updatedNode = (ObjectCreationExpressionSyntax)base.VisitObjectCreationExpression(node)!; + + 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 + if (updatedNode.ArgumentList!.Arguments.Count == 0) + { + return CastExpression(updatedNode.Type, LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0))); + } + + // Add explicit casts for matrix constructors to help the overload resolution + if (SemanticModel.For(node).GetTypeInfo(node).Type is ITypeSymbol matrixType && + HlslKnownTypes.IsMatrixType(matrixType.GetFullMetadataName())) + { + 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(updatedNode.Type, updatedNode.ArgumentList!); + } + + /// + public override SyntaxNode VisitImplicitObjectCreationExpression(ImplicitObjectCreationExpressionSyntax node) + { + var 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.GetFullMetadataName())) + { + 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); + } + + /// + public override SyntaxNode VisitDefaultExpression(DefaultExpressionSyntax node) + { + var updatedNode = (DefaultExpressionSyntax)base.VisitDefaultExpression(node)!; + + updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.Type, node.Type, SemanticModel.For(node), DiscoveredTypes); + + // A default expression becomes (T)0 in HLSL + return CastExpression(updatedNode.Type, LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0))); + } + + /// + public override SyntaxNode? VisitLiteralExpression(LiteralExpressionSyntax node) + { + var updatedNode = (LiteralExpressionSyntax)base.VisitLiteralExpression(node)!; + + if (updatedNode.IsKind(SyntaxKind.DefaultLiteralExpression)) + { + TypeSyntax type = node.TrackType(SemanticModel.For(node), DiscoveredTypes); + + // Same HLSL-style expression in the form (T)0 + return CastExpression(type, LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0))); + } + else if (updatedNode.IsKind(SyntaxKind.NumericLiteralExpression) && + SemanticModel.For(node).GetOperation(node) is ILiteralOperation operation && + operation.Type is INamedTypeSymbol type) + { + // If the expression is a literal floating point value, we need to ensure the proper suffixes are + // used in the HLSL representation. Floating point values accept either f or F, but they don't work + // when the literal doesn't contain a decimal point. Since 32 bit floating point values are the default + // in HLSL, we can remove the suffix entirely. As for 64 bit values, we simply use the 'L' suffix. + if (type.SpecialType == SpecialType.System_Single) + { + string literal = updatedNode.Token.ValueText; + + // If the numeric literal is neither a decimal nor an exponential, add the ".0" suffix + if (literal.IndexOfAny(FloatLiteralSpecialCharacters) == -1) + { + literal += ".0"; + } + + return updatedNode.WithToken(Literal(literal, 0f)); + } + else if (type.SpecialType == SpecialType.System_Double) + { + string literal = updatedNode.Token.ValueText; + + // If the numeric literal is neither a decimal nor an exponential, add the ".0L" suffix. + // This is necessary because otherwise integer literals would actually be of type long. + if (literal.IndexOfAny(FloatLiteralSpecialCharacters) == -1) + { + literal += ".0L"; + } + else + { + literal += "L"; + } + + return updatedNode.WithToken(Literal(literal, 0d)); + } + } + else if (updatedNode.IsKind(SyntaxKind.StringLiteralExpression)) + { + Diagnostics.Add(StringLiteralExpression, node); + } + + return updatedNode; + } + + /// + public override SyntaxNode? VisitElementAccessExpression(ElementAccessExpressionSyntax node) + { + var updatedNode = (ElementAccessExpressionSyntax)base.VisitElementAccessExpression(node)!; + + if (SemanticModel.For(node).GetOperation(node) is IPropertyReferenceOperation operation) + { + string propertyName = operation.Property.GetFullMetadataName(); + + // Rewrite texture resource indices taking individual indices a vector argument, as per HLSL spec. + // For instance: texture[ThreadIds.X, ThreadIds.Y] will be rewritten as texture[int2(ThreadIds.X, ThreadIds.Y)]. + if (HlslKnownProperties.TryGetMappedResourceIndexerTypeName(propertyName, out string? mapping)) + { + var index = InvocationExpression(IdentifierName(mapping!), ArgumentList(updatedNode.ArgumentList.Arguments)); + + return updatedNode.WithArgumentList(BracketedArgumentList(SingletonSeparatedList(Argument(index)))); + } + + // Rewrite texture resource sampled accesses, if needed + if (HlslKnownProperties.TryGetMappedResourceSamplerAccessType(propertyName, out mapping)) + { + return RewriteSampledTextureAccess(operation, updatedNode, mapping); + } + + // If the current property is a swizzled matrix indexer, ensure all the arguments are constants, and rewrite + // the property access to the corresponding HLSL syntax. For instance, m[M11, M12] will become m._m00_m01. + if (HlslKnownProperties.IsKnownMatrixIndexer(propertyName)) + { + bool isValid = true; + + // Validate the arguments + foreach (ArgumentSyntax argument in node.ArgumentList.Arguments) + { + if (SemanticModel.For(node).GetOperation(argument.Expression) is not IFieldReferenceOperation fieldReference || + !HlslKnownProperties.IsKnownMatrixIndex(fieldReference.Field.GetFullMetadataName())) + { + Diagnostics.Add(NonConstantMatrixSwizzledIndex, argument); + + isValid = false; + } + } + + if (isValid) + { + // Rewrite the indexer as a property access + string hlslPropertyName = string.Join("", + from argument in node.ArgumentList.Arguments + let fieldReference = (IFieldReferenceOperation)SemanticModel.For(node).GetOperation(argument.Expression)! + let fieldName = fieldReference.Field.Name + let row = (char)(fieldName[1] - 1) + let column = (char)(fieldName[2] - 1) + select $"_m{row}{column}"); + + return MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + updatedNode.Expression, + IdentifierName(hlslPropertyName)); + } + } + } + + return updatedNode; + } + + /// + public override SyntaxNode? VisitIdentifierName(IdentifierNameSyntax node) + { + var updatedNode = (IdentifierNameSyntax)base.VisitIdentifierName(node)!; + + if (SemanticModel.For(node).GetOperation(node) is IFieldReferenceOperation operation && + operation.Field.IsConst && + operation.Type!.TypeKind != TypeKind.Enum) + { + ConstantDefinitions[operation.Field] = ((IFormattable)operation.Field.ConstantValue!).ToString(null, CultureInfo.InvariantCulture); + + var ownerTypeName = ((INamedTypeSymbol)operation.Field.ContainingSymbol).ToDisplayString().ToHlslIdentifierName(); + var constantName = $"__{ownerTypeName}__{operation.Field.Name}"; + + return IdentifierName(constantName); + } + + return updatedNode; + } + + /// + public override SyntaxToken VisitToken(SyntaxToken token) + { + SyntaxToken updatedToken = base.VisitToken(token); + + // Replace all identifier tokens when needed, to avoid colliding with HLSL keywords + if (updatedToken.IsKind(SyntaxKind.IdentifierToken) && + HlslKnownKeywords.TryGetMappedName(updatedToken.Text, out string? mapped)) + { + return ParseToken(mapped!); + } + + return updatedToken.WithoutTrivia(); + } + + /// + /// Rewrites a sampled texture access. + /// + /// The instance for the sampled texture access. + /// The input instance for the node to rewrite. + /// The mapped type name to use for the sampled access, if any. + /// A representing the rewritten sampled texture access. + private partial SyntaxNode RewriteSampledTextureAccess(IPropertyReferenceOperation operation, ElementAccessExpressionSyntax node, string? mappedType); +} diff --git a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.cs b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.cs index e64e9f4b..d0d8f78c 100644 --- a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.cs +++ b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.cs @@ -1,359 +1,42 @@ -using System; -using System.Collections.Generic; -using System.Collections.Immutable; -using System.Globalization; -using System.Linq; -using ComputeSharp.SourceGeneration.Extensions; -using ComputeSharp.SourceGeneration.Helpers; -using ComputeSharp.SourceGeneration.Mappings; -using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Operations; -using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; namespace ComputeSharp.SourceGeneration.SyntaxRewriters; -/// -/// A base type that processes C# source to convert to HLSL compliant code. -/// This class contains only the shared logic for all derived HLSL source rewriters. -/// -internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter +/// +partial class HlslSourceRewriter { - /// - /// An array with the '.' and 'E' characters. - /// - private static readonly char[] FloatLiteralSpecialCharacters = { '.', 'E' }; - - /// - /// The instance with semantic info on the target syntax tree. - /// - protected readonly SemanticModelProvider SemanticModel; - - /// - /// The collection of discovered custom types. - /// - protected readonly ICollection DiscoveredTypes; - - /// - /// The collection of discovered constant definitions. - /// - protected readonly IDictionary ConstantDefinitions; - - /// - /// The collection of produced instances. - /// - protected readonly ImmutableArray.Builder Diagnostics; - - /// - /// Creates a new instance with the specified parameters. - /// - /// The instance for the target syntax tree. - /// The set of discovered custom types. - /// The collection of discovered constant definitions. - /// The collection of produced instances. - protected HlslSourceRewriter( - SemanticModelProvider semanticModel, - ICollection discoveredTypes, - IDictionary constantDefinitions, - ImmutableArray.Builder diagnostics) - { - SemanticModel = semanticModel; - DiscoveredTypes = discoveredTypes; - ConstantDefinitions = constantDefinitions; - Diagnostics = diagnostics; - } - /// /// Gets whether or not the shader uses a texture sampler at least once. /// public bool IsSamplerUsed { get; private set; } /// - public override SyntaxNode VisitCastExpression(CastExpressionSyntax node) + private partial SyntaxNode RewriteSampledTextureAccess(IPropertyReferenceOperation operation, ElementAccessExpressionSyntax node, string? mappedType) { - var updatedNode = (CastExpressionSyntax)base.VisitCastExpression(node)!; + IsSamplerUsed = true; - return updatedNode.ReplaceAndTrackType(updatedNode.Type, node.Type, SemanticModel.For(node), DiscoveredTypes); - } - - /// - public override SyntaxNode? VisitVariableDeclaration(VariableDeclarationSyntax node) - { - var updatedNode = (VariableDeclarationSyntax)base.VisitVariableDeclaration(node)!; - - if (SemanticModel.For(node).GetTypeInfo(node.Type).Type is ITypeSymbol { IsUnmanagedType: false } type) + // Get the syntax for the argument syntax transformation as described above + ArgumentSyntax coordinateSyntax = mappedType switch { - Diagnostics.Add(InvalidObjectDeclaration, node, type); - } + not null => Argument(InvocationExpression(IdentifierName(mappedType!), ArgumentList(node.ArgumentList.Arguments))), + null => node.ArgumentList.Arguments[0] + }; - // If var is used, replace it with the explicit type - if (updatedNode.Type is IdentifierNameSyntax { IsVar: true }) - { - updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.Type, node.Type, SemanticModel.For(node), DiscoveredTypes); - } - - return updatedNode; - } - - /// - public override SyntaxNode VisitObjectCreationExpression(ObjectCreationExpressionSyntax node) - { - var updatedNode = (ObjectCreationExpressionSyntax)base.VisitObjectCreationExpression(node)!; - - 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 - if (updatedNode.ArgumentList!.Arguments.Count == 0) - { - return CastExpression(updatedNode.Type, LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0))); - } - - // Add explicit casts for matrix constructors to help the overload resolution - if (SemanticModel.For(node).GetTypeInfo(node).Type is ITypeSymbol matrixType && - HlslKnownTypes.IsMatrixType(matrixType.GetFullMetadataName())) - { - 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(updatedNode.Type, updatedNode.ArgumentList!); - } - - /// - public override SyntaxNode VisitImplicitObjectCreationExpression(ImplicitObjectCreationExpressionSyntax node) - { - var 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.GetFullMetadataName())) - { - 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); - } - - /// - public override SyntaxNode VisitDefaultExpression(DefaultExpressionSyntax node) - { - var updatedNode = (DefaultExpressionSyntax)base.VisitDefaultExpression(node)!; - - updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.Type, node.Type, SemanticModel.For(node), DiscoveredTypes); - - // A default expression becomes (T)0 in HLSL - return CastExpression(updatedNode.Type, LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0))); - } - - /// - public override SyntaxNode? VisitLiteralExpression(LiteralExpressionSyntax node) - { - var updatedNode = (LiteralExpressionSyntax)base.VisitLiteralExpression(node)!; - - if (updatedNode.IsKind(SyntaxKind.DefaultLiteralExpression)) - { - TypeSyntax type = node.TrackType(SemanticModel.For(node), DiscoveredTypes); - - // Same HLSL-style expression in the form (T)0 - return CastExpression(type, LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0))); - } - else if (updatedNode.IsKind(SyntaxKind.NumericLiteralExpression) && - SemanticModel.For(node).GetOperation(node) is ILiteralOperation operation && - operation.Type is INamedTypeSymbol type) - { - // If the expression is a literal floating point value, we need to ensure the proper suffixes are - // used in the HLSL representation. Floating point values accept either f or F, but they don't work - // when the literal doesn't contain a decimal point. Since 32 bit floating point values are the default - // in HLSL, we can remove the suffix entirely. As for 64 bit values, we simply use the 'L' suffix. - if (type.SpecialType == SpecialType.System_Single) - { - string literal = updatedNode.Token.ValueText; - - // If the numeric literal is neither a decimal nor an exponential, add the ".0" suffix - if (literal.IndexOfAny(FloatLiteralSpecialCharacters) == -1) - { - literal += ".0"; - } - - return updatedNode.WithToken(Literal(literal, 0f)); - } - else if (type.SpecialType == SpecialType.System_Double) - { - string literal = updatedNode.Token.ValueText; - - // If the numeric literal is neither a decimal nor an exponential, add the ".0L" suffix. - // This is necessary because otherwise integer literals would actually be of type long. - if (literal.IndexOfAny(FloatLiteralSpecialCharacters) == -1) - { - literal += ".0L"; - } - else - { - literal += "L"; - } - - return updatedNode.WithToken(Literal(literal, 0d)); - } - } - else if (updatedNode.IsKind(SyntaxKind.StringLiteralExpression)) - { - Diagnostics.Add(StringLiteralExpression, node); - } - - return updatedNode; - } - - /// - public override SyntaxNode? VisitElementAccessExpression(ElementAccessExpressionSyntax node) - { - var updatedNode = (ElementAccessExpressionSyntax)base.VisitElementAccessExpression(node)!; - - if (SemanticModel.For(node).GetOperation(node) is IPropertyReferenceOperation operation) - { - string propertyName = operation.Property.GetFullMetadataName(); - - // Rewrite texture resource indices taking individual indices a vector argument, as per HLSL spec. - // For instance: texture[ThreadIds.X, ThreadIds.Y] will be rewritten as texture[int2(ThreadIds.X, ThreadIds.Y)]. - if (HlslKnownProperties.TryGetMappedResourceIndexerTypeName(propertyName, out string? mapping)) - { - var index = InvocationExpression(IdentifierName(mapping!), ArgumentList(updatedNode.ArgumentList.Arguments)); - - return updatedNode.WithArgumentList(BracketedArgumentList(SingletonSeparatedList(Argument(index)))); - } - - // Rewrite texture resource sampled accesses, if needed - if (HlslKnownProperties.TryGetMappedResourceSamplerAccessType(propertyName, out mapping)) - { - IsSamplerUsed = true; - - // Get the syntax for the argument syntax transformation as described above - ArgumentSyntax coordinateSyntax = mapping switch - { - not null => Argument(InvocationExpression(IdentifierName(mapping!), ArgumentList(updatedNode.ArgumentList.Arguments))), - null => updatedNode.ArgumentList.Arguments[0] - }; - - // Transform an indexer syntax into a sampling call with the implicit static linear sampler. - // For instance: texture[uv] will be rewritten as texture.SampleLevel(__sampler, uv, 0). - return - InvocationExpression( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - updatedNode.Expression, - IdentifierName("SampleLevel"))) - .AddArgumentListArguments( - Argument(IdentifierName("__sampler")), - coordinateSyntax, - Argument(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0)))); - } - - // If the current property is a swizzled matrix indexer, ensure all the arguments are constants, and rewrite - // the property access to the corresponding HLSL syntax. For instance, m[M11, M12] will become m._m00_m01. - if (HlslKnownProperties.IsKnownMatrixIndexer(propertyName)) - { - bool isValid = true; - - // Validate the arguments - foreach (ArgumentSyntax argument in node.ArgumentList.Arguments) - { - if (SemanticModel.For(node).GetOperation(argument.Expression) is not IFieldReferenceOperation fieldReference || - !HlslKnownProperties.IsKnownMatrixIndex(fieldReference.Field.GetFullMetadataName())) - { - Diagnostics.Add(NonConstantMatrixSwizzledIndex, argument); - - isValid = false; - } - } - - if (isValid) - { - // Rewrite the indexer as a property access - string hlslPropertyName = string.Join("", - from argument in node.ArgumentList.Arguments - let fieldReference = (IFieldReferenceOperation)SemanticModel.For(node).GetOperation(argument.Expression)! - let fieldName = fieldReference.Field.Name - let row = (char)(fieldName[1] - 1) - let column = (char)(fieldName[2] - 1) - select $"_m{row}{column}"); - - return MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - updatedNode.Expression, - IdentifierName(hlslPropertyName)); - } - } - } - - return updatedNode; - } - - /// - public override SyntaxNode? VisitIdentifierName(IdentifierNameSyntax node) - { - var updatedNode = (IdentifierNameSyntax)base.VisitIdentifierName(node)!; - - if (SemanticModel.For(node).GetOperation(node) is IFieldReferenceOperation operation && - operation.Field.IsConst && - operation.Type!.TypeKind != TypeKind.Enum) - { - ConstantDefinitions[operation.Field] = ((IFormattable)operation.Field.ConstantValue!).ToString(null, CultureInfo.InvariantCulture); - - var ownerTypeName = ((INamedTypeSymbol)operation.Field.ContainingSymbol).ToDisplayString().ToHlslIdentifierName(); - var constantName = $"__{ownerTypeName}__{operation.Field.Name}"; - - return IdentifierName(constantName); - } - - return updatedNode; - } - - /// - public override SyntaxToken VisitToken(SyntaxToken token) - { - SyntaxToken updatedToken = base.VisitToken(token); - - // Replace all identifier tokens when needed, to avoid colliding with HLSL keywords - if (updatedToken.IsKind(SyntaxKind.IdentifierToken) && - HlslKnownKeywords.TryGetMappedName(updatedToken.Text, out string? mapped)) - { - return ParseToken(mapped!); - } - - return updatedToken.WithoutTrivia(); + // Transform an indexer syntax into a sampling call with the implicit static linear sampler. + // For instance: texture[uv] will be rewritten as texture.SampleLevel(__sampler, uv, 0). + return + InvocationExpression( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + node.Expression, + IdentifierName("SampleLevel"))) + .AddArgumentListArguments( + Argument(IdentifierName("__sampler")), + coordinateSyntax, + Argument(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0)))); } }