diff --git a/src/ComputeSharp.D2D1.SourceGenerators/AnalyzerReleases.Shipped.md b/src/ComputeSharp.D2D1.SourceGenerators/AnalyzerReleases.Shipped.md index 9378f60c..053cf98a 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/AnalyzerReleases.Shipped.md +++ b/src/ComputeSharp.D2D1.SourceGenerators/AnalyzerReleases.Shipped.md @@ -79,3 +79,4 @@ CMPSD2D0069 | ComputeSharp.D2D1.Shaders | Warning | [Documentation](https://gith CMPSD2D0070 | ComputeSharp.D2D1.Shaders | Warning | [Documentation](https://github.com/Sergio0694/ComputeSharp) CMPSD2D0071 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) CMPSD2D0072 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPSD2D0073 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) diff --git a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.HlslSource.cs b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.HlslSource.cs index e6c8dc8b..8372f9a7 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.HlslSource.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.HlslSource.cs @@ -51,6 +51,7 @@ partial class D2DPixelShaderDescriptorGenerator HashSet discoveredTypes = new(SymbolEqualityComparer.Default); Dictionary staticMethods = new(SymbolEqualityComparer.Default); Dictionary instanceMethods = new(SymbolEqualityComparer.Default); + Dictionary constructors = new(SymbolEqualityComparer.Default); Dictionary constantDefinitions = new(SymbolEqualityComparer.Default); token.ThrowIfCancellationRequested(); @@ -75,6 +76,7 @@ partial class D2DPixelShaderDescriptorGenerator discoveredTypes, staticMethods, instanceMethods, + constructors, constantDefinitions, token, out bool methodsNeedD2D1RequiresScenePosition); @@ -97,7 +99,8 @@ partial class D2DPixelShaderDescriptorGenerator diagnostics, structDeclarationSymbol, discoveredTypes, - instanceMethods); + instanceMethods, + constructors); token.ThrowIfCancellationRequested(); @@ -306,6 +309,7 @@ partial class D2DPixelShaderDescriptorGenerator /// The collection of currently discovered types. /// The set of discovered and processed static methods. /// The collection of discovered instance methods for custom struct types. + /// The collection of discovered constructors for custom struct types. /// The collection of discovered constant definitions. /// Whether or not the shader needs the [D2DRequiresScenePosition] annotation. /// The used to cancel the operation, if needed. @@ -317,6 +321,7 @@ partial class D2DPixelShaderDescriptorGenerator ICollection discoveredTypes, IDictionary staticMethods, IDictionary instanceMethods, + IDictionary constructors, IDictionary constantDefinitions, CancellationToken token, out bool needsD2D1RequiresScenePosition) @@ -360,6 +365,7 @@ partial class D2DPixelShaderDescriptorGenerator discoveredTypes, staticMethods, instanceMethods, + constructors, constantDefinitions, diagnostics, isShaderEntryPoint); diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs b/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs index 9444cf9a..503a5bf3 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs @@ -557,19 +557,19 @@ partial class DiagnosticDescriptors helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); /// - /// Gets a for a method invocation that is not valid from a shader. + /// Gets a for a method or constructor invocation that is not valid from a shader. /// - /// Format: "The method {0} cannot be used in a D2D1 shader (methods need to either be HLSL intrinsics or with source available for analysis)". + /// Format: "The method or constructor {0} cannot be used in a D2D1 shader (methods or constructors need to either be HLSL intrinsics or with source available for analysis)". /// /// - public static readonly DiagnosticDescriptor InvalidMethodCall = new( + public static readonly DiagnosticDescriptor InvalidMethodOrConstructorCall = new( id: "CMPSD2D0040", - title: "Invalid method invocation from a D2D1 shader", - messageFormat: "The method {0} cannot be used in a D2D1 shader (methods need to either be HLSL intrinsics or with source available for analysis)", + title: "Invalid method or constructor invocation from a D2D1 shader", + messageFormat: "The method or constructor {0} cannot be used in a D2D1 shader (methods or constructors need to either be HLSL intrinsics or with source available for analysis)", category: "ComputeSharp.D2D1.Shaders", defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true, - description: "A D2D1 shader can only invoke methods that are either HLSL intrinsics or with source available for analysis.", + description: "A D2D1 shader can only invoke methods or constructors that are either HLSL intrinsics or with source available for analysis.", helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); /// @@ -1080,4 +1080,20 @@ partial class DiagnosticDescriptors isEnabledByDefault: true, description: "A collection expression cannot be used in a pixel shader.", helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for a constructor with a base constructor declaration. + /// + /// Format: "The constructor {0} has a base constructor declaration, which cannot be used in a D2D1 shader (only standalone constructors are allowed)". + /// + /// + public static readonly DiagnosticDescriptor InvalidBaseConstructorDeclaration = new( + id: "CMPSD2D0073", + title: "Invalid base constructor declaration", + messageFormat: "The constructor {0} has a base constructor declaration, which cannot be used in a D2D1 shader (only standalone constructors are allowed)", + category: "ComputeSharp.D2D1.Shaders", + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "Only standalone constructors (with no base constructor declaration) can be used in a D2D1 shader.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); } \ No newline at end of file diff --git a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxProcessors/HlslDefinitionsSyntaxProcessor.cs b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxProcessors/HlslDefinitionsSyntaxProcessor.cs index 74bb3aa0..22919a98 100644 --- a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxProcessors/HlslDefinitionsSyntaxProcessor.cs +++ b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxProcessors/HlslDefinitionsSyntaxProcessor.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Collections.Immutable; -using System.Linq; using ComputeSharp.SourceGeneration.Extensions; using ComputeSharp.SourceGeneration.Helpers; using ComputeSharp.SourceGeneration.Mappings; @@ -46,12 +45,14 @@ internal static class HlslDefinitionsSyntaxProcessor /// The type symbol for the shader type. /// The sequence of discovered custom types. /// The collection of discovered instance methods for custom struct types. + /// The collection of discovered constructors for custom struct types. /// A sequence of custom type definitions to add to the shader source. public static ImmutableArray<(string Name, string Definition)> GetDeclaredTypes( ImmutableArrayBuilder diagnostics, INamedTypeSymbol structDeclarationSymbol, IEnumerable types, - IReadOnlyDictionary instanceMethods) + IReadOnlyDictionary instanceMethods, + IReadOnlyDictionary constructors) { using ImmutableArrayBuilder<(string, string)> builder = new(); @@ -98,12 +99,36 @@ internal static class HlslDefinitionsSyntaxProcessor VariableDeclarator(Identifier(mappedName!))))); } - // Declare the methods of the current type - foreach (KeyValuePair method in instanceMethods.Where(pair => SymbolEqualityComparer.Default.Equals(pair.Key.ContainingType, type))) + // Enumerate all members in a single pass, so we can avoid materializing the collection. + // Additionally, this lets us add all members to the struct declaration in a single go. + static IEnumerable GatherInstanceMethods( + INamedTypeSymbol type, + IReadOnlyDictionary instanceMethods, + IReadOnlyDictionary constructors) { - structDeclaration = structDeclaration.AddMembers(method.Value); + // Normal instance methods + foreach (KeyValuePair method in instanceMethods) + { + if (SymbolEqualityComparer.Default.Equals(method.Key.ContainingType, type)) + { + yield return method.Value; + } + } + + // Constructors and stubs + foreach (KeyValuePair methods in constructors) + { + if (SymbolEqualityComparer.Default.Equals(methods.Key.ContainingType, type)) + { + yield return methods.Value.Stub; + yield return methods.Value.Ctor; + } + } } + // Declare the methods of the current type + structDeclaration = structDeclaration.WithMembers(structDeclaration.Members.AddRange(GatherInstanceMethods(type, instanceMethods, constructors))); + // Insert the trailing ; right after the closing bracket (after normalization) builder.Add(( structType, diff --git a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/HlslSourceRewriter.cs b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/HlslSourceRewriter.cs index 344ec29d..9ccbdbf5 100644 --- a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/HlslSourceRewriter.cs +++ b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/HlslSourceRewriter.cs @@ -118,37 +118,64 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter /// The rewritten for the object creation expression. private SyntaxNode VisitObjectCreationExpression(BaseObjectCreationExpressionSyntax node, BaseObjectCreationExpressionSyntax updatedNode, TypeSyntax targetType) { - // Emit a diagnostic if the object being created is not valid (ie. it's a managed type) - if (SemanticModel.For(node).GetTypeInfo(node).Type is ITypeSymbol { IsUnmanagedType: false } type) + ITypeSymbol? typeSymbol = SemanticModel.For(node).GetTypeInfo(node).Type; + + // Handle the edge case of the type being null (shouldn't really happen) + if (typeSymbol is null) { - Diagnostics.Add(InvalidObjectCreationExpression, node, type); + Diagnostics.Add(InvalidObjectCreationExpression, node, ""); + + return CastExpression(targetType, LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0))); + } + + // Emit a diagnostic if the object being created is not valid (ie. it's a managed type) + if (!typeSymbol.IsUnmanagedType) + { + Diagnostics.Add(InvalidObjectCreationExpression, node, typeSymbol); + + return CastExpression(targetType, LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0))); } // Mutate the syntax like with explicit object creation expressions. This also handles object // initializer expressions. If those are used, the HLSL will just contain a default expression. // There is a diagnostic being emitted to inform the users if that path is hit. If users want // to create an object and immediately set some values, they should use a factory method. - if (updatedNode is not { ArgumentList.Arguments.Count: > 0, Initializer: null }) + if (updatedNode is not { ArgumentList.Arguments.Count: >= 0, Initializer: null }) { return CastExpression(targetType, LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0))); } - // Add explicit casts like with the explicit object creation expressions above - if (SemanticModel.For(node).GetTypeInfo(node).Type is ITypeSymbol matrixType && - HlslKnownTypes.IsMatrixType(matrixType.GetFullyQualifiedMetadataName())) - { - for (int i = 0; i < node.ArgumentList!.Arguments.Count; i++) - { - IArgumentOperation argumentOperation = (IArgumentOperation)SemanticModel.For(node).GetOperation(node.ArgumentList.Arguments[i])!; - INamedTypeSymbol elementType = (INamedTypeSymbol)argumentOperation.Parameter!.Type; + string typeName = typeSymbol.GetFullyQualifiedMetadataName(); - updatedNode = updatedNode.ReplaceNode( - updatedNode.ArgumentList!.Arguments[i].Expression, - CastExpression(IdentifierName(HlslKnownTypes.GetMappedName(elementType)), updatedNode.ArgumentList.Arguments[i].Expression)); + if (HlslKnownTypes.IsKnownHlslType(typeName)) + { + // Special when we have no arguments, ie. we're calling the default parameterless constructor. + // We need to add this check here because for user defined types, there may be explicit constructors. + if (updatedNode.ArgumentList.Arguments.Count == 0) + { + return CastExpression(targetType, LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0))); } + + // Add explicit casts to each individual argument + if (HlslKnownTypes.IsMatrixType(typeName)) + { + for (int i = 0; i < node.ArgumentList!.Arguments.Count; i++) + { + IArgumentOperation argumentOperation = (IArgumentOperation)SemanticModel.For(node).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)); + } + } + + // In either case, for built-in HLSL types, we can just invoke the constructor directly + return InvocationExpression(targetType, updatedNode.ArgumentList!); } - return InvocationExpression(targetType, updatedNode.ArgumentList!); + // We're invoking a user defined constructor + return VisitUserDefinedObjectCreationExpression(node, updatedNode, targetType); } /// @@ -364,4 +391,18 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter return updatedToken.WithoutTrivia(); } + + /// + /// The original input instance. + /// The updated instance with tweaked syntax. + /// The for the object being created. + /// The rewritten for the object creation expression. + protected virtual SyntaxNode VisitUserDefinedObjectCreationExpression( + BaseObjectCreationExpressionSyntax node, + BaseObjectCreationExpressionSyntax updatedNode, + TypeSyntax targetType) + { + // By default, constructors are not supported, so just return an empty value + return CastExpression(targetType, LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0))); + } } \ No newline at end of file diff --git a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/ShaderSourceRewriter.cs b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/ShaderSourceRewriter.cs index 5d540445..b5afaf6f 100644 --- a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/ShaderSourceRewriter.cs +++ b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/ShaderSourceRewriter.cs @@ -13,8 +13,6 @@ using Microsoft.CodeAnalysis.Operations; using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; -#pragma warning disable IDE0052 - namespace ComputeSharp.SourceGeneration.SyntaxRewriters; /// @@ -37,6 +35,11 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter /// private readonly IDictionary instanceMethods; + /// + /// The collection of discovered constructors for custom struct types. + /// + private readonly IDictionary constructors; + /// /// The collection of processed local functions in the current tree. /// @@ -53,7 +56,8 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter private readonly bool isEntryPoint; /// - /// The identifier of the current or tree being visited. + /// The identifier of the current , + /// or tree being visited (used to rewrite local functions). /// private SyntaxToken currentMethodIdentifier; @@ -70,6 +74,7 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter /// The set of discovered custom types. /// The set of discovered and processed static methods. /// The collection of discovered instance methods for custom struct types. + /// The collection of discovered constructors for custom struct types. /// The collection of discovered constant definitions. /// The collection of produced instances. /// Whether or not the current instance is processing a shader entry point. @@ -79,6 +84,7 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter ICollection discoveredTypes, IDictionary staticMethods, IDictionary instanceMethods, + IDictionary constructors, IDictionary constantDefinitions, ImmutableArrayBuilder diagnostics, bool isEntryPoint) @@ -87,6 +93,7 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter this.shaderType = shaderType; this.staticMethods = staticMethods; this.instanceMethods = instanceMethods; + this.constructors = constructors; this.localFunctions = []; this.implicitVariables = []; this.isEntryPoint = isEntryPoint; @@ -99,6 +106,7 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter /// The set of discovered custom types. /// The set of discovered and processed static methods. /// The collection of discovered instance methods for custom struct types. + /// The collection of discovered constructors for custom struct types. /// The collection of discovered constant definitions. /// The collection of produced instances. private ShaderSourceRewriter( @@ -106,12 +114,14 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter ICollection discoveredTypes, IDictionary staticMethods, IDictionary instanceMethods, + IDictionary constructors, IDictionary constantDefinitions, ImmutableArrayBuilder diagnostics) : base(semanticModel, discoveredTypes, constantDefinitions, diagnostics) { this.staticMethods = staticMethods; this.instanceMethods = instanceMethods; + this.constructors = constructors; this.implicitVariables = []; this.localFunctions = []; } @@ -121,6 +131,37 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter /// public IReadOnlyDictionary LocalFunctions => this.localFunctions; + /// + public ConstructorDeclarationSyntax? Visit(ConstructorDeclarationSyntax? node) + { + if (node is null) + { + return null; + } + + this.currentMethodIdentifier = node.Identifier; + + // Constructors have no return type, so there is no return type identifier to replace. + // We simply track the type of the type being constructed and then continue normally. + // This is done separately where the constructor operation is being processed. + ConstructorDeclarationSyntax? updatedNode = (ConstructorDeclarationSyntax?)base.Visit(node)!; + + if (node!.Modifiers.Any(m => m.IsKind(SyntaxKind.UnsafeKeyword))) + { + Diagnostics.Add(UnsafeModifierOnMethodOrFunction, node); + } + + if (updatedNode is not null) + { + BlockSyntax implicitBlock = Block(this.implicitVariables.Select(static v => LocalDeclarationStatement(v)).ToArray()); + + // Add the tracked implicit declarations (at the start of the body) + updatedNode = updatedNode.WithBody(implicitBlock).AddBodyStatements([.. updatedNode.Body!.Statements]); + } + + return updatedNode; + } + /// public MethodDeclarationSyntax? Visit(MethodDeclarationSyntax? node) { @@ -481,7 +522,7 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter { if (method.DeclaringSyntaxReferences.FirstOrDefault()?.GetSyntax() is not MethodDeclarationSyntax methodNode) { - Diagnostics.Add(InvalidMethodCall, node, method); + Diagnostics.Add(InvalidMethodOrConstructorCall, node, method); return updatedNode; } @@ -491,6 +532,7 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter DiscoveredTypes, this.staticMethods, this.instanceMethods, + this.constructors, ConstantDefinitions, Diagnostics); @@ -534,7 +576,7 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter { if (method.DeclaringSyntaxReferences.FirstOrDefault()?.GetSyntax() is not MethodDeclarationSyntax methodNode) { - Diagnostics.Add(InvalidMethodCall, node, method); + Diagnostics.Add(InvalidMethodOrConstructorCall, node, method); return updatedNode; } @@ -544,6 +586,7 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter DiscoveredTypes, this.instanceMethods, this.instanceMethods, + this.constructors, ConstantDefinitions, Diagnostics); @@ -591,6 +634,124 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter return updatedNode; } + /// + protected override SyntaxNode VisitUserDefinedObjectCreationExpression( + BaseObjectCreationExpressionSyntax node, + BaseObjectCreationExpressionSyntax updatedNode, + TypeSyntax targetType) + { + if (SemanticModel.For(node).GetOperation(node) is IObjectCreationOperation { Constructor: IMethodSymbol constructor, Type: INamedTypeSymbol { TypeKind: TypeKind.Struct } typeSymbol }) + { + DiscoveredTypes.Add(typeSymbol); + + // If there are no arguments, check that the constructor is explicitly defined and is not + // the default parameterless constructor. In that case, we just fallback to a default value. + if (updatedNode.ArgumentList is not { Arguments.Count: > 0 } && constructor.IsImplicitlyDeclared) + { + return base.VisitUserDefinedObjectCreationExpression(node, updatedNode, targetType); + } + + string returnTypeHlslIdentifier = typeSymbol.GetFullyQualifiedName().ToHlslIdentifierName(); + + if (!this.constructors.ContainsKey(constructor)) + { + // If we can't find the constructor declaration for the syntax reference of the constructor, it means that either the + // type is from another assembly (hence we have no syntax references at all), or the constructor is compiler generated + // (even if IsImplicitlyDeclared is false) and a primary constructor. This is deliberately not supported, as there + // are very subtle ways in which captures can interact with fields and methods, and we cannot guarantee to track and + // rewrite all of them correctly to exactly preserve the same semantics. So we just block such cases entirely as well. + if (constructor.DeclaringSyntaxReferences.FirstOrDefault()?.GetSyntax() is not ConstructorDeclarationSyntax constructorNode) + { + Diagnostics.Add(InvalidMethodOrConstructorCall, node, constructor); + + return base.VisitUserDefinedObjectCreationExpression(node, updatedNode, targetType); + } + + // Chaining constructors is not supported, so emit a diagnostic to inform the user. + // The rest of the code will work as usual, but the semantics of the other chained + // constructor being invoked is not preserved, so the resulting code is not the same. + if (constructorNode.Initializer is not null) + { + Diagnostics.Add(InvalidBaseConstructorDeclaration, node, constructor); + } + + ShaderSourceRewriter shaderSourceRewriter = new( + SemanticModel, + DiscoveredTypes, + this.instanceMethods, + this.instanceMethods, + this.constructors, + ConstantDefinitions, + Diagnostics); + + ConstructorDeclarationSyntax processedMethod = shaderSourceRewriter.Visit(constructorNode)!.WithoutTrivia(); + + // Extracts the arguments from the list of parameters of the current method + ArgumentSyntax[] ExtractArguments() + { + using ImmutableArrayBuilder arguments = new(); + + foreach (ParameterSyntax parameter in processedMethod.ParameterList.Parameters) + { + arguments.Add(Argument(IdentifierName(parameter.Identifier.Text))); + } + + return arguments.ToArray(); + } + + // Create a static method acting as the constructor stub: + // + // static __ctor() + // { + // __this = ()0; + // + // __this.__ctor__init(); + // + // return __this; + // } + MethodDeclarationSyntax stubNode = + MethodDeclaration(IdentifierName(returnTypeHlslIdentifier), "__ctor") + .AddModifiers(Token(SyntaxKind.StaticKeyword)) + .WithParameterList(processedMethod.ParameterList) + .AddBodyStatements( + LocalDeclarationStatement( + VariableDeclaration(IdentifierName(returnTypeHlslIdentifier)).AddVariables( + VariableDeclarator(Identifier("__this")).WithInitializer(EqualsValueClause( + CastExpression(targetType, LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0))))))), + ExpressionStatement( + InvocationExpression( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName("__this"), + IdentifierName("__ctor__init"))) + .AddArgumentListArguments(ExtractArguments())), + ReturnStatement(IdentifierName("__this"))); + + // Create the actual constructor to invoke, as an instance method: + // + // void __ctor__init() + // { + // + // } + MethodDeclarationSyntax ctorNode = + MethodDeclaration(PredefinedType(Token(SyntaxKind.VoidKeyword)), "__ctor__init") + .WithParameterList(processedMethod.ParameterList) + .WithBody(processedMethod.Body); + + this.constructors.Add(constructor, (stubNode, ctorNode)); + } + + // Rewrite the expression to invoke the rewritten constructor: + // + // ::__ctor(...) + return + InvocationExpression(IdentifierName($"{returnTypeHlslIdentifier}::__ctor")) + .WithArgumentList(updatedNode.ArgumentList!); + } + + return base.VisitUserDefinedObjectCreationExpression(node, updatedNode, targetType); + } + /// /// Rewrites a sampled texture access. /// diff --git a/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Shipped.md b/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Shipped.md index 35b0fc9a..044b323e 100644 --- a/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Shipped.md +++ b/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Shipped.md @@ -66,3 +66,4 @@ CMPS0057 | ComputeSharp.Shaders | Warning | [Documentation](https://github.com/S CMPS0058 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) CMPS0059 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) CMPS0060 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0061 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) diff --git a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.HlslSource.cs b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.HlslSource.cs index 0ee84697..f749251b 100644 --- a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.HlslSource.cs +++ b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.HlslSource.cs @@ -57,6 +57,7 @@ partial class ComputeShaderDescriptorGenerator HashSet discoveredTypes = new(SymbolEqualityComparer.Default); Dictionary staticMethods = new(SymbolEqualityComparer.Default); Dictionary instanceMethods = new(SymbolEqualityComparer.Default); + Dictionary constructors = new(SymbolEqualityComparer.Default); Dictionary constantDefinitions = new(SymbolEqualityComparer.Default); // Setup the semantic model and basic properties @@ -90,6 +91,7 @@ partial class ComputeShaderDescriptorGenerator discoveredTypes, staticMethods, instanceMethods, + constructors, constantDefinitions, isComputeShader, token); @@ -112,7 +114,8 @@ partial class ComputeShaderDescriptorGenerator diagnostics, structDeclarationSymbol, discoveredTypes, - instanceMethods); + instanceMethods, + constructors); token.ThrowIfCancellationRequested(); @@ -359,6 +362,7 @@ partial class ComputeShaderDescriptorGenerator /// The collection of currently discovered types. /// The set of discovered and processed static methods. /// The collection of discovered instance methods for custom struct types. + /// The collection of discovered constructors for custom struct types. /// The collection of discovered constant definitions. /// Indicates whether or not represents a compute shader. /// The used to cancel the operation, if needed. @@ -370,6 +374,7 @@ partial class ComputeShaderDescriptorGenerator ICollection discoveredTypes, IDictionary staticMethods, IDictionary instanceMethods, + IDictionary constructors, IDictionary constantDefinitions, bool isComputeShader, CancellationToken token) @@ -419,6 +424,7 @@ partial class ComputeShaderDescriptorGenerator discoveredTypes, staticMethods, instanceMethods, + constructors, constantDefinitions, diagnostics, isShaderEntryPoint); diff --git a/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs b/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs index 3e77eb76..7e952d64 100644 --- a/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs +++ b/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs @@ -670,19 +670,19 @@ partial class DiagnosticDescriptors helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); /// - /// Gets a for a method invocation that is not valid from a shader. + /// Gets a for a method or constructor invocation that is not valid from a shader. /// - /// Format: "The method {0} cannot be used in a shader (methods need to either be HLSL intrinsics or with source available for analysis)". + /// Format: "The method or constructor {0} cannot be used in a shader (methods or constructors need to either be HLSL intrinsics or with source available for analysis)". /// /// - public static readonly DiagnosticDescriptor InvalidMethodCall = new( + public static readonly DiagnosticDescriptor InvalidMethodOrConstructorCall = new( id: "CMPS0049", - title: "Invalid method invocation from a shader", - messageFormat: "The method {0} cannot be used in a shader (methods need to either be HLSL intrinsics or with source available for analysis)", + title: "Invalid method or constructor invocation from a shader", + messageFormat: "The method or constructor {0} cannot be used in a shader (methods or constructors need to either be HLSL intrinsics or with source available for analysis)", category: "ComputeSharp.Shaders", defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true, - description: "Shaders can only invoke methods that are either HLSL intrinsics or with source available for analysis.", + description: "Shaders can only invoke methods or constructors that are either HLSL intrinsics or with source available for analysis.", helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); /// @@ -856,4 +856,20 @@ partial class DiagnosticDescriptors isEnabledByDefault: true, description: "A collection expression cannot be used in a compute shader.", helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for a constructor with a base constructor declaration. + /// + /// Format: "The constructor {0} has a base constructor declaration, which cannot be used in a shader (only standalone constructors are allowed)". + /// + /// + public static readonly DiagnosticDescriptor InvalidBaseConstructorDeclaration = new( + id: "CMPS0061", + title: "Invalid base constructor declaration", + messageFormat: "The constructor {0} has a base constructor declaration, which cannot be used in a shader (only standalone constructors are allowed)", + category: "ComputeSharp.Shaders", + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "Only standalone constructors (with no base constructor declaration) can be used in a shader.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); } \ No newline at end of file diff --git a/tests/ComputeSharp.D2D1.Tests/Effects/InvertWithUserTypeWithConstructorEffect.cs b/tests/ComputeSharp.D2D1.Tests/Effects/InvertWithUserTypeWithConstructorEffect.cs new file mode 100644 index 00000000..7ef7edfb --- /dev/null +++ b/tests/ComputeSharp.D2D1.Tests/Effects/InvertWithUserTypeWithConstructorEffect.cs @@ -0,0 +1,33 @@ +#pragma warning disable IDE0290 + +namespace ComputeSharp.D2D1.Tests.Effects; + +public struct ColorWrapper +{ + private float4 value; + + public ColorWrapper(float4 color) + { + this.value = color; + } + + public float4 Invert() + { + return new(Hlsl.Saturate(1.0f - this.value.RGB), 1); + } +} + +[D2DInputCount(1)] +[D2DInputSimple(0)] +[D2DShaderProfile(D2D1ShaderProfile.PixelShader50)] +[D2DGeneratedPixelShaderDescriptor] +public partial struct InvertWithUserTypeWithConstructorEffect : ID2D1PixelShader +{ + /// + public float4 Execute() + { + ColorWrapper wrapper = new(D2D.GetInput(0)); + + return wrapper.Invert(); + } +} \ No newline at end of file diff --git a/tests/ComputeSharp.D2D1.Tests/EffectsTests.cs b/tests/ComputeSharp.D2D1.Tests/EffectsTests.cs index 6782a7f5..b454bb65 100644 --- a/tests/ComputeSharp.D2D1.Tests/EffectsTests.cs +++ b/tests/ComputeSharp.D2D1.Tests/EffectsTests.cs @@ -33,6 +33,12 @@ public class EffectsTests D2D1TestRunner.RunAndCompareShader(new InvertWithThresholdEffect(1), null, "Landscape.png", "Landscape_Inverted.png"); } + [TestMethod] + public void InvertWithUserTypeWithConstructor() + { + D2D1TestRunner.RunAndCompareShader(new InvertWithUserTypeWithConstructorEffect(), null, "Landscape.png", "Landscape_Inverted.png"); + } + [TestMethod] public void Pixelate() { diff --git a/tests/ComputeSharp.Tests.SourceGenerators/DiagnosticsTests.cs b/tests/ComputeSharp.Tests.SourceGenerators/DiagnosticsTests.cs index e42ca2c2..7f040069 100644 --- a/tests/ComputeSharp.Tests.SourceGenerators/DiagnosticsTests.cs +++ b/tests/ComputeSharp.Tests.SourceGenerators/DiagnosticsTests.cs @@ -1419,6 +1419,68 @@ public class DiagnosticsTests VerifyGeneratedDiagnostics(source, "CMPS0031", "CMPS0047", "CMPS0060"); } + [TestMethod] + public void InvalidBaseConstructorDeclaration() + { + const string source = """ + using ComputeSharp; + + public struct MyStruct + { + public MyStruct(int x) + { + } + + public MyStruct(float x) + : this((int)x) + { + } + } + + [GeneratedComputeShaderDescriptor] + public partial struct MyShader : IComputeShader + { + public ReadWriteBuffer buffer; + + public void Execute() + { + MyStruct value = new(3.14f); + } + } + """; + + VerifyGeneratedDiagnostics(source, "CMPS0047", "CMPS0061"); + } + + [TestMethod] + public void InvalidMethodOrConstructorCall_PrimaryConstructor() + { + const string source = """ + using ComputeSharp; + + public struct MyStruct(int x) + { + public int PlusOne() + { + return x + 1; + } + } + + [GeneratedComputeShaderDescriptor] + public partial struct MyShader : IComputeShader + { + public ReadWriteBuffer buffer; + + public void Execute() + { + buffer[ThreadIds.X] = new MyStruct(ThreadIds.X).PlusOne(); + } + } + """; + + VerifyGeneratedDiagnostics(source, "CMPS0047", "CMPS0049"); + } + /// /// Verifies the output of a source generator. /// diff --git a/tests/ComputeSharp.Tests/UserDefinedTypeConstructorTests.cs b/tests/ComputeSharp.Tests/UserDefinedTypeConstructorTests.cs new file mode 100644 index 00000000..50912566 --- /dev/null +++ b/tests/ComputeSharp.Tests/UserDefinedTypeConstructorTests.cs @@ -0,0 +1,131 @@ +using ComputeSharp.Tests.Attributes; +using ComputeSharp.Tests.Extensions; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +#pragma warning disable IDE0008, IDE0009, IDE0290, CA1861 + +namespace ComputeSharp.Tests; + +[TestClass] +public partial class UserDefinedTypeConstructorTests +{ + [CombinatorialTestMethod] + [Device(Device.Warp)] + public void ImplicitParameterlessConstructor(Device device) + { + using ReadWriteBuffer buffer = device.Get().AllocateReadWriteBuffer([111, 222]); + + device.Get().For(1, new ImplicitParameterlessConstructorShader(buffer)); + + int[] results = buffer.ToArray(); + + CollectionAssert.AreEqual(new[] { 0, 0 }, results); + } + + public struct MyValueTypeWithNoConstructor + { + public int X; + public int Y; + } + + [ThreadGroupSize(DefaultThreadGroupSizes.X)] + [GeneratedComputeShaderDescriptor] + public readonly partial struct ImplicitParameterlessConstructorShader(ReadWriteBuffer buffer) : IComputeShader + { + public void Execute() + { + MyValueTypeWithNoConstructor valueType = new(); + + buffer[0] = valueType.X; + buffer[1] = valueType.Y; + } + } + + [CombinatorialTestMethod] + [Device(Device.Warp)] + public void ExplicitParameterlessConstructor(Device device) + { + using ReadWriteBuffer buffer = device.Get().AllocateReadWriteBuffer(2); + + device.Get().For(1, new ExplicitParameterlessConstructorShader(buffer)); + + int[] results = buffer.ToArray(); + + CollectionAssert.AreEqual(new[] { 42, 12345 }, results); + } + + public struct MyValueTypeWithParameterlessConstructor + { + public int X; + public int Y; + + public MyValueTypeWithParameterlessConstructor() + { + X = 42; + this.Y = 12345; + } + } + + [ThreadGroupSize(DefaultThreadGroupSizes.X)] + [GeneratedComputeShaderDescriptor] + public readonly partial struct ExplicitParameterlessConstructorShader(ReadWriteBuffer buffer) : IComputeShader + { + public void Execute() + { + MyValueTypeWithParameterlessConstructor valueType = new(); + + buffer[0] = valueType.X; + buffer[1] = valueType.Y; + } + } + + // See https://github.com/Sergio0694/ComputeSharp/issues/481 + [CombinatorialTestMethod] + [Device(Device.Warp)] + public void ConstructorWithParameters(Device device) + { + using ReadWriteBuffer buffer = device.Get().AllocateReadWriteBuffer(8); + + device.Get().For(1, new ConstructorWithParametersShader(buffer)); + + int[] results = buffer.ToArray(); + + CollectionAssert.AreEqual(new[] { 42, 123456, 3, 4, 111, 222, 5, 6 }, results); + } + + public struct MyValueTypeWithConstructorWithParameters + { + public int X; + public int Y; + public float2 Z; + + public MyValueTypeWithConstructorWithParameters(int x, int y, float2 z) + { + X = x; + this.Y = y; + this.Z = z; + } + } + + [ThreadGroupSize(DefaultThreadGroupSizes.X)] + [GeneratedComputeShaderDescriptor] + public readonly partial struct ConstructorWithParametersShader(ReadWriteBuffer buffer) : IComputeShader + { + public void Execute() + { + MyValueTypeWithConstructorWithParameters valueType = new(42, 123456, new float2(3, 4)); + + buffer[0] = valueType.X; + buffer[1] = valueType.Y; + buffer[2] = (int)valueType.Z.X; + buffer[3] = (int)valueType.Z.Y; + + var valueType2 = new MyValueTypeWithConstructorWithParameters(111, 222, new float2(5, 6)); + + buffer[4] = valueType2.X; + buffer[5] = valueType2.Y; + buffer[6] = (int)valueType2.Z.X; + buffer[7] = (int)valueType2.Z.Y; + } + } +} \ No newline at end of file