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; + } + } +}