diff --git a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.cs b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.cs
new file mode 100644
index 00000000..20b225e9
--- /dev/null
+++ b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.cs
@@ -0,0 +1,496 @@
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Linq;
+using ComputeSharp.SourceGenerators.Diagnostics;
+using ComputeSharp.SourceGenerators.Extensions;
+using ComputeSharp.SourceGenerators.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;
+
+namespace ComputeSharp.SourceGenerators.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 class HlslSourceRewriter : CSharpSyntaxRewriter
+ {
+ ///
+ /// 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 current generator context in use.
+ protected HlslSourceRewriter(
+ SemanticModel semanticModel,
+ ICollection discoveredTypes,
+ IDictionary constantDefinitions,
+ GeneratorExecutionContext context)
+ {
+ SemanticModel = semanticModel;
+ DiscoveredTypes = discoveredTypes;
+ ConstantDefinitions = constantDefinitions;
+ Context = context;
+ }
+
+ ///
+ /// The instance with semantic info on the target syntax tree.
+ ///
+ protected readonly SemanticModel SemanticModel;
+
+ ///
+ /// The collection of discovered custom types.
+ ///
+ protected readonly ICollection DiscoveredTypes;
+
+ ///
+ /// The collection of discovered constant definitions.
+ ///
+ protected readonly IDictionary ConstantDefinitions;
+
+ ///
+ /// The current generator context in use.
+ ///
+ protected readonly GeneratorExecutionContext Context;
+
+ ///
+ public override SyntaxNode VisitCastExpression(CastExpressionSyntax node)
+ {
+ var updatedNode = (CastExpressionSyntax)base.VisitCastExpression(node)!;
+
+ return updatedNode.ReplaceAndTrackType(updatedNode.Type, node.Type, SemanticModel, DiscoveredTypes);
+ }
+
+ ///
+ public override SyntaxNode VisitObjectCreationExpression(ObjectCreationExpressionSyntax node)
+ {
+ var updatedNode = (ObjectCreationExpressionSyntax)base.VisitObjectCreationExpression(node)!;
+
+ if (SemanticModel.GetTypeInfo(node).Type is ITypeSymbol { IsUnmanagedType: false } type)
+ {
+ Context.ReportDiagnostic(InvalidObjectCreationExpression, node, type);
+ }
+
+ updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.Type, node, SemanticModel, 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.GetTypeInfo(node).Type is ITypeSymbol matrixType &&
+ HlslKnownTypes.IsMatrixType(matrixType.GetFullMetadataName()))
+ {
+ for (int i = 0; i < node.ArgumentList!.Arguments.Count; i++)
+ {
+ IArgumentOperation argumentOperation = (IArgumentOperation)SemanticModel.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.GetTypeInfo(node).Type is ITypeSymbol { IsUnmanagedType: false } type)
+ {
+ Context.ReportDiagnostic(InvalidObjectCreationExpression, node, type);
+ }
+
+ TypeSyntax explicitType = IdentifierName("").ReplaceAndTrackType(node, SemanticModel, 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.GetTypeInfo(node).Type is ITypeSymbol matrixType &&
+ HlslKnownTypes.IsMatrixType(matrixType.GetFullMetadataName()))
+ {
+ for (int i = 0; i < node.ArgumentList.Arguments.Count; i++)
+ {
+ IArgumentOperation argumentOperation = (IArgumentOperation)SemanticModel.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, 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, 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.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.GetFullMetadataName().Equals(typeof(float).FullName))
+ {
+ string literal = updatedNode.Token.ValueText;
+
+ if (!literal.Contains('.')) literal += ".0";
+
+ return updatedNode.WithToken(Literal(literal, 0f));
+ }
+ else if (type.GetFullMetadataName().Equals(typeof(double).FullName))
+ {
+ return updatedNode.WithToken(Literal(updatedNode.Token.ValueText + "L", 0d));
+ }
+ }
+ else if (updatedNode.IsKind(SyntaxKind.StringLiteralExpression))
+ {
+ Context.ReportDiagnostic(StringLiteralExpression, node);
+ }
+
+ return updatedNode;
+ }
+
+ ///
+ public override SyntaxNode? VisitElementAccessExpression(ElementAccessExpressionSyntax node)
+ {
+ var updatedNode = (ElementAccessExpressionSyntax)base.VisitElementAccessExpression(node)!;
+
+ if (SemanticModel.GetOperation(node) is IPropertyReferenceOperation operation)
+ {
+ string propertyName = operation.Property.GetFullMetadataName();
+
+ // Rewrite texture resource indices taking vectors into individual indices as per HLSL spec.
+ // For instance: texture[ThreadIds.XY] will be rewritten as texture[ThreadIds.X, ThreadIds.Y].
+ if (HlslKnownMembers.TryGetMappedResourceIndexerTypeName(propertyName, out string? mapping))
+ {
+ var index = InvocationExpression(IdentifierName(mapping!), ArgumentList(updatedNode.ArgumentList.Arguments));
+
+ return updatedNode.WithArgumentList(BracketedArgumentList(SingletonSeparatedList(Argument(index))));
+ }
+
+ // 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 (HlslKnownMembers.IsKnownMatrixIndexer(propertyName))
+ {
+ bool isValid = true;
+
+ // Validate the arguments
+ foreach (ArgumentSyntax argument in node.ArgumentList.Arguments)
+ {
+ if (SemanticModel.GetOperation(argument.Expression) is not IFieldReferenceOperation fieldReference ||
+ !HlslKnownMembers.IsKnownMatrixIndex(fieldReference.Field.GetFullMetadataName()))
+ {
+ Context.ReportDiagnostic(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.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.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().Replace(".", "__");
+ var constantName = $"__{ownerTypeName}__{operation.Field.Name}";
+
+ return IdentifierName(constantName);
+ }
+
+ return updatedNode;
+ }
+
+ ///
+ public override SyntaxNode? VisitAnonymousObjectCreationExpression(AnonymousObjectCreationExpressionSyntax node)
+ {
+ var updatedNode = (AnonymousObjectCreationExpressionSyntax)base.VisitAnonymousObjectCreationExpression(node)!;
+
+ Context.ReportDiagnostic(DiagnosticDescriptors.AnonymousObjectCreationExpression, node);
+
+ return updatedNode;
+ }
+
+ ///
+ public override SyntaxNode? VisitAwaitExpression(AwaitExpressionSyntax node)
+ {
+ Context.ReportDiagnostic(DiagnosticDescriptors.AwaitExpression, node);
+
+ return base.VisitAwaitExpression(node);
+ }
+
+ ///
+ public override SyntaxNode? VisitCheckedExpression(CheckedExpressionSyntax node)
+ {
+ Context.ReportDiagnostic(DiagnosticDescriptors.CheckedExpression, node);
+
+ return base.VisitCheckedExpression(node);
+ }
+
+ ///
+ public override SyntaxNode? VisitCheckedStatement(CheckedStatementSyntax node)
+ {
+ Context.ReportDiagnostic(DiagnosticDescriptors.CheckedStatement, node);
+
+ return base.VisitCheckedStatement(node);
+ }
+
+ ///
+ public override SyntaxNode? VisitFixedStatement(FixedStatementSyntax node)
+ {
+ Context.ReportDiagnostic(DiagnosticDescriptors.FixedStatement, node);
+
+ return base.VisitFixedStatement(node);
+ }
+
+ ///
+ public override SyntaxNode? VisitForEachStatement(ForEachStatementSyntax node)
+ {
+ Context.ReportDiagnostic(DiagnosticDescriptors.ForEachStatement, node);
+
+ return base.VisitForEachStatement(node);
+ }
+
+ ///
+ public override SyntaxNode? VisitForEachVariableStatement(ForEachVariableStatementSyntax node)
+ {
+ Context.ReportDiagnostic(DiagnosticDescriptors.ForEachStatement, node);
+
+ return base.VisitForEachVariableStatement(node);
+ }
+
+ ///
+ public override SyntaxNode? VisitLockStatement(LockStatementSyntax node)
+ {
+ Context.ReportDiagnostic(DiagnosticDescriptors.LockStatement, node);
+
+ return base.VisitLockStatement(node);
+ }
+
+ ///
+ public override SyntaxNode? VisitQueryExpression(QueryExpressionSyntax node)
+ {
+ Context.ReportDiagnostic(DiagnosticDescriptors.QueryExpression, node);
+
+ return base.VisitQueryExpression(node);
+ }
+
+ ///
+ public override SyntaxNode? VisitRangeExpression(RangeExpressionSyntax node)
+ {
+ Context.ReportDiagnostic(DiagnosticDescriptors.RangeExpression, node);
+
+ return base.VisitRangeExpression(node);
+ }
+
+ ///
+ public override SyntaxNode? VisitRecursivePattern(RecursivePatternSyntax node)
+ {
+ Context.ReportDiagnostic(DiagnosticDescriptors.RecursivePattern, node);
+
+ return base.VisitRecursivePattern(node);
+ }
+
+ ///
+ public override SyntaxNode? VisitRefType(RefTypeSyntax node)
+ {
+ Context.ReportDiagnostic(DiagnosticDescriptors.RefType, node);
+
+ return base.VisitRefType(node);
+ }
+
+ ///
+ public override SyntaxNode? VisitRelationalPattern(RelationalPatternSyntax node)
+ {
+ Context.ReportDiagnostic(DiagnosticDescriptors.RelationalPattern, node);
+
+ return base.VisitRelationalPattern(node);
+ }
+
+ ///
+ public override SyntaxNode? VisitSizeOfExpression(SizeOfExpressionSyntax node)
+ {
+ Context.ReportDiagnostic(DiagnosticDescriptors.SizeOfExpression, node);
+
+ return base.VisitSizeOfExpression(node);
+ }
+
+ ///
+ public override SyntaxNode? VisitStackAllocArrayCreationExpression(StackAllocArrayCreationExpressionSyntax node)
+ {
+ Context.ReportDiagnostic(DiagnosticDescriptors.StackAllocArrayCreationExpression, node);
+
+ return base.VisitStackAllocArrayCreationExpression(node);
+ }
+
+ ///
+ public override SyntaxNode? VisitThrowExpression(ThrowExpressionSyntax node)
+ {
+ Context.ReportDiagnostic(ThrowExpressionOrStatement, node);
+
+ return base.VisitThrowExpression(node);
+ }
+
+ ///
+ public override SyntaxNode? VisitThrowStatement(ThrowStatementSyntax node)
+ {
+ Context.ReportDiagnostic(ThrowExpressionOrStatement, node);
+
+ return base.VisitThrowStatement(node);
+ }
+
+ ///
+ public override SyntaxNode? VisitTryStatement(TryStatementSyntax node)
+ {
+ Context.ReportDiagnostic(DiagnosticDescriptors.TryStatement, node);
+
+ return base.VisitTryStatement(node);
+ }
+
+ ///
+ public override SyntaxNode? VisitTupleType(TupleTypeSyntax node)
+ {
+ Context.ReportDiagnostic(DiagnosticDescriptors.TupleType, node);
+
+ return base.VisitTupleType(node);
+ }
+
+ ///
+ public override SyntaxNode? VisitUsingStatement(UsingStatementSyntax node)
+ {
+ Context.ReportDiagnostic(UsingStatementOrDeclaration, node);
+
+ return base.VisitUsingStatement(node);
+ }
+
+ ///
+ public override SyntaxNode? VisitVariableDeclarator(VariableDeclaratorSyntax node)
+ {
+ var updatedNode = (VariableDeclaratorSyntax)base.VisitVariableDeclarator(node)!;
+
+ if (node.Initializer is null &&
+ node.Parent is VariableDeclarationSyntax declaration &&
+ SemanticModel.GetTypeInfo(declaration.Type).Type is ITypeSymbol { IsUnmanagedType: false } type)
+ {
+ Context.ReportDiagnostic(InvalidObjectDeclaration, node, type);
+ }
+
+ return updatedNode;
+ }
+
+ ///
+ public override SyntaxNode? VisitYieldStatement(YieldStatementSyntax node)
+ {
+ Context.ReportDiagnostic(DiagnosticDescriptors.YieldStatement, node);
+
+ return base.VisitYieldStatement(node);
+ }
+
+ ///
+ public override SyntaxNode? VisitFunctionPointerType(FunctionPointerTypeSyntax node)
+ {
+ Context.ReportDiagnostic(FunctionPointer, node);
+
+ return base.VisitFunctionPointerType(node);
+ }
+
+ ///
+ public override SyntaxNode? VisitPointerType(PointerTypeSyntax node)
+ {
+ Context.ReportDiagnostic(DiagnosticDescriptors.PointerType, node);
+
+ return base.VisitPointerType(node);
+ }
+
+ ///
+ public override SyntaxNode? VisitUnsafeStatement(UnsafeStatementSyntax node)
+ {
+ Context.ReportDiagnostic(DiagnosticDescriptors.UnsafeStatement, node);
+
+ return base.VisitUnsafeStatement(node);
+ }
+
+ ///
+ 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();
+ }
+ }
+}
diff --git a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs
index a36f9e92..3923134e 100644
--- a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs
+++ b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs
@@ -17,33 +17,18 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters
///
/// A custom type that processes C# methods to convert to HLSL compliant code.
///
- internal sealed class ShaderSourceRewriter : CSharpSyntaxRewriter
+ internal sealed class ShaderSourceRewriter : HlslSourceRewriter
{
///
/// The type symbol for the shader type.
///
private readonly INamedTypeSymbol? shaderType;
- ///
- /// The instance with semantic info on the target syntax tree.
- ///
- private readonly SemanticModel semanticModel;
-
- ///
- /// The collection of discovered custom types.
- ///
- private readonly ICollection discoveredTypes;
-
///
/// The collection of discovered static methods.
///
private readonly IDictionary staticMethods;
- ///
- /// The collection of discovered constant definitions.
- ///
- private readonly IDictionary constantDefinitions;
-
///
/// The collection of processed local functions in the current tree.
///
@@ -54,11 +39,6 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters
///
private readonly List implicitVariables;
- ///
- /// The current generator context in use.
- ///
- private readonly GeneratorExecutionContext context;
-
///
/// Whether or not the current instance is processing a shader entry point.
///
@@ -92,15 +72,12 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters
IDictionary constantDefinitions,
GeneratorExecutionContext context,
bool isEntryPoint)
+ : base(semanticModel, discoveredTypes, constantDefinitions, context)
{
this.shaderType = shaderType;
- this.semanticModel = semanticModel;
- this.discoveredTypes = discoveredTypes;
this.staticMethods = staticMethods;
- this.constantDefinitions = constantDefinitions;
this.localFunctions = new();
this.implicitVariables = new();
- this.context = context;
this.isEntryPoint = isEntryPoint;
}
@@ -118,14 +95,11 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters
IDictionary staticMethods,
IDictionary constantDefinitions,
GeneratorExecutionContext context)
+ : base(semanticModel, discoveredTypes, constantDefinitions, context)
{
- this.semanticModel = semanticModel;
- this.discoveredTypes = discoveredTypes;
this.staticMethods = staticMethods;
- this.constantDefinitions = constantDefinitions;
this.implicitVariables = new();
this.localFunctions = new();
- this.context = context;
}
///
@@ -155,16 +129,16 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters
var updatedNode = (MethodDeclarationSyntax?)base.Visit(node)!;
- updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.ReturnType, node!.ReturnType, this.semanticModel, this.discoveredTypes);
+ updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.ReturnType, node!.ReturnType, SemanticModel, DiscoveredTypes);
if (node!.Modifiers.Any(m => m.IsKind(SyntaxKind.AsyncKeyword)))
{
- this.context.ReportDiagnostic(AsyncModifierOnMethodOrFunction, node);
+ Context.ReportDiagnostic(AsyncModifierOnMethodOrFunction, node);
}
if (node!.Modifiers.Any(m => m.IsKind(SyntaxKind.UnsafeKeyword)))
{
- this.context.ReportDiagnostic(UnsafeModifierOnMethodOrFunction, node);
+ Context.ReportDiagnostic(UnsafeModifierOnMethodOrFunction, node);
}
if (updatedNode is not null)
@@ -197,163 +171,21 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters
return updatedNode
.WithAttributeLists(default)
- .ReplaceAndTrackType(updatedNode.Type!, node.Type!, this.semanticModel, this.discoveredTypes)
+ .ReplaceAndTrackType(updatedNode.Type!, node.Type!, SemanticModel, DiscoveredTypes)
.WithModifiers(TokenList(modifier));
}
- ///
- public override SyntaxNode VisitCastExpression(CastExpressionSyntax node)
- {
- var updatedNode = (CastExpressionSyntax)base.VisitCastExpression(node)!;
-
- return updatedNode.ReplaceAndTrackType(updatedNode.Type, node.Type, this.semanticModel, this.discoveredTypes);
- }
-
///
public override SyntaxNode VisitLocalDeclarationStatement(LocalDeclarationStatementSyntax node)
{
var updatedNode = ((LocalDeclarationStatementSyntax)base.VisitLocalDeclarationStatement(node)!);
- if (this.semanticModel.GetOperation(node) is IOperation { Kind: OperationKind.UsingDeclaration })
+ if (SemanticModel.GetOperation(node) is IOperation { Kind: OperationKind.UsingDeclaration })
{
- this.context.ReportDiagnostic(UsingStatementOrDeclaration, node);
+ Context.ReportDiagnostic(UsingStatementOrDeclaration, node);
}
- return updatedNode.ReplaceAndTrackType(updatedNode.Declaration.Type, node.Declaration.Type, this.semanticModel, this.discoveredTypes);
- }
-
- ///
- public override SyntaxNode VisitObjectCreationExpression(ObjectCreationExpressionSyntax node)
- {
- var updatedNode = (ObjectCreationExpressionSyntax)base.VisitObjectCreationExpression(node)!;
-
- if (this.semanticModel.GetTypeInfo(node).Type is ITypeSymbol { IsUnmanagedType: false } type)
- {
- this.context.ReportDiagnostic(InvalidObjectCreationExpression, node, type);
- }
-
- updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.Type, node, this.semanticModel, this.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 (this.semanticModel.GetTypeInfo(node).Type is ITypeSymbol matrixType &&
- HlslKnownTypes.IsMatrixType(matrixType.GetFullMetadataName()))
- {
- for (int i = 0; i < node.ArgumentList!.Arguments.Count; i++)
- {
- IArgumentOperation argumentOperation = (IArgumentOperation)this.semanticModel.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? VisitAnonymousObjectCreationExpression(AnonymousObjectCreationExpressionSyntax node)
- {
- var updatedNode = (AnonymousObjectCreationExpressionSyntax)base.VisitAnonymousObjectCreationExpression(node)!;
-
- this.context.ReportDiagnostic(DiagnosticDescriptors.AnonymousObjectCreationExpression, node);
-
- return updatedNode;
- }
-
- ///
- public override SyntaxNode VisitImplicitObjectCreationExpression(ImplicitObjectCreationExpressionSyntax node)
- {
- var updatedNode = (ImplicitObjectCreationExpressionSyntax)base.VisitImplicitObjectCreationExpression(node)!;
-
- if (this.semanticModel.GetTypeInfo(node).Type is ITypeSymbol { IsUnmanagedType: false } type)
- {
- this.context.ReportDiagnostic(InvalidObjectCreationExpression, node, type);
- }
-
- TypeSyntax explicitType = IdentifierName("").ReplaceAndTrackType(node, this.semanticModel, this.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 (this.semanticModel.GetTypeInfo(node).Type is ITypeSymbol matrixType &&
- HlslKnownTypes.IsMatrixType(matrixType.GetFullMetadataName()))
- {
- for (int i = 0; i < node.ArgumentList.Arguments.Count; i++)
- {
- IArgumentOperation argumentOperation = (IArgumentOperation)this.semanticModel.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, this.semanticModel, this.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(this.semanticModel, this.discoveredTypes);
-
- // Same HLSL-style expression in the form (T)0
- return CastExpression(type, LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0)));
- }
- else if (updatedNode.IsKind(SyntaxKind.NumericLiteralExpression) &&
- this.semanticModel.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.GetFullMetadataName().Equals(typeof(float).FullName))
- {
- string literal = updatedNode.Token.ValueText;
-
- if (!literal.Contains('.')) literal += ".0";
-
- return updatedNode.WithToken(Literal(literal, 0f));
- }
- else if (type.GetFullMetadataName().Equals(typeof(double).FullName))
- {
- return updatedNode.WithToken(Literal(updatedNode.Token.ValueText + "L", 0d));
- }
- }
- else if (updatedNode.IsKind(SyntaxKind.StringLiteralExpression))
- {
- this.context.ReportDiagnostic(StringLiteralExpression, node);
- }
-
- return updatedNode;
+ return updatedNode.ReplaceAndTrackType(updatedNode.Declaration.Type, node.Declaration.Type, SemanticModel, DiscoveredTypes);
}
///
@@ -361,7 +193,7 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters
{
var updatedNode = (DeclarationExpressionSyntax)base.VisitDeclarationExpression(node)!;
- updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.Type, node.Type, this.semanticModel, this.discoveredTypes);
+ updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.Type, node.Type, SemanticModel, DiscoveredTypes);
// Add the variable to the list of implicit declarations
this.implicitVariables.Add(VariableDeclaration(updatedNode.Type).AddVariables(VariableDeclarator(updatedNode.Designation.ToString())));
@@ -390,16 +222,16 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters
.WithAttributeLists(List())
.WithIdentifier(Identifier($"__{this.currentMethod!.Identifier.Text}__{node.Identifier.Text}"));
- updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.ReturnType, node!.ReturnType, this.semanticModel, this.discoveredTypes);
+ updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.ReturnType, node!.ReturnType, SemanticModel, DiscoveredTypes);
if (node.Modifiers.Any(m => m.IsKind(SyntaxKind.AsyncKeyword)))
{
- this.context.ReportDiagnostic(AsyncModifierOnMethodOrFunction, node);
+ Context.ReportDiagnostic(AsyncModifierOnMethodOrFunction, node);
}
if (node.Modifiers.Any(m => m.IsKind(SyntaxKind.UnsafeKeyword)))
{
- this.context.ReportDiagnostic(UnsafeModifierOnMethodOrFunction, node);
+ Context.ReportDiagnostic(UnsafeModifierOnMethodOrFunction, node);
}
this.localFunctionDepth--;
@@ -419,14 +251,14 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters
var updatedNode = (MemberAccessExpressionSyntax)base.VisitMemberAccessExpression(node)!;
if (node.IsKind(SyntaxKind.SimpleMemberAccessExpression) &&
- this.semanticModel.GetOperation(node) is IMemberReferenceOperation operation)
+ SemanticModel.GetOperation(node) is IMemberReferenceOperation operation)
{
// If the member access is a constant, track it and replace the tree with the processed constant name
if (operation is IFieldReferenceOperation fieldOperation &&
fieldOperation.Field.IsConst &&
fieldOperation.Type.TypeKind != TypeKind.Enum)
{
- this.constantDefinitions[fieldOperation.Field] = ((IFormattable)fieldOperation.Field.ConstantValue!).ToString(null, CultureInfo.InvariantCulture);
+ ConstantDefinitions[fieldOperation.Field] = ((IFormattable)fieldOperation.Field.ConstantValue!).ToString(null, CultureInfo.InvariantCulture);
var ownerTypeName = ((INamedTypeSymbol)fieldOperation.Field.ContainingSymbol).ToDisplayString().Replace(".", "__");
var constantName = $"__{ownerTypeName}__{fieldOperation.Field.Name}";
@@ -452,16 +284,16 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters
{
DiagnosticDescriptor? descriptor = typeName switch
{
- _ when typeName == typeof(ThreadIds).FullName => DiagnosticDescriptors.InvalidThreadIdsUsage,
- _ when typeName == typeof(GroupIds).FullName => DiagnosticDescriptors.InvalidGroupIdsUsage,
- _ when typeName == typeof(GroupSize).FullName => DiagnosticDescriptors.InvalidGroupSizeUsage,
- _ when typeName == typeof(WarpIds).FullName => DiagnosticDescriptors.InvalidWarpIdsUsage,
+ _ when typeName == typeof(ThreadIds).FullName => InvalidThreadIdsUsage,
+ _ when typeName == typeof(GroupIds).FullName => InvalidGroupIdsUsage,
+ _ when typeName == typeof(GroupSize).FullName => InvalidGroupSizeUsage,
+ _ when typeName == typeof(WarpIds).FullName => InvalidWarpIdsUsage,
_ => null
};
if (descriptor is not null)
{
- this.context.ReportDiagnostic(descriptor, node);
+ Context.ReportDiagnostic(descriptor, node);
}
}
}
@@ -490,7 +322,7 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters
if (!this.staticMethods.TryGetValue(key, out MethodDeclarationSyntax? methodSyntax))
{
- INamedTypeSymbol resourceType = (INamedTypeSymbol)this.semanticModel.GetTypeInfo(node.Expression).Type!;
+ INamedTypeSymbol resourceType = (INamedTypeSymbol)SemanticModel.GetTypeInfo(node.Expression).Type!;
string resourceName = HlslKnownTypes.GetMappedName(resourceType);
// Create a static method to get a specified dimension for a target resource type.
@@ -538,7 +370,7 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters
{
var updatedNode = (InvocationExpressionSyntax)base.VisitInvocationExpression(node)!;
- if (this.semanticModel.GetOperation(node) is IInvocationOperation operation &&
+ if (SemanticModel.GetOperation(node) is IInvocationOperation operation &&
operation.TargetMethod is IMethodSymbol method &&
method.IsStatic)
{
@@ -569,7 +401,7 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters
if (!this.staticMethods.ContainsKey(method))
{
- ShaderSourceRewriter shaderSourceRewriter = new(this.semanticModel, this.discoveredTypes, this.staticMethods, this.constantDefinitions, this.context);
+ ShaderSourceRewriter shaderSourceRewriter = new(SemanticModel, DiscoveredTypes, this.staticMethods, ConstantDefinitions, Context);
MethodDeclarationSyntax
methodNode = (MethodDeclarationSyntax)method.DeclaringSyntaxReferences[0].GetSyntax(),
processedMethod = shaderSourceRewriter.Visit(methodNode)!.NormalizeWhitespace().WithoutTrivia();
@@ -584,64 +416,6 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters
return updatedNode;
}
- ///
- public override SyntaxNode? VisitElementAccessExpression(ElementAccessExpressionSyntax node)
- {
- var updatedNode = (ElementAccessExpressionSyntax)base.VisitElementAccessExpression(node)!;
-
- if (this.semanticModel.GetOperation(node) is IPropertyReferenceOperation operation)
- {
- string propertyName = operation.Property.GetFullMetadataName();
-
- // Rewrite texture resource indices taking vectors into individual indices as per HLSL spec.
- // For instance: texture[ThreadIds.XY] will be rewritten as texture[ThreadIds.X, ThreadIds.Y].
- if (HlslKnownMembers.TryGetMappedResourceIndexerTypeName(propertyName, out string? mapping))
- {
- var index = InvocationExpression(IdentifierName(mapping!), ArgumentList(updatedNode.ArgumentList.Arguments));
-
- return updatedNode.WithArgumentList(BracketedArgumentList(SingletonSeparatedList(Argument(index))));
- }
-
- // 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 (HlslKnownMembers.IsKnownMatrixIndexer(propertyName))
- {
- bool isValid = true;
-
- // Validate the arguments
- foreach (ArgumentSyntax argument in node.ArgumentList.Arguments)
- {
- if (this.semanticModel.GetOperation(argument.Expression) is not IFieldReferenceOperation fieldReference ||
- !HlslKnownMembers.IsKnownMatrixIndex(fieldReference.Field.GetFullMetadataName()))
- {
- this.context.ReportDiagnostic(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)this.semanticModel.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? VisitArgument(ArgumentSyntax node)
{
@@ -651,9 +425,9 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters
updatedNode = updatedNode.WithRefKindKeyword(Token(SyntaxKind.None));
// Track and rewrite the discarded declaration
- if (this.semanticModel.GetOperation(node.Expression) is IDiscardOperation operation)
+ if (SemanticModel.GetOperation(node.Expression) is IDiscardOperation operation)
{
- TypeSyntax typeSyntax = operation.Type!.TrackType(this.discoveredTypes);
+ TypeSyntax typeSyntax = operation.Type!.TrackType(DiscoveredTypes);
string identifier = $"__implicit{this.implicitVariables.Count}";
// Add the variable to the list of implicit declarations
@@ -664,239 +438,5 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters
return updatedNode;
}
-
- ///
- public override SyntaxNode? VisitIdentifierName(IdentifierNameSyntax node)
- {
- var updatedNode = (IdentifierNameSyntax)base.VisitIdentifierName(node)!;
-
- if (this.semanticModel.GetOperation(node) is IFieldReferenceOperation operation &&
- operation.Field.IsConst &&
- operation.Type.TypeKind != TypeKind.Enum)
- {
- this.constantDefinitions[operation.Field] = ((IFormattable)operation.Field.ConstantValue!).ToString(null, CultureInfo.InvariantCulture);
-
- var ownerTypeName = ((INamedTypeSymbol)operation.Field.ContainingSymbol).ToDisplayString().Replace(".", "__");
- var constantName = $"__{ownerTypeName}__{operation.Field.Name}";
-
- return IdentifierName(constantName);
- }
-
- return updatedNode;
- }
-
- ///
- public override SyntaxNode? VisitAwaitExpression(AwaitExpressionSyntax node)
- {
- this.context.ReportDiagnostic(DiagnosticDescriptors.AwaitExpression, node);
-
- return base.VisitAwaitExpression(node);
- }
-
- ///
- public override SyntaxNode? VisitCheckedExpression(CheckedExpressionSyntax node)
- {
- this.context.ReportDiagnostic(DiagnosticDescriptors.CheckedExpression, node);
-
- return base.VisitCheckedExpression(node);
- }
-
- ///
- public override SyntaxNode? VisitCheckedStatement(CheckedStatementSyntax node)
- {
- this.context.ReportDiagnostic(DiagnosticDescriptors.CheckedStatement, node);
-
- return base.VisitCheckedStatement(node);
- }
-
- ///
- public override SyntaxNode? VisitFixedStatement(FixedStatementSyntax node)
- {
- this.context.ReportDiagnostic(DiagnosticDescriptors.FixedStatement, node);
-
- return base.VisitFixedStatement(node);
- }
-
- ///
- public override SyntaxNode? VisitForEachStatement(ForEachStatementSyntax node)
- {
- this.context.ReportDiagnostic(DiagnosticDescriptors.ForEachStatement, node);
-
- return base.VisitForEachStatement(node);
- }
-
- ///
- public override SyntaxNode? VisitForEachVariableStatement(ForEachVariableStatementSyntax node)
- {
- this.context.ReportDiagnostic(DiagnosticDescriptors.ForEachStatement, node);
-
- return base.VisitForEachVariableStatement(node);
- }
-
- ///
- public override SyntaxNode? VisitLockStatement(LockStatementSyntax node)
- {
- this.context.ReportDiagnostic(DiagnosticDescriptors.LockStatement, node);
-
- return base.VisitLockStatement(node);
- }
-
- ///
- public override SyntaxNode? VisitQueryExpression(QueryExpressionSyntax node)
- {
- this.context.ReportDiagnostic(DiagnosticDescriptors.QueryExpression, node);
-
- return base.VisitQueryExpression(node);
- }
-
- ///
- public override SyntaxNode? VisitRangeExpression(RangeExpressionSyntax node)
- {
- this.context.ReportDiagnostic(DiagnosticDescriptors.RangeExpression, node);
-
- return base.VisitRangeExpression(node);
- }
-
- ///
- public override SyntaxNode? VisitRecursivePattern(RecursivePatternSyntax node)
- {
- this.context.ReportDiagnostic(DiagnosticDescriptors.RecursivePattern, node);
-
- return base.VisitRecursivePattern(node);
- }
-
- ///
- public override SyntaxNode? VisitRefType(RefTypeSyntax node)
- {
- this.context.ReportDiagnostic(DiagnosticDescriptors.RefType, node);
-
- return base.VisitRefType(node);
- }
-
- ///
- public override SyntaxNode? VisitRelationalPattern(RelationalPatternSyntax node)
- {
- this.context.ReportDiagnostic(DiagnosticDescriptors.RelationalPattern, node);
-
- return base.VisitRelationalPattern(node);
- }
-
- ///
- public override SyntaxNode? VisitSizeOfExpression(SizeOfExpressionSyntax node)
- {
- this.context.ReportDiagnostic(DiagnosticDescriptors.SizeOfExpression, node);
-
- return base.VisitSizeOfExpression(node);
- }
-
- ///
- public override SyntaxNode? VisitStackAllocArrayCreationExpression(StackAllocArrayCreationExpressionSyntax node)
- {
- this.context.ReportDiagnostic(DiagnosticDescriptors.StackAllocArrayCreationExpression, node);
-
- return base.VisitStackAllocArrayCreationExpression(node);
- }
-
- ///
- public override SyntaxNode? VisitThrowExpression(ThrowExpressionSyntax node)
- {
- this.context.ReportDiagnostic(DiagnosticDescriptors.ThrowExpressionOrStatement, node);
-
- return base.VisitThrowExpression(node);
- }
-
- ///
- public override SyntaxNode? VisitThrowStatement(ThrowStatementSyntax node)
- {
- this.context.ReportDiagnostic(DiagnosticDescriptors.ThrowExpressionOrStatement, node);
-
- return base.VisitThrowStatement(node);
- }
-
- ///
- public override SyntaxNode? VisitTryStatement(TryStatementSyntax node)
- {
- this.context.ReportDiagnostic(DiagnosticDescriptors.TryStatement, node);
-
- return base.VisitTryStatement(node);
- }
-
- ///
- public override SyntaxNode? VisitTupleType(TupleTypeSyntax node)
- {
- this.context.ReportDiagnostic(DiagnosticDescriptors.TupleType, node);
-
- return base.VisitTupleType(node);
- }
-
- ///
- public override SyntaxNode? VisitUsingStatement(UsingStatementSyntax node)
- {
- this.context.ReportDiagnostic(DiagnosticDescriptors.UsingStatementOrDeclaration, node);
-
- return base.VisitUsingStatement(node);
- }
-
- ///
- public override SyntaxNode? VisitVariableDeclarator(VariableDeclaratorSyntax node)
- {
- var updatedNode = (VariableDeclaratorSyntax)base.VisitVariableDeclarator(node)!;
-
- if (node.Initializer is null &&
- node.Parent is VariableDeclarationSyntax declaration &&
- this.semanticModel.GetTypeInfo(declaration.Type).Type is ITypeSymbol { IsUnmanagedType: false } type)
- {
- this.context.ReportDiagnostic(InvalidObjectDeclaration, node, type);
- }
-
- return updatedNode;
- }
-
- ///
- public override SyntaxNode? VisitYieldStatement(YieldStatementSyntax node)
- {
- this.context.ReportDiagnostic(DiagnosticDescriptors.YieldStatement, node);
-
- return base.VisitYieldStatement(node);
- }
-
- ///
- public override SyntaxNode? VisitFunctionPointerType(FunctionPointerTypeSyntax node)
- {
- this.context.ReportDiagnostic(DiagnosticDescriptors.FunctionPointer, node);
-
- return base.VisitFunctionPointerType(node);
- }
-
- ///
- public override SyntaxNode? VisitPointerType(PointerTypeSyntax node)
- {
- this.context.ReportDiagnostic(DiagnosticDescriptors.PointerType, node);
-
- return base.VisitPointerType(node);
- }
-
- ///
- public override SyntaxNode? VisitUnsafeStatement(UnsafeStatementSyntax node)
- {
- this.context.ReportDiagnostic(DiagnosticDescriptors.UnsafeStatement, node);
-
- return base.VisitUnsafeStatement(node);
- }
-
- ///
- 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();
- }
}
}