From 8cd02a300bb4def390ca6e7a4445f93b78156ade Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 7 Mar 2021 18:25:49 +0100 Subject: [PATCH 1/9] Added base HLSL rewriter class with shared logic --- .../SyntaxRewriters/HlslSourceRewriter.cs | 496 +++++++++++++++++ .../SyntaxRewriters/ShaderSourceRewriter.cs | 512 +----------------- 2 files changed, 522 insertions(+), 486 deletions(-) create mode 100644 src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.cs 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(); - } } } From a3a58e3a89210d3b16aff93e3ea322fcdd4ff88f Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 7 Mar 2021 18:29:25 +0100 Subject: [PATCH 2/9] Added partial file for HLSL rewriter diagnostics --- .../HlslSourceRewriter.Diagnostics.cs | 221 ++++++++++++++++++ .../SyntaxRewriters/HlslSourceRewriter.cs | 211 +---------------- 2 files changed, 222 insertions(+), 210 deletions(-) create mode 100644 src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.Diagnostics.cs diff --git a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.Diagnostics.cs b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.Diagnostics.cs new file mode 100644 index 00000000..3f34c34b --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.Diagnostics.cs @@ -0,0 +1,221 @@ +using ComputeSharp.SourceGenerators.Diagnostics; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors; + +namespace ComputeSharp.SourceGenerators.SyntaxRewriters +{ + /// + internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter + { + /// + public override SyntaxNode? VisitAnonymousObjectCreationExpression(AnonymousObjectCreationExpressionSyntax node) + { + var updatedNode = (AnonymousObjectCreationExpressionSyntax)base.VisitAnonymousObjectCreationExpression(node)!; + + Context.ReportDiagnostic(AnonymousObjectCreationExpression, node); + + return updatedNode; + } + + /// + public override SyntaxNode? VisitAwaitExpression(AwaitExpressionSyntax node) + { + Context.ReportDiagnostic(AwaitExpression, node); + + return base.VisitAwaitExpression(node); + } + + /// + public override SyntaxNode? VisitCheckedExpression(CheckedExpressionSyntax node) + { + Context.ReportDiagnostic(CheckedExpression, node); + + return base.VisitCheckedExpression(node); + } + + /// + public override SyntaxNode? VisitCheckedStatement(CheckedStatementSyntax node) + { + Context.ReportDiagnostic(CheckedStatement, node); + + return base.VisitCheckedStatement(node); + } + + /// + public override SyntaxNode? VisitFixedStatement(FixedStatementSyntax node) + { + Context.ReportDiagnostic(FixedStatement, node); + + return base.VisitFixedStatement(node); + } + + /// + public override SyntaxNode? VisitForEachStatement(ForEachStatementSyntax node) + { + Context.ReportDiagnostic(ForEachStatement, node); + + return base.VisitForEachStatement(node); + } + + /// + public override SyntaxNode? VisitForEachVariableStatement(ForEachVariableStatementSyntax node) + { + Context.ReportDiagnostic(ForEachStatement, node); + + return base.VisitForEachVariableStatement(node); + } + + /// + public override SyntaxNode? VisitLockStatement(LockStatementSyntax node) + { + Context.ReportDiagnostic(LockStatement, node); + + return base.VisitLockStatement(node); + } + + /// + public override SyntaxNode? VisitQueryExpression(QueryExpressionSyntax node) + { + Context.ReportDiagnostic(QueryExpression, node); + + return base.VisitQueryExpression(node); + } + + /// + public override SyntaxNode? VisitRangeExpression(RangeExpressionSyntax node) + { + Context.ReportDiagnostic(RangeExpression, node); + + return base.VisitRangeExpression(node); + } + + /// + public override SyntaxNode? VisitRecursivePattern(RecursivePatternSyntax node) + { + Context.ReportDiagnostic(RecursivePattern, node); + + return base.VisitRecursivePattern(node); + } + + /// + public override SyntaxNode? VisitRefType(RefTypeSyntax node) + { + Context.ReportDiagnostic(RefType, node); + + return base.VisitRefType(node); + } + + /// + public override SyntaxNode? VisitRelationalPattern(RelationalPatternSyntax node) + { + Context.ReportDiagnostic(RelationalPattern, node); + + return base.VisitRelationalPattern(node); + } + + /// + public override SyntaxNode? VisitSizeOfExpression(SizeOfExpressionSyntax node) + { + Context.ReportDiagnostic(SizeOfExpression, node); + + return base.VisitSizeOfExpression(node); + } + + /// + public override SyntaxNode? VisitStackAllocArrayCreationExpression(StackAllocArrayCreationExpressionSyntax node) + { + Context.ReportDiagnostic(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(TryStatement, node); + + return base.VisitTryStatement(node); + } + + /// + public override SyntaxNode? VisitTupleType(TupleTypeSyntax node) + { + Context.ReportDiagnostic(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(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(PointerType, node); + + return base.VisitPointerType(node); + } + + /// + public override SyntaxNode? VisitUnsafeStatement(UnsafeStatementSyntax node) + { + Context.ReportDiagnostic(UnsafeStatement, node); + + return base.VisitUnsafeStatement(node); + } + } +} diff --git a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.cs b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.cs index 20b225e9..c82554d9 100644 --- a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.cs +++ b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.cs @@ -18,7 +18,7 @@ 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 + internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter { /// /// Creates a new instance with the specified parameters. @@ -269,215 +269,6 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters 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) { From c14c64dbc76df4528b3e979fab897e6512762e6a Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 7 Mar 2021 19:27:39 +0100 Subject: [PATCH 3/9] Added syntax rewriter for static constants --- .../AnalyzerReleases.Unshipped.md | 4 +- .../Diagnostics/DiagnosticDescriptors.cs | 44 ++++-- .../ConstantPropertyRewriter.cs | 140 ++++++++++++++++++ 3 files changed, 175 insertions(+), 13 deletions(-) create mode 100644 src/ComputeSharp.SourceGenerators/SyntaxRewriters/ConstantPropertyRewriter.cs diff --git a/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Unshipped.md b/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Unshipped.md index dad27523..55dfd8b3 100644 --- a/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Unshipped.md +++ b/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Unshipped.md @@ -46,4 +46,6 @@ CMPS0038 | ComputeSharp.SourceGenerators.IComputeShaderDataLoaderGenerator | War CMPS0039 | ComputeSharp.SourceGenerators.IComputeShaderHashCodeGenerator | Warning | IComputeShaderHashCodeGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) CMPS0040 | ComputeSharp.SourceGenerators.IComputeShaderSourceGenerator | Warning | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) CMPS0041 | ComputeSharp.SourceGenerators.ShaderMethodSourceGenerator | Warning | ShaderMethodSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0042 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) \ No newline at end of file +CMPS0042 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0043 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0044 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) \ No newline at end of file diff --git a/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs b/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs index e7e12598..6b444b2a 100644 --- a/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs +++ b/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs @@ -89,9 +89,6 @@ namespace ComputeSharp.SourceGenerators.Diagnostics /// /// Gets a for an invalid usage. - /// - /// Format: "The ThreadIds type is used in method {0} of type {1}". - /// /// public static readonly DiagnosticDescriptor InvalidThreadIdsUsage = new( id: "CMPS0006", @@ -105,9 +102,6 @@ namespace ComputeSharp.SourceGenerators.Diagnostics /// /// Gets a for an invalid usage. - /// - /// Format: "The GroupIds type is used in method {0} of type {1}". - /// /// public static readonly DiagnosticDescriptor InvalidGroupIdsUsage = new( id: "CMPS0007", @@ -121,9 +115,6 @@ namespace ComputeSharp.SourceGenerators.Diagnostics /// /// Gets a for an invalid usage. - /// - /// Format: "The GroupSize type is used in method {0} of type {1}". - /// /// public static readonly DiagnosticDescriptor InvalidGroupSizeUsage = new( id: "CMPS0008", @@ -137,9 +128,6 @@ namespace ComputeSharp.SourceGenerators.Diagnostics /// /// Gets a for an invalid usage. - /// - /// Format: "The WarpIds type is used in method {0} of type {1}". - /// /// public static readonly DiagnosticDescriptor InvalidWarpIdsUsage = new( id: "CMPS0009", @@ -600,5 +588,37 @@ namespace ComputeSharp.SourceGenerators.Diagnostics isEnabledByDefault: true, description: "The arguments in a swizzled indexer for a matrix type must be compile-time constants.", helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for an invalid shader constant property type. + /// + /// Format: "The compute shader of type {0} contains a constant property \"{1}\" of an invalid type {2} (only primitive, vector and matrix types are supported)". + /// + /// + public static readonly DiagnosticDescriptor InvalidShaderConstantPropertyType = new( + id: "CMPS0043", + title: "Invalid shader constant property type", + messageFormat: "The compute shader of type {0} contains a constant property \"{1}\" of an invalid type {2} (only primitive, vector and matrix types are supported)", + category: typeof(IComputeShader).FullName, + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "A type representing a compute shader contains a constant property of a type that is not supported.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for an invalid shader constant property declaration. + /// + /// Format: "The compute shader of type {0} contains a constant property \"{1}\" with an invalid declaration (must use a lambda expression)". + /// + /// + public static readonly DiagnosticDescriptor InvalidShaderConstantPropertyDeclaration = new( + id: "CMPS0044", + title: "Invalid shader constant property", + messageFormat: "The compute shader of type {0} contains a constant property \"{1}\" with an invalid declaration (must use a lambda expression)", + category: typeof(IComputeShader).FullName, + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "A type representing a compute shader contains a constant property with an invalid declaration.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); } } diff --git a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ConstantPropertyRewriter.cs b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ConstantPropertyRewriter.cs new file mode 100644 index 00000000..a62cbeb2 --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ConstantPropertyRewriter.cs @@ -0,0 +1,140 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +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 custom type that processes C# static properties to convert to HLSL static constants. + /// + internal sealed class ConstantPropertyRewriter : 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 current generator context in use. + public ConstantPropertyRewriter( + SemanticModel semanticModel, + ICollection discoveredTypes, + IDictionary constantDefinitions, + GeneratorExecutionContext context) + : base(semanticModel, discoveredTypes, constantDefinitions, context) + { + } + + /// + public ExpressionSyntax? Visit(PropertyDeclarationSyntax? node) + { + if (node!.ExpressionBody is null) + { + Context.ReportDiagnostic( + InvalidShaderConstantPropertyDeclaration, + node, + SemanticModel.GetDeclaredSymbol(node.FirstAncestorOrSelf()!)!, + SemanticModel.GetDeclaredSymbol(node)!.Name); + + return null; + } + + ArrowExpressionClauseSyntax? updatedNode = (ArrowExpressionClauseSyntax?)Visit(node.ExpressionBody)!; + + return updatedNode.Expression; + } + + /// + public override SyntaxNode VisitMemberAccessExpression(MemberAccessExpressionSyntax node) + { + var updatedNode = (MemberAccessExpressionSyntax)base.VisitMemberAccessExpression(node)!; + + if (node.IsKind(SyntaxKind.SimpleMemberAccessExpression) && + SemanticModel.GetOperation(node) is IMemberReferenceOperation operation) + { + // Track and replace constants + if (operation is IFieldReferenceOperation fieldOperation && + fieldOperation.Field.IsConst && + fieldOperation.Type.TypeKind != TypeKind.Enum) + { + 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}"; + + return IdentifierName(constantName); + } + + if (HlslKnownMembers.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 => 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) + { + Context.ReportDiagnostic(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.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; + } + } +} From f8e951dd15838decf6a5aa06f5b79c00f6454ef9 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 7 Mar 2021 20:14:32 +0100 Subject: [PATCH 4/9] Enabled rewriting for shader static constants --- .../IComputeShaderSourceGenerator.cs | 73 ++++++++++++++++++- .../IComputeShaderSourceAttribute.cs | 14 +++- .../Shaders/Renderer/HlslShaderRenderer.cs | 25 ++++++- .../Shaders/Translation/IShaderLoader.cs | 11 ++- .../Shaders/Translation/ShaderLoader{T}.cs | 16 ++-- 5 files changed, 119 insertions(+), 20 deletions(-) diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs index 1970146f..fd5a11a2 100644 --- a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs @@ -71,12 +71,13 @@ namespace ComputeSharp.SourceGenerators Dictionary constantDefinitions = new(SymbolEqualityComparer.Default); // Explore the syntax tree and extract the processed info - var processedMembers = GetProcessedMembers(context, structDeclarationSymbol, discoveredTypes).ToArray(); + var processedMembers = GetProcessedFields(context, structDeclarationSymbol, discoveredTypes).ToArray(); var sharedBuffers = GetGroupSharedMembers(context, structDeclarationSymbol, discoveredTypes).ToArray(); var (entryPoint, localFunctions) = GetProcessedMethods(context, structDeclaration, structDeclarationSymbol, semanticModel, discoveredTypes, staticMethods, constantDefinitions); var processedTypes = GetProcessedTypes(discoveredTypes).ToArray(); var processedMethods = localFunctions.Concat(staticMethods.Values).Select(static method => method.NormalizeWhitespace().ToFullString()).ToArray(); var processedConstants = GetProcessedConstants(constantDefinitions); + var staticConstants = GetConstantProperties(context, semanticModel, structDeclaration, structDeclarationSymbol, discoveredTypes, constantDefinitions); // Create the compilation unit with the source attribute var source = @@ -90,6 +91,7 @@ namespace ComputeSharp.SourceGenerators AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(entryPoint))), AttributeArgument(ArrayExpression(processedMethods)), AttributeArgument(NestedArrayExpression(processedConstants)), + AttributeArgument(NestedArrayExpression(staticConstants)), AttributeArgument(NestedArrayExpression(sharedBuffers))))) .WithOpenBracketToken(Token(TriviaList(Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), SyntaxKind.OpenBracketToken, TriviaList())) .WithTarget(AttributeTargetSpecifier(Token(SyntaxKind.AssemblyKeyword)))) @@ -101,14 +103,14 @@ namespace ComputeSharp.SourceGenerators } /// - /// Gets a sequence of captured members and their mapped names. + /// Gets a sequence of captured fields and their mapped names. /// /// The current generator context in use. /// The input instance to process. /// The collection of currently discovered types. - /// A sequence of captured members in . + /// A sequence of captured fields in . [Pure] - private static IEnumerable> GetProcessedMembers( + private static IEnumerable> GetProcessedFields( GeneratorExecutionContext context, INamedTypeSymbol structDeclarationSymbol, ICollection types) @@ -171,6 +173,69 @@ namespace ComputeSharp.SourceGenerators } } + /// + /// Gets a sequence of shader static constant properties and their mapped names. + /// + /// The current generator context in use. + /// The instance for the type to process. + /// The instance for the current type. + /// The type symbol for the shader type. + /// The collection of currently discovered types. + /// The collection of discovered constant definitions. + /// A sequence of static constant properties in . + [Pure] + private static IEnumerable> GetConstantProperties( + GeneratorExecutionContext context, + SemanticModel semanticModel, + StructDeclarationSyntax structDeclaration, + INamedTypeSymbol structDeclarationSymbol, + ICollection discoveredTypes, + IDictionary constantDefinitions) + { + foreach (var propertyDeclaration in structDeclaration.Members.OfType()) + { + IPropertySymbol propertySymbol = semanticModel.GetDeclaredSymbol(propertyDeclaration)!; + + if (!propertySymbol.IsStatic || !propertySymbol.IsReadOnly) + { + continue; + } + + // Constant properties must be named type symbols + if (propertySymbol.Type is not INamedTypeSymbol typeSymbol) + { + context.ReportDiagnostic(InvalidShaderConstantPropertyType, propertyDeclaration, structDeclarationSymbol, propertySymbol.Name, propertySymbol.Type); + + continue; + } + + string metadataName = typeSymbol.GetFullMetadataName(); + + // Constant properties must be of a primitive, vector or matrix type + if (!HlslKnownTypes.IsKnownHlslType(metadataName)) + { + context.ReportDiagnostic(InvalidShaderConstantPropertyType, propertyDeclaration, structDeclarationSymbol, propertySymbol.Name, propertySymbol.Type); + + continue; + } + + ConstantPropertyRewriter constantPropertyRewriter = new( + semanticModel, + discoveredTypes, + constantDefinitions, + context); + + if (constantPropertyRewriter.Visit(propertyDeclaration) is ExpressionSyntax expression) + { + string typeName = HlslKnownTypes.GetMappedName(typeSymbol); + + _ = HlslKnownKeywords.TryGetMappedName(propertySymbol.Name, out string? mapping); + + yield return new[] { mapping ?? propertySymbol.Name, typeName, expression.NormalizeWhitespace().ToFullString() }; + } + } + } + /// /// Gets a sequence of captured members and their mapped names. /// diff --git a/src/ComputeSharp/Core/Attributes/__Internals/IComputeShaderSourceAttribute.cs b/src/ComputeSharp/Core/Attributes/__Internals/IComputeShaderSourceAttribute.cs index b9f62c79..64f6bba7 100644 --- a/src/ComputeSharp/Core/Attributes/__Internals/IComputeShaderSourceAttribute.cs +++ b/src/ComputeSharp/Core/Attributes/__Internals/IComputeShaderSourceAttribute.cs @@ -24,6 +24,7 @@ namespace ComputeSharp.__Internals /// The mapped collection of shader fields. /// The source code for the method. /// The collection of processed methods. + /// The collection of discovered defines. /// The collection of discovered constants. /// The collection of group shared buffers. public IComputeShaderSourceAttribute( @@ -32,6 +33,7 @@ namespace ComputeSharp.__Internals object[] args, string executeMethod, string[] methods, + object[] defines, object[] constants, object[] sharedBuffers) { @@ -40,7 +42,8 @@ namespace ComputeSharp.__Internals Fields = args.Cast().ToDictionary(static arg => arg[0], static arg => (arg[1], arg[2])); ExecuteMethod = executeMethod; Methods = methods; - Constants = constants.Cast().ToDictionary(static c => c[0], static c => c[1]); + Defines = defines.Cast().ToDictionary(static c => c[0], static c => c[1]); + Constants = constants.Cast().ToDictionary(static arg => arg[0], static arg => (arg[1], arg[2])); SharedBuffers = sharedBuffers.Cast().ToDictionary(static t => (string)t[0], static t => ((string)t[1], (int?)t[2])); } @@ -70,13 +73,18 @@ namespace ComputeSharp.__Internals internal IReadOnlyCollection Methods { get; } /// - /// Gets the collection of discovered constants. + /// Gets the collection of discovered define declarations. /// - internal IReadOnlyDictionary Constants { get; } + internal IReadOnlyDictionary Defines { get; } /// /// Gets the collection of discovered constants. /// + internal IReadOnlyDictionary Constants { get; } + + /// + /// Gets the collection of discovered shared buffers. + /// internal IReadOnlyDictionary SharedBuffers { get; } /// diff --git a/src/ComputeSharp/Shaders/Renderer/HlslShaderRenderer.cs b/src/ComputeSharp/Shaders/Renderer/HlslShaderRenderer.cs index 1232512f..3a48a8aa 100644 --- a/src/ComputeSharp/Shaders/Renderer/HlslShaderRenderer.cs +++ b/src/ComputeSharp/Shaders/Renderer/HlslShaderRenderer.cs @@ -42,13 +42,30 @@ namespace ComputeSharp.Shaders.Renderer builder.Append("#define __GroupSize__get_Z "); builder.AppendLine(threadsZ.ToString()); - // User defined onstants - foreach (var constant in info.ConstantsInfo) + // Define declarations + foreach (var define in info.DefinesInfo) { builder.Append("#define "); - builder.Append(constant.Key); + builder.Append(define.Key); builder.Append(' '); - builder.AppendLine(constant.Value); + builder.AppendLine(define.Value); + } + + // Static constants + if (info.ConstantsInfo.Count > 0) + { + builder.AppendLine(); + + foreach (var constant in info.ConstantsInfo) + { + builder.Append("static const "); + builder.Append(constant.Value.Type); + builder.Append(' '); + builder.Append(constant.Key); + builder.Append(" = "); + builder.Append(constant.Value.Assignment); + builder.AppendLine(";"); + } } // Declared types diff --git a/src/ComputeSharp/Shaders/Translation/IShaderLoader.cs b/src/ComputeSharp/Shaders/Translation/IShaderLoader.cs index 0ff336a8..2d9662ae 100644 --- a/src/ComputeSharp/Shaders/Translation/IShaderLoader.cs +++ b/src/ComputeSharp/Shaders/Translation/IShaderLoader.cs @@ -29,9 +29,14 @@ namespace ComputeSharp.Shaders.Translation IReadOnlyCollection MethodsInfo { get; } /// - /// Gets the collection of constants to be declared in the shader. + /// Gets the collection of define declarations to be added to the shader. /// - IReadOnlyDictionary ConstantsInfo { get; } + IReadOnlyDictionary DefinesInfo { get; } + + /// + /// Gets the collection of discovered constants. + /// + IReadOnlyDictionary ConstantsInfo { get; } /// /// Gets the collection of declared types for the shader. @@ -39,7 +44,7 @@ namespace ComputeSharp.Shaders.Translation IReadOnlyCollection DeclaredTypes { get; } /// - /// Gets the collection of discovered constants. + /// Gets the collection of discovered group shared buffers. /// IReadOnlyDictionary SharedBuffers { get; } } diff --git a/src/ComputeSharp/Shaders/Translation/ShaderLoader{T}.cs b/src/ComputeSharp/Shaders/Translation/ShaderLoader{T}.cs index e0495df5..213f6f32 100644 --- a/src/ComputeSharp/Shaders/Translation/ShaderLoader{T}.cs +++ b/src/ComputeSharp/Shaders/Translation/ShaderLoader{T}.cs @@ -66,9 +66,9 @@ namespace ComputeSharp.Shaders.Translation private readonly List methodsInfo = new(); /// - /// The with the discovered constants for the shader. + /// The with the discovered define declarations for the shader. /// - private readonly Dictionary constantsInfo = new(); + private readonly Dictionary definesInfo = new(); /// /// The with the collected declared types for the shader. @@ -108,11 +108,14 @@ namespace ComputeSharp.Shaders.Translation public IReadOnlyCollection MethodsInfo => this.methodsInfo; /// - public IReadOnlyDictionary ConstantsInfo => this.constantsInfo; + public IReadOnlyDictionary DefinesInfo => this.definesInfo; /// public IReadOnlyCollection DeclaredTypes => this.declaredTypes; + /// + public IReadOnlyDictionary ConstantsInfo { get; private set; } + /// public IReadOnlyDictionary SharedBuffers { get; private set; } @@ -143,14 +146,15 @@ namespace ComputeSharp.Shaders.Translation private void LoadMethodMetadata() { EntryPoint = Attribute.ExecuteMethod; + ConstantsInfo = Attribute.Constants; SharedBuffers = Attribute.SharedBuffers; this.declaredTypes.AddRange(Attribute.Types); this.methodsInfo.AddRange(Attribute.Methods); - foreach (var pair in Attribute.Constants) + foreach (var pair in Attribute.Defines) { - this.constantsInfo.Add(pair.Key, pair.Value); + this.definesInfo.Add(pair.Key, pair.Value); } } @@ -233,7 +237,7 @@ namespace ComputeSharp.Shaders.Translation foreach (var pair in methodSource.Constants) { - this.constantsInfo[pair.Key] = pair.Value; + this.definesInfo[pair.Key] = pair.Value; } } else ThrowHelper.ThrowArgumentException("Invalid captured variable"); From 7c02100df1e7cc21242a735a9193a0b0da3d9d1c Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 7 Mar 2021 20:28:52 +0100 Subject: [PATCH 5/9] Added more shader constant property diagnostics --- .../AnalyzerReleases.Unshipped.md | 4 ++- .../Diagnostics/DiagnosticDescriptors.cs | 32 +++++++++++++++++++ .../IComputeShaderSourceGenerator.cs | 11 ++++++- 3 files changed, 45 insertions(+), 2 deletions(-) diff --git a/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Unshipped.md b/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Unshipped.md index 55dfd8b3..6bbf251f 100644 --- a/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Unshipped.md +++ b/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Unshipped.md @@ -48,4 +48,6 @@ CMPS0040 | ComputeSharp.SourceGenerators.IComputeShaderSourceGenerator | Warning CMPS0041 | ComputeSharp.SourceGenerators.ShaderMethodSourceGenerator | Warning | ShaderMethodSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) CMPS0042 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) CMPS0043 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0044 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) \ No newline at end of file +CMPS0044 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0045 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0046 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) \ No newline at end of file diff --git a/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs b/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs index 6b444b2a..9dc7506e 100644 --- a/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs +++ b/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs @@ -620,5 +620,37 @@ namespace ComputeSharp.SourceGenerators.Diagnostics isEnabledByDefault: true, description: "A type representing a compute shader contains a constant property with an invalid declaration.", helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for an invalid shader constant property declaration. + /// + /// Format: "The compute shader of type {0} contains a mutable property \"{1}\" (only readonly properties are supported)". + /// + /// + public static readonly DiagnosticDescriptor NonReadonlyShaderPropertyDeclaration = new( + id: "CMPS0045", + title: "Invalid shader constant property", + messageFormat: "The compute shader of type {0} contains a mutable property \"{1}\" (only readonly properties are supported)", + category: typeof(IComputeShader).FullName, + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "A type representing a compute shader contains a non readonly property declaration.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for an invalid shader constant property declaration. + /// + /// Format: "The compute shader of type {0} contains an instance property \"{1}\" (only static properties are supported)". + /// + /// + public static readonly DiagnosticDescriptor InstanceShaderPropertyDeclaration = new( + id: "CMPS0046", + title: "Invalid shader constant property", + messageFormat: "The compute shader of type {0} contains an instance property \"{1}\" (only static properties are supported)", + category: typeof(IComputeShader).FullName, + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "A type representing a compute shader contains an instance property declaration.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); } } diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs index fd5a11a2..1f8dff73 100644 --- a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs @@ -196,8 +196,17 @@ namespace ComputeSharp.SourceGenerators { IPropertySymbol propertySymbol = semanticModel.GetDeclaredSymbol(propertyDeclaration)!; - if (!propertySymbol.IsStatic || !propertySymbol.IsReadOnly) + if (!propertySymbol.IsStatic) { + context.ReportDiagnostic(InstanceShaderPropertyDeclaration, propertyDeclaration, structDeclarationSymbol, propertySymbol.Name); + + continue; + } + + if (!propertySymbol.IsReadOnly) + { + context.ReportDiagnostic(NonReadonlyShaderPropertyDeclaration, propertyDeclaration, structDeclarationSymbol, propertySymbol.Name); + continue; } From 1817d97df5c32b59125baa57d641630e9a45ebc6 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 7 Mar 2021 20:29:04 +0100 Subject: [PATCH 6/9] Added unit tests for shader constant properties --- .../DiagnosticsTests.cs | 143 ++++++++++++++++++ 1 file changed, 143 insertions(+) diff --git a/tests/ComputeSharp.Tests.Internals.SourceGenerators/DiagnosticsTests.cs b/tests/ComputeSharp.Tests.Internals.SourceGenerators/DiagnosticsTests.cs index 40ea4c4a..2eaa16b3 100644 --- a/tests/ComputeSharp.Tests.Internals.SourceGenerators/DiagnosticsTests.cs +++ b/tests/ComputeSharp.Tests.Internals.SourceGenerators/DiagnosticsTests.cs @@ -1138,6 +1138,149 @@ namespace ComputeSharp.Tests.Internals VerifyGeneratedDiagnostics(source, "CMPS0042"); } + [TestMethod] + public void InvalidShaderConstantPropertyType() + { + string source = @" + using ComputeSharp; + + namespace ComputeSharp + { + public class ReadWriteBuffer { } + } + + namespace MyFancyApp.Sample + { + public struct MyShader : IComputeShader + { + public ReadWriteBuffer buffer; + + private static string Pi => ""Hello""; + + public void Execute() + { + } + } + }"; + + VerifyGeneratedDiagnostics(source, "CMPS0043"); + } + + [TestMethod] + public void InvalidShaderConstantPropertyDeclaration_AutoProp() + { + string source = @" + using ComputeSharp; + + namespace ComputeSharp + { + public class ReadWriteBuffer { } + } + + namespace MyFancyApp.Sample + { + public struct MyShader : IComputeShader + { + public ReadWriteBuffer buffer; + + private static float Pi { get; } = 3.14f; + + public void Execute() + { + } + } + }"; + + VerifyGeneratedDiagnostics(source, "CMPS0044"); + } + + [TestMethod] + public void InvalidShaderConstantPropertyDeclaration_GetterBlock() + { + string source = @" + using ComputeSharp; + + namespace ComputeSharp + { + public class ReadWriteBuffer { } + } + + namespace MyFancyApp.Sample + { + public struct MyShader : IComputeShader + { + public ReadWriteBuffer buffer; + + private static float Pi + { + get => 3.14f; + } + + public void Execute() + { + } + } + }"; + + VerifyGeneratedDiagnostics(source, "CMPS0044"); + } + + [TestMethod] + public void NonReadonlyShaderPropertyDeclaration() + { + string source = @" + using ComputeSharp; + + namespace ComputeSharp + { + public class ReadWriteBuffer { } + } + + namespace MyFancyApp.Sample + { + public struct MyShader : IComputeShader + { + public ReadWriteBuffer buffer; + + private static float Pi { get; set; } = 3.14f; + + public void Execute() + { + } + } + }"; + + VerifyGeneratedDiagnostics(source, "CMPS0045"); + } + + [TestMethod] + public void InstanceShaderPropertyDeclaration() + { + string source = @" + using ComputeSharp; + + namespace ComputeSharp + { + public class ReadWriteBuffer { } + } + + namespace MyFancyApp.Sample + { + public struct MyShader : IComputeShader + { + public ReadWriteBuffer buffer; + + private float Pi => 3.14f; + + public void Execute() + { + } + } + }"; + + VerifyGeneratedDiagnostics(source, "CMPS0046"); + } + /// /// Verifies the output of a source generator. /// From 1436d1a2b2bd4135299a0fb851b90257111b40b8 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 7 Mar 2021 20:37:59 +0100 Subject: [PATCH 7/9] Added functional unit tests with shader constant properties --- .../ComputeSharp.Tests/ShaderMembersTests.cs | 56 +++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 tests/ComputeSharp.Tests/ShaderMembersTests.cs diff --git a/tests/ComputeSharp.Tests/ShaderMembersTests.cs b/tests/ComputeSharp.Tests/ShaderMembersTests.cs new file mode 100644 index 00000000..f782c338 --- /dev/null +++ b/tests/ComputeSharp.Tests/ShaderMembersTests.cs @@ -0,0 +1,56 @@ +using System; +using System.Linq; +using ComputeSharp.Resources; +using ComputeSharp.Tests.Attributes; +using ComputeSharp.Tests.Extensions; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace ComputeSharp.Tests +{ + [TestClass] + [TestCategory("ShaderMembers")] + public partial class ShaderMembersTests + { + [CombinatorialTestMethod] + [AllDevices] + public void StaticConstants(Device device) + { + using ReadWriteBuffer buffer = device.Get().AllocateReadWriteBuffer(8); + + device.Get().For(1, new StaticConstantsShader(buffer)); + + float[] results = buffer.ToArray(); + + Assert.IsTrue(Math.Abs(3.14f - results[0]) < 0.00001f); + Assert.IsTrue(Math.Abs(results[1] - results[2]) < 0.00001f); + Assert.IsTrue(Math.Abs(1 - results[3]) < 0.00001f); + Assert.IsTrue(Math.Abs(2 - results[4]) < 0.00001f); + Assert.IsTrue(Math.Abs(3 - results[5]) < 0.00001f); + Assert.IsTrue(Math.Abs(4 - results[6]) < 0.00001f); + Assert.IsTrue(Math.Abs(3.14f - results[7]) < 0.00001f); + } + + [AutoConstructor] + internal readonly partial struct StaticConstantsShader : IComputeShader + { + public readonly ReadWriteBuffer buffer; + + static float Pi => 3.14f; + static float SinPi => Hlsl.Sin(Pi); + static Int2x2 Mat => new(1, 2, 3, 4); + static float Combo => Hlsl.Abs(Hlsl.Clamp(Hlsl.Min(Hlsl.Max(3.14f, 2), 10), 0, 42)); + + public void Execute() + { + buffer[0] = Pi; + buffer[1] = SinPi; + buffer[2] = Hlsl.Sin(3.14f); + buffer[3] = Mat.M11; + buffer[4] = Mat.M12; + buffer[5] = Mat.M21; + buffer[6] = Mat.M22; + buffer[7] = Combo; + } + } + } +} From 6255c348cb279f38ac5f9b95345bea3162b92433 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 7 Mar 2021 20:46:58 +0100 Subject: [PATCH 8/9] Refactored sample shaders to use shader constants --- .../Shaders/MengerJourney.cs | 15 ++++++++++----- .../Shaders/ProteanClouds.cs | 4 ++-- 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/samples/ComputeSharp.SwapChain/Shaders/MengerJourney.cs b/samples/ComputeSharp.SwapChain/Shaders/MengerJourney.cs index 024ef622..f4446dc6 100644 --- a/samples/ComputeSharp.SwapChain/Shaders/MengerJourney.cs +++ b/samples/ComputeSharp.SwapChain/Shaders/MengerJourney.cs @@ -30,6 +30,12 @@ private const float Ambient = 0.32184f; private const float Diffuse = 0.5f; + private static Float3 LightDir => 1.0f; + private static Float3 LightColor => new(1.0f, 1.0f, 0.858824f); + private static Float3 LightDir2 => new(1.0f, -1.0f, 1.0f); + private static Float3 LightColor2 => new(0, 0.333333f, 1.0f); + private static Float3 Offset => new(0.92858f, 0.92858f, 0.32858f); + /// /// Rotates a given value by a specified amount. /// @@ -44,15 +50,15 @@ /// private static Float3 GetLight(in Float3 color, in Float3 normal) { - Float3 lightDir = Hlsl.Normalize((Float3)1); + Float3 lightDir = Hlsl.Normalize(LightDir); float diffuse = Hlsl.Max(0.0f, Hlsl.Dot(-normal, lightDir)); - Float3 lightDir2 = Hlsl.Normalize(new Float3(1.0f, -1.0f, 1.0f)); + Float3 lightDir2 = Hlsl.Normalize(LightDir2); float diffuse2 = Hlsl.Max(0.0f, Hlsl.Dot(-normal, lightDir2)); return - (diffuse * Diffuse) * (new Float3(1.0f, 1.0f, 0.858824f) * color) + - (diffuse2 * Diffuse) * (new Float3(0.0f, 0.333333f, 1.0f) * color); + (diffuse * Diffuse) * (LightColor * color) + + (diffuse2 * Diffuse) * (LightColor2 * color); } /// @@ -70,7 +76,6 @@ z = Hlsl.Abs(1.0f - Mod(z, 2.0f)); float d = 1000.0f; - Float3 Offset = new(0.92858f, 0.92858f, 0.32858f); for (int n = 0; n < Iterations; n++) { diff --git a/samples/ComputeSharp.SwapChain/Shaders/ProteanClouds.cs b/samples/ComputeSharp.SwapChain/Shaders/ProteanClouds.cs index 1a197dce..5909f259 100644 --- a/samples/ComputeSharp.SwapChain/Shaders/ProteanClouds.cs +++ b/samples/ComputeSharp.SwapChain/Shaders/ProteanClouds.cs @@ -19,6 +19,8 @@ /// public readonly float time; + private static Float3x3 m3 => new Float3x3(0.33338f, 0.56034f, -0.71817f, -0.87887f, 0.32651f, -0.15323f, 0.15162f, 0.69596f, 0.61339f) * 1.93f; + private static Float2x2 Rotate(in float a) { float c = Hlsl.Cos(a), s = Hlsl.Sin(a); @@ -59,8 +61,6 @@ z *= 0.57f; trk *= 1.4f; - Float3x3 m3 = new Float3x3(0.33338f, 0.56034f, -0.71817f, -0.87887f, 0.32651f, -0.15323f, 0.15162f, 0.69596f, 0.61339f) * 1.93f; - p = Hlsl.Mul(p, m3); } From c2fd1f0ac248fbacb491c5b883a78aa098207f86 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 7 Mar 2021 22:35:21 +0100 Subject: [PATCH 9/9] Added readme docs about shader constants --- README.md | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 7dfbcafb..37b7fe60 100644 --- a/README.md +++ b/README.md @@ -13,6 +13,7 @@ - [GPU resource types](#gpu-resource-types) - [HLSL vector and matrix types](#hlsl-vector-and-matrix-types) - [HLSL intrinsics](#hlsl-intrinsics) + - [Shader constants](#shader-constants) - [Working with images](#working-with-images) - [Shader metaprogramming](#shader-metaprogramming) - [Requirements](#requirements) @@ -139,7 +140,7 @@ public readonly struct SoftmaxActivation : IComputeShader public readonly ReadWriteBuffer buffer; public readonly float k; - public void Execute(ThreadIds ids) + public void Execute() { float exp = Hlsl.Exp(k * buffer[ThreadIds.X]); float log = Hlsl.Log(1 + exp); @@ -149,6 +150,28 @@ public readonly struct SoftmaxActivation : IComputeShader } ``` +## Shader constants + +One common approach to make shaders easier to modify and experiment with is to separate the parameters being used from the code using them, by defining them as constants. **ComputeSharp** has special handling for this, and will rewrite static readonly properties as static constants in the generated shaders, which are optimized by the compiler for frequent access during execution. The advantage of using constants is that they're directly embedded into a compiled shader, so they don't need to be loaded in memory whenever a shader is dispatched. Constant properties can be of any of the supported HLSL primitive types, including vector and matrix types. Furthermore, the initialization of these constants can also use any of the available HLSL intrinsics. If the same result is being used multiple times while a shader is executed, moving values to a shader constant is a good way to avoid repeatedly computing the same value over and over for each invocation. + +Here is an example of how shader constants can be declared and used: + +```csharp +[AutoConstructor] +public readonly struct SampleShaderWithConstants : IComputeShader +{ + public readonly ReadWriteBuffer buffer; + + private static float Pi => 3.14f; + private static Float2 SinCosPi => new(Hlsl.Sin(Pi), Hlsl.Cos(Pi)); + + public void Execute() + { + buffer[ThreadIds.X] = Pi + SinCosPi.X * SinCosPi.Y; + } +} +``` + ## Working with images As mentioned in the [GPU resource types](#gpu-resource-types) paragraph, there are several texture types that are specialized to work on image pixels, such as `ReadWriteTexture2D`. Let's imagine we want to write a compute shader that applies some image processing filter: we will need to load an image (eg. using [ImageSharp](https://github.com/SixLabors/ImageSharp), or just the `System.Drawing` APIs) and then process it on the GPU, but without spending time on the CPU to convert pixels from a format such as RGBA32 to the normalized `float` values we want our shader to work on. We can do this by utilizing the `ReadWriteTexture2D` type as follows: