From 9a220c1adaf1dc538f1321ba38b0cff541155684 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 24 Nov 2020 14:06:05 +0100 Subject: [PATCH] Added initial SG syntax rewriter --- .../Extensions/SyntaxNodeExtensions.cs | 64 +++++++++++ .../IComputeShaderSourceAttributeGenerator.cs | 108 ++++++++++++++++-- .../Mappings/HlslKnownTypes.cs | 55 +++++++++ 3 files changed, 220 insertions(+), 7 deletions(-) create mode 100644 src/ComputeSharp.SourceGenerators/Extensions/SyntaxNodeExtensions.cs create mode 100644 src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs diff --git a/src/ComputeSharp.SourceGenerators/Extensions/SyntaxNodeExtensions.cs b/src/ComputeSharp.SourceGenerators/Extensions/SyntaxNodeExtensions.cs new file mode 100644 index 00000000..24d9371a --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/Extensions/SyntaxNodeExtensions.cs @@ -0,0 +1,64 @@ +using System.Diagnostics.Contracts; +using ComputeSharp.SourceGenerators.Mappings; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; + +namespace ComputeSharp.SourceGenerators.Extensions +{ + /// + /// A with some extension methods for C# syntax nodes. + /// + internal static class SyntaxNodeExtensions + { + private static readonly SymbolDisplayFormat FullyQualifiedWithoutGlobalFormat = new( + globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted, + typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, + genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters); + + /// + /// Checks a value and replaces the value type to be HLSL compatible, if needed. + /// + /// The type of the input instance. + /// The input to check and modify if needed. + /// The target node to replace. + /// The source to use to get type into from . + /// The instance with info on the input tree. + /// A instance that represents a type compatible with HLSL. + [Pure] + public static TRoot ReplaceType(this TRoot node, TypeSyntax targetType, TypeSyntax sourceType, SemanticModel semanticModel) + where TRoot : SyntaxNode + { + if (semanticModel.GetTypeInfo(sourceType).Type is ITypeSymbol typeSymbol && + HlslKnownTypes.TryGetMappedName(typeSymbol.ToDisplayString(FullyQualifiedWithoutGlobalFormat), out string? mappedName)) + { + TypeSyntax newType = ParseTypeName(mappedName!); + + return node.ReplaceNode(targetType, newType); + } + + return node; + } + + /// + /// Checks a value and replaces the value type to be HLSL compatible, if needed. + /// + /// The type of the input instance. + /// The input to check and modify if needed. + /// The to use for the input node. + /// A instance that represents a type compatible with HLSL. + [Pure] + public static TypeSyntax ReplaceType(this LiteralExpressionSyntax node, SemanticModel semanticModel) + { + ITypeSymbol typeSymbol = semanticModel.GetTypeInfo(node).Type!; + string typeName = typeSymbol.ToDisplayString(FullyQualifiedWithoutGlobalFormat); + + if (HlslKnownTypes.TryGetMappedName(typeName, out string? mappedName)) + { + return ParseTypeName(mappedName!); + } + + return ParseTypeName(typeName); + } + } +} diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceAttributeGenerator.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceAttributeGenerator.cs index d40d0d64..cc89734d 100644 --- a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceAttributeGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceAttributeGenerator.cs @@ -48,12 +48,19 @@ namespace ComputeSharp.SourceGenerators IMethodSymbol methodDeclarationSymbol = semanticModel.GetDeclaredSymbol(methodDeclaration)!; // Extract the source from either a block or an expression body - var methodSource = ((methodDeclaration.Body, methodDeclaration.ExpressionBody) switch - { - (BlockSyntax block, _) => block, - (_, ArrowExpressionClauseSyntax arrow) => Block(ExpressionStatement(arrow.Expression)), - _ => Block() - }).NormalizeWhitespace().ToFullString(); + var methodWithBlockBody = methodDeclaration.WithBody( + (methodDeclaration.Body, methodDeclaration.ExpressionBody) switch + { + (BlockSyntax block, _) => block, + (_, ArrowExpressionClauseSyntax arrow) => Block(ExpressionStatement(arrow.Expression)), + _ => Block() + }); + + // Rewrite the method syntax tree + var processedMethod = new ShaderSourceRewriter(semanticModel) + .Visit(methodWithBlockBody) + .NormalizeWhitespace() + .ToFullString(); // Create the compilation unit with the source attribute var source = @@ -62,7 +69,7 @@ namespace ComputeSharp.SourceGenerators Attribute(IdentifierName("ComputeSharp.IComputeShaderSource")).AddArgumentListArguments( AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(structFullName))), AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(methodDeclarationSymbol.Name))), - AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(methodSource)))))) + AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(processedMethod)))))) .WithOpenBracketToken(Token(TriviaList(Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), SyntaxKind.OpenBracketToken, TriviaList())) .WithTarget(AttributeTargetSpecifier(Token(SyntaxKind.AssemblyKeyword)))) .NormalizeWhitespace() @@ -75,6 +82,93 @@ namespace ComputeSharp.SourceGenerators } } } + + /// + /// A custom type that processes C# methods to convert to HLSL compliant code. + /// + private sealed class ShaderSourceRewriter : CSharpSyntaxRewriter + { + /// + /// The instance with semantic info on the target syntax tree. + /// + private readonly SemanticModel semanticModel; + + /// + /// Creates a new instance with the specified parameters. + /// + /// The instance for the target syntax tree. + public ShaderSourceRewriter(SemanticModel semanticModel) + { + this.semanticModel = semanticModel; + } + + /// + public override SyntaxNode VisitParameter(ParameterSyntax node) + { + var updatedNode = (ParameterSyntax)base.VisitParameter(node)!; + + return updatedNode + .WithAttributeLists(default) + .ReplaceType(updatedNode.Type!, node.Type!, this.semanticModel); + } + + /// + public override SyntaxNode VisitCastExpression(CastExpressionSyntax node) + { + var updatedNode = (CastExpressionSyntax)base.VisitCastExpression(node)!; + + return updatedNode.ReplaceType(updatedNode.Type, node.Type, this.semanticModel); + } + + /// + public override SyntaxNode VisitLocalDeclarationStatement(LocalDeclarationStatementSyntax node) + { + var updatedNode = ((LocalDeclarationStatementSyntax)base.VisitLocalDeclarationStatement(node)!); + + return updatedNode.ReplaceType(updatedNode.Declaration.Type, node.Declaration.Type, this.semanticModel); + } + + /// + public override SyntaxNode VisitObjectCreationExpression(ObjectCreationExpressionSyntax node) + { + var updatedNode = (ObjectCreationExpressionSyntax)base.VisitObjectCreationExpression(node)!; + + updatedNode = updatedNode.ReplaceType(updatedNode.Type, node.Type, this.semanticModel); + + // 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))); + } + + return InvocationExpression(updatedNode.Type, updatedNode.ArgumentList); + } + + /// + public override SyntaxNode VisitDefaultExpression(DefaultExpressionSyntax node) + { + var updatedNode = (DefaultExpressionSyntax)base.VisitDefaultExpression(node)!; + + updatedNode = updatedNode.ReplaceType(updatedNode.Type, node.Type, this.semanticModel); + + // A default expression becomes (T)0 in HLSL + return CastExpression(updatedNode.Type, LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0))); + } + + /// + public override SyntaxNode? VisitLiteralExpression(LiteralExpressionSyntax node) + { + node = ((LiteralExpressionSyntax)base.VisitLiteralExpression(node)!); + + if (node.IsKind(SyntaxKind.DefaultLiteralExpression)) + { + // Same HLSL-style expression in the form (T)0 + return CastExpression(node.ReplaceType(this.semanticModel), LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0))); + } + + return node; + } + } } } diff --git a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs new file mode 100644 index 00000000..57530b71 --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs @@ -0,0 +1,55 @@ +using System.Collections.Generic; +using System.Numerics; + +namespace ComputeSharp.SourceGenerators.Mappings +{ + /// + /// A that contains and maps known HLSL type names to common .NET types. + /// + internal static class HlslKnownTypes + { + /// + /// The mapping of supported known types to HLSL types. + /// + private static readonly IReadOnlyDictionary KnownTypes = new Dictionary + { + [typeof(bool).FullName!] = "bool", + ["ComputeSharp.Bool"] = "bool", + ["ComputeSharp.Bool2"] = "bool2", + ["ComputeSharp.Bool3"] = "bool3", + ["ComputeSharp.Bool4"] = "bool4", + [typeof(int).FullName!] = "int", + ["ComputeSharp.Int2"] = "int2", + ["ComputeSharp.Int3"] = "int3", + ["ComputeSharp.Int4"] = "int4", + [typeof(uint).FullName!] = "uint", + ["ComputeSharp.UInt2"] = "uint2", + ["ComputeSharp.UInt3"] = "uint3", + ["ComputeSharp.UInt4"] = "uint4", + [typeof(float).FullName!] = "float", + ["ComputeSharp.Float2"] = "float2", + ["ComputeSharp.Float3"] = "float3", + ["ComputeSharp.Float4"] = "float4", + [typeof(Vector2).FullName] = "float2", + [typeof(Vector3).FullName] = "float3", + [typeof(Vector4).FullName] = "float4", + [typeof(double).FullName!] = "double", + ["ComputeSharp.Double2"] = "double2", + ["ComputeSharp.Double3"] = "double3", + ["ComputeSharp.Double4"] = "double4", + ["ComputeSharp.ThreadIds"] = "uint3", + ["ComputeSharp.ReadOnlyBuffer"] = "StructuredBuffer", + ["ComputeSharp.ReadWriteBuffer"] = "RWStructuredBuffer" + }; + + /// + /// Gets the mapped HLSL-compatible type name for the input type name. + /// + /// The input type name to map. + /// The HLSL-compatible type name that can be used in an HLSL shader. + public static bool TryGetMappedName(string originalName, out string? mappedName) + { + return KnownTypes.TryGetValue(originalName, out mappedName); + } + } +}