diff --git a/src/ComputeSharp.SourceGenerators/AutoConstructorAttributeGenerator.cs b/src/ComputeSharp.SourceGenerators/AutoConstructorAttributeGenerator.cs index 78716f52..e0beb62d 100644 --- a/src/ComputeSharp.SourceGenerators/AutoConstructorAttributeGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/AutoConstructorAttributeGenerator.cs @@ -73,17 +73,26 @@ namespace ComputeSharp.SourceGenerators // this.c = c; // ... // } - // - // This will be placed inside the original namespace, and with all the - // necessary using directive at the top for the input parameters. - var source = - CompilationUnit().AddMembers( - NamespaceDeclaration(IdentifierName(namespaceName)).AddMembers( + var structDeclarationSyntax = StructDeclaration(structName).WithModifiers(structModifiers).AddMembers( ConstructorDeclaration(structName) .AddModifiers(Token(SyntaxKind.PublicKeyword)) .AddParameterListParameters(fields.Select(field => Parameter(field.Identifier).WithType(field.Type)).ToArray()) - .AddBodyStatements(fields.Select(field => ParseStatement($"this.{field.Identifier} = {field.Identifier};")).ToArray())))) + .AddBodyStatements(fields.Select(field => ParseStatement($"this.{field.Identifier} = {field.Identifier};")).ToArray())); + + TypeDeclarationSyntax typeDeclarationSyntax = structDeclarationSyntax; + + // Add all parent types in ascending order, if any + foreach (var parentType in structDeclaration.Ancestors().OfType()) + { + typeDeclarationSyntax = parentType.WithMembers(SingletonList(typeDeclarationSyntax)); + } + + // Create the compilation unit with the namespace and target member. + // From this, we can finally generate the source code to output. + var source = + CompilationUnit().AddMembers( + NamespaceDeclaration(IdentifierName(namespaceName)).AddMembers(typeDeclarationSyntax)) .NormalizeWhitespace() .ToFullString(); diff --git a/tests/ComputeSharp.Tests.Internals/SourceGeneratorTests.cs b/tests/ComputeSharp.Tests.Internals/SourceGeneratorTests.cs index bb4e3b1b..23e526c0 100644 --- a/tests/ComputeSharp.Tests.Internals/SourceGeneratorTests.cs +++ b/tests/ComputeSharp.Tests.Internals/SourceGeneratorTests.cs @@ -29,23 +29,35 @@ namespace ComputeSharp.Tests.Internals namespace MyFancyApp.Sample { - [AutoConstructor] - public readonly partial struct MyShader + public partial interface IFoo { - private readonly Buffer A; - private readonly float B; + public partial class Foo + { + [AutoConstructor] + public readonly partial struct MyShader + { + private readonly Buffer A; + private readonly float B; + } + } } }"; string expected = @" namespace MyFancyApp.Sample { - public readonly partial struct MyShader + public partial interface IFoo { - public MyShader(MyLibrary.Buffer A, float B) + public partial class Foo { - this.A = A; - this.B = B; + public readonly partial struct MyShader + { + public MyShader(MyLibrary.Buffer A, float B) + { + this.A = A; + this.B = B; + } + } } } }";