diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs b/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs index e3b47f1e..a1d5d3a2 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs @@ -1,13 +1,11 @@ using Microsoft.CodeAnalysis; -namespace ComputeSharp.D2D1.SourceGenerators.Diagnostics; +namespace ComputeSharp.SourceGeneration.Diagnostics; #pragma warning disable IDE0090 // Use 'new(...)' -/// -/// A container for all instances for errors reported by analyzers in this project. -/// -internal static class DiagnosticDescriptors +/// +partial class DiagnosticDescriptors { /// /// Gets a for an invalid shader field. diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateBuildHlslSourceMethod.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateBuildHlslSourceMethod.cs index 49c433df..9119924c 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateBuildHlslSourceMethod.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateBuildHlslSourceMethod.cs @@ -3,14 +3,14 @@ using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Text; -using ComputeSharp.D2D1.SourceGenerators.SyntaxRewriters; using ComputeSharp.SourceGeneration.Extensions; using ComputeSharp.SourceGeneration.Helpers; using ComputeSharp.SourceGeneration.Mappings; +using ComputeSharp.SourceGeneration.SyntaxRewriters; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; -using static ComputeSharp.D2D1.SourceGenerators.Diagnostics.DiagnosticDescriptors; +using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; #pragma warning disable CS0618, RS1024 @@ -289,7 +289,8 @@ partial class ID2D1ShaderGenerator discoveredTypes, staticMethods, constantDefinitions, - diagnostics); + diagnostics, + isShaderEntryPoint); // Rewrite the method syntax tree MethodDeclarationSyntax? processedMethod = shaderSourceRewriter.Visit(methodDeclaration)!.WithoutTrivia(); diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateGetInputTypeMethod.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateGetInputTypeMethod.cs index 06c844fb..255b23bb 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateGetInputTypeMethod.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateGetInputTypeMethod.cs @@ -4,7 +4,7 @@ using System.Collections.Immutable; using System.Linq; using ComputeSharp.SourceGeneration.Extensions; using Microsoft.CodeAnalysis; -using static ComputeSharp.D2D1.SourceGenerators.Diagnostics.DiagnosticDescriptors; +using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors; namespace ComputeSharp.D2D1.SourceGenerators; diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.cs index 5df1008d..a9cc40d5 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.cs @@ -15,7 +15,7 @@ using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using TerraFX.Interop.DirectX; using TerraFX.Interop.Windows; -using static ComputeSharp.D2D1.SourceGenerators.Diagnostics.DiagnosticDescriptors; +using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors; namespace ComputeSharp.D2D1.SourceGenerators; diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadDispatchDataMethod.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadDispatchDataMethod.cs index 714ed97b..a99339bc 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadDispatchDataMethod.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadDispatchDataMethod.cs @@ -8,7 +8,7 @@ using ComputeSharp.D2D1.SourceGenerators.Models; using ComputeSharp.SourceGeneration.Extensions; using ComputeSharp.SourceGeneration.Mappings; using Microsoft.CodeAnalysis; -using static ComputeSharp.D2D1.SourceGenerators.Diagnostics.DiagnosticDescriptors; +using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors; namespace ComputeSharp.D2D1.SourceGenerators; diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadInputDescriptionsMethod.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadInputDescriptionsMethod.cs index f110aae9..04228cff 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadInputDescriptionsMethod.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadInputDescriptionsMethod.cs @@ -5,7 +5,7 @@ using System.Linq; using ComputeSharp.D2D1.SourceGenerators.Models; using ComputeSharp.SourceGeneration.Extensions; using Microsoft.CodeAnalysis; -using static ComputeSharp.D2D1.SourceGenerators.Diagnostics.DiagnosticDescriptors; +using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors; namespace ComputeSharp.D2D1.SourceGenerators; diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadResourceTextureDescriptionsMethod.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadResourceTextureDescriptionsMethod.cs index 80be7b41..0d9d6340 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadResourceTextureDescriptionsMethod.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadResourceTextureDescriptionsMethod.cs @@ -5,7 +5,7 @@ using ComputeSharp.D2D1.SourceGenerators.Models; using ComputeSharp.SourceGeneration.Extensions; using ComputeSharp.SourceGeneration.Mappings; using Microsoft.CodeAnalysis; -using static ComputeSharp.D2D1.SourceGenerators.Diagnostics.DiagnosticDescriptors; +using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors; namespace ComputeSharp.D2D1.SourceGenerators; diff --git a/src/ComputeSharp.D2D1.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.Diagnostics.cs b/src/ComputeSharp.D2D1.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.Diagnostics.cs deleted file mode 100644 index 8e6bc2eb..00000000 --- a/src/ComputeSharp.D2D1.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.Diagnostics.cs +++ /dev/null @@ -1,205 +0,0 @@ -using ComputeSharp.SourceGeneration.Extensions; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Syntax; -using static ComputeSharp.D2D1.SourceGenerators.Diagnostics.DiagnosticDescriptors; - -namespace ComputeSharp.D2D1.SourceGenerators.SyntaxRewriters; - -/// -partial class HlslSourceRewriter : CSharpSyntaxRewriter -{ - /// - public override SyntaxNode? VisitAnonymousObjectCreationExpression(AnonymousObjectCreationExpressionSyntax node) - { - var updatedNode = (AnonymousObjectCreationExpressionSyntax)base.VisitAnonymousObjectCreationExpression(node)!; - - Diagnostics.Add(AnonymousObjectCreationExpression, node); - - return updatedNode; - } - - /// - public override SyntaxNode? VisitAwaitExpression(AwaitExpressionSyntax node) - { - Diagnostics.Add(AwaitExpression, node); - - return base.VisitAwaitExpression(node); - } - - /// - public override SyntaxNode? VisitCheckedExpression(CheckedExpressionSyntax node) - { - Diagnostics.Add(CheckedExpression, node); - - return base.VisitCheckedExpression(node); - } - - /// - public override SyntaxNode? VisitCheckedStatement(CheckedStatementSyntax node) - { - Diagnostics.Add(CheckedStatement, node); - - return base.VisitCheckedStatement(node); - } - - /// - public override SyntaxNode? VisitFixedStatement(FixedStatementSyntax node) - { - Diagnostics.Add(FixedStatement, node); - - return base.VisitFixedStatement(node); - } - - /// - public override SyntaxNode? VisitForEachStatement(ForEachStatementSyntax node) - { - Diagnostics.Add(ForEachStatement, node); - - return base.VisitForEachStatement(node); - } - - /// - public override SyntaxNode? VisitForEachVariableStatement(ForEachVariableStatementSyntax node) - { - Diagnostics.Add(ForEachStatement, node); - - return base.VisitForEachVariableStatement(node); - } - - /// - public override SyntaxNode? VisitLockStatement(LockStatementSyntax node) - { - Diagnostics.Add(LockStatement, node); - - return base.VisitLockStatement(node); - } - - /// - public override SyntaxNode? VisitQueryExpression(QueryExpressionSyntax node) - { - Diagnostics.Add(QueryExpression, node); - - return base.VisitQueryExpression(node); - } - - /// - public override SyntaxNode? VisitRangeExpression(RangeExpressionSyntax node) - { - Diagnostics.Add(RangeExpression, node); - - return base.VisitRangeExpression(node); - } - - /// - public override SyntaxNode? VisitRecursivePattern(RecursivePatternSyntax node) - { - Diagnostics.Add(RecursivePattern, node); - - return base.VisitRecursivePattern(node); - } - - /// - public override SyntaxNode? VisitRefType(RefTypeSyntax node) - { - Diagnostics.Add(RefType, node); - - return base.VisitRefType(node); - } - - /// - public override SyntaxNode? VisitRelationalPattern(RelationalPatternSyntax node) - { - Diagnostics.Add(RelationalPattern, node); - - return base.VisitRelationalPattern(node); - } - - /// - public override SyntaxNode? VisitSizeOfExpression(SizeOfExpressionSyntax node) - { - Diagnostics.Add(SizeOfExpression, node); - - return base.VisitSizeOfExpression(node); - } - - /// - public override SyntaxNode? VisitStackAllocArrayCreationExpression(StackAllocArrayCreationExpressionSyntax node) - { - Diagnostics.Add(StackAllocArrayCreationExpression, node); - - return base.VisitStackAllocArrayCreationExpression(node); - } - - /// - public override SyntaxNode? VisitThrowExpression(ThrowExpressionSyntax node) - { - Diagnostics.Add(ThrowExpressionOrStatement, node); - - return base.VisitThrowExpression(node); - } - - /// - public override SyntaxNode? VisitThrowStatement(ThrowStatementSyntax node) - { - Diagnostics.Add(ThrowExpressionOrStatement, node); - - return base.VisitThrowStatement(node); - } - - /// - public override SyntaxNode? VisitTryStatement(TryStatementSyntax node) - { - Diagnostics.Add(TryStatement, node); - - return base.VisitTryStatement(node); - } - - /// - public override SyntaxNode? VisitTupleType(TupleTypeSyntax node) - { - Diagnostics.Add(TupleType, node); - - return base.VisitTupleType(node); - } - - /// - public override SyntaxNode? VisitUsingStatement(UsingStatementSyntax node) - { - Diagnostics.Add(UsingStatementOrDeclaration, node); - - return base.VisitUsingStatement(node); - } - - /// - public override SyntaxNode? VisitYieldStatement(YieldStatementSyntax node) - { - Diagnostics.Add(YieldStatement, node); - - return base.VisitYieldStatement(node); - } - - /// - public override SyntaxNode? VisitFunctionPointerType(FunctionPointerTypeSyntax node) - { - Diagnostics.Add(FunctionPointer, node); - - return base.VisitFunctionPointerType(node); - } - - /// - public override SyntaxNode? VisitPointerType(PointerTypeSyntax node) - { - Diagnostics.Add(PointerType, node); - - return base.VisitPointerType(node); - } - - /// - public override SyntaxNode? VisitUnsafeStatement(UnsafeStatementSyntax node) - { - Diagnostics.Add(UnsafeStatement, node); - - return base.VisitUnsafeStatement(node); - } -} diff --git a/src/ComputeSharp.D2D1.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.cs b/src/ComputeSharp.D2D1.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.cs index f76c7843..d33cd576 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.cs @@ -1,358 +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.D2D1.SourceGenerators.Diagnostics.DiagnosticDescriptors; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; -namespace ComputeSharp.D2D1.SourceGenerators.SyntaxRewriters; +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 needs the [D2DRequiresScenePosition] attribute. - /// - public bool NeedsD2DRequiresScenePositionAttribute { get; protected set; } - /// - 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.D2D1.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs b/src/ComputeSharp.D2D1.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs index a45647db..98ff4360 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs @@ -1,408 +1,30 @@ -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 ComputeSharp.SourceGeneration.Mappings; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Operations; -using static ComputeSharp.D2D1.SourceGenerators.Diagnostics.DiagnosticDescriptors; -using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; -namespace ComputeSharp.D2D1.SourceGenerators.SyntaxRewriters; +namespace ComputeSharp.SourceGeneration.SyntaxRewriters; -/// -/// A custom type that processes C# methods to convert to HLSL compliant code. -/// -internal sealed class ShaderSourceRewriter : HlslSourceRewriter +/// +partial class ShaderSourceRewriter { /// - /// The type symbol for the shader type. + /// Gets whether or not the shader needs the [D2DRequiresScenePosition] attribute. /// - private readonly INamedTypeSymbol? shaderType; + public bool NeedsD2DRequiresScenePositionAttribute { get; private set; } - /// - /// The collection of discovered static methods. - /// - private readonly IDictionary staticMethods; - - /// - /// The collection of processed local functions in the current tree. - /// - private readonly Dictionary localFunctions; - - /// - /// The list of implicit variables to declare at the start of the body. - /// - private readonly List implicitVariables; - - /// - /// The current tree being visited. - /// - private MethodDeclarationSyntax? currentMethod; - - /// - /// Creates a new instance with the specified parameters. - /// - /// The type symbol for the shader type. - /// 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 constant definitions. - /// The collection of produced instances. - public ShaderSourceRewriter( - INamedTypeSymbol shaderType, - SemanticModelProvider semanticModel, - ICollection discoveredTypes, - IDictionary staticMethods, - IDictionary constantDefinitions, - ImmutableArray.Builder diagnostics) - : base(semanticModel, discoveredTypes, constantDefinitions, diagnostics) + /// + private partial void TrackKnownPropertyAccess(IMemberReferenceOperation operation, MemberAccessExpressionSyntax node, string mappedName) { - this.shaderType = shaderType; - this.staticMethods = staticMethods; - this.localFunctions = new(); - this.implicitVariables = new(); - } - - /// - /// Creates a new instance with the specified parameters. - /// - /// 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 constant definitions. - /// The collection of produced instances. - private ShaderSourceRewriter( - SemanticModelProvider semanticModel, - ICollection discoveredTypes, - IDictionary staticMethods, - IDictionary constantDefinitions, - ImmutableArray.Builder diagnostics) - : base(semanticModel, discoveredTypes, constantDefinitions, diagnostics) - { - this.staticMethods = staticMethods; - this.implicitVariables = new(); - this.localFunctions = new(); - } - - /// - /// Gets the collection of processed local functions in the current tree. - /// - public IReadOnlyDictionary LocalFunctions => this.localFunctions; - - /// - public MethodDeclarationSyntax? Visit(MethodDeclarationSyntax? node) - { - this.currentMethod = node; - - var updatedNode = (MethodDeclarationSyntax?)base.Visit(node)!; - - updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.ReturnType, node!.ReturnType, SemanticModel.For(node), DiscoveredTypes); - - if (node!.Modifiers.Any(m => m.IsKind(SyntaxKind.AsyncKeyword))) - { - Diagnostics.Add(AsyncModifierOnMethodOrFunction, node); - } - - if (node!.Modifiers.Any(m => m.IsKind(SyntaxKind.UnsafeKeyword))) - { - Diagnostics.Add(UnsafeModifierOnMethodOrFunction, node); - } - - if (updatedNode is not null) - { - var implicitBlock = Block(this.implicitVariables.Select(static v => LocalDeclarationStatement(v)).ToArray()); - - // Add the tracked implicit declarations (at the start of the body) - updatedNode = updatedNode.WithBody(implicitBlock).AddBodyStatements(updatedNode.Body!.Statements.ToArray()); - } - - return updatedNode; + // No special tracking is needed for D2D1 shaders } /// - public override SyntaxNode VisitParameter(ParameterSyntax node) + private partial void TrackKnownMethodInvocation(string metadataName) { - var updatedNode = (ParameterSyntax)base.VisitParameter(node)!; - - // Convert the C# parameter modifiers to the HLSL equivalent - SyntaxToken modifier = - node.Modifiers - .Where(static m => m.Kind() is SyntaxKind.OutKeyword or SyntaxKind.RefKeyword or SyntaxKind.InKeyword) - .Select(static m => m.Kind() switch - { - SyntaxKind.OutKeyword => m, - SyntaxKind.InKeyword => m, - SyntaxKind.RefKeyword => ParseToken("inout"), - _ => Token(SyntaxKind.None) - }).FirstOrDefault(); - - return updatedNode - .WithAttributeLists(default) - .ReplaceAndTrackType(updatedNode.Type!, node.Type!, SemanticModel.For(node), DiscoveredTypes) - .WithModifiers(TokenList(modifier)); - } - - /// - public override SyntaxNode VisitLocalDeclarationStatement(LocalDeclarationStatementSyntax node) - { - var updatedNode = ((LocalDeclarationStatementSyntax)base.VisitLocalDeclarationStatement(node)!); - - if (SemanticModel.For(node).GetOperation(node) is IOperation { Kind: OperationKind.UsingDeclaration }) + // Track whether the method needs [D2DRequiresScenePosition] + if (HlslKnownMethods.NeedsD2DRequiresScenePositionAttribute(metadataName)) { - Diagnostics.Add(UsingStatementOrDeclaration, node); + NeedsD2DRequiresScenePositionAttribute = true; } - - return updatedNode.ReplaceAndTrackType(updatedNode.Declaration.Type, node.Declaration.Type, SemanticModel.For(node), DiscoveredTypes); - } - - /// - public override SyntaxNode? VisitDeclarationExpression(DeclarationExpressionSyntax node) - { - var updatedNode = (DeclarationExpressionSyntax)base.VisitDeclarationExpression(node)!; - - updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.Type, node.Type, SemanticModel.For(node), DiscoveredTypes); - - // Add the variable to the list of implicit declarations - this.implicitVariables.Add(VariableDeclaration(updatedNode.Type).AddVariables(VariableDeclarator(updatedNode.Designation.ToString()))); - - return IdentifierName(updatedNode.Designation.ToString()); - } - - /// - public override SyntaxNode? VisitMethodDeclaration(MethodDeclarationSyntax node) - { - return - ((MethodDeclarationSyntax)base.VisitMethodDeclaration(node)!) - .WithBlockBody() - .WithoutAccessibilityModifiers() - .WithAttributeLists(List()); - } - - /// - public override SyntaxNode? VisitLocalFunctionStatement(LocalFunctionStatementSyntax node) - { - var updatedNode = - ((LocalFunctionStatementSyntax)base.VisitLocalFunctionStatement(node)!) - .WithBlockBody() - .WithAttributeLists(List()) - .WithIdentifier(Identifier($"__{this.currentMethod!.Identifier.Text}__{node.Identifier.Text}")); - - updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.ReturnType, node!.ReturnType, SemanticModel.For(node), DiscoveredTypes); - - if (node.Modifiers.Any(m => m.IsKind(SyntaxKind.AsyncKeyword))) - { - Diagnostics.Add(AsyncModifierOnMethodOrFunction, node); - } - - if (node.Modifiers.Any(m => m.IsKind(SyntaxKind.UnsafeKeyword))) - { - Diagnostics.Add(UnsafeModifierOnMethodOrFunction, node); - } - - // HLSL doesn't support local functions, so we first process them as usual and then remove - // them from the current syntax tree completely. These will be added to the shader source - // as external static method with a special name to avoid conflicts with other methods. - // The name will simply be in the format: "____". - this.localFunctions.Add(updatedNode.Identifier.Text, updatedNode); - - return null; - } - - /// - public override SyntaxNode VisitMemberAccessExpression(MemberAccessExpressionSyntax node) - { - var updatedNode = (MemberAccessExpressionSyntax)base.VisitMemberAccessExpression(node)!; - - if (node.IsKind(SyntaxKind.SimpleMemberAccessExpression) && - SemanticModel.For(node).GetOperation(node) is IMemberReferenceOperation operation) - { - if (operation is IFieldReferenceOperation fieldOperation) - { - // If the member access is a constant, track it and replace the tree with the processed constant name - if (fieldOperation.Field.IsConst && - fieldOperation.Type!.TypeKind != TypeKind.Enum) - { - if (HlslKnownFields.TryGetMappedName(fieldOperation.Member.ToDisplayString(), out string? constantLiteral)) - { - return ParseExpression(constantLiteral!); - } - - ConstantDefinitions[fieldOperation.Field] = ((IFormattable)fieldOperation.Field.ConstantValue!).ToString(null, CultureInfo.InvariantCulture); - - var ownerTypeName = ((INamedTypeSymbol)fieldOperation.Field.ContainingSymbol).ToDisplayString().ToHlslIdentifierName(); - var constantName = $"__{ownerTypeName}__{fieldOperation.Field.Name}"; - - return IdentifierName(constantName); - } - - // If the member access is a this. access, rewrite it to strip "this." - if (node.Expression.IsKind(SyntaxKind.ThisExpression)) - { - return updatedNode.Name; - } - } - - // If the current member access is a field or property access, check the lookup table - // to see if the member should be rewritten for HLSL compliance, and rewrite if needed. - if (HlslKnownProperties.TryGetMappedName(operation.Member.ToDisplayString(), out string? mapping)) - { - // Static and instance members are handled differently, with static members being - // converted into a literal expression, and instance getting an updated identifier. - // For instance, consider these three cases: - // - Vector3.One (static) => float3(1.0f, 1.0f, 1.0f) - // - ThreadIds.X (custom) => ThreadIds.x - // - uint3.X (instance) => [arg].x - return operation.Member.IsStatic switch - { - true => ParseExpression(mapping!), - false => updatedNode.WithName(IdentifierName(mapping!)) - }; - } - - // If the current member access is an access to any of the size properties in the available - // resource types (either buffer or texture types), then rewrite the subtree to transform the - // property access into an invocation of an autogenerated static helper method to get the target - // dimension for the buffer in use. The helper method is added to the list of static helpers. - if (operation is IPropertyReferenceOperation propertyOperation && - HlslKnownProperties.TryGetAccessorRankAndAxis(propertyOperation.Property.GetFullMetadataName(), out int rank, out int axis)) - { - IMethodSymbol key = propertyOperation.Property.GetMethod!; - - if (!this.staticMethods.TryGetValue(key, out MethodDeclarationSyntax? methodSyntax)) - { - INamedTypeSymbol resourceType = (INamedTypeSymbol)SemanticModel.For(node).GetTypeInfo(node.Expression).Type!; - string resourceName = HlslKnownTypes.GetMappedName(resourceType); - - // Create a static method to get a specified dimension for a target resource type. - // The method will automatically create the necessary number of temporary variables - // depending on the rank of the input resource (eg. 2 for Texture2D resources). - // For instance, this code will generate the following tree for Texture2D.Width: - // - // static int __get_Dimension0(Texture2D texture) - // { - // uint _0, _1; - // texture.GetDimensions(_0, _1); - // - // return _0; - // } - methodSyntax = - MethodDeclaration(PredefinedType(Token(SyntaxKind.IntKeyword)), $"__get_Dimension{axis}") - .AddModifiers(Token(SyntaxKind.StaticKeyword)) - .AddParameterListParameters( - Parameter(Identifier("resource")) - .WithType(IdentifierName(resourceName))) - .WithBody(Block( - LocalDeclarationStatement( - VariableDeclaration(PredefinedType(Token(SyntaxKind.UIntKeyword))) - .AddVariables(Enumerable.Range(0, rank).Select(static i => VariableDeclarator(Identifier("_" + i))).ToArray())), - ExpressionStatement( - InvocationExpression(MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("resource"), - IdentifierName("GetDimensions"))) - .AddArgumentListArguments(Enumerable.Range(0, rank).Select(static i => Argument(IdentifierName("_" + i))).ToArray())), - ReturnStatement(IdentifierName("_" + axis)))); - - this.staticMethods.Add(key, methodSyntax); - } - - return InvocationExpression(IdentifierName(methodSyntax.Identifier)).AddArgumentListArguments(Argument(updatedNode.Expression)); - } - } - - return updatedNode; - } - - /// - public override SyntaxNode? VisitInvocationExpression(InvocationExpressionSyntax node) - { - var updatedNode = (InvocationExpressionSyntax)base.VisitInvocationExpression(node)!; - - if (SemanticModel.For(node).GetOperation(node) is IInvocationOperation operation && - operation.TargetMethod is IMethodSymbol method && - method.IsStatic) - { - string metadataName = method.GetFullMetadataName(); - - // If the invocation consists of invoking a static method that has a direct - // mapping to HLSL, rewrite the expression in the current invocation node. - // For instance: Math.Abs(expr) => abs(expr). - if (HlslKnownMethods.TryGetMappedName(metadataName, out string? mapping)) - { - // Track whether the method needs [D2DRequiresScenePosition] - if (HlslKnownMethods.NeedsD2DRequiresScenePositionAttribute(metadataName)) - { - NeedsD2DRequiresScenePositionAttribute = true; - } - - return updatedNode.WithExpression(ParseExpression(mapping!)); - } - - // Update the name if the target is a local function. The exact schema for the - // updated name is detailed in the override handling the local function statement. - if (method.MethodKind == MethodKind.LocalFunction) - { - var functionIdentifier = $"__{this.currentMethod!.Identifier.Text}__{method.Name}"; - - return updatedNode.WithExpression(ParseExpression(functionIdentifier)); - } - - // If the method is an external static method, import and rewrite it as well. - // This assumes that the target method is actually part of the same compilation. - // We need to check the declaring type to avoid rewriting static methods in the shader - // type as well, as they will be processed by the generator in a different path. - if (!SymbolEqualityComparer.Default.Equals(this.shaderType, method.ContainingType)) - { - var methodIdentifier = method.GetFullMetadataName().ToHlslIdentifierName(); - - if (!this.staticMethods.ContainsKey(method)) - { - if (method.DeclaringSyntaxReferences.FirstOrDefault()?.GetSyntax() is not MethodDeclarationSyntax methodNode) - { - Diagnostics.Add(InvalidMethodCall, node, method); - - return updatedNode; - } - - ShaderSourceRewriter shaderSourceRewriter = new(SemanticModel, DiscoveredTypes, this.staticMethods, ConstantDefinitions, Diagnostics); - MethodDeclarationSyntax processedMethod = shaderSourceRewriter.Visit(methodNode)!.NormalizeWhitespace(eol: "\n").WithoutTrivia(); - - this.staticMethods.Add(method, processedMethod.WithIdentifier(Identifier(methodIdentifier))); - } - - return updatedNode.WithExpression(ParseExpression(methodIdentifier)); - } - } - - return updatedNode; - } - - /// - public override SyntaxNode? VisitArgument(ArgumentSyntax node) - { - var updatedNode = (ArgumentSyntax)base.VisitArgument(node)!; - - // Strip the ref keywords from arguments - updatedNode = updatedNode.WithRefKindKeyword(Token(SyntaxKind.None)); - - // Track and rewrite the discarded declaration - if (SemanticModel.For(node).GetOperation(node.Expression) is IDiscardOperation operation) - { - TypeSyntax typeSyntax = ParseTypeName(HlslKnownTypes.TrackType(operation.Type!, DiscoveredTypes)); - string identifier = $"__implicit{this.implicitVariables.Count}"; - - // Add the variable to the list of implicit declarations - this.implicitVariables.Add(VariableDeclaration(typeSyntax).AddVariables(VariableDeclarator(identifier))); - - return updatedNode.WithExpression(IdentifierName(identifier)); - } - - return updatedNode; } } diff --git a/src/ComputeSharp.D2D1.SourceGenerators/SyntaxRewriters/StaticFieldRewriter.cs b/src/ComputeSharp.D2D1.SourceGenerators/SyntaxRewriters/StaticFieldRewriter.cs index 91f5ea3c..1a5c5410 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/SyntaxRewriters/StaticFieldRewriter.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/SyntaxRewriters/StaticFieldRewriter.cs @@ -1,123 +1,28 @@ -using System; -using System.Collections.Generic; -using System.Collections.Immutable; -using System.Globalization; -using ComputeSharp.SourceGeneration.Extensions; -using ComputeSharp.SourceGeneration.Helpers; -using ComputeSharp.SourceGeneration.Mappings; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; +using ComputeSharp.SourceGeneration.Mappings; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Operations; -using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; -namespace ComputeSharp.D2D1.SourceGenerators.SyntaxRewriters; +namespace ComputeSharp.SourceGeneration.SyntaxRewriters; -/// -/// A custom type that processes C# static field to convert to HLSL static fields (possibly constant). -/// -internal sealed class StaticFieldRewriter : HlslSourceRewriter +/// +partial class StaticFieldRewriter { - /// - /// 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. - public StaticFieldRewriter( - SemanticModelProvider semanticModel, - ICollection discoveredTypes, - IDictionary constantDefinitions, - ImmutableArray.Builder diagnostics) - : base(semanticModel, discoveredTypes, constantDefinitions, diagnostics) - { - } + /// + public bool NeedsD2DRequiresScenePositionAttribute { get; private set; } - /// - public ExpressionSyntax? Visit(VariableDeclaratorSyntax? node) + /// + private partial void TrackKnownPropertyAccess(IMemberReferenceOperation operation, MemberAccessExpressionSyntax node) { - if (node?.Initializer is EqualsValueClauseSyntax fieldInitializer) - { - return ((EqualsValueClauseSyntax)Visit(fieldInitializer))!.Value; - } - - return null; + // No special tracking is needed for D2D1 shaders } /// - public override SyntaxNode VisitMemberAccessExpression(MemberAccessExpressionSyntax node) + private partial void TrackKnownMethodInvocation(string metadataName) { - var updatedNode = (MemberAccessExpressionSyntax)base.VisitMemberAccessExpression(node)!; - - if (node.IsKind(SyntaxKind.SimpleMemberAccessExpression) && - SemanticModel.For(node).GetOperation(node) is IMemberReferenceOperation operation) + // Track whether the method needs [D2DRequiresScenePosition] + if (HlslKnownMethods.NeedsD2DRequiresScenePositionAttribute(metadataName)) { - // Track and replace constants - if (operation is IFieldReferenceOperation fieldOperation && - fieldOperation.Field.IsConst && - fieldOperation.Type!.TypeKind != TypeKind.Enum) - { - if (HlslKnownFields.TryGetMappedName(fieldOperation.Member.ToDisplayString(), out string? constantLiteral)) - { - return ParseExpression(constantLiteral!); - } - - ConstantDefinitions[fieldOperation.Field] = ((IFormattable)fieldOperation.Field.ConstantValue!).ToString(null, CultureInfo.InvariantCulture); - - var ownerTypeName = ((INamedTypeSymbol)fieldOperation.Field.ContainingSymbol).ToDisplayString().ToHlslIdentifierName(); - var constantName = $"__{ownerTypeName}__{fieldOperation.Field.Name}"; - - return IdentifierName(constantName); - } - - if (HlslKnownProperties.TryGetMappedName(operation.Member.ToDisplayString(), out string? mapping)) - { - // Rewrite static and instance mapped members - return operation.Member.IsStatic switch - { - true => ParseExpression(mapping!), - false => updatedNode.WithName(IdentifierName(mapping!)) - }; - } + NeedsD2DRequiresScenePositionAttribute = true; } - - return updatedNode; - } - - /// - public override SyntaxNode? VisitInvocationExpression(InvocationExpressionSyntax node) - { - var updatedNode = (InvocationExpressionSyntax)base.VisitInvocationExpression(node)!; - - if (SemanticModel.For(node).GetOperation(node) is IInvocationOperation operation && - operation.TargetMethod is IMethodSymbol method && - method.IsStatic) - { - string metadataName = method.GetFullMetadataName(); - - // Rewrite HLSL intrinsic methods - if (HlslKnownMethods.TryGetMappedName(metadataName, out string? mapping)) - { - if (HlslKnownMethods.NeedsD2DRequiresScenePositionAttribute(metadataName)) - { - NeedsD2DRequiresScenePositionAttribute = true; - } - - return updatedNode.WithExpression(ParseExpression(mapping!)); - } - } - - return updatedNode; - } - - /// - public override SyntaxNode? VisitArgument(ArgumentSyntax node) - { - var updatedNode = (ArgumentSyntax)base.VisitArgument(node)!; - - updatedNode = updatedNode.WithRefKindKeyword(Token(SyntaxKind.None)); - - return updatedNode; } } diff --git a/src/ComputeSharp.SourceGeneration.Hlsl/ComputeSharp.SourceGeneration.Hlsl.projitems b/src/ComputeSharp.SourceGeneration.Hlsl/ComputeSharp.SourceGeneration.Hlsl.projitems index f41ade8b..549065be 100644 --- a/src/ComputeSharp.SourceGeneration.Hlsl/ComputeSharp.SourceGeneration.Hlsl.projitems +++ b/src/ComputeSharp.SourceGeneration.Hlsl/ComputeSharp.SourceGeneration.Hlsl.projitems @@ -9,6 +9,7 @@ ComputeSharp.SourceGeneration.Hlsl + @@ -17,5 +18,9 @@ + + + + \ No newline at end of file diff --git a/src/ComputeSharp.SourceGeneration.Hlsl/Diagnostics/DiagnosticDescriptors.cs b/src/ComputeSharp.SourceGeneration.Hlsl/Diagnostics/DiagnosticDescriptors.cs new file mode 100644 index 00000000..ced8e438 --- /dev/null +++ b/src/ComputeSharp.SourceGeneration.Hlsl/Diagnostics/DiagnosticDescriptors.cs @@ -0,0 +1,10 @@ +using Microsoft.CodeAnalysis; + +namespace ComputeSharp.SourceGeneration.Diagnostics; + +/// +/// A container for all instances for errors reported by analyzers in this project. +/// +internal static partial class DiagnosticDescriptors +{ +} diff --git a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.Diagnostics.cs b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/HlslSourceRewriter.Diagnostics.cs similarity index 96% rename from src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.Diagnostics.cs rename to src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/HlslSourceRewriter.Diagnostics.cs index 93b62925..e308f084 100644 --- a/src/ComputeSharp.SourceGenerators/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.SourceGenerators.Diagnostics.DiagnosticDescriptors; +using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors; -namespace ComputeSharp.SourceGenerators.SyntaxRewriters; +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.SourceGeneration.Hlsl/SyntaxRewriters/ShaderSourceRewriter.cs b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/ShaderSourceRewriter.cs new file mode 100644 index 00000000..afc989db --- /dev/null +++ b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/ShaderSourceRewriter.cs @@ -0,0 +1,439 @@ +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 custom type that processes C# methods to convert to HLSL compliant code. +/// +internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter +{ + /// + /// The type symbol for the shader type. + /// + private readonly INamedTypeSymbol? shaderType; + + /// + /// The collection of discovered static methods. + /// + private readonly IDictionary staticMethods; + + /// + /// The collection of processed local functions in the current tree. + /// + private readonly Dictionary localFunctions; + + /// + /// The list of implicit variables to declare at the start of the body. + /// + private readonly List implicitVariables; + + /// + /// Whether or not the current instance is processing a shader entry point. + /// + private readonly bool isEntryPoint; + + /// + /// The current tree being visited. + /// + private MethodDeclarationSyntax? currentMethod; + + /// + /// The current depth inside local declarations. + /// + private int localFunctionDepth; + + /// + /// Creates a new instance with the specified parameters. + /// + /// The type symbol for the shader type. + /// 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 constant definitions. + /// The collection of produced instances. + /// Whether or not the current instance is processing a shader entry point. + public ShaderSourceRewriter( + INamedTypeSymbol shaderType, + SemanticModelProvider semanticModel, + ICollection discoveredTypes, + IDictionary staticMethods, + IDictionary constantDefinitions, + ImmutableArray.Builder diagnostics, + bool isEntryPoint) + : base(semanticModel, discoveredTypes, constantDefinitions, diagnostics) + { + this.shaderType = shaderType; + this.staticMethods = staticMethods; + this.localFunctions = new(); + this.implicitVariables = new(); + this.isEntryPoint = isEntryPoint; + } + + /// + /// Creates a new instance with the specified parameters. + /// + /// 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 constant definitions. + /// The collection of produced instances. + public ShaderSourceRewriter( + SemanticModelProvider semanticModel, + ICollection discoveredTypes, + IDictionary staticMethods, + IDictionary constantDefinitions, + ImmutableArray.Builder diagnostics) + : base(semanticModel, discoveredTypes, constantDefinitions, diagnostics) + { + this.staticMethods = staticMethods; + this.implicitVariables = new(); + this.localFunctions = new(); + } + + /// + /// Gets the collection of processed local functions in the current tree. + /// + public IReadOnlyDictionary LocalFunctions => this.localFunctions; + + /// + public MethodDeclarationSyntax? Visit(MethodDeclarationSyntax? node) + { + this.currentMethod = node; + + var updatedNode = (MethodDeclarationSyntax?)base.Visit(node)!; + + updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.ReturnType, node!.ReturnType, SemanticModel.For(node), DiscoveredTypes); + + if (node!.Modifiers.Any(m => m.IsKind(SyntaxKind.AsyncKeyword))) + { + Diagnostics.Add(AsyncModifierOnMethodOrFunction, node); + } + + if (node!.Modifiers.Any(m => m.IsKind(SyntaxKind.UnsafeKeyword))) + { + Diagnostics.Add(UnsafeModifierOnMethodOrFunction, node); + } + + if (updatedNode is not null) + { + var implicitBlock = Block(this.implicitVariables.Select(static v => LocalDeclarationStatement(v)).ToArray()); + + // Add the tracked implicit declarations (at the start of the body) + updatedNode = updatedNode.WithBody(implicitBlock).AddBodyStatements(updatedNode.Body!.Statements.ToArray()); + } + + return updatedNode; + } + + /// + public override SyntaxNode VisitParameter(ParameterSyntax node) + { + var updatedNode = (ParameterSyntax)base.VisitParameter(node)!; + + // Convert the C# parameter modifiers to the HLSL equivalent + SyntaxToken modifier = + node.Modifiers + .Where(static m => m.Kind() is SyntaxKind.OutKeyword or SyntaxKind.RefKeyword or SyntaxKind.InKeyword) + .Select(static m => m.Kind() switch + { + SyntaxKind.OutKeyword => m, + SyntaxKind.InKeyword => m, + SyntaxKind.RefKeyword => ParseToken("inout"), + _ => Token(SyntaxKind.None) + }).FirstOrDefault(); + + return updatedNode + .WithAttributeLists(default) + .ReplaceAndTrackType(updatedNode.Type!, node.Type!, SemanticModel.For(node), DiscoveredTypes) + .WithModifiers(TokenList(modifier)); + } + + /// + public override SyntaxNode VisitLocalDeclarationStatement(LocalDeclarationStatementSyntax node) + { + var updatedNode = ((LocalDeclarationStatementSyntax)base.VisitLocalDeclarationStatement(node)!); + + if (SemanticModel.For(node).GetOperation(node) is IOperation { Kind: OperationKind.UsingDeclaration }) + { + Diagnostics.Add(UsingStatementOrDeclaration, node); + } + + return updatedNode.ReplaceAndTrackType(updatedNode.Declaration.Type, node.Declaration.Type, SemanticModel.For(node), DiscoveredTypes); + } + + /// + public override SyntaxNode? VisitDeclarationExpression(DeclarationExpressionSyntax node) + { + var updatedNode = (DeclarationExpressionSyntax)base.VisitDeclarationExpression(node)!; + + updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.Type, node.Type, SemanticModel.For(node), DiscoveredTypes); + + // Add the variable to the list of implicit declarations + this.implicitVariables.Add(VariableDeclaration(updatedNode.Type).AddVariables(VariableDeclarator(updatedNode.Designation.ToString()))); + + return IdentifierName(updatedNode.Designation.ToString()); + } + + /// + public override SyntaxNode? VisitMethodDeclaration(MethodDeclarationSyntax node) + { + return + ((MethodDeclarationSyntax)base.VisitMethodDeclaration(node)!) + .WithBlockBody() + .WithoutAccessibilityModifiers() + .WithAttributeLists(List()); + } + + /// + public override SyntaxNode? VisitLocalFunctionStatement(LocalFunctionStatementSyntax node) + { + this.localFunctionDepth++; + + var updatedNode = + ((LocalFunctionStatementSyntax)base.VisitLocalFunctionStatement(node)!) + .WithBlockBody() + .WithAttributeLists(List()) + .WithIdentifier(Identifier($"__{this.currentMethod!.Identifier.Text}__{node.Identifier.Text}")); + + updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.ReturnType, node!.ReturnType, SemanticModel.For(node), DiscoveredTypes); + + if (node.Modifiers.Any(m => m.IsKind(SyntaxKind.AsyncKeyword))) + { + Diagnostics.Add(AsyncModifierOnMethodOrFunction, node); + } + + if (node.Modifiers.Any(m => m.IsKind(SyntaxKind.UnsafeKeyword))) + { + Diagnostics.Add(UnsafeModifierOnMethodOrFunction, node); + } + + this.localFunctionDepth--; + + // HLSL doesn't support local functions, so we first process them as usual and then remove + // them from the current syntax tree completely. These will be added to the shader source + // as external static method with a special name to avoid conflicts with other methods. + // The name will simply be in the format: "____". + this.localFunctions.Add(updatedNode.Identifier.Text, updatedNode); + + return null; + } + + /// + public override SyntaxNode VisitMemberAccessExpression(MemberAccessExpressionSyntax node) + { + var updatedNode = (MemberAccessExpressionSyntax)base.VisitMemberAccessExpression(node)!; + + if (node.IsKind(SyntaxKind.SimpleMemberAccessExpression) && + SemanticModel.For(node).GetOperation(node) is IMemberReferenceOperation operation) + { + if (operation is IFieldReferenceOperation fieldOperation) + { + // If the member access is a constant, track it and replace the tree with the processed constant name + if (fieldOperation.Field.IsConst && + fieldOperation.Type!.TypeKind != TypeKind.Enum) + { + if (HlslKnownFields.TryGetMappedName(fieldOperation.Member.ToDisplayString(), out string? constantLiteral)) + { + return ParseExpression(constantLiteral!); + } + + ConstantDefinitions[fieldOperation.Field] = ((IFormattable)fieldOperation.Field.ConstantValue!).ToString(null, CultureInfo.InvariantCulture); + + var ownerTypeName = ((INamedTypeSymbol)fieldOperation.Field.ContainingSymbol).ToDisplayString().ToHlslIdentifierName(); + var constantName = $"__{ownerTypeName}__{fieldOperation.Field.Name}"; + + return IdentifierName(constantName); + } + + // If the member access is a this. access, rewrite it to strip "this." + if (node.Expression.IsKind(SyntaxKind.ThisExpression)) + { + return updatedNode.Name; + } + } + + // If the current member access is a field or property access, check the lookup table + // to see if the member should be rewritten for HLSL compliance, and rewrite if needed. + if (HlslKnownProperties.TryGetMappedName(operation.Member.ToDisplayString(), out string? mapping)) + { + // Allow specialized rewriters to track the property, if needed (eg. to emit diagnostics) + TrackKnownPropertyAccess(operation, node, mapping!); + + // Static and instance members are handled differently, with static members being + // converted into a literal expression, and instance getting an updated identifier. + // For instance, consider these three cases: + // - Vector3.One (static) => float3(1.0f, 1.0f, 1.0f) + // - ThreadIds.X (custom) => ThreadIds.x + // - uint3.X (instance) => [arg].x + return operation.Member.IsStatic switch + { + true => ParseExpression(mapping!), + false => updatedNode.WithName(IdentifierName(mapping!)) + }; + } + + // If the current member access is an access to any of the size properties in the available + // resource types (either buffer or texture types), then rewrite the subtree to transform the + // property access into an invocation of an autogenerated static helper method to get the target + // dimension for the buffer in use. The helper method is added to the list of static helpers. + if (operation is IPropertyReferenceOperation propertyOperation && + HlslKnownProperties.TryGetAccessorRankAndAxis(propertyOperation.Property.GetFullMetadataName(), out int rank, out int axis)) + { + IMethodSymbol key = propertyOperation.Property.GetMethod!; + + if (!this.staticMethods.TryGetValue(key, out MethodDeclarationSyntax? methodSyntax)) + { + INamedTypeSymbol resourceType = (INamedTypeSymbol)SemanticModel.For(node).GetTypeInfo(node.Expression).Type!; + string resourceName = HlslKnownTypes.GetMappedName(resourceType); + + // Create a static method to get a specified dimension for a target resource type. + // The method will automatically create the necessary number of temporary variables + // depending on the rank of the input resource (eg. 2 for Texture2D resources). + // For instance, this code will generate the following tree for Texture2D.Width: + // + // static int __get_Dimension0(Texture2D texture) + // { + // uint _0, _1; + // texture.GetDimensions(_0, _1); + // + // return _0; + // } + methodSyntax = + MethodDeclaration(PredefinedType(Token(SyntaxKind.IntKeyword)), $"__get_Dimension{axis}") + .AddModifiers(Token(SyntaxKind.StaticKeyword)) + .AddParameterListParameters( + Parameter(Identifier("resource")) + .WithType(IdentifierName(resourceName))) + .WithBody(Block( + LocalDeclarationStatement( + VariableDeclaration(PredefinedType(Token(SyntaxKind.UIntKeyword))) + .AddVariables(Enumerable.Range(0, rank).Select(static i => VariableDeclarator(Identifier("_" + i))).ToArray())), + ExpressionStatement( + InvocationExpression(MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName("resource"), + IdentifierName("GetDimensions"))) + .AddArgumentListArguments(Enumerable.Range(0, rank).Select(static i => Argument(IdentifierName("_" + i))).ToArray())), + ReturnStatement(IdentifierName("_" + axis)))); + + this.staticMethods.Add(key, methodSyntax); + } + + return InvocationExpression(IdentifierName(methodSyntax.Identifier)).AddArgumentListArguments(Argument(updatedNode.Expression)); + } + } + + return updatedNode; + } + + /// + public override SyntaxNode? VisitInvocationExpression(InvocationExpressionSyntax node) + { + var updatedNode = (InvocationExpressionSyntax)base.VisitInvocationExpression(node)!; + + if (SemanticModel.For(node).GetOperation(node) is IInvocationOperation operation && + operation.TargetMethod is IMethodSymbol method && + method.IsStatic) + { + string metadataName = method.GetFullMetadataName(); + + // If the invocation consists of invoking a static method that has a direct + // mapping to HLSL, rewrite the expression in the current invocation node. + // For instance: Math.Abs(expr) => abs(expr). + if (HlslKnownMethods.TryGetMappedName(metadataName, out string? mapping)) + { + // Allow specialized types to track the method invocation, if needed + TrackKnownMethodInvocation(metadataName); + + return updatedNode.WithExpression(ParseExpression(mapping!)); + } + + // Update the name if the target is a local function. The exact schema for the + // updated name is detailed in the override handling the local function statement. + if (method.MethodKind == MethodKind.LocalFunction) + { + var functionIdentifier = $"__{this.currentMethod!.Identifier.Text}__{method.Name}"; + + return updatedNode.WithExpression(ParseExpression(functionIdentifier)); + } + + // If the method is an external static method, import and rewrite it as well. + // This assumes that the target method is actually part of the same compilation. + // We need to check the declaring type to avoid rewriting static methods in the shader + // type as well, as they will be processed by the generator in a different path. + if (!SymbolEqualityComparer.Default.Equals(this.shaderType, method.ContainingType)) + { + var methodIdentifier = method.GetFullMetadataName().ToHlslIdentifierName(); + + if (!this.staticMethods.ContainsKey(method)) + { + if (method.DeclaringSyntaxReferences.FirstOrDefault()?.GetSyntax() is not MethodDeclarationSyntax methodNode) + { + Diagnostics.Add(InvalidMethodCall, node, method); + + return updatedNode; + } + + ShaderSourceRewriter shaderSourceRewriter = new(SemanticModel, DiscoveredTypes, this.staticMethods, ConstantDefinitions, Diagnostics); + MethodDeclarationSyntax processedMethod = shaderSourceRewriter.Visit(methodNode)!.NormalizeWhitespace(eol: "\n").WithoutTrivia(); + + this.staticMethods.Add(method, processedMethod.WithIdentifier(Identifier(methodIdentifier))); + } + + return updatedNode.WithExpression(ParseExpression(methodIdentifier)); + } + } + + return updatedNode; + } + + /// + public override SyntaxNode? VisitArgument(ArgumentSyntax node) + { + var updatedNode = (ArgumentSyntax)base.VisitArgument(node)!; + + // Strip the ref keywords from arguments + updatedNode = updatedNode.WithRefKindKeyword(Token(SyntaxKind.None)); + + // Track and rewrite the discarded declaration + if (SemanticModel.For(node).GetOperation(node.Expression) is IDiscardOperation operation) + { + TypeSyntax typeSyntax = ParseTypeName(HlslKnownTypes.TrackType(operation.Type!, DiscoveredTypes)); + string identifier = $"__implicit{this.implicitVariables.Count}"; + + // Add the variable to the list of implicit declarations + this.implicitVariables.Add(VariableDeclaration(typeSyntax).AddVariables(VariableDeclarator(identifier))); + + return updatedNode.WithExpression(IdentifierName(identifier)); + } + + return updatedNode; + } + + /// + /// Tracks a property access to a known HLSL property. + /// + /// The instance for the operation. + /// The instance for the operation. + /// The mapped name for the property access. + private partial void TrackKnownPropertyAccess(IMemberReferenceOperation operation, MemberAccessExpressionSyntax node, string mappedName); + + /// + /// Tracks a method invocation for a known HLSL method. + /// + /// The metadata name of the method being invoked. + private partial void TrackKnownMethodInvocation(string metadataName); +} diff --git a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/StaticFieldRewriter.cs b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/StaticFieldRewriter.cs new file mode 100644 index 00000000..319e43f4 --- /dev/null +++ b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/StaticFieldRewriter.cs @@ -0,0 +1,132 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Globalization; +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 Microsoft.CodeAnalysis.CSharp.SyntaxFactory; + +namespace ComputeSharp.SourceGeneration.SyntaxRewriters; + +/// +/// A custom type that processes C# static field to convert to HLSL static fields (possibly constant). +/// +internal sealed partial class StaticFieldRewriter : HlslSourceRewriter +{ + /// + /// 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. + public StaticFieldRewriter( + SemanticModelProvider semanticModel, + ICollection discoveredTypes, + IDictionary constantDefinitions, + ImmutableArray.Builder diagnostics) + : base(semanticModel, discoveredTypes, constantDefinitions, diagnostics) + { + } + + /// + public ExpressionSyntax? Visit(VariableDeclaratorSyntax? node) + { + if (node?.Initializer is EqualsValueClauseSyntax fieldInitializer) + { + return ((EqualsValueClauseSyntax)Visit(fieldInitializer))!.Value; + } + + return null; + } + + /// + public override SyntaxNode VisitMemberAccessExpression(MemberAccessExpressionSyntax node) + { + var updatedNode = (MemberAccessExpressionSyntax)base.VisitMemberAccessExpression(node)!; + + if (node.IsKind(SyntaxKind.SimpleMemberAccessExpression) && + SemanticModel.For(node).GetOperation(node) is IMemberReferenceOperation operation) + { + // Track and replace constants + if (operation is IFieldReferenceOperation fieldOperation && + fieldOperation.Field.IsConst && + fieldOperation.Type!.TypeKind != TypeKind.Enum) + { + if (HlslKnownFields.TryGetMappedName(fieldOperation.Member.ToDisplayString(), out string? constantLiteral)) + { + return ParseExpression(constantLiteral!); + } + + ConstantDefinitions[fieldOperation.Field] = ((IFormattable)fieldOperation.Field.ConstantValue!).ToString(null, CultureInfo.InvariantCulture); + + var ownerTypeName = ((INamedTypeSymbol)fieldOperation.Field.ContainingSymbol).ToDisplayString().ToHlslIdentifierName(); + var constantName = $"__{ownerTypeName}__{fieldOperation.Field.Name}"; + + return IdentifierName(constantName); + } + + if (HlslKnownProperties.TryGetMappedName(operation.Member.ToDisplayString(), out string? mapping)) + { + // Allow specialized types to track the member access, if needed + TrackKnownPropertyAccess(operation, node); + + // Rewrite static and instance mapped members + return operation.Member.IsStatic switch + { + true => ParseExpression(mapping!), + false => updatedNode.WithName(IdentifierName(mapping!)) + }; + } + } + + return updatedNode; + } + + /// + public override SyntaxNode? VisitInvocationExpression(InvocationExpressionSyntax node) + { + var updatedNode = (InvocationExpressionSyntax)base.VisitInvocationExpression(node)!; + + if (SemanticModel.For(node).GetOperation(node) is IInvocationOperation operation && + operation.TargetMethod is IMethodSymbol method && + method.IsStatic) + { + // Rewrite HLSL intrinsic methods + if (HlslKnownMethods.TryGetMappedName(method.GetFullMetadataName(), out string? mapping)) + { + return updatedNode.WithExpression(ParseExpression(mapping!)); + } + } + + return updatedNode; + } + + /// + public override SyntaxNode? VisitArgument(ArgumentSyntax node) + { + var updatedNode = (ArgumentSyntax)base.VisitArgument(node)!; + + updatedNode = updatedNode.WithRefKindKeyword(Token(SyntaxKind.None)); + + return updatedNode; + } + + /// + /// Tracks a property access to a known HLSL property. + /// + /// The instance for the operation. + /// The instance for the operation. + private partial void TrackKnownPropertyAccess(IMemberReferenceOperation operation, MemberAccessExpressionSyntax node); + + /// + /// Tracks a method invocation for a known HLSL method. + /// + /// The metadata name of the method being invoked. + private partial void TrackKnownMethodInvocation(string metadataName); +} diff --git a/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs b/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs index 1e9e4d7f..5a51d70b 100644 --- a/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs +++ b/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs @@ -1,13 +1,11 @@ using Microsoft.CodeAnalysis; -namespace ComputeSharp.SourceGenerators.Diagnostics; +namespace ComputeSharp.SourceGeneration.Diagnostics; -#pragma warning disable IDE0090 // Use 'new(...)' +#pragma warning disable IDE0090 // Use 'new(...)' -/// -/// A container for all instances for errors reported by analyzers in this project. -/// -internal static class DiagnosticDescriptors +/// +partial class DiagnosticDescriptors { /// /// Gets a for an invalid shader field. diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.cs index 990a6aae..a2c6f83b 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.cs @@ -6,13 +6,13 @@ using System.Text; using ComputeSharp.SourceGeneration.Extensions; using ComputeSharp.SourceGeneration.Helpers; using ComputeSharp.SourceGeneration.Mappings; -using ComputeSharp.SourceGenerators.Diagnostics; +using ComputeSharp.SourceGeneration.SyntaxRewriters; using ComputeSharp.SourceGenerators.Models; using ComputeSharp.SourceGenerators.SyntaxRewriters; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; -using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors; +using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; #pragma warning disable CS0618, RS1024 diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadBytecodeMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadBytecodeMethod.cs index 5f6643b2..8ecf75a9 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadBytecodeMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadBytecodeMethod.cs @@ -18,7 +18,7 @@ using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; using TerraFX.Interop.DirectX; using TerraFX.Interop.Windows; -using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors; +using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors; namespace ComputeSharp.SourceGenerators; diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.cs index 8451edff..665162db 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.cs @@ -8,7 +8,7 @@ using ComputeSharp.SourceGeneration.Extensions; using ComputeSharp.SourceGeneration.Mappings; using ComputeSharp.SourceGenerators.Models; using Microsoft.CodeAnalysis; -using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors; +using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors; namespace ComputeSharp.SourceGenerators; diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs index 908dc4fc..63921ab1 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs @@ -3,9 +3,9 @@ using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Text; +using ComputeSharp.SourceGeneration.Diagnostics; using ComputeSharp.SourceGeneration.Extensions; using ComputeSharp.SourceGeneration.Models; -using ComputeSharp.SourceGenerators.Diagnostics; using ComputeSharp.SourceGenerators.Models; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; diff --git a/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs b/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs index eecc3347..52dde8f1 100644 --- a/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs @@ -6,8 +6,8 @@ using ComputeSharp.__Internals; using ComputeSharp.SourceGeneration.Extensions; using ComputeSharp.SourceGeneration.Helpers; using ComputeSharp.SourceGeneration.Models; +using ComputeSharp.SourceGeneration.SyntaxRewriters; using ComputeSharp.SourceGenerators.Models; -using ComputeSharp.SourceGenerators.SyntaxRewriters; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; diff --git a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ExecuteMethodRewriter.cs b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ExecuteMethodRewriter.cs index f3e20a2e..e26a322c 100644 --- a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ExecuteMethodRewriter.cs +++ b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ExecuteMethodRewriter.cs @@ -1,4 +1,5 @@ -using Microsoft.CodeAnalysis; +using ComputeSharp.SourceGeneration.SyntaxRewriters; +using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; diff --git a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.cs b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.cs index 215daa8b..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.SourceGenerators.Diagnostics.DiagnosticDescriptors; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; -namespace ComputeSharp.SourceGenerators.SyntaxRewriters; +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)))); } } diff --git a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs index ff8329ff..9ce11b03 100644 --- a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs +++ b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs @@ -1,113 +1,15 @@ 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.SourceGenerators.Diagnostics.DiagnosticDescriptors; -using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; +using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors; -namespace ComputeSharp.SourceGenerators.SyntaxRewriters; +namespace ComputeSharp.SourceGeneration.SyntaxRewriters; -/// -/// A custom type that processes C# methods to convert to HLSL compliant code. -/// -internal sealed class ShaderSourceRewriter : HlslSourceRewriter +/// +partial class ShaderSourceRewriter { - /// - /// The type symbol for the shader type. - /// - private readonly INamedTypeSymbol? shaderType; - - /// - /// The collection of discovered static methods. - /// - private readonly IDictionary staticMethods; - - /// - /// The collection of processed local functions in the current tree. - /// - private readonly Dictionary localFunctions; - - /// - /// The list of implicit variables to declare at the start of the body. - /// - private readonly List implicitVariables; - - /// - /// Whether or not the current instance is processing a shader entry point. - /// - private readonly bool isEntryPoint; - - /// - /// The current tree being visited. - /// - private MethodDeclarationSyntax? currentMethod; - - /// - /// The current depth inside local declarations. - /// - private int localFunctionDepth; - - /// - /// Creates a new instance with the specified parameters. - /// - /// The type symbol for the shader type. - /// 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 constant definitions. - /// The collection of produced instances. - /// Whether or not the current instance is processing a shader entry point. - public ShaderSourceRewriter( - INamedTypeSymbol shaderType, - SemanticModelProvider semanticModel, - ICollection discoveredTypes, - IDictionary staticMethods, - IDictionary constantDefinitions, - ImmutableArray.Builder diagnostics, - bool isEntryPoint) - : base(semanticModel, discoveredTypes, constantDefinitions, diagnostics) - { - this.shaderType = shaderType; - this.staticMethods = staticMethods; - this.localFunctions = new(); - this.implicitVariables = new(); - this.isEntryPoint = isEntryPoint; - } - - /// - /// Creates a new instance with the specified parameters. - /// - /// 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 constant definitions. - /// The collection of produced instances. - public ShaderSourceRewriter( - SemanticModelProvider semanticModel, - ICollection discoveredTypes, - IDictionary staticMethods, - IDictionary constantDefinitions, - ImmutableArray.Builder diagnostics) - : base(semanticModel, discoveredTypes, constantDefinitions, diagnostics) - { - this.staticMethods = staticMethods; - this.implicitVariables = new(); - this.localFunctions = new(); - } - - /// - /// Gets the collection of processed local functions in the current tree. - /// - public IReadOnlyDictionary LocalFunctions => this.localFunctions; - /// /// Gets whether or not the shader uses at least once (except ). /// @@ -123,339 +25,42 @@ internal sealed class ShaderSourceRewriter : HlslSourceRewriter /// public bool IsGridIdsUsed { get; set; } - /// - public MethodDeclarationSyntax? Visit(MethodDeclarationSyntax? node) - { - this.currentMethod = node; - - var updatedNode = (MethodDeclarationSyntax?)base.Visit(node)!; - - updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.ReturnType, node!.ReturnType, SemanticModel.For(node), DiscoveredTypes); - - if (node!.Modifiers.Any(m => m.IsKind(SyntaxKind.AsyncKeyword))) - { - Diagnostics.Add(AsyncModifierOnMethodOrFunction, node); - } - - if (node!.Modifiers.Any(m => m.IsKind(SyntaxKind.UnsafeKeyword))) - { - Diagnostics.Add(UnsafeModifierOnMethodOrFunction, node); - } - - if (updatedNode is not null) - { - var implicitBlock = Block(this.implicitVariables.Select(static v => LocalDeclarationStatement(v)).ToArray()); - - // Add the tracked implicit declarations (at the start of the body) - updatedNode = updatedNode.WithBody(implicitBlock).AddBodyStatements(updatedNode.Body!.Statements.ToArray()); - } - - return updatedNode; - } - /// - public override SyntaxNode VisitParameter(ParameterSyntax node) + private partial void TrackKnownPropertyAccess(IMemberReferenceOperation operation, MemberAccessExpressionSyntax node, string mappedName) { - var updatedNode = (ParameterSyntax)base.VisitParameter(node)!; + // Mark which dispatch properties have been used, to optimize the declaration afterwards + if (operation.Member.IsStatic) + { + string typeName = operation.Member.ContainingType.GetFullMetadataName(); - // Convert the C# parameter modifiers to the HLSL equivalent - SyntaxToken modifier = - node.Modifiers - .Where(static m => m.Kind() is SyntaxKind.OutKeyword or SyntaxKind.RefKeyword or SyntaxKind.InKeyword) - .Select(static m => m.Kind() switch + if (mappedName == $"__{nameof(GroupIds)}__get_Index") IsGroupIdsIndexUsed = true; + else if (typeName == typeof(GroupIds).FullName) IsGroupIdsUsed = true; + else if (typeName == typeof(GridIds).FullName) IsGridIdsUsed = true; + + // Check that the dispatch info types are only used from the main shader body + if (!this.isEntryPoint || this.localFunctionDepth > 0) { - SyntaxKind.OutKeyword => m, - SyntaxKind.InKeyword => m, - SyntaxKind.RefKeyword => ParseToken("inout"), - _ => Token(SyntaxKind.None) - }).FirstOrDefault(); - - return updatedNode - .WithAttributeLists(default) - .ReplaceAndTrackType(updatedNode.Type!, node.Type!, SemanticModel.For(node), DiscoveredTypes) - .WithModifiers(TokenList(modifier)); - } - - /// - public override SyntaxNode VisitLocalDeclarationStatement(LocalDeclarationStatementSyntax node) - { - var updatedNode = ((LocalDeclarationStatementSyntax)base.VisitLocalDeclarationStatement(node)!); - - if (SemanticModel.For(node).GetOperation(node) is IOperation { Kind: OperationKind.UsingDeclaration }) - { - Diagnostics.Add(UsingStatementOrDeclaration, node); - } - - return updatedNode.ReplaceAndTrackType(updatedNode.Declaration.Type, node.Declaration.Type, SemanticModel.For(node), DiscoveredTypes); - } - - /// - public override SyntaxNode? VisitDeclarationExpression(DeclarationExpressionSyntax node) - { - var updatedNode = (DeclarationExpressionSyntax)base.VisitDeclarationExpression(node)!; - - updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.Type, node.Type, SemanticModel.For(node), DiscoveredTypes); - - // Add the variable to the list of implicit declarations - this.implicitVariables.Add(VariableDeclaration(updatedNode.Type).AddVariables(VariableDeclarator(updatedNode.Designation.ToString()))); - - return IdentifierName(updatedNode.Designation.ToString()); - } - - /// - public override SyntaxNode? VisitMethodDeclaration(MethodDeclarationSyntax node) - { - return - ((MethodDeclarationSyntax)base.VisitMethodDeclaration(node)!) - .WithBlockBody() - .WithoutAccessibilityModifiers() - .WithAttributeLists(List()); - } - - /// - public override SyntaxNode? VisitLocalFunctionStatement(LocalFunctionStatementSyntax node) - { - this.localFunctionDepth++; - - var updatedNode = - ((LocalFunctionStatementSyntax)base.VisitLocalFunctionStatement(node)!) - .WithBlockBody() - .WithAttributeLists(List()) - .WithIdentifier(Identifier($"__{this.currentMethod!.Identifier.Text}__{node.Identifier.Text}")); - - updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.ReturnType, node!.ReturnType, SemanticModel.For(node), DiscoveredTypes); - - if (node.Modifiers.Any(m => m.IsKind(SyntaxKind.AsyncKeyword))) - { - Diagnostics.Add(AsyncModifierOnMethodOrFunction, node); - } - - if (node.Modifiers.Any(m => m.IsKind(SyntaxKind.UnsafeKeyword))) - { - Diagnostics.Add(UnsafeModifierOnMethodOrFunction, node); - } - - this.localFunctionDepth--; - - // HLSL doesn't support local functions, so we first process them as usual and then remove - // them from the current syntax tree completely. These will be added to the shader source - // as external static method with a special name to avoid conflicts with other methods. - // The name will simply be in the format: "____". - this.localFunctions.Add(updatedNode.Identifier.Text, updatedNode); - - return null; - } - - /// - public override SyntaxNode VisitMemberAccessExpression(MemberAccessExpressionSyntax node) - { - var updatedNode = (MemberAccessExpressionSyntax)base.VisitMemberAccessExpression(node)!; - - if (node.IsKind(SyntaxKind.SimpleMemberAccessExpression) && - SemanticModel.For(node).GetOperation(node) is IMemberReferenceOperation operation) - { - if (operation is IFieldReferenceOperation fieldOperation) - { - // If the member access is a constant, track it and replace the tree with the processed constant name - if (fieldOperation.Field.IsConst && - fieldOperation.Type!.TypeKind != TypeKind.Enum) + DiagnosticDescriptor? descriptor = typeName switch { - if (HlslKnownFields.TryGetMappedName(fieldOperation.Member.ToDisplayString(), out string? constantLiteral)) - { - return ParseExpression(constantLiteral!); - } - - ConstantDefinitions[fieldOperation.Field] = ((IFormattable)fieldOperation.Field.ConstantValue!).ToString(null, CultureInfo.InvariantCulture); - - var ownerTypeName = ((INamedTypeSymbol)fieldOperation.Field.ContainingSymbol).ToDisplayString().ToHlslIdentifierName(); - var constantName = $"__{ownerTypeName}__{fieldOperation.Field.Name}"; - - return IdentifierName(constantName); - } - - // If the member access is a this. access, rewrite it to strip "this." - if (node.Expression.IsKind(SyntaxKind.ThisExpression)) - { - return updatedNode.Name; - } - } - - // If the current member access is a field or property access, check the lookup table - // to see if the member should be rewritten for HLSL compliance, and rewrite if needed. - if (HlslKnownProperties.TryGetMappedName(operation.Member.ToDisplayString(), out string? mapping)) - { - // Mark which dispatch properties have been used, to optimize the declaration afterwards - if (operation.Member.IsStatic) - { - string typeName = operation.Member.ContainingType.GetFullMetadataName(); - - if (mapping == $"__{nameof(GroupIds)}__get_Index") IsGroupIdsIndexUsed = true; - else if (typeName == typeof(GroupIds).FullName) IsGroupIdsUsed = true; - else if (typeName == typeof(GridIds).FullName) IsGridIdsUsed = true; - - // Check that the dispatch info types are only used from the main shader body - if (!this.isEntryPoint || this.localFunctionDepth > 0) - { - DiagnosticDescriptor? descriptor = typeName switch - { - _ when typeName == typeof(ThreadIds).FullName || typeName == typeof(ThreadIds.Normalized).FullName => InvalidThreadIdsUsage, - _ when typeName == typeof(GroupIds).FullName => InvalidGroupIdsUsage, - _ when typeName == typeof(GroupSize).FullName => InvalidGroupSizeUsage, - _ when typeName == typeof(GridIds).FullName => InvalidGridIdsUsage, - _ when typeName == typeof(DispatchSize).FullName => InvalidDispatchSizeUsage, - _ => null - }; - - if (descriptor is not null) - { - Diagnostics.Add(descriptor, node); - } - } - } - - // Static and instance members are handled differently, with static members being - // converted into a literal expression, and instance getting an updated identifier. - // For instance, consider these three cases: - // - Vector3.One (static) => float3(1.0f, 1.0f, 1.0f) - // - ThreadIds.X (custom) => ThreadIds.x - // - uint3.X (instance) => [arg].x - return operation.Member.IsStatic switch - { - true => ParseExpression(mapping!), - false => updatedNode.WithName(IdentifierName(mapping!)) + _ when typeName == typeof(ThreadIds).FullName || typeName == typeof(ThreadIds.Normalized).FullName => InvalidThreadIdsUsage, + _ when typeName == typeof(GroupIds).FullName => InvalidGroupIdsUsage, + _ when typeName == typeof(GroupSize).FullName => InvalidGroupSizeUsage, + _ when typeName == typeof(GridIds).FullName => InvalidGridIdsUsage, + _ when typeName == typeof(DispatchSize).FullName => InvalidDispatchSizeUsage, + _ => null }; - } - // If the current member access is an access to any of the size properties in the available - // resource types (either buffer or texture types), then rewrite the subtree to transform the - // property access into an invocation of an autogenerated static helper method to get the target - // dimension for the buffer in use. The helper method is added to the list of static helpers. - if (operation is IPropertyReferenceOperation propertyOperation && - HlslKnownProperties.TryGetAccessorRankAndAxis(propertyOperation.Property.GetFullMetadataName(), out int rank, out int axis)) - { - IMethodSymbol key = propertyOperation.Property.GetMethod!; - - if (!this.staticMethods.TryGetValue(key, out MethodDeclarationSyntax? methodSyntax)) + if (descriptor is not null) { - INamedTypeSymbol resourceType = (INamedTypeSymbol)SemanticModel.For(node).GetTypeInfo(node.Expression).Type!; - string resourceName = HlslKnownTypes.GetMappedName(resourceType); - - // Create a static method to get a specified dimension for a target resource type. - // The method will automatically create the necessary number of temporary variables - // depending on the rank of the input resource (eg. 2 for Texture2D resources). - // For instance, this code will generate the following tree for Texture2D.Width: - // - // static int __get_Dimension0(Texture2D texture) - // { - // uint _0, _1; - // texture.GetDimensions(_0, _1); - // - // return _0; - // } - methodSyntax = - MethodDeclaration(PredefinedType(Token(SyntaxKind.IntKeyword)), $"__get_Dimension{axis}") - .AddModifiers(Token(SyntaxKind.StaticKeyword)) - .AddParameterListParameters( - Parameter(Identifier("resource")) - .WithType(IdentifierName(resourceName))) - .WithBody(Block( - LocalDeclarationStatement( - VariableDeclaration(PredefinedType(Token(SyntaxKind.UIntKeyword))) - .AddVariables(Enumerable.Range(0, rank).Select(static i => VariableDeclarator(Identifier("_" + i))).ToArray())), - ExpressionStatement( - InvocationExpression(MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("resource"), - IdentifierName("GetDimensions"))) - .AddArgumentListArguments(Enumerable.Range(0, rank).Select(static i => Argument(IdentifierName("_" + i))).ToArray())), - ReturnStatement(IdentifierName("_" + axis)))); - - this.staticMethods.Add(key, methodSyntax); + Diagnostics.Add(descriptor, node); } - - return InvocationExpression(IdentifierName(methodSyntax.Identifier)).AddArgumentListArguments(Argument(updatedNode.Expression)); } } - - return updatedNode; } /// - public override SyntaxNode? VisitInvocationExpression(InvocationExpressionSyntax node) + private partial void TrackKnownMethodInvocation(string metadataName) { - var updatedNode = (InvocationExpressionSyntax)base.VisitInvocationExpression(node)!; - - if (SemanticModel.For(node).GetOperation(node) is IInvocationOperation operation && - operation.TargetMethod is IMethodSymbol method && - method.IsStatic) - { - // If the invocation consists of invoking a static method that has a direct - // mapping to HLSL, rewrite the expression in the current invocation node. - // For instance: Math.Abs(expr) => abs(expr). - if (HlslKnownMethods.TryGetMappedName(method.GetFullMetadataName(), out string? mapping)) - { - return updatedNode.WithExpression(ParseExpression(mapping!)); - } - - // Update the name if the target is a local function. The exact schema for the - // updated name is detailed in the override handling the local function statement. - if (method.MethodKind == MethodKind.LocalFunction) - { - var functionIdentifier = $"__{this.currentMethod!.Identifier.Text}__{method.Name}"; - - return updatedNode.WithExpression(ParseExpression(functionIdentifier)); - } - - // If the method is an external static method, import and rewrite it as well. - // This assumes that the target method is actually part of the same compilation. - // We need to check the declaring type to avoid rewriting static methods in the shader - // type as well, as they will be processed by the generator in a different path. - if (!SymbolEqualityComparer.Default.Equals(this.shaderType, method.ContainingType)) - { - var methodIdentifier = method.GetFullMetadataName().ToHlslIdentifierName(); - - if (!this.staticMethods.ContainsKey(method)) - { - if (method.DeclaringSyntaxReferences.FirstOrDefault()?.GetSyntax() is not MethodDeclarationSyntax methodNode) - { - Diagnostics.Add(InvalidMethodCall, node, method); - - return updatedNode; - } - - ShaderSourceRewriter shaderSourceRewriter = new(SemanticModel, DiscoveredTypes, this.staticMethods, ConstantDefinitions, Diagnostics); - MethodDeclarationSyntax processedMethod = shaderSourceRewriter.Visit(methodNode)!.NormalizeWhitespace(eol: "\n").WithoutTrivia(); - - this.staticMethods.Add(method, processedMethod.WithIdentifier(Identifier(methodIdentifier))); - } - - return updatedNode.WithExpression(ParseExpression(methodIdentifier)); - } - } - - return updatedNode; - } - - /// - public override SyntaxNode? VisitArgument(ArgumentSyntax node) - { - var updatedNode = (ArgumentSyntax)base.VisitArgument(node)!; - - // Strip the ref keywords from arguments - updatedNode = updatedNode.WithRefKindKeyword(Token(SyntaxKind.None)); - - // Track and rewrite the discarded declaration - if (SemanticModel.For(node).GetOperation(node.Expression) is IDiscardOperation operation) - { - TypeSyntax typeSyntax = ParseTypeName(HlslKnownTypes.TrackType(operation.Type!, DiscoveredTypes)); - string identifier = $"__implicit{this.implicitVariables.Count}"; - - // Add the variable to the list of implicit declarations - this.implicitVariables.Add(VariableDeclaration(typeSyntax).AddVariables(VariableDeclarator(identifier))); - - return updatedNode.WithExpression(IdentifierName(identifier)); - } - - return updatedNode; + // No special tracking is needed for DX12 compute shaders } } diff --git a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/StaticFieldRewriter.cs b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/StaticFieldRewriter.cs index 939f8b79..30aa28fc 100644 --- a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/StaticFieldRewriter.cs +++ b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/StaticFieldRewriter.cs @@ -1,138 +1,43 @@ using System; -using System.Collections.Generic; -using System.Collections.Immutable; -using System.Globalization; 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.SourceGenerators.Diagnostics.DiagnosticDescriptors; -using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; +using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors; -namespace ComputeSharp.SourceGenerators.SyntaxRewriters; +namespace ComputeSharp.SourceGeneration.SyntaxRewriters; -/// -/// A custom type that processes C# static field to convert to HLSL static fields (possibly constant). -/// -internal sealed class StaticFieldRewriter : HlslSourceRewriter +/// +partial class StaticFieldRewriter { - /// - /// 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. - public StaticFieldRewriter( - SemanticModelProvider semanticModel, - ICollection discoveredTypes, - IDictionary constantDefinitions, - ImmutableArray.Builder diagnostics) - : base(semanticModel, discoveredTypes, constantDefinitions, diagnostics) + /// + private partial void TrackKnownPropertyAccess(IMemberReferenceOperation operation, MemberAccessExpressionSyntax node) { - } - - /// - public ExpressionSyntax? Visit(VariableDeclaratorSyntax? node) - { - if (node?.Initializer is EqualsValueClauseSyntax fieldInitializer) + if (operation.Member.IsStatic) { - return ((EqualsValueClauseSyntax)Visit(fieldInitializer))!.Value; - } + string typeName = operation.Member.ContainingType.GetFullMetadataName(); - return null; + // Special dispatch types are not supported from static constants + DiagnosticDescriptor? descriptor = typeName switch + { + _ when typeName == typeof(ThreadIds).FullName || typeName == typeof(ThreadIds.Normalized).FullName => InvalidThreadIdsUsage, + _ when typeName == typeof(GroupIds).FullName => InvalidGroupIdsUsage, + _ when typeName == typeof(GroupSize).FullName => InvalidGroupSizeUsage, + _ when typeName == typeof(GridIds).FullName => InvalidGridIdsUsage, + _ when typeName == typeof(DispatchSize).FullName => InvalidDispatchSizeUsage, + _ => null + }; + + if (descriptor is not null) + { + Diagnostics.Add(descriptor, node); + } + } } /// - public override SyntaxNode VisitMemberAccessExpression(MemberAccessExpressionSyntax node) + private partial void TrackKnownMethodInvocation(string metadataName) { - var updatedNode = (MemberAccessExpressionSyntax)base.VisitMemberAccessExpression(node)!; - - if (node.IsKind(SyntaxKind.SimpleMemberAccessExpression) && - SemanticModel.For(node).GetOperation(node) is IMemberReferenceOperation operation) - { - // Track and replace constants - if (operation is IFieldReferenceOperation fieldOperation && - fieldOperation.Field.IsConst && - fieldOperation.Type!.TypeKind != TypeKind.Enum) - { - if (HlslKnownFields.TryGetMappedName(fieldOperation.Member.ToDisplayString(), out string? constantLiteral)) - { - return ParseExpression(constantLiteral!); - } - - ConstantDefinitions[fieldOperation.Field] = ((IFormattable)fieldOperation.Field.ConstantValue!).ToString(null, CultureInfo.InvariantCulture); - - var ownerTypeName = ((INamedTypeSymbol)fieldOperation.Field.ContainingSymbol).ToDisplayString().ToHlslIdentifierName(); - var constantName = $"__{ownerTypeName}__{fieldOperation.Field.Name}"; - - return IdentifierName(constantName); - } - - if (HlslKnownProperties.TryGetMappedName(operation.Member.ToDisplayString(), out string? mapping)) - { - if (operation.Member.IsStatic) - { - string typeName = operation.Member.ContainingType.GetFullMetadataName(); - - // Special dispatch types are not supported from static constants - DiagnosticDescriptor? descriptor = typeName switch - { - _ when typeName == typeof(ThreadIds).FullName || typeName == typeof(ThreadIds.Normalized).FullName => InvalidThreadIdsUsage, - _ when typeName == typeof(GroupIds).FullName => InvalidGroupIdsUsage, - _ when typeName == typeof(GroupSize).FullName => InvalidGroupSizeUsage, - _ when typeName == typeof(GridIds).FullName => InvalidGridIdsUsage, - _ when typeName == typeof(DispatchSize).FullName => InvalidDispatchSizeUsage, - _ => null - }; - - if (descriptor is not null) - { - Diagnostics.Add(descriptor, node); - } - } - - // Rewrite static and instance mapped members - return operation.Member.IsStatic switch - { - true => ParseExpression(mapping!), - false => updatedNode.WithName(IdentifierName(mapping!)) - }; - } - } - - return updatedNode; - } - - /// - public override SyntaxNode? VisitInvocationExpression(InvocationExpressionSyntax node) - { - var updatedNode = (InvocationExpressionSyntax)base.VisitInvocationExpression(node)!; - - if (SemanticModel.For(node).GetOperation(node) is IInvocationOperation operation && - operation.TargetMethod is IMethodSymbol method && - method.IsStatic) - { - // Rewrite HLSL intrinsic methods - if (HlslKnownMethods.TryGetMappedName(method.GetFullMetadataName(), out string? mapping)) - { - return updatedNode.WithExpression(ParseExpression(mapping!)); - } - } - - return updatedNode; - } - - /// - public override SyntaxNode? VisitArgument(ArgumentSyntax node) - { - var updatedNode = (ArgumentSyntax)base.VisitArgument(node)!; - - updatedNode = updatedNode.WithRefKindKeyword(Token(SyntaxKind.None)); - - return updatedNode; + // No special tracking is needed for DX12 compute shaders } }