Added initial SG syntax rewriter

このコミットが含まれているのは:
Sergio Pedri committed 2020-11-25 01:16:55 +01:00
1 親 1df9356ea0
コミット 9a220c1ada
3ファイル変更
+220 -7

検索条件に一致するファイルはありません

+64
ファイルの表示
@@ -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
{
/// <summary>
/// A <see langword="class"/> with some extension methods for C# syntax nodes.
/// </summary>
internal static class SyntaxNodeExtensions
{
private static readonly SymbolDisplayFormat FullyQualifiedWithoutGlobalFormat = new(
globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted,
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters);
/// <summary>
/// Checks a <see cref="SyntaxNode"/> value and replaces the value type to be HLSL compatible, if needed.
/// </summary>
/// <typeparam name="TRoot">The type of the input <see cref="SyntaxNode"/> instance.</typeparam>
/// <param name="node">The input <see cref="SyntaxNode"/> to check and modify if needed.</param>
/// <param name="targetType">The target <see cref="TypeSyntax"/> node to replace.</param>
/// <param name="sourceType">The source <see cref="TypeSyntax"/> to use to get type into from <paramref name="semanticModel"/>.</param>
/// <param name="semanticModel">The <see cref="SemanticModel"/> instance with info on the input tree.</param>
/// <returns>A <see cref="SyntaxNode"/> instance that represents a type compatible with HLSL.</returns>
[Pure]
public static TRoot ReplaceType<TRoot>(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;
}
/// <summary>
/// Checks a <see cref="SyntaxNode"/> value and replaces the value type to be HLSL compatible, if needed.
/// </summary>
/// <typeparam name="TRoot">The type of the input <see cref="SyntaxNode"/> instance.</typeparam>
/// <param name="node">The input <see cref="SyntaxNode"/> to check and modify if needed.</param>
/// <param name="type">The <see cref="TypeSyntax"/> to use for the input node.</param>
/// <returns>A <see cref="SyntaxNode"/> instance that represents a type compatible with HLSL.</returns>
[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);
}
}
}
+101 -7
ファイルの表示
@@ -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
}
}
}
/// <summary>
/// A custom <see cref="CSharpSyntaxRewriter"/> type that processes C# methods to convert to HLSL compliant code.
/// </summary>
private sealed class ShaderSourceRewriter : CSharpSyntaxRewriter
{
/// <summary>
/// The <see cref="SemanticModel"/> instance with semantic info on the target syntax tree.
/// </summary>
private readonly SemanticModel semanticModel;
/// <summary>
/// Creates a new <see cref="ShaderSourceRewriter"/> instance with the specified parameters.
/// </summary>
/// <param name="semanticModel">The <see cref="SemanticModel"/> instance for the target syntax tree.</param>
public ShaderSourceRewriter(SemanticModel semanticModel)
{
this.semanticModel = semanticModel;
}
/// <inheritdoc/>
public override SyntaxNode VisitParameter(ParameterSyntax node)
{
var updatedNode = (ParameterSyntax)base.VisitParameter(node)!;
return updatedNode
.WithAttributeLists(default)
.ReplaceType(updatedNode.Type!, node.Type!, this.semanticModel);
}
/// <inheritdoc/>
public override SyntaxNode VisitCastExpression(CastExpressionSyntax node)
{
var updatedNode = (CastExpressionSyntax)base.VisitCastExpression(node)!;
return updatedNode.ReplaceType(updatedNode.Type, node.Type, this.semanticModel);
}
/// <inheritdoc/>
public override SyntaxNode VisitLocalDeclarationStatement(LocalDeclarationStatementSyntax node)
{
var updatedNode = ((LocalDeclarationStatementSyntax)base.VisitLocalDeclarationStatement(node)!);
return updatedNode.ReplaceType(updatedNode.Declaration.Type, node.Declaration.Type, this.semanticModel);
}
/// <inheritdoc/>
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);
}
/// <inheritdoc/>
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)));
}
/// <inheritdoc/>
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;
}
}
}
}
+55
ファイルの表示
@@ -0,0 +1,55 @@
using System.Collections.Generic;
using System.Numerics;
namespace ComputeSharp.SourceGenerators.Mappings
{
/// <summary>
/// A <see langword="class"/> that contains and maps known HLSL type names to common .NET types.
/// </summary>
internal static class HlslKnownTypes
{
/// <summary>
/// The mapping of supported known types to HLSL types.
/// </summary>
private static readonly IReadOnlyDictionary<string, string> KnownTypes = new Dictionary<string, string>
{
[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<T>"] = "StructuredBuffer",
["ComputeSharp.ReadWriteBuffer<T>"] = "RWStructuredBuffer"
};
/// <summary>
/// Gets the mapped HLSL-compatible type name for the input type name.
/// </summary>
/// <param name="name">The input type name to map.</param>
/// <returns>The HLSL-compatible type name that can be used in an HLSL shader.</returns>
public static bool TryGetMappedName(string originalName, out string? mappedName)
{
return KnownTypes.TryGetValue(originalName, out mappedName);
}
}
}