diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInitializeFromDispatchDataMethod.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInitializeFromDispatchDataMethod.Syntax.cs index 4dfa6969..8c207652 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInitializeFromDispatchDataMethod.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInitializeFromDispatchDataMethod.Syntax.cs @@ -39,7 +39,7 @@ partial class ID2D1ShaderGenerator // Get a reference to the data through the generated native layout type writer.WriteLine(); - writer.WriteLine("ref readonly ConstantBuffer buffer = ref global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.InteropServices.MemoryMarshal.GetReference(data));"); + writer.WriteLine("ref readonly global::ComputeSharp.D2D1.Generated.ConstantBuffer buffer = ref global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.InteropServices.MemoryMarshal.GetReference(data));"); // Generate loading statements for each captured field foreach (FieldInfo fieldInfo in info.Fields) diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInputDescriptionsProperty.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInputDescriptionsProperty.Syntax.cs index ad20fe54..f3dbb302 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInputDescriptionsProperty.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInputDescriptionsProperty.Syntax.cs @@ -31,7 +31,7 @@ partial class ID2D1ShaderGenerator } else { - writer.WriteLine("Data.InputDescriptions;"); + writer.WriteLine("global::ComputeSharp.D2D1.Generated.Data.InputDescriptions;"); } } @@ -40,7 +40,11 @@ partial class ID2D1ShaderGenerator /// /// The input instance with gathered shader info. /// The registered callbacks to generate additional types. - public static void RegisterAdditionalTypeSyntax(D2D1ShaderInfo info, ImmutableArrayBuilder> callbacks) + /// The using directives needed by the generated code. + public static void RegisterAdditionalTypeSyntax( + D2D1ShaderInfo info, + ImmutableArrayBuilder> callbacks, + ImmutableHashSetBuilder usingDirectives) { // If there are no necessary data members, stop here if (info.InputDescriptions.IsEmpty && @@ -49,13 +53,20 @@ partial class ID2D1ShaderGenerator return; } + usingDirectives.Add("global::System.CodeDom.Compiler"); + usingDirectives.Add("global::System.Diagnostics"); + usingDirectives.Add("global::System.Diagnostics.CodeAnalysis"); + + AddAdditionalDataMemberUsingDirectives(info, usingDirectives); + ResourceTextureDescriptions.AddAdditionalDataMemberUsingDirectives(info, usingDirectives); + // Declare the additional data type static void Callback(D2D1ShaderInfo info, IndentedTextWriter writer) { writer.WriteLine($$"""/// """); writer.WriteLine($$"""/// A container type for additional data needed by the shader."""); writer.WriteLine($$"""/// """); - writer.WriteGeneratedAttributes(typeof(ID2D1ShaderGenerator)); + writer.WriteGeneratedAttributes(typeof(ID2D1ShaderGenerator), useFullyQualifiedTypeNames: false); writer.WriteLine($$"""file static class Data"""); using (writer.WriteBlock()) @@ -80,6 +91,22 @@ partial class ID2D1ShaderGenerator callbacks.Add(Callback); } + /// + /// Adds any using directives for the additional data member, if needed. + /// + /// The input instance with gathered shader info. + /// The using directives needed by the generated code. + public static void AddAdditionalDataMemberUsingDirectives(D2D1ShaderInfo info, ImmutableHashSetBuilder usingDirectives) + { + if (info.InputDescriptions.IsEmpty) + { + return; + } + + usingDirectives.Add("global::ComputeSharp.D2D1"); + usingDirectives.Add("global::ComputeSharp.D2D1.Interop"); + } + /// /// Registers a callback to generate an additional data member, if needed. /// @@ -96,15 +123,15 @@ partial class ID2D1ShaderGenerator // Declare the shared array with input descriptions static void Callback(D2D1ShaderInfo info, IndentedTextWriter writer) { - writer.WriteLine("""/// The singleton array instance."""); - writer.WriteLine("""public static readonly global::ComputeSharp.D2D1.Interop.D2D1InputDescription[] InputDescriptions = """); + writer.WriteLine("""/// The singleton array instance."""); + writer.WriteLine("""public static readonly D2D1InputDescription[] InputDescriptions = """); writer.WriteLine("""{"""); writer.IncreaseIndent(); // Initialize all input descriptions writer.WriteInitializationExpressions(info.InputDescriptions.AsSpan(), static (description, writer) => { - writer.Write($$"""new global::ComputeSharp.D2D1.Interop.D2D1InputDescription({{description.Index}}, global::ComputeSharp.D2D1.D2D1Filter.{{description.Filter}}) { LevelOfDetailCount = {{description.LevelOfDetailCount}} }"""); + writer.Write($$"""new D2D1InputDescription({{description.Index}}, D2D1Filter.{{description.Filter}}) { LevelOfDetailCount = {{description.LevelOfDetailCount}} }"""); }); writer.DecreaseIndent(); diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInputTypesProperty.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInputTypesProperty.Syntax.cs index ea98461e..3f556167 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInputTypesProperty.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInputTypesProperty.Syntax.cs @@ -29,7 +29,7 @@ partial class ID2D1ShaderGenerator } else { - writer.WriteLine("InputTypesMemoryManager.Instance.Memory;"); + writer.WriteLine("global::ComputeSharp.D2D1.Generated.InputTypesMemoryManager.Instance.Memory;"); } } @@ -38,7 +38,11 @@ partial class ID2D1ShaderGenerator /// /// The input instance with gathered shader info. /// The registered callbacks to generate additional types. - public static void RegisterAdditionalTypeSyntax(D2D1ShaderInfo info, ImmutableArrayBuilder> callbacks) + /// The using directives needed by the generated code. + public static void RegisterAdditionalTypeSyntax( + D2D1ShaderInfo info, + ImmutableArrayBuilder> callbacks, + ImmutableHashSetBuilder usingDirectives) { // If there are no inputs, no memory manager is needed if (info.InputTypes.IsEmpty) @@ -46,14 +50,23 @@ partial class ID2D1ShaderGenerator return; } + usingDirectives.Add("global::System"); + usingDirectives.Add("global::System.Buffers"); + usingDirectives.Add("global::System.CodeDom.Compiler"); + usingDirectives.Add("global::System.Diagnostics"); + usingDirectives.Add("global::System.Diagnostics.CodeAnalysis"); + usingDirectives.Add("global::System.Runtime.CompilerServices"); + usingDirectives.Add("global::System.Runtime.InteropServices"); + usingDirectives.Add("global::ComputeSharp.D2D1.Interop"); + // Declare the InputTypesMemoryManager custom memory manager type static void Callback(D2D1ShaderInfo info, IndentedTextWriter writer) { writer.WriteLine($$"""/// """); - writer.WriteLine($$"""/// A implementation to get the input types."""); + writer.WriteLine($$"""/// A implementation to get the input types."""); writer.WriteLine($$"""/// """); - writer.WriteGeneratedAttributes(typeof(ID2D1ShaderGenerator)); - writer.WriteLine($$"""file sealed class InputTypesMemoryManager : global::System.Buffers.MemoryManager"""); + writer.WriteGeneratedAttributes(typeof(ID2D1ShaderGenerator), useFullyQualifiedTypeNames: false); + writer.WriteLine($$"""file sealed class InputTypesMemoryManager : MemoryManager"""); using (writer.WriteBlock()) { @@ -64,14 +77,14 @@ partial class ID2D1ShaderGenerator // RVA field writer.WriteLine(); writer.WriteLine("/// The RVA data with the input type info."); - writer.WriteLine("private static global::System.ReadOnlySpan Data => new[]"); + writer.WriteLine("private static global::System.ReadOnlySpan Data => new[]"); writer.WriteLine("{"); writer.IncreaseIndent(); // Input types, one per line in the RVA field initializer writer.WriteInitializationExpressions(info.InputTypes.AsSpan(), static (type, writer) => { - writer.Write("global::ComputeSharp.D2D1.Interop.D2D1PixelShaderInputType."); + writer.Write("D2D1PixelShaderInputType."); writer.Write(type == 0 ? "Simple" : "Complex"); }); @@ -83,22 +96,22 @@ partial class ID2D1ShaderGenerator // Add the remaining members for the memory manager writer.WriteLine(""" /// - public override unsafe global::System.Span GetSpan() + public override unsafe Span GetSpan() { - return new(global::System.Runtime.CompilerServices.Unsafe.AsPointer(ref global::System.Runtime.InteropServices.MemoryMarshal.GetReference(Data)), Data.Length); + return new(Unsafe.AsPointer(ref MemoryMarshal.GetReference(Data)), Data.Length); } /// - public override global::System.Memory Memory + public override Memory Memory { - [global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] get => CreateMemory(Data.Length); } /// - public override unsafe global::System.Buffers.MemoryHandle Pin(int elementIndex) + public override unsafe MemoryHandle Pin(int elementIndex) { - return new(global::System.Runtime.CompilerServices.Unsafe.AsPointer(ref global::System.Runtime.CompilerServices.Unsafe.AsRef(in Data[elementIndex])), pinnable: this); + return new(Unsafe.AsPointer(ref Unsafe.AsRef(in Data[elementIndex])), pinnable: this); } /// diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.Syntax.cs index ef657cc5..76f2b105 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.Syntax.cs @@ -63,7 +63,7 @@ partial class ID2D1ShaderGenerator } else { - writer.WriteLine("HlslBytecodeMemoryManager.Instance.Memory;"); + writer.WriteLine("global::ComputeSharp.D2D1.Generated.HlslBytecodeMemoryManager.Instance.Memory;"); } } @@ -72,7 +72,11 @@ partial class ID2D1ShaderGenerator /// /// The input instance with gathered shader info. /// The registered callbacks to generate additional types. - public static void RegisterAdditionalTypeSyntax(D2D1ShaderInfo info, ImmutableArrayBuilder> callbacks) + /// The using directives needed by the generated code. + public static void RegisterAdditionalTypeSyntax( + D2D1ShaderInfo info, + ImmutableArrayBuilder> callbacks, + ImmutableHashSetBuilder usingDirectives) { // If there is no bytecode, no memory manager is needed if (info.HlslInfo is not HlslBytecodeInfo.Success) @@ -80,14 +84,22 @@ partial class ID2D1ShaderGenerator return; } + usingDirectives.Add("global::System"); + usingDirectives.Add("global::System.Buffers"); + usingDirectives.Add("global::System.CodeDom.Compiler"); + usingDirectives.Add("global::System.Diagnostics"); + usingDirectives.Add("global::System.Diagnostics.CodeAnalysis"); + usingDirectives.Add("global::System.Runtime.CompilerServices"); + usingDirectives.Add("global::System.Runtime.InteropServices"); + // Declare the HlslBytecodeMemoryManager custom memory manager type static void Callback(D2D1ShaderInfo info, IndentedTextWriter writer) { writer.WriteLine($$"""/// """); - writer.WriteLine($$"""/// implementation to get the HLSL bytecode."""); + writer.WriteLine($$"""/// implementation to get the HLSL bytecode."""); writer.WriteLine($$"""/// """); - writer.WriteGeneratedAttributes(typeof(ID2D1ShaderGenerator)); - writer.WriteLine($$"""file sealed class HlslBytecodeMemoryManager : global::System.Buffers.MemoryManager"""); + writer.WriteGeneratedAttributes(typeof(ID2D1ShaderGenerator), useFullyQualifiedTypeNames: false); + writer.WriteLine($$"""file sealed class HlslBytecodeMemoryManager : MemoryManager"""); using (writer.WriteBlock()) { @@ -98,7 +110,7 @@ partial class ID2D1ShaderGenerator // RVA field (with the compiled HLSL bytecode, on a single line) writer.WriteLine(); writer.WriteLine("/// The RVA data with the HLSL bytecode."); - writer.Write("private static global::System.ReadOnlySpan Data => new byte[] { "); + writer.Write("private static ReadOnlySpan Data => new byte[] { "); SyntaxFormattingHelper.WriteByteArrayInitializationExpressions(((HlslBytecodeInfo.Success)info.HlslInfo).Bytecode.AsSpan(), writer); @@ -108,22 +120,22 @@ partial class ID2D1ShaderGenerator // Add the remaining members for the memory manager writer.WriteLine(""" /// - public override unsafe global::System.Span GetSpan() + public override unsafe Span GetSpan() { - return new(global::System.Runtime.CompilerServices.Unsafe.AsPointer(ref global::System.Runtime.InteropServices.MemoryMarshal.GetReference(Data)), Data.Length); + return new(Unsafe.AsPointer(ref MemoryMarshal.GetReference(Data)), Data.Length); } /// - public override global::System.Memory Memory + public override Memory Memory { - [global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] get => CreateMemory(Data.Length); } /// - public override unsafe global::System.Buffers.MemoryHandle Pin(int elementIndex) + public override unsafe MemoryHandle Pin(int elementIndex) { - return new(global::System.Runtime.CompilerServices.Unsafe.AsPointer(ref global::System.Runtime.CompilerServices.Unsafe.AsRef(in Data[elementIndex])), pinnable: this); + return new(Unsafe.AsPointer(ref Unsafe.AsRef(in Data[elementIndex])), pinnable: this); } /// diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs index ba98b07f..bb9dea1b 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs @@ -31,7 +31,7 @@ partial class ID2D1ShaderGenerator } else { - writer.WriteLine("ConstantBuffer buffer;"); + writer.WriteLine("global::ComputeSharp.D2D1.Generated.ConstantBuffer buffer;"); // Generate loading statements for each captured field foreach (FieldInfo fieldInfo in info.Fields) @@ -71,7 +71,11 @@ partial class ID2D1ShaderGenerator /// /// The input instance with gathered shader info. /// The registered callbacks to generate additional types. - public static void RegisterAdditionalTypeSyntax(D2D1ShaderInfo info, ImmutableArrayBuilder> callbacks) + /// The using directives needed by the generated code. + public static void RegisterAdditionalTypeSyntax( + D2D1ShaderInfo info, + ImmutableArrayBuilder> callbacks, + ImmutableHashSetBuilder usingDirectives) { // If there are no fields, there is no need for a constant buffer type if (info.Fields.IsEmpty) @@ -79,6 +83,11 @@ partial class ID2D1ShaderGenerator return; } + usingDirectives.Add("global::System.CodeDom.Compiler"); + usingDirectives.Add("global::System.Diagnostics"); + usingDirectives.Add("global::System.Diagnostics.CodeAnalysis"); + usingDirectives.Add("global::System.Runtime.InteropServices"); + // Declare the ConstantBuffer type static void Callback(D2D1ShaderInfo info, IndentedTextWriter writer) { @@ -87,8 +96,8 @@ partial class ID2D1ShaderGenerator writer.WriteLine($$"""/// """); writer.WriteLine($$"""/// A type representing the constant buffer native layout for ."""); writer.WriteLine($$"""/// """); - writer.WriteGeneratedAttributes(typeof(ID2D1ShaderGenerator)); - writer.WriteLine($$"""[global::System.Runtime.InteropServices.StructLayout(global::System.Runtime.InteropServices.LayoutKind.Explicit, Size = {{info.ConstantBufferSizeInBytes}})]"""); + writer.WriteGeneratedAttributes(typeof(ID2D1ShaderGenerator), useFullyQualifiedTypeNames: false); + writer.WriteLine($$"""[StructLayout(LayoutKind.Explicit, Size = {{info.ConstantBufferSizeInBytes}})]"""); writer.WriteLine($$"""file struct ConstantBuffer"""); using (writer.WriteBlock()) @@ -102,14 +111,14 @@ partial class ID2D1ShaderGenerator // Append a field as a global::ComputeSharp.Bool value (will use the implicit conversion from bool values) writer.WriteLine($$"""/// """); - writer.WriteLine($$"""[global::System.Runtime.InteropServices.FieldOffset({{primitive.Offset}})]"""); + writer.WriteLine($$"""[FieldOffset({{primitive.Offset}})]"""); writer.WriteLine($$"""public global::ComputeSharp.Bool {{string.Join("_", primitive.FieldPath)}};"""); break; case FieldInfo.Primitive primitive: // Append primitive fields of other types with their mapped names writer.WriteLine($$"""/// """); - writer.WriteLine($$"""[global::System.Runtime.InteropServices.FieldOffset({{primitive.Offset}})]"""); + writer.WriteLine($$"""[FieldOffset({{primitive.Offset}})]"""); writer.WriteLine($$"""public {{HlslKnownTypes.GetMappedName(primitive.TypeName)}} {{string.Join("_", primitive.FieldPath)}};"""); break; @@ -120,8 +129,9 @@ partial class ID2D1ShaderGenerator // Declare a field for every row of the matrix type for (int j = 0; j < matrix.Rows; j++) { + writer.WriteLineIf(j > 0); writer.WriteLine($$"""/// Row {j} of ."""); - writer.WriteLine($$"""[global::System.Runtime.InteropServices.FieldOffset({{matrix.Offsets[j]}})]"""); + writer.WriteLine($$"""[FieldOffset({{matrix.Offsets[j]}})]"""); writer.WriteLine($$"""public {{rowTypeName}} {{fieldNamePrefix}}_{{j}};"""); } diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateResourceTextureDescriptionsProperty.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateResourceTextureDescriptionsProperty.Syntax.cs index b20e0d0e..d24e6673 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateResourceTextureDescriptionsProperty.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateResourceTextureDescriptionsProperty.Syntax.cs @@ -31,10 +31,25 @@ partial class ID2D1ShaderGenerator } else { - writer.WriteLine("Data.ResourceTextureDescriptions;"); + writer.WriteLine("global::ComputeSharp.D2D1.Generated.Data.ResourceTextureDescriptions;"); } } + /// + /// Adds any using directives for the additional data member, if needed. + /// + /// The input instance with gathered shader info. + /// The using directives needed by the generated code. + public static void AddAdditionalDataMemberUsingDirectives(D2D1ShaderInfo info, ImmutableHashSetBuilder usingDirectives) + { + if (info.ResourceTextureDescriptions.IsEmpty) + { + return; + } + + usingDirectives.Add("global::ComputeSharp.D2D1.Interop"); + } + /// /// Registers a callback to generate an additional data member, if needed. /// @@ -51,15 +66,15 @@ partial class ID2D1ShaderGenerator // Declare the shared array with resource texture descriptions static void Callback(D2D1ShaderInfo info, IndentedTextWriter writer) { - writer.WriteLine("""/// The singleton array instance."""); - writer.WriteLine("""public static readonly global::ComputeSharp.D2D1.Interop.D2D1ResourceTextureDescription[] ResourceTextureDescriptions ="""); + writer.WriteLine("""/// The singleton array instance."""); + writer.WriteLine("""public static readonly D2D1ResourceTextureDescription[] ResourceTextureDescriptions ="""); writer.WriteLine("""{"""); writer.IncreaseIndent(); // Initialize all resource texture descriptions writer.WriteInitializationExpressions(info.ResourceTextureDescriptions.AsSpan(), static (description, writer) => { - writer.Write($"new global::ComputeSharp.D2D1.Interop.D2D1ResourceTextureDescription({description.Index}, {description.Rank})"); + writer.Write($"new D2D1ResourceTextureDescription({description.Index}, {description.Rank})"); }); writer.DecreaseIndent(); diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs index d968e554..c1a0eb76 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs @@ -216,21 +216,45 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator declaredMembers.Add(LoadDispatchData.WriteSyntax); using ImmutableArrayBuilder> additionalTypes = ImmutableArrayBuilder>.Rent(); + using ImmutableHashSetBuilder usingDirectives = ImmutableHashSetBuilder.Rent(); - LoadDispatchData.RegisterAdditionalTypeSyntax(item, additionalTypes); - InputDescriptions.RegisterAdditionalTypeSyntax(item, additionalTypes); - InputTypes.RegisterAdditionalTypeSyntax(item, additionalTypes); - LoadBytecode.RegisterAdditionalTypeSyntax(item, additionalTypes); + LoadDispatchData.RegisterAdditionalTypeSyntax(item, additionalTypes, usingDirectives); + InputDescriptions.RegisterAdditionalTypeSyntax(item, additionalTypes, usingDirectives); + InputTypes.RegisterAdditionalTypeSyntax(item, additionalTypes, usingDirectives); + LoadBytecode.RegisterAdditionalTypeSyntax(item, additionalTypes, usingDirectives); using IndentedTextWriter writer = IndentedTextWriter.Rent(); item.Hierarchy.WriteSyntax(item, writer, declaredMembers.WrittenSpan); - foreach (IndentedTextWriter.Callback additionalType in additionalTypes.WrittenSpan) + // If any generated types are needed, they go into a separate namespace + // This allows the code to use using directives without any conflicts. + if (additionalTypes.Count > 0) { writer.WriteLine(); + writer.WriteLine("namespace ComputeSharp.D2D1.Generated"); - additionalType(item, writer); + using (writer.WriteBlock()) + { + // Add the System directives first, in the correct order + foreach (string usingDirective in usingDirectives.AsEnumerable().Where(static name => name.StartsWith("global::System")).OrderBy(static name => name)) + { + writer.WriteLine($"using {usingDirective};"); + } + + // Add the other directives, also sorted in the correct order + foreach (string usingDirective in usingDirectives.AsEnumerable().Where(static name => !name.StartsWith("global::System")).OrderBy(static name => name)) + { + writer.WriteLine($"using {usingDirective};"); + } + + foreach (IndentedTextWriter.Callback callback in additionalTypes.WrittenSpan) + { + writer.WriteLine(); + + callback(item, writer); + } + } } context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.g.cs", writer.ToString()); diff --git a/src/ComputeSharp.SourceGeneration/ComputeSharp.SourceGeneration.projitems b/src/ComputeSharp.SourceGeneration/ComputeSharp.SourceGeneration.projitems index c258c5c8..3a2bf8d3 100644 --- a/src/ComputeSharp.SourceGeneration/ComputeSharp.SourceGeneration.projitems +++ b/src/ComputeSharp.SourceGeneration/ComputeSharp.SourceGeneration.projitems @@ -21,6 +21,7 @@ + diff --git a/src/ComputeSharp.SourceGeneration/Extensions/IndentedTextWriterExtensions.cs b/src/ComputeSharp.SourceGeneration/Extensions/IndentedTextWriterExtensions.cs index 1b27e198..9803e998 100644 --- a/src/ComputeSharp.SourceGeneration/Extensions/IndentedTextWriterExtensions.cs +++ b/src/ComputeSharp.SourceGeneration/Extensions/IndentedTextWriterExtensions.cs @@ -18,11 +18,34 @@ internal static class IndentedTextWriterExtensions /// /// The instance to write into. /// The type of the running generator. - public static void WriteGeneratedAttributes(this IndentedTextWriter writer, Type generatorType) + /// Whether to use fully qualified type names or not. + public static void WriteGeneratedAttributes(this IndentedTextWriter writer, Type generatorType, bool useFullyQualifiedTypeNames = true) { - writer.WriteLine($$"""[global::System.CodeDom.Compiler.GeneratedCode("{{generatorType.FullName}}", "{{generatorType.Assembly.GetName().Version}}")]"""); - writer.WriteLine($$"""[global::System.Diagnostics.DebuggerNonUserCode]"""); - writer.WriteLine($$"""[global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]"""); + if (useFullyQualifiedTypeNames) + { + writer.WriteLine($$"""[global::System.CodeDom.Compiler.GeneratedCode("{{generatorType.FullName}}", "{{generatorType.Assembly.GetName().Version}}")]"""); + writer.WriteLine($$"""[global::System.Diagnostics.DebuggerNonUserCode]"""); + writer.WriteLine($$"""[global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]"""); + } + else + { + writer.WriteLine($$"""[GeneratedCode("{{generatorType.FullName}}", "{{generatorType.Assembly.GetName().Version}}")]"""); + writer.WriteLine($$"""[DebuggerNonUserCode]"""); + writer.WriteLine($$"""[ExcludeFromCodeCoverage]"""); + } + } + + /// + /// Writes a new line into the target writer depending on an input condition. + /// + /// The instance to write into. + /// The condition to use to decide whether or not to write a new line. + public static void WriteLineIf(this IndentedTextWriter writer, bool condition) + { + if (condition) + { + writer.WriteLine(); + } } /// diff --git a/src/ComputeSharp.SourceGeneration/Models/HierarchyInfo.cs b/src/ComputeSharp.SourceGeneration/Models/HierarchyInfo.cs index cd53fca9..7ab7f352 100644 --- a/src/ComputeSharp.SourceGeneration/Models/HierarchyInfo.cs +++ b/src/ComputeSharp.SourceGeneration/Models/HierarchyInfo.cs @@ -56,11 +56,12 @@ internal sealed partial record HierarchyInfo(string FullyQualifiedMetadataName, writer.WriteLine("#pragma warning disable"); writer.WriteLine(); - // Declare the file scoped namespace, if needed + // Declare the namespace, if needed if (Namespace.Length > 0) { - writer.WriteLine($"namespace {Namespace};"); - writer.WriteLine(); + writer.WriteLine($"namespace {Namespace}"); + writer.WriteLine("{"); + writer.IncreaseIndent(); } // Declare all the opening types until the inner-most one @@ -81,6 +82,13 @@ internal sealed partial record HierarchyInfo(string FullyQualifiedMetadataName, writer.DecreaseIndent(); writer.WriteLine("}"); } + + // Close the namespace scope as well, if needed + if (Namespace.Length > 0) + { + writer.DecreaseIndent(); + writer.WriteLine("}"); + } } ///