From bc77ff3392bcae6e0aeb0def2a14e21aa97509ac Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 25 Sep 2023 02:16:47 +0200 Subject: [PATCH 01/13] Add IndentedTextWriter type --- .../ComputeSharp.SourceGeneration.projitems | 1 + .../Helpers/IndentedTextWriter.cs | 222 ++++++++++++++++++ 2 files changed, 223 insertions(+) create mode 100644 src/ComputeSharp.SourceGeneration/Helpers/IndentedTextWriter.cs diff --git a/src/ComputeSharp.SourceGeneration/ComputeSharp.SourceGeneration.projitems b/src/ComputeSharp.SourceGeneration/ComputeSharp.SourceGeneration.projitems index 289de1ea..a223225c 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/Helpers/IndentedTextWriter.cs b/src/ComputeSharp.SourceGeneration/Helpers/IndentedTextWriter.cs new file mode 100644 index 00000000..07506ebf --- /dev/null +++ b/src/ComputeSharp.SourceGeneration/Helpers/IndentedTextWriter.cs @@ -0,0 +1,222 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; + +namespace ComputeSharp.SourceGeneration.Helpers; + +/// +/// A helper type to build sequences of values with pooled buffers. +/// +internal sealed class IndentedTextWriter : IDisposable +{ + /// + /// The default indentation (4 spaces). + /// + private const string DefaultIndentation = " "; + + /// + /// The default new line ('\n'). + /// + private const char DefaultNewLine = '\n'; + + /// + /// The instance that text will be written to. + /// + private ImmutableArrayBuilder builder; + + /// + /// The current indentation level. + /// + private int currentIndentationLevel; + + /// + /// The current indentation, as text. + /// + private string currentIndentation = ""; + + /// + /// The cached array of available indentations, as text. + /// + private string[] availableIndentations; + + /// + /// Creates an instance with a pooled underlying data writer. + /// + /// An instance to write data to. + public static IndentedTextWriter Rent() + { + return new(ImmutableArrayBuilder.Rent()); + } + + /// + /// Creates a new object with the specified parameters. + /// + /// The target instance to use. + private IndentedTextWriter(ImmutableArrayBuilder builder) + { + this.builder = builder; + this.currentIndentationLevel = 0; + this.currentIndentation = DefaultIndentation; + this.availableIndentations = new string[4]; + + this.availableIndentations[0] = ""; + + for (int i = 1, n = this.availableIndentations.Length; i < n; i++) + { + this.availableIndentations[i] = this.availableIndentations[i - 1] + DefaultIndentation; + } + } + + /// + /// Increases the current indentation level. + /// + public void IncreaseIndent() + { + this.currentIndentationLevel++; + + if (this.currentIndentationLevel == this.availableIndentations.Length) + { + Array.Resize(ref this.availableIndentations, this.availableIndentations.Length * 2); + } + + // Set both the current indentation and the current position in the indentations + // array to the expected indentation for the incremented level (ie. one level more). + this.currentIndentation = this.availableIndentations[this.currentIndentationLevel] + ??= this.availableIndentations[this.currentIndentationLevel - 1] + DefaultIndentation; + } + + /// + /// Decreases the current indentation level. + /// + public void DecreaseIndent() + { + this.currentIndentationLevel--; + this.currentIndentation = this.availableIndentations[this.currentIndentationLevel]; + } + + /// + /// Writes a block to the underlying buffer. + /// + /// A value to close the open block with. + public Block WriteBlock() + { + WriteLine("{"); + IncreaseIndent(); + + return new(this); + } + + /// + /// Writes a line to the underlying buffer. + /// + public void WriteLine() + { + this.builder.Add(DefaultNewLine); + } + + /// + /// Writes content to the underlying buffer. + /// + /// The content to write. + /// Whether the input content is multiline. + public void WriteLine(string content, bool isMultiline = false) + { + WriteLine(content.AsSpan(), isMultiline); + } + + /// + /// Writes content to the underlying buffer. + /// + /// The content to write. + /// Whether the input content is multiline. + public void WriteLine(ReadOnlySpan content, bool isMultiline = false) + { + if (isMultiline) + { + while (content.Length > 0) + { + int newLineIndex = content.IndexOf(DefaultNewLine); + + if (newLineIndex < 0) + { + // There are no new lines left, so the content can be written as a single line + WriteSingleLine(content); + } + else + { + // Write the current line + WriteSingleLine(content[..newLineIndex]); + + // Move past the new line character (the result could be an empty span) + content = content[(newLineIndex + 1)..]; + } + } + } + else + { + WriteSingleLine(content); + } + } + + /// + public override string ToString() + { + return this.builder.ToString(); + } + + /// + public void Dispose() + { + this.builder.Dispose(); + } + + /// + /// Writes a single line to the underlying buffer. + /// + /// The content to write. + private void WriteSingleLine(ReadOnlySpan content) + { + if (this.builder.Count == 0 || this.builder.WrittenSpan[^1] == DefaultNewLine) + { + this.builder.AddRange(this.currentIndentation.AsSpan()); + } + + this.builder.AddRange(content); + } + + /// + /// Represents an indented block that needs to be closed. + /// + public struct Block : IDisposable + { + /// + /// The instance to write to. + /// + private IndentedTextWriter? writer; + + /// + /// Creates a new instance with the specified parameters. + /// + /// The input instance to wrap. + public Block(IndentedTextWriter writer) + { + this.writer = writer; + } + + /// + public void Dispose() + { + IndentedTextWriter? writer = this.writer; + + this.writer = null; + + if (writer is not null) + { + writer.DecreaseIndent(); + writer.WriteLine("}"); + } + } + } +} \ No newline at end of file From b4cfad5554e8954250469be91fe61834e2b073bb Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 25 Sep 2023 02:37:28 +0200 Subject: [PATCH 02/13] Add IndentedTextWriter APIs to write with no new lines --- .../Helpers/IndentedTextWriter.cs | 61 +++++++++++++------ 1 file changed, 41 insertions(+), 20 deletions(-) diff --git a/src/ComputeSharp.SourceGeneration/Helpers/IndentedTextWriter.cs b/src/ComputeSharp.SourceGeneration/Helpers/IndentedTextWriter.cs index 07506ebf..1a83eb75 100644 --- a/src/ComputeSharp.SourceGeneration/Helpers/IndentedTextWriter.cs +++ b/src/ComputeSharp.SourceGeneration/Helpers/IndentedTextWriter.cs @@ -109,11 +109,13 @@ internal sealed class IndentedTextWriter : IDisposable } /// - /// Writes a line to the underlying buffer. + /// Writes content to the underlying buffer. /// - public void WriteLine() + /// The content to write. + /// Whether the input content is multiline. + public void Write(string content, bool isMultiline = false) { - this.builder.Add(DefaultNewLine); + Write(content.AsSpan(), isMultiline); } /// @@ -121,17 +123,7 @@ internal sealed class IndentedTextWriter : IDisposable /// /// The content to write. /// Whether the input content is multiline. - public void WriteLine(string content, bool isMultiline = false) - { - WriteLine(content.AsSpan(), isMultiline); - } - - /// - /// Writes content to the underlying buffer. - /// - /// The content to write. - /// Whether the input content is multiline. - public void WriteLine(ReadOnlySpan content, bool isMultiline = false) + public void Write(ReadOnlySpan content, bool isMultiline = false) { if (isMultiline) { @@ -142,12 +134,12 @@ internal sealed class IndentedTextWriter : IDisposable if (newLineIndex < 0) { // There are no new lines left, so the content can be written as a single line - WriteSingleLine(content); + WriteRawText(content); } else { // Write the current line - WriteSingleLine(content[..newLineIndex]); + WriteRawText(content[..newLineIndex]); // Move past the new line character (the result could be an empty span) content = content[(newLineIndex + 1)..]; @@ -156,10 +148,39 @@ internal sealed class IndentedTextWriter : IDisposable } else { - WriteSingleLine(content); + WriteRawText(content); } } + /// + /// Writes a line to the underlying buffer. + /// + public void WriteLine() + { + this.builder.Add(DefaultNewLine); + } + + /// + /// Writes content to the underlying buffer and appends a trailing new line. + /// + /// The content to write. + /// Whether the input content is multiline. + public void WriteLine(string content, bool isMultiline = false) + { + WriteLine(content.AsSpan(), isMultiline); + } + + /// + /// Writes content to the underlying buffer and appends a trailing new line. + /// + /// The content to write. + /// Whether the input content is multiline. + public void WriteLine(ReadOnlySpan content, bool isMultiline = false) + { + Write(content, isMultiline); + WriteLine(); + } + /// public override string ToString() { @@ -173,10 +194,10 @@ internal sealed class IndentedTextWriter : IDisposable } /// - /// Writes a single line to the underlying buffer. + /// Writes raw text to the underlying buffer, adding leading indentation if needed. /// - /// The content to write. - private void WriteSingleLine(ReadOnlySpan content) + /// The raw text to write. + private void WriteRawText(ReadOnlySpan content) { if (this.builder.Count == 0 || this.builder.WrittenSpan[^1] == DefaultNewLine) { From 8daf482eb83dd38cb601dd6ea5272853e9972eef Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 26 Sep 2023 12:11:30 +0200 Subject: [PATCH 03/13] Add WriteInterpolatedStringHandler for indented writer --- .../Helpers/IndentedTextWriter.cs | 90 +++++++++++++++++++ 1 file changed, 90 insertions(+) diff --git a/src/ComputeSharp.SourceGeneration/Helpers/IndentedTextWriter.cs b/src/ComputeSharp.SourceGeneration/Helpers/IndentedTextWriter.cs index 1a83eb75..6fadbdae 100644 --- a/src/ComputeSharp.SourceGeneration/Helpers/IndentedTextWriter.cs +++ b/src/ComputeSharp.SourceGeneration/Helpers/IndentedTextWriter.cs @@ -3,6 +3,9 @@ // See the LICENSE file in the project root for more information. using System; +using System.ComponentModel; +using System.Runtime.CompilerServices; +using System.Text; namespace ComputeSharp.SourceGeneration.Helpers; @@ -152,6 +155,15 @@ internal sealed class IndentedTextWriter : IDisposable } } + /// + /// Writes content to the underlying buffer. + /// + /// The interpolated string handler with content to write. + public void Write([InterpolatedStringHandlerArgument("")] ref WriteInterpolatedStringHandler handler) + { + _ = this; + } + /// /// Writes a line to the underlying buffer. /// @@ -181,6 +193,15 @@ internal sealed class IndentedTextWriter : IDisposable WriteLine(); } + /// + /// Writes content to the underlying buffer and appends a trailing new line. + /// + /// The interpolated string handler with content to write. + public void WriteLine([InterpolatedStringHandlerArgument("")] ref WriteInterpolatedStringHandler handler) + { + WriteLine(); + } + /// public override string ToString() { @@ -240,4 +261,73 @@ internal sealed class IndentedTextWriter : IDisposable } } } + + /// + /// Provides a handler used by the language compiler to append interpolated strings into instances. + /// + [EditorBrowsable(EditorBrowsableState.Never)] + [InterpolatedStringHandler] + public readonly ref struct WriteInterpolatedStringHandler + { + /// The associated to which to append. + private readonly IndentedTextWriter writer; + + /// Creates a handler used to append an interpolated string into a . + /// The number of constant characters outside of interpolation expressions in the interpolated string. + /// The number of interpolation expressions in the interpolated string. + /// The associated to which to append. + /// This is intended to be called only by compiler-generated code. Arguments are not validated as they'd otherwise be for members intended to be used directly. + public WriteInterpolatedStringHandler(int literalLength, int formattedCount, IndentedTextWriter writer) + { + this.writer = writer; + } + + /// Writes the specified string to the handler. + /// The string to write. + public void AppendLiteral(string value) + { + this.writer.Write(value); + } + + /// Writes the specified value to the handler. + /// The value to write. + public void AppendFormatted(string? value) + { + AppendFormatted(value); + } + + /// Writes the specified character span to the handler. + /// The span to write. + public void AppendFormatted(ReadOnlySpan value) + { + this.writer.Write(value); + } + + /// Writes the specified value to the handler. + /// The value to write. + /// The type of the value to write. + public void AppendFormatted(T value) + { + if (value is not null) + { + this.writer.Write(value.ToString()); + } + } + + /// Writes the specified value to the handler. + /// The value to write. + /// The format string. + /// The type of the value to write. + public void AppendFormatted(T value, string? format) + { + if (value is IFormattable) + { + this.writer.Write(((IFormattable)value).ToString(format)); + } + else if (value is not null) + { + this.writer.Write(value.ToString()); + } + } + } } \ No newline at end of file From 117bdc2ab3363c25716898a7b7f6da7312ea3939 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 26 Sep 2023 18:34:49 +0200 Subject: [PATCH 04/13] Add Advance APIs to builder and writer types --- .../Helpers/ImmutableArrayBuilder{T}.cs | 26 +++++++++++++++++++ .../Helpers/IndentedTextWriter.cs | 20 ++++++++++++++ 2 files changed, 46 insertions(+) diff --git a/src/ComputeSharp.SourceGeneration/Helpers/ImmutableArrayBuilder{T}.cs b/src/ComputeSharp.SourceGeneration/Helpers/ImmutableArrayBuilder{T}.cs index 3aa5b62b..aa1d495a 100644 --- a/src/ComputeSharp.SourceGeneration/Helpers/ImmutableArrayBuilder{T}.cs +++ b/src/ComputeSharp.SourceGeneration/Helpers/ImmutableArrayBuilder{T}.cs @@ -60,6 +60,20 @@ internal struct ImmutableArrayBuilder : IDisposable get => this.writer!.WrittenSpan.Length; } + /// + /// Advances the current writer and gets a to the requested memory area. + /// + /// The requested size to advance by. + /// A to the requested memory area. + /// + /// No other data should be written to the builder while the returned + /// is in use, as it could invalidate the memory area wrapped by it, if resizing occurs. + /// + public readonly Span Advance(int requestedSize) + { + return this.writer!.Advance(requestedSize); + } + /// public readonly void Add(T item) { @@ -159,6 +173,18 @@ internal struct ImmutableArrayBuilder : IDisposable get => new(this.array, 0, this.index); } + /// + public Span Advance(int requestedSize) + { + EnsureCapacity(requestedSize); + + Span span = this.array.AsSpan(this.index, requestedSize); + + this.index += requestedSize; + + return span; + } + /// public void Add(T value) { diff --git a/src/ComputeSharp.SourceGeneration/Helpers/IndentedTextWriter.cs b/src/ComputeSharp.SourceGeneration/Helpers/IndentedTextWriter.cs index 6fadbdae..470f6696 100644 --- a/src/ComputeSharp.SourceGeneration/Helpers/IndentedTextWriter.cs +++ b/src/ComputeSharp.SourceGeneration/Helpers/IndentedTextWriter.cs @@ -72,6 +72,26 @@ internal sealed class IndentedTextWriter : IDisposable } } + /// + /// Advances the current writer and gets a to the requested memory area. + /// + /// The requested size to advance by. + /// A to the requested memory area. + /// + /// No other data should be written to the writer while the returned + /// is in use, as it could invalidate the memory area wrapped by it, if resizing occurs. + /// + public Span Advance(int requestedSize) + { + // Add the leading whitespace if needed (same as WriteRawText below) + if (this.builder.Count == 0 || this.builder.WrittenSpan[^1] == DefaultNewLine) + { + this.builder.AddRange(this.currentIndentation.AsSpan()); + } + + return this.builder.Advance(requestedSize); + } + /// /// Increases the current indentation level. /// From bc1fc17b2135d1b6525731a6a71220cb384a35f1 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 26 Sep 2023 18:45:49 +0200 Subject: [PATCH 05/13] Add new WriteByteArrayInitializationExpressions API --- .../Helpers/SyntaxFormattingHelper.cs | 52 +++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/src/ComputeSharp.SourceGeneration.Hlsl/Helpers/SyntaxFormattingHelper.cs b/src/ComputeSharp.SourceGeneration.Hlsl/Helpers/SyntaxFormattingHelper.cs index da489b18..da5256a7 100644 --- a/src/ComputeSharp.SourceGeneration.Hlsl/Helpers/SyntaxFormattingHelper.cs +++ b/src/ComputeSharp.SourceGeneration.Hlsl/Helpers/SyntaxFormattingHelper.cs @@ -30,6 +30,58 @@ internal static class SyntaxFormattingHelper "0xF0", "0xF1", "0xF2", "0xF3", "0xF4", "0xF5", "0xF6", "0xF7", "0xF8", "0xF9", "0xFA", "0xFB", "0xFC", "0xFD", "0xFE", "0xFF" }; + /// + /// Writes a formatted expression to initialize a with a given content. + /// + /// The input byte content to serialize. + /// The instance to write the expressions to. + /// + /// This function will write raw byte initialization expressions, such as: + /// [1, 2, 3, 4, 5] => 0x01, 0x02, 0x03, 0x04, 0x05. + /// + public static void WriteByteArrayInitializationExpressions(ReadOnlySpan bytecode, IndentedTextWriter writer) + { + if (bytecode.Length == 0) + { + return; + } + + // Calculate the buffer size: + // - 4 characters per item (eg. "0x00") + // - 2 characters between each pair of items (ie. ", ") + int length = (bytecode.Length * 4) + ((bytecode.Length - 1) * 2); + + // Reserve the space and get a span into the writer buffer + Span span = writer.Advance(length); + + // Cache the value expressions to avoid accessing the static fields multiple times + ReadOnlySpan expressions = FormattedBytes.AsSpan(); + + // First write the first item (which has no leading separator) + expressions[0].AsSpan().CopyTo(span); + + // Special case: stop early if there's only one element + if (bytecode.Length == 1) + { + return; + } + + // Advance the span to right past the item we've already written. + // This is so that each new item can assume it's starting from 0. + span = span.Slice(4); + + // Loop over all remaining items, and add the separator and encoded value. + // Then slice the remaining span so following items can repeat the same. + foreach (byte b in bytecode.Slice(1)) + { + span[0] = ','; + span[1] = ' '; + expressions[b].AsSpan().CopyTo(span.Slice(2)); + + span = span.Slice(6); + } + } + /// /// Creates a formatted expression to initialize a with a given content. /// From 6accd17c9fca035da3a4cee30b17bc8c4d9b20ed Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Fri, 29 Sep 2023 21:40:07 +0200 Subject: [PATCH 06/13] Switch D2D1 generation methods to use indented writer --- ...Generator.CreateEffectIdProperty.Syntax.cs | 130 +++--- ...r.CreateEffectMetadataProperties.Syntax.cs | 79 ++-- ...nerator.CreateHlslSourceProperty.Syntax.cs | 33 +- ...InitializeFromDispatchDataMethod.Syntax.cs | 192 +++------ ...nerator.CreateInputCountProperty.Syntax.cs | 26 +- ....CreateInputDescriptionsProperty.Syntax.cs | 132 ++----- ...nerator.CreateInputTypesProperty.Syntax.cs | 337 ++++------------ ...nerator.CreateLoadBytecodeMethod.Syntax.cs | 374 +++++------------- ...tor.CreateLoadDispatchDataMethod.Syntax.cs | 362 +++++------------ ...tor.CreateOutputBufferProperties.Syntax.cs | 83 ++-- ...rator.CreatePixelOptionsProperty.Syntax.cs | 44 +-- ...ourceTextureDescriptionsProperty.Syntax.cs | 115 ++---- .../Helpers/SyntaxFormattingHelper.cs | 12 +- .../Helpers/IndentedTextWriter.cs | 8 + 14 files changed, 555 insertions(+), 1372 deletions(-) diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectIdProperty.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectIdProperty.Syntax.cs index 061a20e5..cf0a71d8 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectIdProperty.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectIdProperty.Syntax.cs @@ -1,10 +1,5 @@ -using ComputeSharp.D2D1.__Internals; +using ComputeSharp.D2D1.SourceGenerators.Models; using ComputeSharp.SourceGeneration.Helpers; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Syntax; -using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; - -#pragma warning disable CS0618 namespace ComputeSharp.D2D1.SourceGenerators; @@ -15,85 +10,62 @@ partial class ID2D1ShaderGenerator partial class EffectId { /// - /// Creates a instance for the EffectId property. + /// Writes the EffectId property. /// - /// The input instance with the effect GUID. - /// The resulting instance for the EffectId property. - public static PropertyDeclarationSyntax GetSyntax(EquatableArray info) + /// The input instance with gathered shader info. + /// The instance to write into. + public static void WriteSyntax(D2D1ShaderInfo info, IndentedTextWriter writer) { - // Prepare the initialization text - string effectIdLiterals = SyntaxFormattingHelper.BuildByteArrayInitializationExpressionString(info.AsSpan()); + writer.WriteLine("readonly ref readonly global::System.Guid global::ComputeSharp.D2D1.__Internals.ID2D1Shader.EffectId"); - ExpressionSyntax effectIdExpression = ParseExpression($$"""new byte[] { {{effectIdLiterals}} }"""); + using (writer.WriteBlock()) + { + writer.WriteLine("[global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]"); + writer.WriteLine("get"); - // Create the local declaration: - // - // global::System.ReadOnlySpan bytes = new byte[] { }; - LocalDeclarationStatementSyntax guidBytesDeclaration = - LocalDeclarationStatement( - VariableDeclaration( - GenericName(Identifier("global::System.ReadOnlySpan")) - .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ByteKeyword)))) - .AddVariables( - VariableDeclarator(Identifier("bytes")) - .WithInitializer( - EqualsValueClause(effectIdExpression)))); + using (writer.WriteBlock()) + { + writer.WriteLine($"global::System.ReadOnlySpan bytes = new byte[]"); - // Prepare the return statement: - // - // return - // ref global::System.Runtime.CompilerServices.Unsafe.As( - // ref global::System.Runtime.InteropServices.MemoryMarshal.GetReference(bytes)); - ReturnStatementSyntax returnStatement = - ReturnStatement( - RefExpression( - InvocationExpression( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("global::System.Runtime.CompilerServices.Unsafe"), - GenericName(Identifier("As")) - .AddTypeArgumentListArguments( - PredefinedType(Token(SyntaxKind.ByteKeyword)), - IdentifierName("global::System.Guid")))) - .AddArgumentListArguments( - Argument( - InvocationExpression( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("global::System.Runtime.InteropServices.MemoryMarshal"), - IdentifierName("GetReference"))) - .AddArgumentListArguments(Argument(IdentifierName("bytes")))) - .WithRefOrOutKeyword(Token(SyntaxKind.RefKeyword))))); + using (writer.WriteBlock()) + { + // Write the bytes like so: + // + // b[0], b[1], b[2], b[3], + // b[4], b[5], + // b[6], b[7], + // b[8], + // b[9], + // b[10], + // b[11], + // b[12], + // b[13], + // b[14], + // b[15], + // b[16], + // b[17] + SyntaxFormattingHelper.WriteByteArrayInitializationExpressions(info.EffectId.AsSpan()[..4], writer); + writer.WriteLine(","); + SyntaxFormattingHelper.WriteByteArrayInitializationExpressions(info.EffectId.AsSpan()[4..6], writer); + writer.WriteLine(","); + SyntaxFormattingHelper.WriteByteArrayInitializationExpressions(info.EffectId.AsSpan()[6..8], writer); + writer.WriteLine(","); + writer.WriteLine($"{SyntaxFormattingHelper.GetByteExpression(info.EffectId[8])},"); + writer.WriteLine($"{SyntaxFormattingHelper.GetByteExpression(info.EffectId[9])},"); + writer.WriteLine($"{SyntaxFormattingHelper.GetByteExpression(info.EffectId[10])},"); + writer.WriteLine($"{SyntaxFormattingHelper.GetByteExpression(info.EffectId[11])},"); + writer.WriteLine($"{SyntaxFormattingHelper.GetByteExpression(info.EffectId[12])},"); + writer.WriteLine($"{SyntaxFormattingHelper.GetByteExpression(info.EffectId[13])},"); + writer.WriteLine($"{SyntaxFormattingHelper.GetByteExpression(info.EffectId[14])},"); + writer.WriteLine($"{SyntaxFormattingHelper.GetByteExpression(info.EffectId[15])},"); + writer.WriteLine($"{SyntaxFormattingHelper.GetByteExpression(info.EffectId[16])},"); + writer.WriteLine(SyntaxFormattingHelper.GetByteExpression(info.EffectId[17])); + } - // This code produces a property declaration as follows: - // - // readonly ref readonly global::System.Guid global::ComputeSharp.D2D1.__Internals.ID2D1Shader.EffectId - // { - // [global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - // get - // { - // - // - // } - // } - return - PropertyDeclaration( - RefType(IdentifierName("global::System.Guid")).WithReadOnlyKeyword(Token(SyntaxKind.ReadOnlyKeyword)), - Identifier(nameof(EffectId))) - .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.D2D1.__Internals.{nameof(ID2D1Shader)}"))) - .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword)) - .AddAccessorListAccessors( - AccessorDeclaration(SyntaxKind.GetAccessorDeclaration) - .AddAttributeLists( - AttributeList(SingletonSeparatedList( - Attribute(IdentifierName("global::System.Runtime.CompilerServices.MethodImpl")) - .AddArgumentListArguments( - AttributeArgument( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("global::System.Runtime.CompilerServices.MethodImplOptions"), - IdentifierName("AggressiveInlining"))))))) - .AddBodyStatements(guidBytesDeclaration, returnStatement)); + writer.WriteLine(); + writer.WriteLine("return ref global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.InteropServices.MemoryMarshal.GetReference(bytes));"); + } + } } } } \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectMetadataProperties.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectMetadataProperties.Syntax.cs index fee46c11..c78732ad 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectMetadataProperties.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectMetadataProperties.Syntax.cs @@ -1,9 +1,5 @@ -using ComputeSharp.D2D1.__Internals; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Syntax; -using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; - -#pragma warning disable CS0618 +using ComputeSharp.D2D1.SourceGenerators.Models; +using ComputeSharp.SourceGeneration.Helpers; namespace ComputeSharp.D2D1.SourceGenerators; @@ -14,69 +10,64 @@ partial class ID2D1ShaderGenerator partial class EffectMetadata { /// - /// Creates a instance for the EffectDisplayName property. + /// Writes the EffectDisplayName property. /// - /// The input effect display name value, if available. - /// The resulting instance for the EffectDisplayName property. - public static PropertyDeclarationSyntax GetEffectDisplayNameSyntax(string? effectDisplayName) + /// The input instance with gathered shader info. + /// The instance to write into. + public static void WriteEffectDisplayNameSyntax(D2D1ShaderInfo info, IndentedTextWriter writer) { - return GetEffectMetadataSyntax("EffectDisplayName", effectDisplayName); + WriteEffectMetadataSyntax("EffectDisplayName", info.EffectDisplayName, writer); } /// - /// Creates a instance for the EffectDescription property. + /// Writes the EffectDescription property. /// - /// The input effect description value, if available. - /// The resulting instance for the EffectDescription property. - public static PropertyDeclarationSyntax GetEffectDescriptionSyntax(string? effectDescription) + /// The input instance with gathered shader info. + /// The instance to write into. + public static void WriteEffectDescriptionSyntax(D2D1ShaderInfo info, IndentedTextWriter writer) { - return GetEffectMetadataSyntax("EffectDescription", effectDescription); + WriteEffectMetadataSyntax("EffectDescription", info.EffectDescription, writer); } /// - /// Creates a instance for the EffectCategory property. + /// Writes the EffectCategory property. /// - /// The input effect category value, if available. - /// The resulting instance for the EffectCategory property. - public static PropertyDeclarationSyntax GetEffectCategorySyntax(string? effectCategory) + /// The input instance with gathered shader info. + /// The instance to write into. + public static void WriteEffectCategorySyntax(D2D1ShaderInfo info, IndentedTextWriter writer) { - return GetEffectMetadataSyntax("EffectCategory", effectCategory); + WriteEffectMetadataSyntax("EffectCategory", info.EffectCategory, writer); } /// - /// Creates a instance for the EffectAuthor property. + /// Writes the EffectAuthor property. /// - /// The input effect author value, if available. - /// The resulting instance for the EffectAuthor property. - public static PropertyDeclarationSyntax GetEffectAuthorSyntax(string? effectAuthor) + /// The input instance with gathered shader info. + /// The instance to write into. + public static void WriteEffectAuthorSyntax(D2D1ShaderInfo info, IndentedTextWriter writer) { - return GetEffectMetadataSyntax("EffectAuthor", effectAuthor); + WriteEffectMetadataSyntax("EffectAuthor", info.EffectAuthor, writer); } /// - /// Creates a instance for a given metadata property. + /// Writes a specified metadata property. /// /// The property name to generate. /// The input effect metadata value, if available. - /// The resulting instance for the given metadata property. - private static PropertyDeclarationSyntax GetEffectMetadataSyntax(string propertyName, string? metadataValue) + /// The instance to write into. + private static void WriteEffectMetadataSyntax(string propertyName, string? metadataValue, IndentedTextWriter writer) { - // Get the expression: either a string literal, or just null - ExpressionSyntax metadataValueExpression = metadataValue switch - { - { } => LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(metadataValue)), - _ => LiteralExpression(SyntaxKind.NullLiteralExpression) - }; + writer.Write($"readonly string? global::ComputeSharp.D2D1.__Internals.ID2D1Shader.{propertyName} => "); - // This code produces a method declaration as follows: - // - // readonly string? global::ComputeSharp.D2D1.__Internals.ID2D1Shader. => ; - return - PropertyDeclaration(NullableType(PredefinedType(Token(SyntaxKind.StringKeyword))), Identifier(propertyName)) - .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.D2D1.__Internals.{nameof(ID2D1Shader)}"))) - .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword)) - .WithExpressionBody(ArrowExpressionClause(metadataValueExpression)) - .WithSemicolonToken(Token(SyntaxKind.SemicolonToken)); + // Append null or the metadata value as a string literal + if (metadataValue is null) + { + writer.WriteLine("null;"); + } + else + { + writer.WriteLine($"\"{metadataValue}\";"); + } } } } \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateHlslSourceProperty.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateHlslSourceProperty.Syntax.cs index 70c3c9e8..3a508bd5 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateHlslSourceProperty.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateHlslSourceProperty.Syntax.cs @@ -1,11 +1,5 @@ -using ComputeSharp.D2D1.__Internals; +using ComputeSharp.D2D1.SourceGenerators.Models; using ComputeSharp.SourceGeneration.Helpers; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Syntax; -using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; - -#pragma warning disable CS0618 namespace ComputeSharp.D2D1.SourceGenerators; @@ -16,25 +10,16 @@ partial class ID2D1ShaderGenerator partial class HlslSource { /// - /// Creates a instance for the HlslSource property. + /// Writes the HlslSource property. /// - /// The input HLSL source. - /// The depth of the hierarchy for this type (used to calculate the right indentation). - /// The resulting instance for the HlslSource property. - public static PropertyDeclarationSyntax GetSyntax(string hlslSource, int hierarchyDepth) + /// The input instance with gathered shader info. + /// The instance to write into. + public static void WriteSyntax(D2D1ShaderInfo info, IndentedTextWriter writer) { - // The indentation level is the current depth + 1 (for the property) - SyntaxToken hlslSourceLiteralExpression = SyntaxTokenHelper.CreateRawMultilineStringLiteral(hlslSource, hierarchyDepth + 1); - - // This code produces a property declaration as follows: - // - // readonly string global::ComputeSharp.D2D1.__Internals.ID2D1Shader.HlslSource => ; - return - PropertyDeclaration(PredefinedType(Token(SyntaxKind.StringKeyword)), Identifier("HlslSource")) - .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.D2D1.__Internals.{nameof(ID2D1Shader)}"))) - .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword)) - .WithExpressionBody(ArrowExpressionClause(LiteralExpression(SyntaxKind.StringLiteralExpression, hlslSourceLiteralExpression))) - .WithSemicolonToken(Token(SyntaxKind.SemicolonToken)); + writer.WriteLine("readonly string global::ComputeSharp.D2D1.__Internals.ID2D1Shader.HlslSource =>"); + writer.WriteLine("\"\"\""); + writer.WriteLine(info.HlslInfoKey.HlslSource, isMultiline: true); + writer.WriteLine("\"\"\";"); } } } \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInitializeFromDispatchDataMethod.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInitializeFromDispatchDataMethod.Syntax.cs index 6848e527..1c15a7df 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInitializeFromDispatchDataMethod.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInitializeFromDispatchDataMethod.Syntax.cs @@ -1,12 +1,5 @@ -using System.Collections.Immutable; -using ComputeSharp.D2D1.__Internals; using ComputeSharp.D2D1.SourceGenerators.Models; using ComputeSharp.SourceGeneration.Helpers; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Syntax; -using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; - -#pragma warning disable CS0618 namespace ComputeSharp.D2D1.SourceGenerators; @@ -17,156 +10,63 @@ partial class ID2D1ShaderGenerator partial class InitializeFromDispatchData { /// - /// Creates a instance for the InitializeFromDispatchData method. + /// Writes the InitializeFromDispatchData method. /// - /// The discovered fields of the current shader. - /// The resulting instance for the InitializeFromDispatchData method. - public static MethodDeclarationSyntax GetSyntax(EquatableArray fields) + /// The input instance with gathered shader info. + /// The instance to write into. + public static void WriteSyntax(D2D1ShaderInfo info, IndentedTextWriter writer) { - // This code produces a method declaration as follows: - // - // readonly void global::ComputeSharp.D2D1.__Internals.ID2D1Shader.InitializeFromDispatchData(global::System.ReadOnlySpan data) - // { - // - // } - return - MethodDeclaration(PredefinedType(Token(SyntaxKind.VoidKeyword)), Identifier(nameof(InitializeFromDispatchData))) - .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.D2D1.__Internals.{nameof(ID2D1Shader)}"))) - .AddParameterListParameters(Parameter(Identifier("data")).WithType( - GenericName(Identifier("global::System.ReadOnlySpan")) - .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ByteKeyword))))) - .WithBody(Block(GetDispatchDataUnloadingStatements(fields))); - } + writer.WriteLine("readonly void global::ComputeSharp.D2D1.__Internals.ID2D1Shader.InitializeFromDispatchData(global::System.ReadOnlySpan data)"); - /// - /// Gets a sequence of statements to initialize a shader from a serialized dispatch data buffer. - /// - /// The array of values for all captured fields. - /// The sequence of instances to initialize a shader from the serialized dispatch data buffer. - private static ImmutableArray GetDispatchDataUnloadingStatements(ImmutableArray fieldInfos) - { - // If there are no fields, just return no statements - if (fieldInfos.IsEmpty) + using (writer.WriteBlock()) { - return ImmutableArray.Empty; - } - - using ImmutableArrayBuilder statements = ImmutableArrayBuilder.Rent(); - - // Insert the fallback for empty shaders. This will generate the following code: - // - // if (data.IsEmpty) - // { - // return; - // } - statements.Add( - IfStatement( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("data"), - IdentifierName("IsEmpty")), - Block(ReturnStatement()))); - - // ref readonly ConstantBuffer buffer = ref global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.InteropServices.MemoryMarshal.GetReference(data)); - statements.Add( - LocalDeclarationStatement( - VariableDeclaration(RefType(IdentifierName("ConstantBuffer")).WithReadOnlyKeyword(Token(SyntaxKind.ReadOnlyKeyword))) - .AddVariables( - VariableDeclarator(Identifier("buffer")) - .WithInitializer( - EqualsValueClause(RefExpression( - InvocationExpression( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("global::System.Runtime.CompilerServices.Unsafe"), - GenericName(Identifier("As")) - .AddTypeArgumentListArguments( - PredefinedType(Token(SyntaxKind.ByteKeyword)), - IdentifierName("ConstantBuffer")))) - .AddArgumentListArguments( - Argument( - InvocationExpression( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("global::System.Runtime.InteropServices.MemoryMarshal"), - IdentifierName("GetReference"))) - .AddArgumentListArguments(Argument(IdentifierName("data")))) - .WithRefOrOutKeyword(Token(SyntaxKind.RefKeyword))))))))); - - // Generate loading statements for each captured field - foreach (FieldInfo fieldInfo in fieldInfos) - { - switch (fieldInfo) + // If there are no fields, the method body is just empty + if (info.Fields.IsEmpty) { - case FieldInfo.Primitive primitive: + return; + } - // Read a primitive value: - // - // global::System.Runtime.CompilerServices.Unsafe.AsRef(in this.) = buffer.; - statements.Add( - ExpressionStatement( - AssignmentExpression( - SyntaxKind.SimpleAssignmentExpression, - InvocationExpression( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("global::System.Runtime.CompilerServices.Unsafe"), - IdentifierName("AsRef"))) - .AddArgumentListArguments( - Argument(MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - ThisExpression(), - IdentifierName(string.Join(".", primitive.FieldPath)))) - .WithRefKindKeyword(Token(SyntaxKind.InKeyword))), - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("buffer"), - IdentifierName(string.Join("_", primitive.FieldPath)))))); - break; + // Insert the fallback for empty shaders. This will generate the following code: + writer.WriteLine("if (data.IsEmpty)"); - case FieldInfo.NonLinearMatrix matrix: - string fieldPath = string.Join(".", matrix.FieldPath); - string fieldNamePrefix = string.Join("_", matrix.FieldPath); + using (writer.WriteBlock()) + { + writer.WriteLine("return;"); + } - // Read all rows of a given matrix type: - // - // global::System.Runtime.CompilerServices.Unsafe.AsRef(in this.)[0] = buffer.; - // global::System.Runtime.CompilerServices.Unsafe.AsRef(in this.)[1] = buffer.; - // ... - // global::System.Runtime.CompilerServices.Unsafe.AsRef(in this.)[N] = buffer.; - for (int j = 0; j < matrix.Rows; j++) - { - statements.Add( - ExpressionStatement( - AssignmentExpression( - SyntaxKind.SimpleAssignmentExpression, - ElementAccessExpression( - InvocationExpression( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("global::System.Runtime.CompilerServices.Unsafe"), - IdentifierName("AsRef"))) - .AddArgumentListArguments( - Argument(MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - ThisExpression(), - IdentifierName(fieldPath))) - .WithRefKindKeyword(Token(SyntaxKind.InKeyword)))) - .AddArgumentListArguments( - Argument(LiteralExpression( - SyntaxKind.NumericLiteralExpression, - Literal(j)))), - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("buffer"), - IdentifierName($"{fieldNamePrefix}_{j}"))))); - } + // Get a reference to the data through the generated native layout type + writer.WriteLine("ref readonly ConstantBuffer buffer = ref global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.InteropServices.MemoryMarshal.GetReference(data));"); - break; + // Generate loading statements for each captured field + foreach (FieldInfo fieldInfo in info.Fields) + { + switch (fieldInfo) + { + case FieldInfo.Primitive primitive: + + // Read a primitive value + writer.WriteLine($"global::System.Runtime.CompilerServices.Unsafe.AsRef(in this.{string.Join(".", primitive.FieldPath)}) = buffer.{string.Join("_", primitive.FieldPath)};"); + break; + + case FieldInfo.NonLinearMatrix matrix: + string fieldPath = string.Join(".", matrix.FieldPath); + string fieldNamePrefix = string.Join("_", matrix.FieldPath); + + // Read all rows of a given matrix type: + // + // global::System.Runtime.CompilerServices.Unsafe.AsRef(in this.)[0] = buffer.; + // global::System.Runtime.CompilerServices.Unsafe.AsRef(in this.)[1] = buffer.; + // ... + // global::System.Runtime.CompilerServices.Unsafe.AsRef(in this.)[N] = buffer.; + for (int j = 0; j < matrix.Rows; j++) + { + writer.WriteLine($"global::System.Runtime.CompilerServices.Unsafe.AsRef(in this.{fieldPath})[0] = buffer.{fieldNamePrefix}_{j};"); + } + + break; + } } } - - return statements.ToImmutable(); } } } \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInputCountProperty.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInputCountProperty.Syntax.cs index e92a4b0e..ba8579df 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInputCountProperty.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInputCountProperty.Syntax.cs @@ -1,9 +1,5 @@ -using ComputeSharp.D2D1.__Internals; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Syntax; -using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; - -#pragma warning disable CS0618 +using ComputeSharp.D2D1.SourceGenerators.Models; +using ComputeSharp.SourceGeneration.Helpers; namespace ComputeSharp.D2D1.SourceGenerators; @@ -16,21 +12,13 @@ partial class ID2D1ShaderGenerator private static partial class InputCount { /// - /// Creates a instance for the InputCount property. + /// Writes the InputCount property. /// - /// The number of inputs for the shader. - /// The resulting instance for the InputCount property. - public static PropertyDeclarationSyntax GetSyntax(int inputCount) + /// The input instance with gathered shader info. + /// The instance to write into. + public static void WriteSyntax(D2D1ShaderInfo info, IndentedTextWriter writer) { - // This code produces a property declaration as follows: - // - // readonly int global::ComputeSharp.D2D1.__Internals.ID2D1Shader.InputCount => ; - return - PropertyDeclaration(PredefinedType(Token(SyntaxKind.IntKeyword)), Identifier(nameof(InputCount))) - .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.D2D1.__Internals.{nameof(ID2D1Shader)}"))) - .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword)) - .WithExpressionBody(ArrowExpressionClause(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(inputCount)))) - .WithSemicolonToken(Token(SyntaxKind.SemicolonToken)); + writer.WriteLine($"readonly int global::ComputeSharp.D2D1.__Internals.ID2D1Shader.InputCount => {info.InputTypes.Length};"); } } } \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInputDescriptionsProperty.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInputDescriptionsProperty.Syntax.cs index d5597ef5..50c429f4 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInputDescriptionsProperty.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInputDescriptionsProperty.Syntax.cs @@ -1,5 +1,4 @@ using System; -using ComputeSharp.D2D1.__Internals; using ComputeSharp.D2D1.SourceGenerators.Models; using ComputeSharp.SourceGeneration.Helpers; using Microsoft.CodeAnalysis; @@ -7,8 +6,6 @@ using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; -#pragma warning disable CS0618 - namespace ComputeSharp.D2D1.SourceGenerators; /// @@ -18,112 +15,63 @@ partial class ID2D1ShaderGenerator private static partial class InputDescriptions { /// - /// Creates a instance for the InputDescriptions property. + /// Writes the InputDescriptions property. /// - /// The input descriptions info gathered for the current shader. - /// Any additional instances needed by the generated code, if needed. - /// The resulting instance for the InputDescriptions property. - public static PropertyDeclarationSyntax GetSyntax(EquatableArray inputDescriptions, out MemberDeclarationSyntax[] additionalDataMembers) + /// The input instance with gathered shader info. + /// The instance to write into. + public static void WriteSyntax(D2D1ShaderInfo info, IndentedTextWriter writer) { - ExpressionSyntax memoryExpression; + writer.WriteLine("readonly global::System.ReadOnlyMemory global::ComputeSharp.D2D1.__Internals.ID2D1Shader.InputDescriptions => "); // If there are no input descriptions, just return a default expression. - // Otherwise, declare the shared array and return it from the property. - if (inputDescriptions.Length == 0) + // Otherwise, return the shared array with cached input descriptions. + if (info.InputDescriptions.IsEmpty) { - memoryExpression = LiteralExpression(SyntaxKind.DefaultLiteralExpression, Token(SyntaxKind.DefaultKeyword)); - additionalDataMembers = Array.Empty(); + writer.WriteLine("default;"); } else { - memoryExpression = MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("Data"), - IdentifierName(nameof(InputDescriptions))); - - additionalDataMembers = new[] { GetArrayDeclaration(inputDescriptions) }; + writer.WriteLine("Data.InputDescriptions;"); } - - // This code produces a method declaration as follows: - // - // readonly global::System.ReadOnlyMemory global::ComputeSharp.D2D1.__Internals.ID2D1Shader.InputDescriptions => ; - return - PropertyDeclaration( - GenericName(Identifier("global::System.ReadOnlyMemory")) - .AddTypeArgumentListArguments(IdentifierName("global::ComputeSharp.D2D1.Interop.D2D1InputDescription")), - Identifier(nameof(InputDescriptions))) - .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.D2D1.__Internals.{nameof(ID2D1Shader)}"))) - .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword)) - .WithExpressionBody(ArrowExpressionClause(memoryExpression)) - .WithSemicolonToken(Token(SyntaxKind.SemicolonToken)); } /// - /// Gets the array declaration for the given input descriptions. + /// Registers a callback to generate an additional data member, if needed. /// - /// The input descriptions info gathered for the current shader. - /// The array declaration for the given input descriptions. - private static MemberDeclarationSyntax GetArrayDeclaration(EquatableArray inputDescriptions) + /// The input instance with gathered shader info. + /// The registered callbacks to generate additional data members. + public static void RegisterAdditionalDataMemberSyntax(D2D1ShaderInfo info, ImmutableArrayBuilder> callbacks) { - using ImmutableArrayBuilder inputDescriptionExpressions = ImmutableArrayBuilder.Rent(); - - foreach (InputDescription inputDescription in inputDescriptions) + // If there are no input descriptions, there is nothing to di + if (info.ResourceTextureDescriptions.IsEmpty) { - // Create the description expression (excluding level of detail): - // - // new(, ) - ImplicitObjectCreationExpressionSyntax inputDescriptionExpression = - ImplicitObjectCreationExpression() - .AddArgumentListArguments( - Argument(LiteralExpression( - SyntaxKind.NumericLiteralExpression, - Literal(inputDescription.Index))), - Argument( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("global::ComputeSharp.D2D1.D2D1Filter"), - IdentifierName(inputDescription.Filter.ToString())))); - - // Add the level of detail, if needed: - // - // { LevelOfDetailCount = } - if (inputDescription.LevelOfDetailCount != 0) - { - inputDescriptionExpression = - inputDescriptionExpression - .WithInitializer( - InitializerExpression(SyntaxKind.ObjectInitializerExpression) - .AddExpressions( - AssignmentExpression( - SyntaxKind.SimpleAssignmentExpression, - IdentifierName("LevelOfDetailCount"), - LiteralExpression( - SyntaxKind.NumericLiteralExpression, - Literal(inputDescription.LevelOfDetailCount))))); - } - - inputDescriptionExpressions.Add(inputDescriptionExpression); + return; } - // Declare the singleton property to get the memory instance: - // - // /// The singleton array instance. - // public static readonly global::ComputeSharp.D2D1.Interop.D2D1InputDescription[] InputDescriptions = { }; - return - FieldDeclaration( - VariableDeclaration( - ArrayType(IdentifierName("global::ComputeSharp.D2D1.Interop.D2D1InputDescription")) - .AddRankSpecifiers(ArrayRankSpecifier(SingletonSeparatedList(OmittedArraySizeExpression())))) - .AddVariables( - VariableDeclarator(Identifier(nameof(InputDescriptions))) - .WithInitializer(EqualsValueClause( - InitializerExpression(SyntaxKind.ArrayInitializerExpression) - .AddExpressions(inputDescriptionExpressions.ToArray()))))) - .AddModifiers( - Token(SyntaxKind.PublicKeyword), - Token(SyntaxKind.StaticKeyword), - Token(SyntaxKind.ReadOnlyKeyword)) - .WithLeadingTrivia(Comment("""/// The singleton array instance.""")); + // 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 = """); + + // Initialize all input descriptions + using (writer.WriteBlock()) + { + for (int i = 0; i < info.InputDescriptions.Length; i++) + { + InputDescription description = info.InputDescriptions[i]; + + writer.Write($$"""new global::ComputeSharp.D2D1.Interop.D2D1InputDescription({description.Index}, {description.Filter}) { LevelOfDetailCount = {{description.LevelOfDetailCount}} }"""); + + if (i < info.InputDescriptions.Length - 1) + { + writer.WriteLine(","); + } + } + } + } + + callbacks.Add(Callback); } /// diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInputTypesProperty.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInputTypesProperty.Syntax.cs index fe837ca3..4d536efa 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInputTypesProperty.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInputTypesProperty.Syntax.cs @@ -1,13 +1,5 @@ -using System; -using System.Collections.Immutable; -using ComputeSharp.D2D1.__Internals; +using ComputeSharp.D2D1.SourceGenerators.Models; using ComputeSharp.SourceGeneration.Helpers; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Syntax; -using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; - -#pragma warning disable CS0618 namespace ComputeSharp.D2D1.SourceGenerators; @@ -18,270 +10,111 @@ partial class ID2D1ShaderGenerator partial class InputTypes { /// - /// Creates a instance for the InputTypes property. + /// Writes the InputTypes property. /// - /// The input types for the shader. - /// Any additional instances needed by the generated code, if needed. - /// The resulting instance for the InputTypes property. - public static PropertyDeclarationSyntax GetSyntax(ImmutableArray inputTypes, out TypeDeclarationSyntax[] additionalTypes) + /// The input instance with gathered shader info. + /// The instance to write into. + public static void WriteSyntax(D2D1ShaderInfo info, IndentedTextWriter writer) { - ExpressionSyntax memoryExpression; + writer.WriteLine("readonly global::System.ReadOnlyMemory global::ComputeSharp.D2D1.__Internals.ID2D1Shader.InputTypes => "); - // If there are no inputs, simply return a default expression. - // Otherwise, declare the memory manager and access it. - if (inputTypes.Length == 0) + // If there are no inputs, simply return a default expression. Otherwise, create + // a ReadOnlyMemory instance from the memory manager. + if (info.InputTypes.IsEmpty) { - memoryExpression = LiteralExpression(SyntaxKind.DefaultLiteralExpression, Token(SyntaxKind.DefaultKeyword)); - additionalTypes = Array.Empty(); + writer.WriteLine("default;"); } else { - // Create a ReadOnlyMemory instance from the memory manager: - // - // InputTypesMemoryManager.Instance.Memory - memoryExpression = - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("InputTypesMemoryManager"), - IdentifierName("Instance")), - IdentifierName("Memory")); - - additionalTypes = new TypeDeclarationSyntax[] { GetMemoryManagerDeclaration(inputTypes) }; + writer.WriteLine("InputTypesMemoryManager.Instance.Memory;"); } - - // This code produces a method declaration as follows: - // - // readonly global::System.ReadOnlyMemory global::ComputeSharp.D2D1.__Internals.ID2D1Shader.InputTypes => ; - return - PropertyDeclaration( - GenericName(Identifier("global::System.ReadOnlyMemory")) - .AddTypeArgumentListArguments(IdentifierName("global::ComputeSharp.D2D1.Interop.D2D1PixelShaderInputType")), - Identifier(nameof(InputTypes))) - .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.D2D1.__Internals.{nameof(ID2D1Shader)}"))) - .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword)) - .WithExpressionBody(ArrowExpressionClause(memoryExpression)) - .WithSemicolonToken(Token(SyntaxKind.SemicolonToken)); } /// - /// Gets the memory manager declaration for the input type data. + /// Registers a callback to generate an additional type, if needed. /// - /// The input types for the shader. - /// The memory manager declaration for the input type data. - private static TypeDeclarationSyntax GetMemoryManagerDeclaration(ImmutableArray inputTypes) + /// The input instance with gathered shader info. + /// The registered callbacks to generate additional types. + public static void RegisterAdditionalTypeSyntax(D2D1ShaderInfo info, ImmutableArrayBuilder> callbacks) { - // Create the MemoryManager declaration: - // - // /// - // /// A implementation to get the input types. - // /// - // [global::System.CodeDom.Compiler.GeneratedCode("...", "...")] - // [global::System.Diagnostics.DebuggerNonUserCode] - // [global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] - // file sealed InputTypesMemoryManager : global::System.Buffers.MemoryManager - // { - // } - TypeDeclarationSyntax typeDeclaration = - ClassDeclaration("InputTypesMemoryManager") - .AddModifiers(Token(SyntaxKind.FileKeyword), Token(SyntaxKind.SealedKeyword)) - .AddBaseListTypes(SimpleBaseType( - GenericName(Identifier("global::System.Buffers.MemoryManager")) - .AddTypeArgumentListArguments(IdentifierName("global::ComputeSharp.D2D1.Interop.D2D1PixelShaderInputType")))) - .AddAttributeLists( - AttributeList(SingletonSeparatedList( - Attribute(IdentifierName("global::System.CodeDom.Compiler.GeneratedCode")).AddArgumentListArguments( - AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(ID2D1ShaderGenerator).FullName))), - AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(ID2D1ShaderGenerator).Assembly.GetName().Version.ToString())))))), - AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Diagnostics.DebuggerNonUserCode")))), - AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage"))))) - .WithLeadingTrivia( - Comment("/// "), - Comment("""/// A implementation to get the input types."""), - Comment("/// ")); - - using ImmutableArrayBuilder memberDeclarations = ImmutableArrayBuilder.Rent(); - - // Declare the singleton property to get the memory manager: - // - // /// The singleton instance to use. - // public static readonly InputTypesMemoryManager Instance = new(); - memberDeclarations.Add( - FieldDeclaration( - VariableDeclaration(IdentifierName("InputTypesMemoryManager")) - .AddVariables( - VariableDeclarator(Identifier("Instance")) - .WithInitializer(EqualsValueClause(ImplicitObjectCreationExpression())))) - .AddModifiers( - Token(SyntaxKind.PublicKeyword), - Token(SyntaxKind.StaticKeyword), - Token(SyntaxKind.ReadOnlyKeyword)) - .WithLeadingTrivia(Comment("""/// The singleton instance to use."""))); - - using (ImmutableArrayBuilder inputTypeExpressions = ImmutableArrayBuilder.Rent()) + // If there are no inputs, no memory manager is needed + if (info.InputTypes.IsEmpty) { - // Build the sequence of expressions for all input types - foreach (uint inputType in inputTypes) - { - inputTypeExpressions.Add( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("global::ComputeSharp.D2D1.Interop.D2D1PixelShaderInputType"), - IdentifierName(inputType == 0 ? "Simple" : "Complex"))); - } - - // Construct the RVA span property: - // - // /// The RVA data with the input type info. - // private static global::System.ReadOnlySpan Data => new[] { }; - memberDeclarations.Add( - PropertyDeclaration( - GenericName(Identifier("global::System.ReadOnlySpan")) - .AddTypeArgumentListArguments(IdentifierName("global::ComputeSharp.D2D1.Interop.D2D1PixelShaderInputType")), - Identifier("Data")) - .AddModifiers(Token(SyntaxKind.PrivateKeyword), Token(SyntaxKind.StaticKeyword)) - .WithExpressionBody( - ArrowExpressionClause( - ImplicitArrayCreationExpression( - InitializerExpression( - SyntaxKind.ArrayInitializerExpression, - SeparatedList(inputTypeExpressions.ToArray()))))) - .WithSemicolonToken(Token(SyntaxKind.SemicolonToken)) - .WithLeadingTrivia(Comment("/// The RVA data with the input type info."))); + return; } - // Add the GetSpan() method: - // - // /// - // public override unsafe global::System.Span GetSpan - // { - // return new(global::System.Runtime.CompilerServices.Unsafe.AsPointer(ref global::System.Runtime.InteropServices.MemoryMarshal(Data)), Data.Length); - // } - memberDeclarations.Add( - MethodDeclaration( - GenericName(Identifier("global::System.Span")) - .AddTypeArgumentListArguments(IdentifierName("global::ComputeSharp.D2D1.Interop.D2D1PixelShaderInputType")), - Identifier("GetSpan")) - .AddModifiers(Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.OverrideKeyword), Token(SyntaxKind.UnsafeKeyword)) - .AddBodyStatements( - ReturnStatement( - ImplicitObjectCreationExpression() - .AddArgumentListArguments( - Argument( - InvocationExpression( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("global::System.Runtime.CompilerServices.Unsafe"), - IdentifierName("AsPointer"))) - .AddArgumentListArguments( - Argument( - InvocationExpression( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("global::System.Runtime.InteropServices.MemoryMarshal"), - IdentifierName("GetReference"))) - .AddArgumentListArguments(Argument(IdentifierName("Data")))) - .WithRefOrOutKeyword(Token(SyntaxKind.RefKeyword)))), - Argument( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("Data"), - IdentifierName("Length")))))) - .WithLeadingTrivia(Comment("/// "))); + // 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($$"""/// """); + writer.WriteLine($$"""[global::System.CodeDom.Compiler.GeneratedCode("{{typeof(ID2D1ShaderGenerator).FullName}}", "{{typeof(ID2D1ShaderGenerator).Assembly.GetName().Version}}")]"""); + writer.WriteLine($$"""[global::System.Diagnostics.DebuggerNonUserCode]"""); + writer.WriteLine($$"""[global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]"""); + writer.WriteLine($$"""file sealed class InputTypesMemoryManager : global::System.Buffers.MemoryManager"""); - // Override the Memory property: - // - // /// - // public override global::System.Memory Memory - // { - // [global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - // get => CreateMemory(Data.Length); - // } - memberDeclarations.Add( - PropertyDeclaration( - GenericName(Identifier("global::System.Memory")) - .AddTypeArgumentListArguments(IdentifierName("global::ComputeSharp.D2D1.Interop.D2D1PixelShaderInputType")), - Identifier("Memory")) - .AddModifiers(Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.OverrideKeyword)) - .AddAccessorListAccessors( - AccessorDeclaration(SyntaxKind.GetAccessorDeclaration) - .AddAttributeLists( - AttributeList( - SingletonSeparatedList( - Attribute(IdentifierName("global::System.Runtime.CompilerServices.MethodImpl")) - .AddArgumentListArguments( - AttributeArgument( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("global::System.Runtime.CompilerServices.MethodImplOptions"), - IdentifierName("AggressiveInlining"))))))) - .WithExpressionBody( - ArrowExpressionClause( - InvocationExpression(IdentifierName("CreateMemory")) - .AddArgumentListArguments( - Argument( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("Data"), - IdentifierName("Length")))))) - .WithSemicolonToken(Token(SyntaxKind.SemicolonToken))) - .WithLeadingTrivia(Comment("/// "))); + using (writer.WriteBlock()) + { + // Static singleton instance (the object goes in the frozen heap, so there's no static constructor) + writer.WriteLine($$"""/// The singleton instance to use."""); + writer.WriteLine($$"""public static readonly InputTypesMemoryManager Instance = new();"""); - // Add the Pin(int elementIndex) method: - // - // /// - // public override unsafe global::System.Buffers.MemoryHandle Pin(int elementIndex) - // { - // return new(Unsafe.AsPointer(ref Unsafe.AsRef(in Data[elementIndex])), pinnable: this); - // } - memberDeclarations.Add( - MethodDeclaration(IdentifierName("global::System.Buffers.MemoryHandle"), Identifier("Pin")) - .AddModifiers(Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.OverrideKeyword), Token(SyntaxKind.UnsafeKeyword)) - .AddParameterListParameters(Parameter(Identifier("elementIndex")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword)))) - .AddBodyStatements( - ReturnStatement( - ImplicitObjectCreationExpression() - .AddArgumentListArguments( - Argument( - InvocationExpression( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("global::System.Runtime.CompilerServices.Unsafe"), - IdentifierName("AsPointer"))) - .AddArgumentListArguments( - Argument( - InvocationExpression( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("global::System.Runtime.CompilerServices.Unsafe"), - IdentifierName("AsRef"))) - .AddArgumentListArguments( - Argument( - ElementAccessExpression(IdentifierName("Data")) - .AddArgumentListArguments(Argument(IdentifierName("elementIndex")))) - .WithRefOrOutKeyword(Token(SyntaxKind.InKeyword)))) - .WithRefOrOutKeyword(Token(SyntaxKind.RefKeyword)))), - Argument(ThisExpression()).WithNameColon(NameColon(IdentifierName("pinnable")))))) - .WithLeadingTrivia(Comment("/// "))); + // RVA field + writer.WriteLine(); + writer.WriteLine("/// The RVA data with the input type info."); + writer.WriteLine("private static global::System.ReadOnlySpan Data => new[]"); - // Add the empty Unpin() method - memberDeclarations.Add( - MethodDeclaration(PredefinedType(Token(SyntaxKind.VoidKeyword)), Identifier("Unpin")) - .AddModifiers(Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.OverrideKeyword)) - .WithBody(Block()) - .WithLeadingTrivia(Comment("/// "))); + // Input types, one per line in the RVA field initializer + using (writer.WriteBlock()) + { + for (int i = 0; i < info.InputTypes.Length; i++) + { + writer.Write("global::ComputeSharp.D2D1.Interop.D2D1PixelShaderInputType."); + writer.Write(info.InputTypes[i] == 0 ? "Simple" : "Complex"); - // Add the empty Dispose(bool disposing) method - memberDeclarations.Add( - MethodDeclaration(PredefinedType(Token(SyntaxKind.VoidKeyword)), Identifier("Dispose")) - .AddModifiers(Token(SyntaxKind.ProtectedKeyword), Token(SyntaxKind.OverrideKeyword)) - .AddParameterListParameters( - Parameter(Identifier("disposing")).WithType(PredefinedType(Token(SyntaxKind.BoolKeyword)))) - .WithBody(Block()) - .WithLeadingTrivia(Comment("/// "))); + if (i < info.InputTypes.Length - 1) + { + writer.WriteLine(","); + } + } + } - return typeDeclaration.AddMembers(memberDeclarations.ToArray()); + // Add the remaining members for the memory manager + writer.WriteLine(""" + /// + public override unsafe global::System.Span GetSpan + { + return new(global::System.Runtime.CompilerServices.Unsafe.AsPointer(ref global::System.Runtime.InteropServices.MemoryMarshal(Data)), Data.Length); + } + + /// + public override global::System.Memory Memory + { + [global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + get => CreateMemory(Data.Length); + } + + /// + public override unsafe global::System.Buffers.MemoryHandle Pin(int elementIndex) + { + return new(Unsafe.AsPointer(ref Unsafe.AsRef(in Data[elementIndex])), pinnable: this); + } + + /// + public override void Unpin() + { + } + + /// + protected override void Dispose(bool disposing) + { + } + """, isMultiline: true); + } + } + + callbacks.Add(Callback); } } } \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.Syntax.cs index 66af8d0a..2c021ad6 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.Syntax.cs @@ -1,17 +1,7 @@ -using System; -using System.Globalization; using System.Linq; -using System.Text; -using ComputeSharp.D2D1.__Internals; using ComputeSharp.D2D1.SourceGenerators.Models; using ComputeSharp.SourceGeneration.Helpers; using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Syntax; -using Microsoft.CodeAnalysis.Text; -using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; - -#pragma warning disable CS0618 namespace ComputeSharp.D2D1.SourceGenerators; @@ -22,316 +12,128 @@ partial class ID2D1ShaderGenerator partial class LoadBytecode { /// - /// Creates a instance for the ShaderProfile property. + /// Writes the ShaderProfile property. /// - /// The input shader profile. - /// The resulting instance for the ShaderProfile property. - public static PropertyDeclarationSyntax GetShaderProfileSyntax(D2D1ShaderProfile shaderProfile) + /// The input instance with gathered shader info. + /// The instance to write into. + public static void WriteShaderProfileSyntax(D2D1ShaderInfo info, IndentedTextWriter writer) { - // This code produces a method declaration as follows: - // - // readonly ComputeSharp.D2D1.D2D1ShaderProfile global::ComputeSharp.D2D1.__Internals.ID2D1Shader.ShaderProfile => ; - return - PropertyDeclaration(IdentifierName("ComputeSharp.D2D1.D2D1ShaderProfile"), Identifier(nameof(ID2D1Shader.ShaderProfile))) - .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.D2D1.__Internals.{nameof(ID2D1Shader)}"))) - .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword)) - .WithExpressionBody(ArrowExpressionClause( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("global::ComputeSharp.D2D1.D2D1ShaderProfile"), - IdentifierName(shaderProfile.ToString(CultureInfo.InvariantCulture))))) - .WithSemicolonToken(Token(SyntaxKind.SemicolonToken)); + writer.WriteLine($"readonly ComputeSharp.D2D1.D2D1ShaderProfile global::ComputeSharp.D2D1.__Internals.ID2D1Shader.ShaderProfile => global::ComputeSharp.D2D1.D2D1ShaderProfile.{info.HlslInfoKey.EffectiveShaderProfile};"); } /// - /// Creates a instance for the CompileOptions property. + /// Writes the CompileOptions property. /// - /// The input compile options. - /// The resulting instance for the CompileOptions property. - public static PropertyDeclarationSyntax GetCompileOptionsSyntax(D2D1CompileOptions compileOptions) + /// The input instance with gathered shader info. + /// The instance to write into. + public static void WriteCompileOptionsSyntax(D2D1ShaderInfo info, IndentedTextWriter writer) { // Get a formatted representation of the compile options being used - ExpressionSyntax compileOptionsExpression = - ParseExpression( - compileOptions - .ToString(CultureInfo.InvariantCulture) - .Split(',') - .Select(static name => $"global::ComputeSharp.D2D1.D2D1CompileOptions.{name.Trim()}") - .Aggregate("", static (left, right) => left.Length > 0 ? $"{left} | {right}" : right)); + string compileOptionsExpression = + info.HlslInfoKey.EffectiveCompileOptions + .ToString() + .Split(',') + .Select(static name => $"global::ComputeSharp.D2D1.D2D1CompileOptions.{name.Trim()}") + .Aggregate("", static (left, right) => left.Length > 0 ? $"{left} | {right}" : right); - // This code produces a method declaration as follows: - // - // readonly ComputeSharp.D2D1.D2D1CompileOptions global::ComputeSharp.D2D1.__Internals.ID2D1Shader.CompileOptions => ; - return - PropertyDeclaration(IdentifierName("ComputeSharp.D2D1.D2D1CompileOptions"), Identifier(nameof(ID2D1Shader.CompileOptions))) - .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.D2D1.__Internals.{nameof(ID2D1Shader)}"))) - .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword)) - .WithExpressionBody(ArrowExpressionClause(compileOptionsExpression)) - .WithSemicolonToken(Token(SyntaxKind.SemicolonToken)); + writer.Write($"readonly ComputeSharp.D2D1.D2D1CompileOptions global::ComputeSharp.D2D1.__Internals.ID2D1Shader.CompileOptions => {compileOptionsExpression};"); } /// - /// Creates a instance for the HlslBytecode property. + /// Writes the HlslBytecode property. /// - /// The input bytecode info. - /// An opaque instance to transform the final tree into text. - /// Any additional instances needed by the generated code, if needed. - /// The resulting instance for the HlslBytecode property. - public static PropertyDeclarationSyntax GetHlslBytecodeSyntax( - HlslBytecodeInfo bytecodeInfo, - out Func fixup, - out TypeDeclarationSyntax[] additionalTypes) + /// The input instance with gathered shader info. + /// The instance to write into. + public static void WriteHlslBytecodeSyntax(D2D1ShaderInfo info, IndentedTextWriter writer) { - ExpressionSyntax memoryExpression; + writer.WriteLine("readonly global::System.ReadOnlyMemory global::ComputeSharp.D2D1.__Internals.ID2D1Shader.ResourceTextureDescriptions => "); - // If there is no bytecode, simply return a default expression. - // Otherwise, declare the memory manager and access it. - if (bytecodeInfo is not HlslBytecodeInfo.Success success) + // If there is no bytecode, just return a default expression. + // Otherwise, return the memory manager backed memory instance. + if (info.HlslInfo is not HlslBytecodeInfo.Success) { - memoryExpression = LiteralExpression(SyntaxKind.DefaultLiteralExpression, Token(SyntaxKind.DefaultKeyword)); - fixup = static tree => tree.GetText(Encoding.UTF8); - additionalTypes = Array.Empty(); + writer.WriteLine("default;"); } else { - // Create a ReadOnlyMemory instance from the memory manager: - // - // HlslBytecodeMemoryManager.Instance.Memory - memoryExpression = - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("HlslBytecodeMemoryManager"), - IdentifierName("Instance")), - IdentifierName("Memory")); - - TypeDeclarationSyntax memoryManagerDeclaration = GetMemoryManagerDeclaration(); - string bytecodeLiterals = SyntaxFormattingHelper.BuildByteArrayInitializationExpressionString(success.Bytecode.AsSpan()); - - additionalTypes = new TypeDeclarationSyntax[] { memoryManagerDeclaration }; - fixup = tree => SourceText.From(tree.ToFullString().Replace("__EMBEDDED_SHADER_BYTECODE", bytecodeLiterals), Encoding.UTF8); + writer.WriteLine("HlslBytecodeMemoryManager.Instance.Memory;"); } - - // This code produces a method declaration as follows: - // - // readonly global::System.ReadOnlyMemory global::ComputeSharp.D2D1.__Internals.ID2D1Shader.HlslBytecode => ; - return - PropertyDeclaration( - GenericName(Identifier("global::System.ReadOnlyMemory")) - .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ByteKeyword))), - Identifier(nameof(ID2D1Shader.HlslBytecode))) - .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.D2D1.__Internals.{nameof(ID2D1Shader)}"))) - .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword)) - .WithExpressionBody(ArrowExpressionClause(memoryExpression)) - .WithSemicolonToken(Token(SyntaxKind.SemicolonToken)); } /// - /// Gets a instance with the logic to try to get a compiled shader bytecode. + /// Registers a callback to generate an additional type, if needed. /// - /// The instance trying to retrieve the precompiled shader. - private static unsafe TypeDeclarationSyntax GetMemoryManagerDeclaration() + /// The input instance with gathered shader info. + /// The registered callbacks to generate additional types. + public static void RegisterAdditionalTypeSyntax(D2D1ShaderInfo info, ImmutableArrayBuilder> callbacks) { - // Create the MemoryManager declaration: - // - // /// - // /// implementation to get the HLSL bytecode. - // /// - // [global::System.CodeDom.Compiler.GeneratedCode("...", "...")] - // [global::System.Diagnostics.DebuggerNonUserCode] - // [global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] - // file sealed HlslBytecodeMemoryManager : global::System.Buffers.MemoryManager - // { - // } - TypeDeclarationSyntax typeDeclaration = - ClassDeclaration("HlslBytecodeMemoryManager") - .AddModifiers(Token(SyntaxKind.FileKeyword), Token(SyntaxKind.SealedKeyword)) - .AddBaseListTypes(SimpleBaseType( - GenericName(Identifier("global::System.Buffers.MemoryManager")) - .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ByteKeyword))))) - .AddAttributeLists( - AttributeList(SingletonSeparatedList( - Attribute(IdentifierName("global::System.CodeDom.Compiler.GeneratedCode")).AddArgumentListArguments( - AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(ID2D1ShaderGenerator).FullName))), - AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(ID2D1ShaderGenerator).Assembly.GetName().Version.ToString())))))), - AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Diagnostics.DebuggerNonUserCode")))), - AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage"))))) - .WithLeadingTrivia( - Comment("/// "), - Comment("""/// A implementation to get the HLSL bytecode."""), - Comment("/// ")); + // If there is no bytecode, no memory manager is needed + if (info.HlslInfo is not HlslBytecodeInfo.Success) + { + return; + } - using ImmutableArrayBuilder memberDeclarations = ImmutableArrayBuilder.Rent(); + // 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($$"""/// """); + writer.WriteLine($$"""[global::System.CodeDom.Compiler.GeneratedCode("{{typeof(ID2D1ShaderGenerator).FullName}}", "{{typeof(ID2D1ShaderGenerator).Assembly.GetName().Version}}")]"""); + writer.WriteLine($$"""[global::System.Diagnostics.DebuggerNonUserCode]"""); + writer.WriteLine($$"""[global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]"""); + writer.WriteLine($$"""file sealed class HlslBytecodeMemoryManager : global::System.Buffers.MemoryManager"""); - // Declare the singleton property to get the memory manager: - // - // /// The singleton instance to use. - // public static readonly HlslBytecodeMemoryManager Instance = new(); - memberDeclarations.Add( - FieldDeclaration( - VariableDeclaration(IdentifierName("HlslBytecodeMemoryManager")) - .AddVariables( - VariableDeclarator(Identifier("Instance")) - .WithInitializer(EqualsValueClause(ImplicitObjectCreationExpression())))) - .AddModifiers( - Token(SyntaxKind.PublicKeyword), - Token(SyntaxKind.StaticKeyword), - Token(SyntaxKind.ReadOnlyKeyword)) - .WithLeadingTrivia(Comment("""/// The singleton instance to use."""))); + using (writer.WriteBlock()) + { + // Static singleton instance (to avoid the static constructor, just like with the input types) + writer.WriteLine($$"""/// The singleton instance to use."""); + writer.WriteLine($$"""public static readonly HlslBytecodeMemoryManager Instance = new();"""); - // Construct the RVA span property: - // - // /// The RVA data with the HLSL bytecode. - // private static global::System.ReadOnlySpan Data => new byte[] { __EMBEDDED_SHADER_BYTECODE }; - memberDeclarations.Add( - PropertyDeclaration( - GenericName(Identifier("global::System.ReadOnlySpan")) - .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ByteKeyword))), - Identifier("Data")) - .AddModifiers(Token(SyntaxKind.PrivateKeyword), Token(SyntaxKind.StaticKeyword)) - .WithExpressionBody( - ArrowExpressionClause( - ArrayCreationExpression( - ArrayType(PredefinedType(Token(SyntaxKind.ByteKeyword))) - .AddRankSpecifiers(ArrayRankSpecifier(SingletonSeparatedList(OmittedArraySizeExpression()))), - InitializerExpression( - SyntaxKind.ArrayInitializerExpression, - SingletonSeparatedList(IdentifierName("__EMBEDDED_SHADER_BYTECODE")))))) - .WithSemicolonToken(Token(SyntaxKind.SemicolonToken)) - .WithLeadingTrivia(Comment("/// The RVA data with the HLSL bytecode."))); + // 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[] { "); - // Override the Memory property: - // - // /// - // public override global::System.Memory Memory - // { - // [global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - // get => CreateMemory(Data.Length); - // } - memberDeclarations.Add( - PropertyDeclaration( - GenericName(Identifier("global::System.Memory")) - .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ByteKeyword))), - Identifier("Memory")) - .AddModifiers(Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.OverrideKeyword)) - .AddAccessorListAccessors( - AccessorDeclaration(SyntaxKind.GetAccessorDeclaration) - .AddAttributeLists( - AttributeList( - SingletonSeparatedList( - Attribute(IdentifierName("global::System.Runtime.CompilerServices.MethodImpl")) - .AddArgumentListArguments( - AttributeArgument( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("global::System.Runtime.CompilerServices.MethodImplOptions"), - IdentifierName("AggressiveInlining"))))))) - .WithExpressionBody( - ArrowExpressionClause( - InvocationExpression(IdentifierName("CreateMemory")) - .AddArgumentListArguments( - Argument( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("Data"), - IdentifierName("Length")))))) - .WithSemicolonToken(Token(SyntaxKind.SemicolonToken))) - .WithLeadingTrivia(Comment("/// "))); + SyntaxFormattingHelper.WriteByteArrayInitializationExpressions(((HlslBytecodeInfo.Success)info.HlslInfo).Bytecode.AsSpan(), writer); - // Add the GetSpan() method: - // - // /// - // public override unsafe global::System.Span GetSpan - // { - // return new(global::System.Runtime.CompilerServices.Unsafe.AsPointer(ref global::System.Runtime.InteropServices.MemoryMarshal(Data)), Data.Length); - // } - memberDeclarations.Add( - MethodDeclaration( - GenericName(Identifier("global::System.Span")) - .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ByteKeyword))), - Identifier("GetSpan")) - .AddModifiers(Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.OverrideKeyword), Token(SyntaxKind.UnsafeKeyword)) - .AddBodyStatements( - ReturnStatement( - ImplicitObjectCreationExpression() - .AddArgumentListArguments( - Argument( - InvocationExpression( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("global::System.Runtime.CompilerServices.Unsafe"), - IdentifierName("AsPointer"))) - .AddArgumentListArguments( - Argument( - InvocationExpression( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("global::System.Runtime.InteropServices.MemoryMarshal"), - IdentifierName("GetReference"))) - .AddArgumentListArguments(Argument(IdentifierName("Data")))) - .WithRefOrOutKeyword(Token(SyntaxKind.RefKeyword)))), - Argument( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("Data"), - IdentifierName("Length")))))) - .WithLeadingTrivia(Comment("/// "))); + writer.WriteLine(" };"); - // Add the Pin(int elementIndex) method: - // - // /// - // public override unsafe global::System.Buffers.MemoryHandle Pin(int elementIndex) - // { - // return new(Unsafe.AsPointer(ref Unsafe.AsRef(in Data[elementIndex])), pinnable: this); - // } - memberDeclarations.Add( - MethodDeclaration(IdentifierName("global::System.Buffers.MemoryHandle"), Identifier("Pin")) - .AddModifiers(Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.OverrideKeyword), Token(SyntaxKind.UnsafeKeyword)) - .AddParameterListParameters(Parameter(Identifier("elementIndex")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword)))) - .AddBodyStatements( - ReturnStatement( - ImplicitObjectCreationExpression() - .AddArgumentListArguments( - Argument( - InvocationExpression( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("global::System.Runtime.CompilerServices.Unsafe"), - IdentifierName("AsPointer"))) - .AddArgumentListArguments( - Argument( - InvocationExpression( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("global::System.Runtime.CompilerServices.Unsafe"), - IdentifierName("AsRef"))) - .AddArgumentListArguments( - Argument( - ElementAccessExpression(IdentifierName("Data")) - .AddArgumentListArguments(Argument(IdentifierName("elementIndex")))) - .WithRefOrOutKeyword(Token(SyntaxKind.InKeyword)))) - .WithRefOrOutKeyword(Token(SyntaxKind.RefKeyword)))), - Argument(ThisExpression()).WithNameColon(NameColon(IdentifierName("pinnable")))))) - .WithLeadingTrivia(Comment("/// "))); + // Add the remaining members for the memory manager + writer.WriteLine(""" + /// + public override unsafe global::System.Span GetSpan + { + return new(global::System.Runtime.CompilerServices.Unsafe.AsPointer(ref global::System.Runtime.InteropServices.MemoryMarshal(Data)), Data.Length); + } - // Add the empty Unpin() method - memberDeclarations.Add( - MethodDeclaration(PredefinedType(Token(SyntaxKind.VoidKeyword)), Identifier("Unpin")) - .AddModifiers(Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.OverrideKeyword)) - .WithBody(Block()) - .WithLeadingTrivia(Comment("/// "))); + /// + public override global::System.Memory Memory + { + [global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + get => CreateMemory(Data.Length); + } - // Add the empty Dispose(bool disposing) method - memberDeclarations.Add( - MethodDeclaration(PredefinedType(Token(SyntaxKind.VoidKeyword)), Identifier("Dispose")) - .AddModifiers(Token(SyntaxKind.ProtectedKeyword), Token(SyntaxKind.OverrideKeyword)) - .AddParameterListParameters( - Parameter(Identifier("disposing")).WithType(PredefinedType(Token(SyntaxKind.BoolKeyword)))) - .WithBody(Block()) - .WithLeadingTrivia(Comment("/// "))); + /// + public override unsafe global::System.Buffers.MemoryHandle Pin(int elementIndex) + { + return new(Unsafe.AsPointer(ref Unsafe.AsRef(in Data[elementIndex])), pinnable: this); + } - return typeDeclaration.AddMembers(memberDeclarations.ToArray()); + /// + public override void Unpin() + { + } + + /// + protected override void Dispose(bool disposing) + { + } + """, isMultiline: true); + } + } + + callbacks.Add(Callback); } } } \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs index 413d6342..54e5242e 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs @@ -1,16 +1,6 @@ -using System; -using System.Collections.Immutable; -using ComputeSharp.D2D1.__Internals; using ComputeSharp.D2D1.SourceGenerators.Models; using ComputeSharp.SourceGeneration.Helpers; using ComputeSharp.SourceGeneration.Mappings; -using ComputeSharp.SourceGeneration.Models; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Syntax; -using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; - -#pragma warning disable CS0618 namespace ComputeSharp.D2D1.SourceGenerators; @@ -21,274 +11,126 @@ partial class ID2D1ShaderGenerator partial class LoadDispatchData { /// - /// Creates a instance for the LoadDispatchDataMethod method. + /// Writes the LoadDispatchData method. /// - /// The hiararchy info of the shader type. - /// The description on shader instance fields. - /// The size of the shader constant buffer. - /// Any additional instances needed by the generated code, if needed. - /// The resulting instance for the LoadDispatchDataMethod method. - public static MethodDeclarationSyntax GetSyntax( - HierarchyInfo hierarchyInfo, - EquatableArray fields, - int constantBufferSizeInBytes, - out TypeDeclarationSyntax[] additionalTypes) + /// The input instance with gathered shader info. + /// The instance to write into. + public static void WriteSyntax(D2D1ShaderInfo info, IndentedTextWriter writer) { - // Declare the mapping constant buffer type, if needed (ie. if the shader has at least one field) - if (fields.Length == 0) - { - additionalTypes = Array.Empty(); - } - else - { - additionalTypes = new[] { GetConstantBufferDeclaration(hierarchyInfo, fields, constantBufferSizeInBytes) }; - } + writer.WriteLine("readonly unsafe void global::ComputeSharp.D2D1.__Internals.ID2D1Shader.LoadDispatchData(ref TLoader loader)"); - // This code produces a method declaration as follows: - // - // readonly unsafe void global::ComputeSharp.D2D1.__Internals.ID2D1Shader.LoadDispatchData(ref TLoader loader) - // { - // - // } - return - MethodDeclaration(PredefinedType(Token(SyntaxKind.VoidKeyword)), Identifier(nameof(LoadDispatchData))) - .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.D2D1.__Internals.{nameof(ID2D1Shader)}"))) - .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword), Token(SyntaxKind.UnsafeKeyword)) - .AddTypeParameterListParameters(TypeParameter(Identifier("TLoader"))) - .AddParameterListParameters(Parameter(Identifier("loader")).AddModifiers(Token(SyntaxKind.RefKeyword)).WithType(IdentifierName("TLoader"))) - .WithBody(Block(GetDispatchDataLoadingStatements(fields, constantBufferSizeInBytes))); + using (writer.WriteBlock()) + { + // If there are no fields, just load an empty buffer + if (info.Fields.IsEmpty) + { + writer.WriteLine("loader.LoadConstantBuffer(default);"); + } + else + { + writer.WriteLine("ConstantBuffer buffer;"); + + // Generate loading statements for each captured field + foreach (FieldInfo fieldInfo in info.Fields) + { + switch (fieldInfo) + { + case FieldInfo.Primitive primitive: + + // Assign a primitive value + writer.WriteLine($"buffer.{string.Join("_", primitive.FieldPath)} = this.{string.Join(".", primitive.FieldPath)};"); + break; + + case FieldInfo.NonLinearMatrix matrix: + string fieldPath = string.Join(".", matrix.FieldPath); + string fieldNamePrefix = string.Join("_", matrix.FieldPath); + + // Assign all rows of a given matrix type: + // + // buffer. = this.[0]; + // buffer. = this.[1]; + // ... + // buffer. = this.[N]; + for (int j = 0; j < matrix.Rows; j++) + { + writer.WriteLine($"buffer.{fieldNamePrefix}_{j} = this.{fieldPath}[{j}];"); + } + + break; + } + } + } + } } /// - /// Gets a type definition to map the constant buffer of a given shader type. + /// Registers a callback to generate an additional type, if needed. /// - /// The hiararchy info of the shader type. - /// The array of values for all captured fields. - /// The size of the shader constant buffer. - /// The object for the mapped constant buffer for the current shader type. - private static TypeDeclarationSyntax GetConstantBufferDeclaration(HierarchyInfo hierarchyInfo, ImmutableArray fieldInfos, int constantBufferSizeInBytes) + /// The input instance with gathered shader info. + /// The registered callbacks to generate additional types. + public static void RegisterAdditionalTypeSyntax(D2D1ShaderInfo info, ImmutableArrayBuilder> callbacks) { - string fullyQualifiedTypeName = hierarchyInfo.GetFullyQualifiedTypeName(); - - using ImmutableArrayBuilder fieldDeclarations = ImmutableArrayBuilder.Rent(); - - // Appends a new field declaration for a constant buffer field: - // - // - // [global::System.Runtime.InteropServices.FieldOffset()] - // public ; - void AppendFieldDeclaration( - string comment, - TypeSyntax typeIdentifier, - string identifierName, - int fieldOffset) + // If there are no fields, there is no need for a constant buffer type + if (info.Fields.IsEmpty) { - fieldDeclarations.Add( - FieldDeclaration( - VariableDeclaration(typeIdentifier) - .AddVariables(VariableDeclarator(Identifier(identifierName)))) - .AddAttributeLists(AttributeList(SingletonSeparatedList( - Attribute(IdentifierName("global::System.Runtime.InteropServices.FieldOffset")) - .AddArgumentListArguments(AttributeArgument( - LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(fieldOffset))))))) - .AddModifiers(Token(SyntaxKind.PublicKeyword)) - .WithLeadingTrivia(Comment(comment))); + return; } - // Declare fields for every mapped item from the shader layout - foreach (FieldInfo fieldInfo in fieldInfos) + // Declare the ConstantBuffer type + static void Callback(D2D1ShaderInfo info, IndentedTextWriter writer) { - switch (fieldInfo) + string fullyQualifiedTypeName = info.Hierarchy.GetFullyQualifiedTypeName(); + + writer.WriteLine($$"""/// """); + writer.WriteLine($$"""/// A type representing the constant buffer native layout for ."""); + writer.WriteLine($$"""/// """); + writer.WriteLine($$"""[global::System.CodeDom.Compiler.GeneratedCode("{{typeof(ID2D1ShaderGenerator).FullName}}", "{{typeof(ID2D1ShaderGenerator).Assembly.GetName().Version}}")]"""); + writer.WriteLine($$"""[global::System.Diagnostics.DebuggerNonUserCode]"""); + writer.WriteLine($$"""[global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]"""); + writer.WriteLine($$"""[global::System.Runtime.InteropServices.StructLayout(global::System.Runtime.InteropServices.LayoutKind.Explicit, Size = {{info.ConstantBufferSizeInBytes}})]"""); + writer.WriteLine($$"""file struct ConstantBuffer"""); + + using (writer.WriteBlock()) { - case FieldInfo.Primitive { TypeName: "System.Boolean" } primitive: - - // Append a field as a global::ComputeSharp.Bool value (will use the implicit conversion from bool values) - AppendFieldDeclaration( - comment: $"""/// """, - typeIdentifier: IdentifierName("global::ComputeSharp.Bool"), - identifierName: string.Join("_", primitive.FieldPath), - fieldOffset: primitive.Offset); - break; - case FieldInfo.Primitive primitive: - - // Append primitive fields of other types with their mapped names - AppendFieldDeclaration( - comment: $"""/// """, - typeIdentifier: IdentifierName(HlslKnownTypes.GetMappedName(primitive.TypeName)), - identifierName: string.Join("_", primitive.FieldPath), - fieldOffset: primitive.Offset); - break; - - case FieldInfo.NonLinearMatrix matrix: - string rowTypeName = HlslKnownTypes.GetMappedName($"ComputeSharp.{matrix.ElementName}{matrix.Columns}"); - string fieldNamePrefix = string.Join("_", matrix.FieldPath); - - // Declare a field for every row of the matrix type - for (int j = 0; j < matrix.Rows; j++) + // Declare fields for every mapped item from the shader layout + for (int i = 0; i < info.Fields.Length; i++) + { + switch (info.Fields[i]) { - AppendFieldDeclaration( - comment: $"""/// Row {j} of .""", - typeIdentifier: IdentifierName(rowTypeName), - identifierName: $"{fieldNamePrefix}_{j}", - fieldOffset: matrix.Offsets[j]); - } + case FieldInfo.Primitive { TypeName: "System.Boolean" } primitive: - break; + // 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($$"""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($$"""public {{HlslKnownTypes.GetMappedName(primitive.TypeName)}} {{string.Join("_", primitive.FieldPath)}};"""); + break; + + case FieldInfo.NonLinearMatrix matrix: + string rowTypeName = HlslKnownTypes.GetMappedName($"ComputeSharp.{matrix.ElementName}{matrix.Columns}"); + string fieldNamePrefix = string.Join("_", matrix.FieldPath); + + // Declare a field for every row of the matrix type + for (int j = 0; j < matrix.Rows; j++) + { + writer.WriteLine($$"""/// Row {j} of ."""); + writer.WriteLine($$"""[global::System.Runtime.InteropServices.FieldOffset({{matrix.Offsets[j]}})]"""); + writer.WriteLine($$"""public {{rowTypeName}} {{fieldNamePrefix}}_{{j}};"""); + } + + break; + } + } } } - // Create the constant buffer type: - // - // /// - // /// A type representing the constant buffer native layout for . - // /// - // [global::System.CodeDom.Compiler.GeneratedCode("...", "...")] - // [global::System.Diagnostics.DebuggerNonUserCode] - // [global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] - // [global::System.Runtime.InteropServices.StructLayout(global::System.Runtime.InteropServices.LayoutKind.Explicit, Size = )] - // file struct ConstantBuffer - // { - // - // } - return - StructDeclaration("ConstantBuffer") - .AddModifiers(Token(SyntaxKind.FileKeyword)) - .AddAttributeLists( - AttributeList(SingletonSeparatedList( - Attribute(IdentifierName("global::System.CodeDom.Compiler.GeneratedCode")).AddArgumentListArguments( - AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(ID2D1ShaderGenerator).FullName))), - AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(ID2D1ShaderGenerator).Assembly.GetName().Version.ToString())))))), - AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Diagnostics.DebuggerNonUserCode")))), - AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage")))), - AttributeList(SingletonSeparatedList( - Attribute(IdentifierName("global::System.Runtime.InteropServices.StructLayout")).AddArgumentListArguments( - AttributeArgument(MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("global::System.Runtime.InteropServices.LayoutKind"), - IdentifierName("Explicit"))), - AttributeArgument(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(constantBufferSizeInBytes))) - .WithNameEquals(NameEquals(IdentifierName("Size"))))))) - .AddMembers(fieldDeclarations.ToArray()) - .WithLeadingTrivia( - Comment("/// "), - Comment($"""/// A type representing the constant buffer native layout for ."""), - Comment("/// ")); - } - - /// - /// Gets a sequence of statements to load the dispatch data for a given shader. - /// - /// The array of values for all captured fields. - /// The size of the shader constant buffer. - /// The sequence of instances to load the shader dispatch data. - private static ImmutableArray GetDispatchDataLoadingStatements(ImmutableArray fieldInfos, int constantBufferSizeInBytes) - { - // If there are no fields, just load an empty buffer: - // - // loader.LoadConstantBuffer(default); - if (fieldInfos.IsEmpty) - { - return - ImmutableArray.Create( - ExpressionStatement( - InvocationExpression( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("loader"), - IdentifierName("LoadConstantBuffer"))) - .AddArgumentListArguments(Argument( - LiteralExpression( - SyntaxKind.DefaultLiteralExpression, - Token(SyntaxKind.DefaultKeyword)))))); - } - - using ImmutableArrayBuilder statements = ImmutableArrayBuilder.Rent(); - - // ConstantBuffer buffer; - statements.Add( - LocalDeclarationStatement( - VariableDeclaration(IdentifierName("ConstantBuffer")) - .AddVariables(VariableDeclarator(Identifier("buffer"))))); - - // Generate loading statements for each captured field - foreach (FieldInfo fieldInfo in fieldInfos) - { - switch (fieldInfo) - { - case FieldInfo.Primitive primitive: - - // Assign a primitive value: - // - // buffer. = this.; - statements.Add( - ExpressionStatement( - AssignmentExpression( - SyntaxKind.SimpleAssignmentExpression, - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("buffer"), - IdentifierName(string.Join("_", primitive.FieldPath))), - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - ThisExpression(), - IdentifierName(string.Join(".", primitive.FieldPath)))))); - break; - - case FieldInfo.NonLinearMatrix matrix: - string fieldPath = string.Join(".", matrix.FieldPath); - string fieldNamePrefix = string.Join("_", matrix.FieldPath); - - // Assign all rows of a given matrix type: - // - // buffer. = this.[0]; - // buffer. = this.[1]; - // ... - // buffer. = this.[N]; - for (int j = 0; j < matrix.Rows; j++) - { - statements.Add( - ExpressionStatement( - AssignmentExpression( - SyntaxKind.SimpleAssignmentExpression, - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("buffer"), - IdentifierName($"{fieldNamePrefix}_{j}")), - ElementAccessExpression( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - ThisExpression(), - IdentifierName(fieldPath))) - .AddArgumentListArguments( - Argument(LiteralExpression( - SyntaxKind.NumericLiteralExpression, - Literal(j))))))); - } - - break; - } - } - - // loader.LoadConstantBuffer(new global::System.ReadOnlySpan(&buffer, sizeof(ConstantBuffer))); - statements.Add( - ExpressionStatement( - InvocationExpression( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("loader"), - IdentifierName("LoadConstantBuffer"))) - .AddArgumentListArguments(Argument( - ObjectCreationExpression( - GenericName(Identifier("global::System.ReadOnlySpan")) - .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ByteKeyword)))) - .AddArgumentListArguments( - Argument( - PrefixUnaryExpression( - SyntaxKind.AddressOfExpression, - IdentifierName("buffer"))), - Argument(SizeOfExpression(IdentifierName("ConstantBuffer")))))))); - - return statements.ToImmutable(); + callbacks.Add(Callback); } } } \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateOutputBufferProperties.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateOutputBufferProperties.Syntax.cs index f36ce9ee..8a6400c0 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateOutputBufferProperties.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateOutputBufferProperties.Syntax.cs @@ -1,10 +1,6 @@ using System; -using ComputeSharp.D2D1.__Internals; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Syntax; -using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; - -#pragma warning disable CS0618 +using ComputeSharp.D2D1.SourceGenerators.Models; +using ComputeSharp.SourceGeneration.Helpers; namespace ComputeSharp.D2D1.SourceGenerators; @@ -15,73 +11,38 @@ partial class ID2D1ShaderGenerator partial class OutputBuffer { /// - /// Creates a instance for the BufferPrecision property. + /// Writes the BufferPrecision property. /// - /// The buffer precision for the resulting output buffer. - /// The resulting instance for the BufferPrecision property. - public static PropertyDeclarationSyntax GetBufferPrecisionSyntax(D2D1BufferPrecision bufferPrecision) + /// The input instance with gathered shader info. + /// The instance to write into. + public static void WriteBufferPrecisionSyntax(D2D1ShaderInfo info, IndentedTextWriter writer) { - ExpressionSyntax bufferPrecisionExpression; - - // Set the right expression if the buffer options are valid - if (Enum.IsDefined(typeof(D2D1BufferPrecision), bufferPrecision)) + // Set the right expression if the buffer options are valid. + // If they are not, just return default (the analyzer will emit a diagnostic). + string bufferPrecisionExpression = Enum.IsDefined(typeof(D2D1BufferPrecision), info.BufferPrecision) switch { - bufferPrecisionExpression = - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("ComputeSharp.D2D1.D2D1BufferPrecision"), - IdentifierName(bufferPrecision.ToString())); - } - else - { - // Otherwise just return default (the analyzer will emit a diagnostic) - bufferPrecisionExpression = LiteralExpression(SyntaxKind.DefaultLiteralExpression, Token(SyntaxKind.DefaultKeyword)); - } + true => $"global::ComputeSharp.D2D1.D2D1BufferPrecision.{info.BufferPrecision}", + false => "default" + }; - // This code produces a property declaration as follows: - // - // readonly ComputeSharp.D2D1.D2D1BufferPrecision global::ComputeSharp.D2D1.__Internals.ID2D1Shader.BufferPrecision => ; - return - PropertyDeclaration(IdentifierName("ComputeSharp.D2D1.D2D1BufferPrecision"), Identifier("BufferPrecision")) - .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.D2D1.__Internals.{nameof(ID2D1Shader)}"))) - .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword)) - .WithExpressionBody(ArrowExpressionClause(bufferPrecisionExpression)) - .WithSemicolonToken(Token(SyntaxKind.SemicolonToken)); + writer.WriteLine($"readonly ComputeSharp.D2D1.D2D1BufferPrecision global::ComputeSharp.D2D1.__Internals.ID2D1Shader.BufferPrecision => {bufferPrecisionExpression};"); } /// - /// Creates a instance for the ChannelDepth property. + /// Writes the ChannelDepth property. /// - /// The channel depth for the resulting output buffer. - /// The resulting instance for the ChannelDepth property. - public static PropertyDeclarationSyntax GetChannelDepthSyntax(D2D1ChannelDepth channelDepth) + /// The input instance with gathered shader info. + /// The instance to write into. + public static void WriteChannelDepthSyntax(D2D1ShaderInfo info, IndentedTextWriter writer) { - ExpressionSyntax channelDepthExpression; - // Set the right expression if the buffer options are valid - if (Enum.IsDefined(typeof(D2D1ChannelDepth), channelDepth)) + string channelDepthExpression = Enum.IsDefined(typeof(D2D1ChannelDepth), info.ChannelDepth) switch { - channelDepthExpression = - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("ComputeSharp.D2D1.D2D1ChannelDepth"), - IdentifierName(channelDepth.ToString())); - } - else - { - // Otherwise just return default (the analyzer will emit a diagnostic) - channelDepthExpression = LiteralExpression(SyntaxKind.DefaultLiteralExpression, Token(SyntaxKind.DefaultKeyword)); - } + true => $"global::ComputeSharp.D2D1.D2D1ChannelDepth.{info.ChannelDepth}", + false => "default" + }; - // This code produces a property declaration as follows: - // - // readonly ComputeSharp.D2D1.D2D1ChannelDepth global::ComputeSharp.D2D1.__Internals.ID2D1Shader.ChannelDepth => ; - return - PropertyDeclaration(IdentifierName("ComputeSharp.D2D1.D2D1ChannelDepth"), Identifier("ChannelDepth")) - .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.D2D1.__Internals.{nameof(ID2D1Shader)}"))) - .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword)) - .WithExpressionBody(ArrowExpressionClause(channelDepthExpression)) - .WithSemicolonToken(Token(SyntaxKind.SemicolonToken)); + writer.WriteLine($"readonly ComputeSharp.D2D1.D2D1ChannelDepth global::ComputeSharp.D2D1.__Internals.ID2D1Shader.ChannelDepth => {channelDepthExpression};"); } } } \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreatePixelOptionsProperty.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreatePixelOptionsProperty.Syntax.cs index 7dac3342..2c408811 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreatePixelOptionsProperty.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreatePixelOptionsProperty.Syntax.cs @@ -1,9 +1,5 @@ -using ComputeSharp.D2D1.__Internals; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Syntax; -using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; - -#pragma warning disable CS0618 +using ComputeSharp.D2D1.SourceGenerators.Models; +using ComputeSharp.SourceGeneration.Helpers; namespace ComputeSharp.D2D1.SourceGenerators; @@ -14,38 +10,20 @@ partial class ID2D1ShaderGenerator partial class PixelOptions { /// - /// Creates a instance for the PixelOptions property. + /// Writes the PixelOptions property. /// - /// The pixel options for the shader. - /// The resulting instance for the PixelOptions property. - public static PropertyDeclarationSyntax GetSyntax(D2D1PixelOptions pixelOptions) + /// The input instance with gathered shader info. + /// The instance to write into. + public static void WriteSyntax(D2D1ShaderInfo info, IndentedTextWriter writer) { - ExpressionSyntax pixelOptionsExpression; - // Set the right expression if the pixel options are valid - if (pixelOptions is D2D1PixelOptions.None or D2D1PixelOptions.TrivialSampling) + string pixelOptionsExpression = (info.PixelOptions is D2D1PixelOptions.None or D2D1PixelOptions.TrivialSampling) switch { - pixelOptionsExpression = - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("ComputeSharp.D2D1.D2D1PixelOptions"), - IdentifierName(pixelOptions.ToString())); - } - else - { - // Otherwise just return default (the analyzer will emit a diagnostic) - pixelOptionsExpression = LiteralExpression(SyntaxKind.DefaultLiteralExpression, Token(SyntaxKind.DefaultKeyword)); - } + true => $"global::ComputeSharp.D2D1.D2D1PixelOptions.{info.PixelOptions}", + false => "default" + }; - // This code produces a property declaration as follows: - // - // readonly ComputeSharp.D2D1.D2D1PixelOptions global::ComputeSharp.D2D1.__Internals.ID2D1Shader.PixelOptions => ; - return - PropertyDeclaration(IdentifierName("ComputeSharp.D2D1.D2D1PixelOptions"), Identifier(nameof(PixelOptions))) - .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.D2D1.__Internals.{nameof(ID2D1Shader)}"))) - .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword)) - .WithExpressionBody(ArrowExpressionClause(pixelOptionsExpression)) - .WithSemicolonToken(Token(SyntaxKind.SemicolonToken)); + writer.WriteLine($"readonly ComputeSharp.D2D1.D2D1PixelOptions global::ComputeSharp.D2D1.__Internals.ID2D1Shader.PixelOptions => {pixelOptionsExpression};"); } } } \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateResourceTextureDescriptionsProperty.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateResourceTextureDescriptionsProperty.Syntax.cs index dc3fb916..914f54e9 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateResourceTextureDescriptionsProperty.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateResourceTextureDescriptionsProperty.Syntax.cs @@ -1,13 +1,5 @@ -using System; -using ComputeSharp.D2D1.__Internals; using ComputeSharp.D2D1.SourceGenerators.Models; using ComputeSharp.SourceGeneration.Helpers; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Syntax; -using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; - -#pragma warning disable CS0618 namespace ComputeSharp.D2D1.SourceGenerators; @@ -18,90 +10,63 @@ partial class ID2D1ShaderGenerator private static partial class ResourceTextureDescriptions { /// - /// Creates a instance for the ResourceTextureDescriptions property. + /// Writes the ResourceTextureDescriptions property. /// - /// The resource texture descriptions info gathered for the current shader. - /// Any additional instances needed by the generated code, if needed. - /// The resulting instance for the ResourceTextureDescriptions property. - public static PropertyDeclarationSyntax GetSyntax(EquatableArray resourceTextureDescriptions, out MemberDeclarationSyntax[] additionalDataMembers) + /// The input instance with gathered shader info. + /// The instance to write into. + public static void WriteSyntax(D2D1ShaderInfo info, IndentedTextWriter writer) { - ExpressionSyntax memoryExpression; + writer.WriteLine("readonly global::System.ReadOnlyMemory global::ComputeSharp.D2D1.__Internals.ID2D1Shader.ResourceTextureDescriptions => "); // If there are no resource texture descriptions, just return a default expression. - // Otherwise, declare the shared array and return it from the property. - if (resourceTextureDescriptions.Length == 0) + // Otherwise, return a memory instance from the generated static readonly array. + if (info.ResourceTextureDescriptions.IsEmpty) { - memoryExpression = LiteralExpression(SyntaxKind.DefaultLiteralExpression, Token(SyntaxKind.DefaultKeyword)); - additionalDataMembers = Array.Empty(); + writer.WriteLine("default;"); } else { - memoryExpression = MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("Data"), - IdentifierName(nameof(ResourceTextureDescriptions))); - - additionalDataMembers = new[] { GetArrayDeclaration(resourceTextureDescriptions) }; + writer.WriteLine("Data.ResourceTextureDescriptions;"); } - - // This code produces a method declaration as follows: - // - // readonly global::System.ReadOnlyMemory global::ComputeSharp.D2D1.__Internals.ID2D1Shader.ResourceTextureDescriptions => ; - return - PropertyDeclaration( - GenericName(Identifier("global::System.ReadOnlyMemory")) - .AddTypeArgumentListArguments(IdentifierName("global::ComputeSharp.D2D1.Interop.D2D1ResourceTextureDescription")), - Identifier(nameof(ResourceTextureDescriptions))) - .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.D2D1.__Internals.{nameof(ID2D1Shader)}"))) - .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword)) - .WithExpressionBody(ArrowExpressionClause(memoryExpression)) - .WithSemicolonToken(Token(SyntaxKind.SemicolonToken)); } /// - /// Gets the array declaration for the given resource texture descriptions. + /// Registers a callback to generate an additional data member, if needed. /// - /// The resource texture descriptions info gathered for the current shader. - /// The array declaration for the given resource texture descriptions. - private static MemberDeclarationSyntax GetArrayDeclaration(EquatableArray resourceTextureDescriptions) + /// The input instance with gathered shader info. + /// The registered callbacks to generate additional data members. + public static void RegisterAdditionalDataMemberSyntax(D2D1ShaderInfo info, ImmutableArrayBuilder> callbacks) { - using ImmutableArrayBuilder resourceTextureDescriptionExpressions = ImmutableArrayBuilder.Rent(); - - foreach (ResourceTextureDescription resourceTextureDescription in resourceTextureDescriptions) + // If there are no resource texture descriptions, there is nothing to di + if (info.ResourceTextureDescriptions.IsEmpty) { - // Create the description expression: - // - // new(, ) - resourceTextureDescriptionExpressions.Add( - ImplicitObjectCreationExpression() - .AddArgumentListArguments( - Argument(LiteralExpression( - SyntaxKind.NumericLiteralExpression, - Literal(resourceTextureDescription.Index))), - Argument(LiteralExpression( - SyntaxKind.NumericLiteralExpression, - Literal(resourceTextureDescription.Rank))))); + return; } - // Declare the singleton property to get the memory instance: - // - // /// The singleton array instance. - // public static readonly global::ComputeSharp.D2D1.Interop.D2D1ResourceTextureDescription[] ResourceTextureDescriptions = { }; - return - FieldDeclaration( - VariableDeclaration( - ArrayType(IdentifierName("global::ComputeSharp.D2D1.Interop.D2D1ResourceTextureDescription")) - .AddRankSpecifiers(ArrayRankSpecifier(SingletonSeparatedList(OmittedArraySizeExpression())))) - .AddVariables( - VariableDeclarator(Identifier(nameof(ResourceTextureDescriptions))) - .WithInitializer(EqualsValueClause( - InitializerExpression(SyntaxKind.ArrayInitializerExpression) - .AddExpressions(resourceTextureDescriptionExpressions.ToArray()))))) - .AddModifiers( - Token(SyntaxKind.PublicKeyword), - Token(SyntaxKind.StaticKeyword), - Token(SyntaxKind.ReadOnlyKeyword)) - .WithLeadingTrivia(Comment("""/// The singleton array instance.""")); + // 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 ="""); + + // Initialize all resource texture descriptions + using (writer.WriteBlock()) + { + for (int i = 0; i < info.ResourceTextureDescriptions.Length; i++) + { + ResourceTextureDescription description = info.ResourceTextureDescriptions[i]; + + writer.Write($"new global::ComputeSharp.D2D1.Interop.D2D1ResourceTextureDescription({description.Index}, {description.Rank})"); + + if (i < info.ResourceTextureDescriptions.Length - 1) + { + writer.WriteLine(","); + } + } + } + } + + callbacks.Add(Callback); } } } \ No newline at end of file diff --git a/src/ComputeSharp.SourceGeneration.Hlsl/Helpers/SyntaxFormattingHelper.cs b/src/ComputeSharp.SourceGeneration.Hlsl/Helpers/SyntaxFormattingHelper.cs index da5256a7..d8d0fd01 100644 --- a/src/ComputeSharp.SourceGeneration.Hlsl/Helpers/SyntaxFormattingHelper.cs +++ b/src/ComputeSharp.SourceGeneration.Hlsl/Helpers/SyntaxFormattingHelper.cs @@ -30,6 +30,16 @@ internal static class SyntaxFormattingHelper "0xF0", "0xF1", "0xF2", "0xF3", "0xF4", "0xF5", "0xF6", "0xF7", "0xF8", "0xF9", "0xFA", "0xFB", "0xFC", "0xFD", "0xFE", "0xFF" }; + /// + /// Gets an expression representing a single byte. + /// + /// The byte to format. + /// The expression for . + public static string GetByteExpression(byte value) + { + return FormattedBytes[value]; + } + /// /// Writes a formatted expression to initialize a with a given content. /// @@ -58,7 +68,7 @@ internal static class SyntaxFormattingHelper ReadOnlySpan expressions = FormattedBytes.AsSpan(); // First write the first item (which has no leading separator) - expressions[0].AsSpan().CopyTo(span); + expressions[bytecode[0]].AsSpan().CopyTo(span); // Special case: stop early if there's only one element if (bytecode.Length == 1) diff --git a/src/ComputeSharp.SourceGeneration/Helpers/IndentedTextWriter.cs b/src/ComputeSharp.SourceGeneration/Helpers/IndentedTextWriter.cs index 470f6696..2fce1242 100644 --- a/src/ComputeSharp.SourceGeneration/Helpers/IndentedTextWriter.cs +++ b/src/ComputeSharp.SourceGeneration/Helpers/IndentedTextWriter.cs @@ -248,6 +248,14 @@ internal sealed class IndentedTextWriter : IDisposable this.builder.AddRange(content); } + /// + /// A delegate representing a callback to write data into an instance. + /// + /// The type of data to use. + /// The input data to use to write into . + /// The instance to write into. + public delegate void Callback(T value, IndentedTextWriter writer); + /// /// Represents an indented block that needs to be closed. /// From 5d859266d8c464c3ab730661a77ccb2ce4d20347 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Fri, 29 Sep 2023 23:40:00 +0200 Subject: [PATCH 07/13] Fully enable D2D1 generator to run on indented text writer --- ...Generator.CreateEffectIdProperty.Syntax.cs | 67 +++++------ ...nerator.CreateHlslSourceProperty.Syntax.cs | 4 +- ...InitializeFromDispatchDataMethod.Syntax.cs | 1 + ....CreateInputDescriptionsProperty.Syntax.cs | 112 +++++++++--------- ...nerator.CreateInputTypesProperty.Syntax.cs | 30 +++-- ...nerator.CreateLoadBytecodeMethod.Syntax.cs | 15 +-- ...tor.CreateLoadDispatchDataMethod.Syntax.cs | 5 + ...ourceTextureDescriptionsProperty.Syntax.cs | 25 ++-- .../ID2D1ShaderGenerator.cs | 76 ++++++------ .../Helpers/IndentedTextWriter.cs | 6 +- .../Models/HierarchyInfo.cs | 49 ++++++++ .../Models/TypeInfo.cs | 15 +++ 12 files changed, 241 insertions(+), 164 deletions(-) diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectIdProperty.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectIdProperty.Syntax.cs index cf0a71d8..e23348f7 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectIdProperty.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectIdProperty.Syntax.cs @@ -25,42 +25,39 @@ partial class ID2D1ShaderGenerator using (writer.WriteBlock()) { - writer.WriteLine($"global::System.ReadOnlySpan bytes = new byte[]"); + writer.WriteLine("global::System.ReadOnlySpan bytes = new byte[]"); + writer.WriteLine("{"); + writer.IncreaseIndent(); - using (writer.WriteBlock()) - { - // Write the bytes like so: - // - // b[0], b[1], b[2], b[3], - // b[4], b[5], - // b[6], b[7], - // b[8], - // b[9], - // b[10], - // b[11], - // b[12], - // b[13], - // b[14], - // b[15], - // b[16], - // b[17] - SyntaxFormattingHelper.WriteByteArrayInitializationExpressions(info.EffectId.AsSpan()[..4], writer); - writer.WriteLine(","); - SyntaxFormattingHelper.WriteByteArrayInitializationExpressions(info.EffectId.AsSpan()[4..6], writer); - writer.WriteLine(","); - SyntaxFormattingHelper.WriteByteArrayInitializationExpressions(info.EffectId.AsSpan()[6..8], writer); - writer.WriteLine(","); - writer.WriteLine($"{SyntaxFormattingHelper.GetByteExpression(info.EffectId[8])},"); - writer.WriteLine($"{SyntaxFormattingHelper.GetByteExpression(info.EffectId[9])},"); - writer.WriteLine($"{SyntaxFormattingHelper.GetByteExpression(info.EffectId[10])},"); - writer.WriteLine($"{SyntaxFormattingHelper.GetByteExpression(info.EffectId[11])},"); - writer.WriteLine($"{SyntaxFormattingHelper.GetByteExpression(info.EffectId[12])},"); - writer.WriteLine($"{SyntaxFormattingHelper.GetByteExpression(info.EffectId[13])},"); - writer.WriteLine($"{SyntaxFormattingHelper.GetByteExpression(info.EffectId[14])},"); - writer.WriteLine($"{SyntaxFormattingHelper.GetByteExpression(info.EffectId[15])},"); - writer.WriteLine($"{SyntaxFormattingHelper.GetByteExpression(info.EffectId[16])},"); - writer.WriteLine(SyntaxFormattingHelper.GetByteExpression(info.EffectId[17])); - } + // Write the bytes like so: + // + // b[0], b[1], b[2], b[3], + // b[4], b[5], + // b[6], b[7], + // b[8], + // b[9], + // b[10], + // b[11], + // b[12], + // b[13], + // b[14], + // b[15] + SyntaxFormattingHelper.WriteByteArrayInitializationExpressions(info.EffectId.AsSpan()[..4], writer); + writer.WriteLine(","); + SyntaxFormattingHelper.WriteByteArrayInitializationExpressions(info.EffectId.AsSpan()[4..6], writer); + writer.WriteLine(","); + SyntaxFormattingHelper.WriteByteArrayInitializationExpressions(info.EffectId.AsSpan()[6..8], writer); + writer.WriteLine(","); + writer.WriteLine($"{SyntaxFormattingHelper.GetByteExpression(info.EffectId[8])},"); + writer.WriteLine($"{SyntaxFormattingHelper.GetByteExpression(info.EffectId[9])},"); + writer.WriteLine($"{SyntaxFormattingHelper.GetByteExpression(info.EffectId[10])},"); + writer.WriteLine($"{SyntaxFormattingHelper.GetByteExpression(info.EffectId[11])},"); + writer.WriteLine($"{SyntaxFormattingHelper.GetByteExpression(info.EffectId[12])},"); + writer.WriteLine($"{SyntaxFormattingHelper.GetByteExpression(info.EffectId[13])},"); + writer.WriteLine($"{SyntaxFormattingHelper.GetByteExpression(info.EffectId[14])},"); + writer.WriteLine(SyntaxFormattingHelper.GetByteExpression(info.EffectId[15])); + writer.DecreaseIndent(); + writer.WriteLine("};"); writer.WriteLine(); writer.WriteLine("return ref global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.InteropServices.MemoryMarshal.GetReference(bytes));"); diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateHlslSourceProperty.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateHlslSourceProperty.Syntax.cs index 3a508bd5..18b07eb7 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateHlslSourceProperty.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateHlslSourceProperty.Syntax.cs @@ -17,9 +17,11 @@ partial class ID2D1ShaderGenerator public static void WriteSyntax(D2D1ShaderInfo info, IndentedTextWriter writer) { writer.WriteLine("readonly string global::ComputeSharp.D2D1.__Internals.ID2D1Shader.HlslSource =>"); + writer.IncreaseIndent(); writer.WriteLine("\"\"\""); - writer.WriteLine(info.HlslInfoKey.HlslSource, isMultiline: true); + writer.Write(info.HlslInfoKey.HlslSource, isMultiline: true); writer.WriteLine("\"\"\";"); + writer.DecreaseIndent(); } } } \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInitializeFromDispatchDataMethod.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInitializeFromDispatchDataMethod.Syntax.cs index 1c15a7df..32b0acb7 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInitializeFromDispatchDataMethod.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInitializeFromDispatchDataMethod.Syntax.cs @@ -35,6 +35,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));"); // Generate loading statements for each captured field diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInputDescriptionsProperty.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInputDescriptionsProperty.Syntax.cs index 50c429f4..4f822624 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInputDescriptionsProperty.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInputDescriptionsProperty.Syntax.cs @@ -1,10 +1,5 @@ -using System; using ComputeSharp.D2D1.SourceGenerators.Models; using ComputeSharp.SourceGeneration.Helpers; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Syntax; -using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; namespace ComputeSharp.D2D1.SourceGenerators; @@ -21,7 +16,7 @@ partial class ID2D1ShaderGenerator /// The instance to write into. public static void WriteSyntax(D2D1ShaderInfo info, IndentedTextWriter writer) { - writer.WriteLine("readonly global::System.ReadOnlyMemory global::ComputeSharp.D2D1.__Internals.ID2D1Shader.InputDescriptions => "); + writer.Write("readonly global::System.ReadOnlyMemory global::ComputeSharp.D2D1.__Internals.ID2D1Shader.InputDescriptions => "); // If there are no input descriptions, just return a default expression. // Otherwise, return the shared array with cached input descriptions. @@ -36,36 +31,44 @@ partial class ID2D1ShaderGenerator } /// - /// Registers a callback to generate an additional data member, if needed. + /// Registers a callback to generate an additional type, if needed. /// /// The input instance with gathered shader info. - /// The registered callbacks to generate additional data members. - public static void RegisterAdditionalDataMemberSyntax(D2D1ShaderInfo info, ImmutableArrayBuilder> callbacks) + /// The registered callbacks to generate additional types. + public static void RegisterAdditionalTypeSyntax(D2D1ShaderInfo info, ImmutableArrayBuilder> callbacks) { - // If there are no input descriptions, there is nothing to di - if (info.ResourceTextureDescriptions.IsEmpty) + // If there are no necessary data members, stop here + if (info.InputDescriptions.IsEmpty && + info.ResourceTextureDescriptions.IsEmpty) { return; } - // Declare the shared array with input descriptions + // Declare the additional data type 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($$"""/// """); + writer.WriteLine($$"""/// A container type for additional data needed by the shader."""); + writer.WriteLine($$"""/// """); + writer.WriteLine($$"""[global::System.CodeDom.Compiler.GeneratedCode("{{typeof(ID2D1ShaderGenerator).FullName}}", "{{typeof(ID2D1ShaderGenerator).Assembly.GetName().Version}}")]"""); + writer.WriteLine($$"""[global::System.Diagnostics.DebuggerNonUserCode]"""); + writer.WriteLine($$"""[global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]"""); + writer.WriteLine($$"""file static class Data"""); - // Initialize all input descriptions using (writer.WriteBlock()) { - for (int i = 0; i < info.InputDescriptions.Length; i++) + using ImmutableArrayBuilder> dataMembers = ImmutableArrayBuilder>.Rent(); + + RegisterAdditionalDataMemberSyntax(info, dataMembers); + ResourceTextureDescriptions.RegisterAdditionalDataMemberSyntax(info, dataMembers); + + for (int i = 0; i < dataMembers.WrittenSpan.Length; i++) { - InputDescription description = info.InputDescriptions[i]; + dataMembers.WrittenSpan[i](info, writer); - writer.Write($$"""new global::ComputeSharp.D2D1.Interop.D2D1InputDescription({description.Index}, {description.Filter}) { LevelOfDetailCount = {{description.LevelOfDetailCount}} }"""); - - if (i < info.InputDescriptions.Length - 1) + if (i < dataMembers.WrittenSpan.Length - 1) { - writer.WriteLine(","); + writer.WriteLine(); } } } @@ -75,46 +78,45 @@ partial class ID2D1ShaderGenerator } /// - /// Gets any type declarations for additional members. + /// Registers a callback to generate an additional data member, if needed. /// - /// The additional members that are needed. - /// Any type declarations for additional members. - public static TypeDeclarationSyntax[] GetDataTypeDeclarations(MemberDeclarationSyntax[] memberDeclarations) + /// The input instance with gathered shader info. + /// The registered callbacks to generate additional data members. + public static void RegisterAdditionalDataMemberSyntax(D2D1ShaderInfo info, ImmutableArrayBuilder> callbacks) { - if (memberDeclarations.Length == 0) + // If there are no input descriptions, there is nothing to di + if (info.InputDescriptions.IsEmpty) { - return Array.Empty(); + return; } - // Create the container type declaration: - // - // /// - // /// A container type for additional data needed by the shader. - // /// - // [global::System.CodeDom.Compiler.GeneratedCode("...", "...")] - // [global::System.Diagnostics.DebuggerNonUserCode] - // [global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] - // file static class Data - // { - // - // } - TypeDeclarationSyntax dataTypeDeclaration = - ClassDeclaration("Data") - .AddModifiers(Token(SyntaxKind.FileKeyword), Token(SyntaxKind.StaticKeyword)) - .AddAttributeLists( - AttributeList(SingletonSeparatedList( - Attribute(IdentifierName("global::System.CodeDom.Compiler.GeneratedCode")).AddArgumentListArguments( - AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(ID2D1ShaderGenerator).FullName))), - AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(ID2D1ShaderGenerator).Assembly.GetName().Version.ToString())))))), - AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Diagnostics.DebuggerNonUserCode")))), - AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage"))))) - .AddMembers(memberDeclarations) - .WithLeadingTrivia( - Comment("/// "), - Comment("/// A container type for input descriptions."), - Comment("/// ")); + // 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("""{"""); + writer.IncreaseIndent(); - return new[] { dataTypeDeclaration }; + // Initialize all input descriptions + for (int i = 0; i < info.InputDescriptions.Length; i++) + { + InputDescription description = info.InputDescriptions[i]; + + writer.Write($$"""new global::ComputeSharp.D2D1.Interop.D2D1InputDescription({{description.Index}}, global::ComputeSharp.D2D1.D2D1Filter.{{description.Filter}}) { LevelOfDetailCount = {{description.LevelOfDetailCount}} }"""); + + if (i < info.InputDescriptions.Length - 1) + { + writer.WriteLine(","); + } + } + + writer.DecreaseIndent(); + writer.WriteLine(); + writer.WriteLine("};"); + } + + callbacks.Add(Callback); } } } \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInputTypesProperty.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInputTypesProperty.Syntax.cs index 4d536efa..3a8a9e00 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInputTypesProperty.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInputTypesProperty.Syntax.cs @@ -16,7 +16,7 @@ partial class ID2D1ShaderGenerator /// The instance to write into. public static void WriteSyntax(D2D1ShaderInfo info, IndentedTextWriter writer) { - writer.WriteLine("readonly global::System.ReadOnlyMemory global::ComputeSharp.D2D1.__Internals.ID2D1Shader.InputTypes => "); + writer.Write("readonly global::System.ReadOnlyMemory global::ComputeSharp.D2D1.__Internals.ID2D1Shader.InputTypes => "); // If there are no inputs, simply return a default expression. Otherwise, create // a ReadOnlyMemory instance from the memory manager. @@ -64,28 +64,32 @@ partial class ID2D1ShaderGenerator writer.WriteLine(); writer.WriteLine("/// The RVA data with the input type info."); writer.WriteLine("private static global::System.ReadOnlySpan Data => new[]"); + writer.WriteLine("{"); + writer.IncreaseIndent(); // Input types, one per line in the RVA field initializer - using (writer.WriteBlock()) + for (int i = 0; i < info.InputTypes.Length; i++) { - for (int i = 0; i < info.InputTypes.Length; i++) - { - writer.Write("global::ComputeSharp.D2D1.Interop.D2D1PixelShaderInputType."); - writer.Write(info.InputTypes[i] == 0 ? "Simple" : "Complex"); + writer.Write("global::ComputeSharp.D2D1.Interop.D2D1PixelShaderInputType."); + writer.Write(info.InputTypes[i] == 0 ? "Simple" : "Complex"); - if (i < info.InputTypes.Length - 1) - { - writer.WriteLine(","); - } + if (i < info.InputTypes.Length - 1) + { + writer.WriteLine(","); } } + writer.DecreaseIndent(); + writer.WriteLine(); + writer.WriteLine("};"); + writer.WriteLine(); + // Add the remaining members for the memory manager writer.WriteLine(""" /// - public override unsafe global::System.Span GetSpan + public override unsafe global::System.Span GetSpan() { - return new(global::System.Runtime.CompilerServices.Unsafe.AsPointer(ref global::System.Runtime.InteropServices.MemoryMarshal(Data)), Data.Length); + return new(global::System.Runtime.CompilerServices.Unsafe.AsPointer(ref global::System.Runtime.InteropServices.MemoryMarshal.GetReference(Data)), Data.Length); } /// @@ -98,7 +102,7 @@ partial class ID2D1ShaderGenerator /// public override unsafe global::System.Buffers.MemoryHandle Pin(int elementIndex) { - return new(Unsafe.AsPointer(ref Unsafe.AsRef(in Data[elementIndex])), pinnable: this); + return new(global::System.Runtime.CompilerServices.Unsafe.AsPointer(ref global::System.Runtime.CompilerServices.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 2c021ad6..3ef62dc6 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.Syntax.cs @@ -36,7 +36,7 @@ partial class ID2D1ShaderGenerator .Select(static name => $"global::ComputeSharp.D2D1.D2D1CompileOptions.{name.Trim()}") .Aggregate("", static (left, right) => left.Length > 0 ? $"{left} | {right}" : right); - writer.Write($"readonly ComputeSharp.D2D1.D2D1CompileOptions global::ComputeSharp.D2D1.__Internals.ID2D1Shader.CompileOptions => {compileOptionsExpression};"); + writer.WriteLine($"readonly ComputeSharp.D2D1.D2D1CompileOptions global::ComputeSharp.D2D1.__Internals.ID2D1Shader.CompileOptions => {compileOptionsExpression};"); } /// @@ -46,7 +46,7 @@ partial class ID2D1ShaderGenerator /// The instance to write into. public static void WriteHlslBytecodeSyntax(D2D1ShaderInfo info, IndentedTextWriter writer) { - writer.WriteLine("readonly global::System.ReadOnlyMemory global::ComputeSharp.D2D1.__Internals.ID2D1Shader.ResourceTextureDescriptions => "); + writer.Write("readonly global::System.ReadOnlyMemory global::ComputeSharp.D2D1.__Internals.ID2D1Shader.HlslBytecode => "); // If there is no bytecode, just return a default expression. // Otherwise, return the memory manager backed memory instance. @@ -77,7 +77,7 @@ partial class ID2D1ShaderGenerator 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.WriteLine($$"""[global::System.CodeDom.Compiler.GeneratedCode("{{typeof(ID2D1ShaderGenerator).FullName}}", "{{typeof(ID2D1ShaderGenerator).Assembly.GetName().Version}}")]"""); writer.WriteLine($$"""[global::System.Diagnostics.DebuggerNonUserCode]"""); @@ -93,18 +93,19 @@ 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[] { "); + writer.Write("private static global::System.ReadOnlySpan Data => new byte[] { "); SyntaxFormattingHelper.WriteByteArrayInitializationExpressions(((HlslBytecodeInfo.Success)info.HlslInfo).Bytecode.AsSpan(), writer); writer.WriteLine(" };"); + writer.WriteLine(); // Add the remaining members for the memory manager writer.WriteLine(""" /// - public override unsafe global::System.Span GetSpan + public override unsafe global::System.Span GetSpan() { - return new(global::System.Runtime.CompilerServices.Unsafe.AsPointer(ref global::System.Runtime.InteropServices.MemoryMarshal(Data)), Data.Length); + return new(global::System.Runtime.CompilerServices.Unsafe.AsPointer(ref global::System.Runtime.InteropServices.MemoryMarshal.GetReference(Data)), Data.Length); } /// @@ -117,7 +118,7 @@ partial class ID2D1ShaderGenerator /// public override unsafe global::System.Buffers.MemoryHandle Pin(int elementIndex) { - return new(Unsafe.AsPointer(ref Unsafe.AsRef(in Data[elementIndex])), pinnable: this); + return new(global::System.Runtime.CompilerServices.Unsafe.AsPointer(ref global::System.Runtime.CompilerServices.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 54e5242e..d22e2de0 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs @@ -95,6 +95,11 @@ partial class ID2D1ShaderGenerator // Declare fields for every mapped item from the shader layout for (int i = 0; i < info.Fields.Length; i++) { + if (i > 0) + { + writer.WriteLine(); + } + switch (info.Fields[i]) { case FieldInfo.Primitive { TypeName: "System.Boolean" } primitive: diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateResourceTextureDescriptionsProperty.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateResourceTextureDescriptionsProperty.Syntax.cs index 914f54e9..76e4f735 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateResourceTextureDescriptionsProperty.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateResourceTextureDescriptionsProperty.Syntax.cs @@ -16,7 +16,7 @@ partial class ID2D1ShaderGenerator /// The instance to write into. public static void WriteSyntax(D2D1ShaderInfo info, IndentedTextWriter writer) { - writer.WriteLine("readonly global::System.ReadOnlyMemory global::ComputeSharp.D2D1.__Internals.ID2D1Shader.ResourceTextureDescriptions => "); + writer.Write("readonly global::System.ReadOnlyMemory global::ComputeSharp.D2D1.__Internals.ID2D1Shader.ResourceTextureDescriptions => "); // If there are no resource texture descriptions, just return a default expression. // Otherwise, return a memory instance from the generated static readonly array. @@ -48,22 +48,25 @@ partial class ID2D1ShaderGenerator { writer.WriteLine("""/// The singleton array instance."""); writer.WriteLine("""public static readonly global::ComputeSharp.D2D1.Interop.D2D1ResourceTextureDescription[] ResourceTextureDescriptions ="""); + writer.WriteLine("""{"""); + writer.IncreaseIndent(); // Initialize all resource texture descriptions - using (writer.WriteBlock()) + for (int i = 0; i < info.ResourceTextureDescriptions.Length; i++) { - for (int i = 0; i < info.ResourceTextureDescriptions.Length; i++) + ResourceTextureDescription description = info.ResourceTextureDescriptions[i]; + + writer.Write($"new global::ComputeSharp.D2D1.Interop.D2D1ResourceTextureDescription({description.Index}, {description.Rank})"); + + if (i < info.ResourceTextureDescriptions.Length - 1) { - ResourceTextureDescription description = info.ResourceTextureDescriptions[i]; - - writer.Write($"new global::ComputeSharp.D2D1.Interop.D2D1ResourceTextureDescription({description.Index}, {description.Rank})"); - - if (i < info.ResourceTextureDescriptions.Length - 1) - { - writer.WriteLine(","); - } + writer.WriteLine(","); } } + + writer.DecreaseIndent(); + writer.WriteLine(); + writer.WriteLine("};"); } callbacks.Add(Callback); diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs index 044b2e32..d968e554 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Immutable; using System.Linq; using ComputeSharp.D2D1.SourceGenerators.Models; @@ -8,7 +7,6 @@ using ComputeSharp.SourceGeneration.Models; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; -using Microsoft.CodeAnalysis.Text; namespace ComputeSharp.D2D1.SourceGenerators; @@ -196,48 +194,46 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator // Generate the source files, if any context.RegisterSourceOutput(outputInfo, static (context, item) => { - PropertyDeclarationSyntax effectIdProperty = EffectId.GetSyntax(item.EffectId); - PropertyDeclarationSyntax effectDisplayNameProperty = EffectMetadata.GetEffectDisplayNameSyntax(item.EffectDisplayName); - PropertyDeclarationSyntax effectDescriptionProperty = EffectMetadata.GetEffectDescriptionSyntax(item.EffectDescription); - PropertyDeclarationSyntax effectCategoryProperty = EffectMetadata.GetEffectCategorySyntax(item.EffectCategory); - PropertyDeclarationSyntax effectAuthorProperty = EffectMetadata.GetEffectAuthorSyntax(item.EffectAuthor); - PropertyDeclarationSyntax inputCountProperty = InputCount.GetSyntax(item.InputTypes.Length); - PropertyDeclarationSyntax inputTypesProperty = InputTypes.GetSyntax(item.InputTypes, out TypeDeclarationSyntax[] inputTypesAdditionalTypes); - PropertyDeclarationSyntax inputDescriptionsProperty = InputDescriptions.GetSyntax(item.InputDescriptions, out MemberDeclarationSyntax[] inputDescriptionsAdditionalDataMembers); - PropertyDeclarationSyntax resourceTextureDescriptionsProperty = ResourceTextureDescriptions.GetSyntax(item.ResourceTextureDescriptions, out MemberDeclarationSyntax[] resourceTexturesAditionalDataMembers); - PropertyDeclarationSyntax hlslStringProperty = HlslSource.GetSyntax(item.HlslInfoKey.HlslSource, item.Hierarchy.Hierarchy.Length); - PropertyDeclarationSyntax hlslBytecodeProperty = LoadBytecode.GetHlslBytecodeSyntax(item.HlslInfo, out Func fixup, out TypeDeclarationSyntax[] hlslBytecodeAdditionalTypes); - PropertyDeclarationSyntax shaderProfileProperty = LoadBytecode.GetShaderProfileSyntax(item.HlslInfoKey.EffectiveShaderProfile); - PropertyDeclarationSyntax compileOptionsProperty = LoadBytecode.GetCompileOptionsSyntax(item.HlslInfoKey.EffectiveCompileOptions); - PropertyDeclarationSyntax bufferPrecisionProperty = OutputBuffer.GetBufferPrecisionSyntax(item.BufferPrecision); - PropertyDeclarationSyntax channelDepthProperty = OutputBuffer.GetChannelDepthSyntax(item.ChannelDepth); - PropertyDeclarationSyntax pixelOptionsProperty = PixelOptions.GetSyntax(item.PixelOptions); + using ImmutableArrayBuilder> declaredMembers = ImmutableArrayBuilder>.Rent(); - MethodDeclarationSyntax initializeFromDispatchDataMethod = InitializeFromDispatchData.GetSyntax(item.Fields); - MethodDeclarationSyntax loadDispatchDataMethod = LoadDispatchData.GetSyntax(item.Hierarchy, item.Fields, item.ConstantBufferSizeInBytes, out TypeDeclarationSyntax[] loadDispatchDataAditionalTypes); + declaredMembers.Add(EffectId.WriteSyntax); + declaredMembers.Add(EffectMetadata.WriteEffectDisplayNameSyntax); + declaredMembers.Add(EffectMetadata.WriteEffectDescriptionSyntax); + declaredMembers.Add(EffectMetadata.WriteEffectCategorySyntax); + declaredMembers.Add(EffectMetadata.WriteEffectAuthorSyntax); + declaredMembers.Add(InputCount.WriteSyntax); + declaredMembers.Add(InputTypes.WriteSyntax); + declaredMembers.Add(InputDescriptions.WriteSyntax); + declaredMembers.Add(ResourceTextureDescriptions.WriteSyntax); + declaredMembers.Add(PixelOptions.WriteSyntax); + declaredMembers.Add(OutputBuffer.WriteBufferPrecisionSyntax); + declaredMembers.Add(OutputBuffer.WriteChannelDepthSyntax); + declaredMembers.Add(LoadBytecode.WriteShaderProfileSyntax); + declaredMembers.Add(LoadBytecode.WriteCompileOptionsSyntax); + declaredMembers.Add(HlslSource.WriteSyntax); + declaredMembers.Add(LoadBytecode.WriteHlslBytecodeSyntax); + declaredMembers.Add(InitializeFromDispatchData.WriteSyntax); + declaredMembers.Add(LoadDispatchData.WriteSyntax); - CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMembers( - hierarchyInfo: item.Hierarchy, - memberDeclarations: new (MemberDeclarationSyntax, bool)[] - { - (effectIdProperty, false), (effectDisplayNameProperty, false), (effectDescriptionProperty, false), (effectCategoryProperty, false), (effectAuthorProperty, false), - (inputCountProperty, false), (inputTypesProperty, false), (inputDescriptionsProperty, false), (resourceTextureDescriptionsProperty, false), (hlslStringProperty, false), - (hlslBytecodeProperty, false), (shaderProfileProperty, false), (compileOptionsProperty, false), (bufferPrecisionProperty, false), (channelDepthProperty, false), - (pixelOptionsProperty, false), (initializeFromDispatchDataMethod, true), (loadDispatchDataMethod, true) - }, - additionalMemberDeclarations: new TypeDeclarationSyntax[][] - { - loadDispatchDataAditionalTypes, - InputDescriptions.GetDataTypeDeclarations(new[] { inputDescriptionsAdditionalDataMembers, resourceTexturesAditionalDataMembers }.SelectMany(static members => members).ToArray()), - inputTypesAdditionalTypes, hlslBytecodeAdditionalTypes - } - .SelectMany(static types => types) - .Cast() - .ToArray()); + using ImmutableArrayBuilder> additionalTypes = ImmutableArrayBuilder>.Rent(); - SourceText sourceText = fixup(compilationUnit); + LoadDispatchData.RegisterAdditionalTypeSyntax(item, additionalTypes); + InputDescriptions.RegisterAdditionalTypeSyntax(item, additionalTypes); + InputTypes.RegisterAdditionalTypeSyntax(item, additionalTypes); + LoadBytecode.RegisterAdditionalTypeSyntax(item, additionalTypes); - context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.g.cs", sourceText); + using IndentedTextWriter writer = IndentedTextWriter.Rent(); + + item.Hierarchy.WriteSyntax(item, writer, declaredMembers.WrittenSpan); + + foreach (IndentedTextWriter.Callback additionalType in additionalTypes.WrittenSpan) + { + writer.WriteLine(); + + additionalType(item, writer); + } + + context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.g.cs", writer.ToString()); }); } } \ No newline at end of file diff --git a/src/ComputeSharp.SourceGeneration/Helpers/IndentedTextWriter.cs b/src/ComputeSharp.SourceGeneration/Helpers/IndentedTextWriter.cs index 2fce1242..9497cf23 100644 --- a/src/ComputeSharp.SourceGeneration/Helpers/IndentedTextWriter.cs +++ b/src/ComputeSharp.SourceGeneration/Helpers/IndentedTextWriter.cs @@ -61,9 +61,8 @@ internal sealed class IndentedTextWriter : IDisposable { this.builder = builder; this.currentIndentationLevel = 0; - this.currentIndentation = DefaultIndentation; + this.currentIndentation = ""; this.availableIndentations = new string[4]; - this.availableIndentations[0] = ""; for (int i = 1, n = this.availableIndentations.Length; i < n; i++) @@ -158,11 +157,14 @@ internal sealed class IndentedTextWriter : IDisposable { // There are no new lines left, so the content can be written as a single line WriteRawText(content); + + break; } else { // Write the current line WriteRawText(content[..newLineIndex]); + WriteLine(); // Move past the new line character (the result could be an empty span) content = content[(newLineIndex + 1)..]; diff --git a/src/ComputeSharp.SourceGeneration/Models/HierarchyInfo.cs b/src/ComputeSharp.SourceGeneration/Models/HierarchyInfo.cs index 520bd83b..6452144d 100644 --- a/src/ComputeSharp.SourceGeneration/Models/HierarchyInfo.cs +++ b/src/ComputeSharp.SourceGeneration/Models/HierarchyInfo.cs @@ -42,6 +42,55 @@ internal sealed partial record HierarchyInfo(string FullyQualifiedMetadataName, hierarchy.ToImmutable()); } + /// + /// Writes syntax for the current hierarchy into a target writer. + /// + /// The type of state to pass to callbacks. + /// The input state to pass to callbacks. + /// The target instance to write text to. + /// The callbacks to use to write members into the declared type. + public void WriteSyntax(T state, IndentedTextWriter writer, ReadOnlySpan> memberCallbacks) + { + // Write the generated file header + writer.WriteLine("// "); + writer.WriteLine("#pragma warning disable"); + writer.WriteLine(); + + // Declare the file scoped namespace, if needed + if (Namespace.Length > 0) + { + writer.WriteLine($"namespace {Namespace};"); + writer.WriteLine(); + } + + // Declare all the opening types until the inner-most one + for (int i = Hierarchy.Length - 1; i >= 0; i--) + { + writer.WriteLine($$"""/// """); + writer.WriteLine($$"""partial {{Hierarchy[i].GetTypeKeyword()}} {{Hierarchy[i].QualifiedName}}"""); + writer.WriteLine($$"""{"""); + writer.IncreaseIndent(); + } + + // Generate all nested members + for (int i = 0; i < memberCallbacks.Length; i++) + { + if (i > 0) + { + writer.WriteLine(); + } + + memberCallbacks[i](state, writer); + } + + // Close all scopes and reduce the indentation + for (int i = 0; i < Hierarchy.Length; i++) + { + writer.DecreaseIndent(); + writer.WriteLine("}"); + } + } + /// /// Gets the fully qualified type name for the current instance. /// diff --git a/src/ComputeSharp.SourceGeneration/Models/TypeInfo.cs b/src/ComputeSharp.SourceGeneration/Models/TypeInfo.cs index 9341a459..95439d24 100644 --- a/src/ComputeSharp.SourceGeneration/Models/TypeInfo.cs +++ b/src/ComputeSharp.SourceGeneration/Models/TypeInfo.cs @@ -13,6 +13,21 @@ namespace ComputeSharp.SourceGeneration.Models; /// Whether the type is a record type. internal sealed record TypeInfo(string QualifiedName, TypeKind Kind, bool IsRecord) { + /// + /// Gets the keyword for the current type kind. + /// + /// The keyword for the current type kind. + public string GetTypeKeyword() + { + return Kind switch + { + TypeKind.Struct => "struct", + TypeKind.Interface => "interface", + TypeKind.Class when IsRecord => "record", + _ => "class" + }; + } + /// /// Creates a instance for the current info. /// From eba861e20ef4eb3a538a9c83075f63319e6d0f2e Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 30 Sep 2023 00:03:50 +0200 Subject: [PATCH 08/13] Add and adopt IndentedTextWriterExtensions --- ....CreateInputDescriptionsProperty.Syntax.cs | 14 ++--- ...nerator.CreateInputTypesProperty.Syntax.cs | 12 ++-- ...tor.CreateLoadDispatchDataMethod.Syntax.cs | 12 ++-- ...ourceTextureDescriptionsProperty.Syntax.cs | 14 ++--- .../ComputeSharp.SourceGeneration.projitems | 1 + .../IndentedTextWriterExtensions.cs | 56 +++++++++++++++++++ .../Models/HierarchyInfo.cs | 10 +--- 7 files changed, 76 insertions(+), 43 deletions(-) create mode 100644 src/ComputeSharp.SourceGeneration/Extensions/IndentedTextWriterExtensions.cs diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInputDescriptionsProperty.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInputDescriptionsProperty.Syntax.cs index 4f822624..0af11a60 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInputDescriptionsProperty.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInputDescriptionsProperty.Syntax.cs @@ -1,6 +1,9 @@ using ComputeSharp.D2D1.SourceGenerators.Models; +using ComputeSharp.SourceGeneration.Extensions; using ComputeSharp.SourceGeneration.Helpers; +#pragma warning disable IDE0053 + namespace ComputeSharp.D2D1.SourceGenerators; /// @@ -99,17 +102,10 @@ partial class ID2D1ShaderGenerator writer.IncreaseIndent(); // Initialize all input descriptions - for (int i = 0; i < info.InputDescriptions.Length; i++) + writer.WriteInitializationExpressions(info.InputDescriptions.AsSpan(), static (description, writer) => { - InputDescription description = info.InputDescriptions[i]; - writer.Write($$"""new global::ComputeSharp.D2D1.Interop.D2D1InputDescription({{description.Index}}, global::ComputeSharp.D2D1.D2D1Filter.{{description.Filter}}) { LevelOfDetailCount = {{description.LevelOfDetailCount}} }"""); - - if (i < info.InputDescriptions.Length - 1) - { - writer.WriteLine(","); - } - } + }); writer.DecreaseIndent(); writer.WriteLine(); diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInputTypesProperty.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInputTypesProperty.Syntax.cs index 3a8a9e00..dc114166 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInputTypesProperty.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInputTypesProperty.Syntax.cs @@ -1,4 +1,5 @@ using ComputeSharp.D2D1.SourceGenerators.Models; +using ComputeSharp.SourceGeneration.Extensions; using ComputeSharp.SourceGeneration.Helpers; namespace ComputeSharp.D2D1.SourceGenerators; @@ -68,16 +69,11 @@ partial class ID2D1ShaderGenerator writer.IncreaseIndent(); // Input types, one per line in the RVA field initializer - for (int i = 0; i < info.InputTypes.Length; i++) + writer.WriteInitializationExpressions(info.InputTypes.AsSpan(), static (type, writer) => { writer.Write("global::ComputeSharp.D2D1.Interop.D2D1PixelShaderInputType."); - writer.Write(info.InputTypes[i] == 0 ? "Simple" : "Complex"); - - if (i < info.InputTypes.Length - 1) - { - writer.WriteLine(","); - } - } + writer.Write(type == 0 ? "Simple" : "Complex"); + }); writer.DecreaseIndent(); writer.WriteLine(); diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs index d22e2de0..5a9605fd 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs @@ -1,4 +1,5 @@ using ComputeSharp.D2D1.SourceGenerators.Models; +using ComputeSharp.SourceGeneration.Extensions; using ComputeSharp.SourceGeneration.Helpers; using ComputeSharp.SourceGeneration.Mappings; @@ -93,14 +94,9 @@ partial class ID2D1ShaderGenerator using (writer.WriteBlock()) { // Declare fields for every mapped item from the shader layout - for (int i = 0; i < info.Fields.Length; i++) + writer.WriteLineSeparatedMembers(info.Fields.AsSpan(), (field, writer) => { - if (i > 0) - { - writer.WriteLine(); - } - - switch (info.Fields[i]) + switch (field) { case FieldInfo.Primitive { TypeName: "System.Boolean" } primitive: @@ -131,7 +127,7 @@ partial class ID2D1ShaderGenerator break; } - } + }); } } diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateResourceTextureDescriptionsProperty.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateResourceTextureDescriptionsProperty.Syntax.cs index 76e4f735..4514e9f9 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateResourceTextureDescriptionsProperty.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateResourceTextureDescriptionsProperty.Syntax.cs @@ -1,6 +1,9 @@ using ComputeSharp.D2D1.SourceGenerators.Models; +using ComputeSharp.SourceGeneration.Extensions; using ComputeSharp.SourceGeneration.Helpers; +#pragma warning disable IDE0053 + namespace ComputeSharp.D2D1.SourceGenerators; /// @@ -52,17 +55,10 @@ partial class ID2D1ShaderGenerator writer.IncreaseIndent(); // Initialize all resource texture descriptions - for (int i = 0; i < info.ResourceTextureDescriptions.Length; i++) + writer.WriteInitializationExpressions(info.ResourceTextureDescriptions.AsSpan(), static (description, writer) => { - ResourceTextureDescription description = info.ResourceTextureDescriptions[i]; - writer.Write($"new global::ComputeSharp.D2D1.Interop.D2D1ResourceTextureDescription({description.Index}, {description.Rank})"); - - if (i < info.ResourceTextureDescriptions.Length - 1) - { - writer.WriteLine(","); - } - } + }); writer.DecreaseIndent(); writer.WriteLine(); diff --git a/src/ComputeSharp.SourceGeneration/ComputeSharp.SourceGeneration.projitems b/src/ComputeSharp.SourceGeneration/ComputeSharp.SourceGeneration.projitems index a223225c..c258c5c8 100644 --- a/src/ComputeSharp.SourceGeneration/ComputeSharp.SourceGeneration.projitems +++ b/src/ComputeSharp.SourceGeneration/ComputeSharp.SourceGeneration.projitems @@ -13,6 +13,7 @@ + diff --git a/src/ComputeSharp.SourceGeneration/Extensions/IndentedTextWriterExtensions.cs b/src/ComputeSharp.SourceGeneration/Extensions/IndentedTextWriterExtensions.cs new file mode 100644 index 00000000..f7b1f2a6 --- /dev/null +++ b/src/ComputeSharp.SourceGeneration/Extensions/IndentedTextWriterExtensions.cs @@ -0,0 +1,56 @@ +using System; +using ComputeSharp.SourceGeneration.Helpers; + +namespace ComputeSharp.SourceGeneration.Extensions; + +/// +/// Extension methods for the type. +/// +internal static class IndentedTextWriterExtensions +{ + /// + /// Writes a series of members separated by one line between each of them. + /// + /// The type of input items to process. + /// The instance to write into. + /// The input items to process. + /// The instance to invoke for each item. + public static void WriteLineSeparatedMembers( + this IndentedTextWriter writer, + ReadOnlySpan items, + IndentedTextWriter.Callback callback) + { + for (int i = 0; i < items.Length; i++) + { + if (i > 0) + { + writer.WriteLine(); + } + + callback(items[i], writer); + } + } + + /// + /// Writes a series of initialization expressions separated by a comma between each of them. + /// + /// The type of input items to process. + /// The instance to write into. + /// The input items to process. + /// The instance to invoke for each item. + public static void WriteInitializationExpressions( + this IndentedTextWriter writer, + ReadOnlySpan items, + IndentedTextWriter.Callback callback) + { + for (int i = 0; i < items.Length; i++) + { + callback(items[i], writer); + + if (i < items.Length - 1) + { + writer.WriteLine(","); + } + } + } +} \ No newline at end of file diff --git a/src/ComputeSharp.SourceGeneration/Models/HierarchyInfo.cs b/src/ComputeSharp.SourceGeneration/Models/HierarchyInfo.cs index 6452144d..cd53fca9 100644 --- a/src/ComputeSharp.SourceGeneration/Models/HierarchyInfo.cs +++ b/src/ComputeSharp.SourceGeneration/Models/HierarchyInfo.cs @@ -73,15 +73,7 @@ internal sealed partial record HierarchyInfo(string FullyQualifiedMetadataName, } // Generate all nested members - for (int i = 0; i < memberCallbacks.Length; i++) - { - if (i > 0) - { - writer.WriteLine(); - } - - memberCallbacks[i](state, writer); - } + writer.WriteLineSeparatedMembers(memberCallbacks, (callback, writer) => callback(state, writer)); // Close all scopes and reduce the indentation for (int i = 0; i < Hierarchy.Length; i++) From 648f6e5c3319c7c00db1be419ab4bcf574e03469 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 30 Sep 2023 00:11:45 +0200 Subject: [PATCH 09/13] Add attributes to generated types and members --- ...erGenerator.CreateEffectIdProperty.Syntax.cs | 3 +++ ...tor.CreateEffectMetadataProperties.Syntax.cs | 3 +++ ...Generator.CreateHlslSourceProperty.Syntax.cs | 3 +++ ...teInitializeFromDispatchDataMethod.Syntax.cs | 3 +++ ...Generator.CreateInputCountProperty.Syntax.cs | 3 +++ ...or.CreateInputDescriptionsProperty.Syntax.cs | 6 +++--- ...Generator.CreateInputTypesProperty.Syntax.cs | 6 +++--- ...Generator.CreateLoadBytecodeMethod.Syntax.cs | 11 ++++++++--- ...rator.CreateLoadDispatchDataMethod.Syntax.cs | 6 +++--- ...rator.CreateOutputBufferProperties.Syntax.cs | 5 +++++ ...nerator.CreatePixelOptionsProperty.Syntax.cs | 3 +++ ...esourceTextureDescriptionsProperty.Syntax.cs | 2 ++ .../Extensions/IndentedTextWriterExtensions.cs | 17 +++++++++++++++++ 13 files changed, 59 insertions(+), 12 deletions(-) diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectIdProperty.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectIdProperty.Syntax.cs index e23348f7..b9bdcc22 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectIdProperty.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectIdProperty.Syntax.cs @@ -1,4 +1,5 @@ using ComputeSharp.D2D1.SourceGenerators.Models; +using ComputeSharp.SourceGeneration.Extensions; using ComputeSharp.SourceGeneration.Helpers; namespace ComputeSharp.D2D1.SourceGenerators; @@ -16,6 +17,8 @@ partial class ID2D1ShaderGenerator /// The instance to write into. public static void WriteSyntax(D2D1ShaderInfo info, IndentedTextWriter writer) { + writer.WriteLine("/// "); + writer.WriteGeneratedAttributes(typeof(ID2D1ShaderGenerator)); writer.WriteLine("readonly ref readonly global::System.Guid global::ComputeSharp.D2D1.__Internals.ID2D1Shader.EffectId"); using (writer.WriteBlock()) diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectMetadataProperties.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectMetadataProperties.Syntax.cs index c78732ad..a5cc487a 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectMetadataProperties.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectMetadataProperties.Syntax.cs @@ -1,4 +1,5 @@ using ComputeSharp.D2D1.SourceGenerators.Models; +using ComputeSharp.SourceGeneration.Extensions; using ComputeSharp.SourceGeneration.Helpers; namespace ComputeSharp.D2D1.SourceGenerators; @@ -57,6 +58,8 @@ partial class ID2D1ShaderGenerator /// The instance to write into. private static void WriteEffectMetadataSyntax(string propertyName, string? metadataValue, IndentedTextWriter writer) { + writer.WriteLine("/// "); + writer.WriteGeneratedAttributes(typeof(ID2D1ShaderGenerator)); writer.Write($"readonly string? global::ComputeSharp.D2D1.__Internals.ID2D1Shader.{propertyName} => "); // Append null or the metadata value as a string literal diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateHlslSourceProperty.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateHlslSourceProperty.Syntax.cs index 18b07eb7..e0b0f645 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateHlslSourceProperty.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateHlslSourceProperty.Syntax.cs @@ -1,4 +1,5 @@ using ComputeSharp.D2D1.SourceGenerators.Models; +using ComputeSharp.SourceGeneration.Extensions; using ComputeSharp.SourceGeneration.Helpers; namespace ComputeSharp.D2D1.SourceGenerators; @@ -16,6 +17,8 @@ partial class ID2D1ShaderGenerator /// The instance to write into. public static void WriteSyntax(D2D1ShaderInfo info, IndentedTextWriter writer) { + writer.WriteLine("/// "); + writer.WriteGeneratedAttributes(typeof(ID2D1ShaderGenerator)); writer.WriteLine("readonly string global::ComputeSharp.D2D1.__Internals.ID2D1Shader.HlslSource =>"); writer.IncreaseIndent(); writer.WriteLine("\"\"\""); diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInitializeFromDispatchDataMethod.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInitializeFromDispatchDataMethod.Syntax.cs index 32b0acb7..4dfa6969 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInitializeFromDispatchDataMethod.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInitializeFromDispatchDataMethod.Syntax.cs @@ -1,4 +1,5 @@ using ComputeSharp.D2D1.SourceGenerators.Models; +using ComputeSharp.SourceGeneration.Extensions; using ComputeSharp.SourceGeneration.Helpers; namespace ComputeSharp.D2D1.SourceGenerators; @@ -16,6 +17,8 @@ partial class ID2D1ShaderGenerator /// The instance to write into. public static void WriteSyntax(D2D1ShaderInfo info, IndentedTextWriter writer) { + writer.WriteLine("/// "); + writer.WriteGeneratedAttributes(typeof(ID2D1ShaderGenerator)); writer.WriteLine("readonly void global::ComputeSharp.D2D1.__Internals.ID2D1Shader.InitializeFromDispatchData(global::System.ReadOnlySpan data)"); using (writer.WriteBlock()) diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInputCountProperty.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInputCountProperty.Syntax.cs index ba8579df..bbde29e1 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInputCountProperty.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInputCountProperty.Syntax.cs @@ -1,4 +1,5 @@ using ComputeSharp.D2D1.SourceGenerators.Models; +using ComputeSharp.SourceGeneration.Extensions; using ComputeSharp.SourceGeneration.Helpers; namespace ComputeSharp.D2D1.SourceGenerators; @@ -18,6 +19,8 @@ partial class ID2D1ShaderGenerator /// The instance to write into. public static void WriteSyntax(D2D1ShaderInfo info, IndentedTextWriter writer) { + writer.WriteLine("/// "); + writer.WriteGeneratedAttributes(typeof(ID2D1ShaderGenerator)); writer.WriteLine($"readonly int global::ComputeSharp.D2D1.__Internals.ID2D1Shader.InputCount => {info.InputTypes.Length};"); } } diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInputDescriptionsProperty.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInputDescriptionsProperty.Syntax.cs index 0af11a60..ad20fe54 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInputDescriptionsProperty.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInputDescriptionsProperty.Syntax.cs @@ -19,6 +19,8 @@ partial class ID2D1ShaderGenerator /// The instance to write into. public static void WriteSyntax(D2D1ShaderInfo info, IndentedTextWriter writer) { + writer.WriteLine("/// "); + writer.WriteGeneratedAttributes(typeof(ID2D1ShaderGenerator)); writer.Write("readonly global::System.ReadOnlyMemory global::ComputeSharp.D2D1.__Internals.ID2D1Shader.InputDescriptions => "); // If there are no input descriptions, just return a default expression. @@ -53,9 +55,7 @@ partial class ID2D1ShaderGenerator writer.WriteLine($$"""/// """); writer.WriteLine($$"""/// A container type for additional data needed by the shader."""); writer.WriteLine($$"""/// """); - writer.WriteLine($$"""[global::System.CodeDom.Compiler.GeneratedCode("{{typeof(ID2D1ShaderGenerator).FullName}}", "{{typeof(ID2D1ShaderGenerator).Assembly.GetName().Version}}")]"""); - writer.WriteLine($$"""[global::System.Diagnostics.DebuggerNonUserCode]"""); - writer.WriteLine($$"""[global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]"""); + writer.WriteGeneratedAttributes(typeof(ID2D1ShaderGenerator)); writer.WriteLine($$"""file static class Data"""); using (writer.WriteBlock()) diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInputTypesProperty.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInputTypesProperty.Syntax.cs index dc114166..ea98461e 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInputTypesProperty.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInputTypesProperty.Syntax.cs @@ -17,6 +17,8 @@ partial class ID2D1ShaderGenerator /// The instance to write into. public static void WriteSyntax(D2D1ShaderInfo info, IndentedTextWriter writer) { + writer.WriteLine("/// "); + writer.WriteGeneratedAttributes(typeof(ID2D1ShaderGenerator)); writer.Write("readonly global::System.ReadOnlyMemory global::ComputeSharp.D2D1.__Internals.ID2D1Shader.InputTypes => "); // If there are no inputs, simply return a default expression. Otherwise, create @@ -50,9 +52,7 @@ partial class ID2D1ShaderGenerator writer.WriteLine($$"""/// """); writer.WriteLine($$"""/// A implementation to get the input types."""); writer.WriteLine($$"""/// """); - writer.WriteLine($$"""[global::System.CodeDom.Compiler.GeneratedCode("{{typeof(ID2D1ShaderGenerator).FullName}}", "{{typeof(ID2D1ShaderGenerator).Assembly.GetName().Version}}")]"""); - writer.WriteLine($$"""[global::System.Diagnostics.DebuggerNonUserCode]"""); - writer.WriteLine($$"""[global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]"""); + writer.WriteGeneratedAttributes(typeof(ID2D1ShaderGenerator)); writer.WriteLine($$"""file sealed class InputTypesMemoryManager : global::System.Buffers.MemoryManager"""); using (writer.WriteBlock()) diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.Syntax.cs index 3ef62dc6..ef657cc5 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.Syntax.cs @@ -1,5 +1,6 @@ using System.Linq; using ComputeSharp.D2D1.SourceGenerators.Models; +using ComputeSharp.SourceGeneration.Extensions; using ComputeSharp.SourceGeneration.Helpers; using Microsoft.CodeAnalysis; @@ -18,6 +19,8 @@ partial class ID2D1ShaderGenerator /// The instance to write into. public static void WriteShaderProfileSyntax(D2D1ShaderInfo info, IndentedTextWriter writer) { + writer.WriteLine("/// "); + writer.WriteGeneratedAttributes(typeof(ID2D1ShaderGenerator)); writer.WriteLine($"readonly ComputeSharp.D2D1.D2D1ShaderProfile global::ComputeSharp.D2D1.__Internals.ID2D1Shader.ShaderProfile => global::ComputeSharp.D2D1.D2D1ShaderProfile.{info.HlslInfoKey.EffectiveShaderProfile};"); } @@ -36,6 +39,8 @@ partial class ID2D1ShaderGenerator .Select(static name => $"global::ComputeSharp.D2D1.D2D1CompileOptions.{name.Trim()}") .Aggregate("", static (left, right) => left.Length > 0 ? $"{left} | {right}" : right); + writer.WriteLine("/// "); + writer.WriteGeneratedAttributes(typeof(ID2D1ShaderGenerator)); writer.WriteLine($"readonly ComputeSharp.D2D1.D2D1CompileOptions global::ComputeSharp.D2D1.__Internals.ID2D1Shader.CompileOptions => {compileOptionsExpression};"); } @@ -46,6 +51,8 @@ partial class ID2D1ShaderGenerator /// The instance to write into. public static void WriteHlslBytecodeSyntax(D2D1ShaderInfo info, IndentedTextWriter writer) { + writer.WriteLine("/// "); + writer.WriteGeneratedAttributes(typeof(ID2D1ShaderGenerator)); writer.Write("readonly global::System.ReadOnlyMemory global::ComputeSharp.D2D1.__Internals.ID2D1Shader.HlslBytecode => "); // If there is no bytecode, just return a default expression. @@ -79,9 +86,7 @@ partial class ID2D1ShaderGenerator writer.WriteLine($$"""/// """); writer.WriteLine($$"""/// implementation to get the HLSL bytecode."""); writer.WriteLine($$"""/// """); - writer.WriteLine($$"""[global::System.CodeDom.Compiler.GeneratedCode("{{typeof(ID2D1ShaderGenerator).FullName}}", "{{typeof(ID2D1ShaderGenerator).Assembly.GetName().Version}}")]"""); - writer.WriteLine($$"""[global::System.Diagnostics.DebuggerNonUserCode]"""); - writer.WriteLine($$"""[global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]"""); + writer.WriteGeneratedAttributes(typeof(ID2D1ShaderGenerator)); writer.WriteLine($$"""file sealed class HlslBytecodeMemoryManager : global::System.Buffers.MemoryManager"""); using (writer.WriteBlock()) diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs index 5a9605fd..ba98b07f 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs @@ -18,6 +18,8 @@ partial class ID2D1ShaderGenerator /// The instance to write into. public static void WriteSyntax(D2D1ShaderInfo info, IndentedTextWriter writer) { + writer.WriteLine("/// "); + writer.WriteGeneratedAttributes(typeof(ID2D1ShaderGenerator)); writer.WriteLine("readonly unsafe void global::ComputeSharp.D2D1.__Internals.ID2D1Shader.LoadDispatchData(ref TLoader loader)"); using (writer.WriteBlock()) @@ -85,9 +87,7 @@ partial class ID2D1ShaderGenerator writer.WriteLine($$"""/// """); writer.WriteLine($$"""/// A type representing the constant buffer native layout for ."""); writer.WriteLine($$"""/// """); - writer.WriteLine($$"""[global::System.CodeDom.Compiler.GeneratedCode("{{typeof(ID2D1ShaderGenerator).FullName}}", "{{typeof(ID2D1ShaderGenerator).Assembly.GetName().Version}}")]"""); - writer.WriteLine($$"""[global::System.Diagnostics.DebuggerNonUserCode]"""); - writer.WriteLine($$"""[global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]"""); + writer.WriteGeneratedAttributes(typeof(ID2D1ShaderGenerator)); writer.WriteLine($$"""[global::System.Runtime.InteropServices.StructLayout(global::System.Runtime.InteropServices.LayoutKind.Explicit, Size = {{info.ConstantBufferSizeInBytes}})]"""); writer.WriteLine($$"""file struct ConstantBuffer"""); diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateOutputBufferProperties.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateOutputBufferProperties.Syntax.cs index 8a6400c0..ca889f0e 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateOutputBufferProperties.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateOutputBufferProperties.Syntax.cs @@ -1,5 +1,6 @@ using System; using ComputeSharp.D2D1.SourceGenerators.Models; +using ComputeSharp.SourceGeneration.Extensions; using ComputeSharp.SourceGeneration.Helpers; namespace ComputeSharp.D2D1.SourceGenerators; @@ -25,6 +26,8 @@ partial class ID2D1ShaderGenerator false => "default" }; + writer.WriteLine("/// "); + writer.WriteGeneratedAttributes(typeof(ID2D1ShaderGenerator)); writer.WriteLine($"readonly ComputeSharp.D2D1.D2D1BufferPrecision global::ComputeSharp.D2D1.__Internals.ID2D1Shader.BufferPrecision => {bufferPrecisionExpression};"); } @@ -42,6 +45,8 @@ partial class ID2D1ShaderGenerator false => "default" }; + writer.WriteLine("/// "); + writer.WriteGeneratedAttributes(typeof(ID2D1ShaderGenerator)); writer.WriteLine($"readonly ComputeSharp.D2D1.D2D1ChannelDepth global::ComputeSharp.D2D1.__Internals.ID2D1Shader.ChannelDepth => {channelDepthExpression};"); } } diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreatePixelOptionsProperty.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreatePixelOptionsProperty.Syntax.cs index 2c408811..f5207ece 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreatePixelOptionsProperty.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreatePixelOptionsProperty.Syntax.cs @@ -1,4 +1,5 @@ using ComputeSharp.D2D1.SourceGenerators.Models; +using ComputeSharp.SourceGeneration.Extensions; using ComputeSharp.SourceGeneration.Helpers; namespace ComputeSharp.D2D1.SourceGenerators; @@ -23,6 +24,8 @@ partial class ID2D1ShaderGenerator false => "default" }; + writer.WriteLine("/// "); + writer.WriteGeneratedAttributes(typeof(ID2D1ShaderGenerator)); writer.WriteLine($"readonly ComputeSharp.D2D1.D2D1PixelOptions global::ComputeSharp.D2D1.__Internals.ID2D1Shader.PixelOptions => {pixelOptionsExpression};"); } } diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateResourceTextureDescriptionsProperty.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateResourceTextureDescriptionsProperty.Syntax.cs index 4514e9f9..b20e0d0e 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateResourceTextureDescriptionsProperty.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateResourceTextureDescriptionsProperty.Syntax.cs @@ -19,6 +19,8 @@ partial class ID2D1ShaderGenerator /// The instance to write into. public static void WriteSyntax(D2D1ShaderInfo info, IndentedTextWriter writer) { + writer.WriteLine("/// "); + writer.WriteGeneratedAttributes(typeof(ID2D1ShaderGenerator)); writer.Write("readonly global::System.ReadOnlyMemory global::ComputeSharp.D2D1.__Internals.ID2D1Shader.ResourceTextureDescriptions => "); // If there are no resource texture descriptions, just return a default expression. diff --git a/src/ComputeSharp.SourceGeneration/Extensions/IndentedTextWriterExtensions.cs b/src/ComputeSharp.SourceGeneration/Extensions/IndentedTextWriterExtensions.cs index f7b1f2a6..1b27e198 100644 --- a/src/ComputeSharp.SourceGeneration/Extensions/IndentedTextWriterExtensions.cs +++ b/src/ComputeSharp.SourceGeneration/Extensions/IndentedTextWriterExtensions.cs @@ -8,6 +8,23 @@ namespace ComputeSharp.SourceGeneration.Extensions; /// internal static class IndentedTextWriterExtensions { + /// + /// Writes the following attributes into a target writer: + /// + /// [global::System.CodeDom.Compiler.GeneratedCode("...", "...")] + /// [global::System.Diagnostics.DebuggerNonUserCode] + /// [global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] + /// + /// + /// The instance to write into. + /// The type of the running generator. + public static void WriteGeneratedAttributes(this IndentedTextWriter writer, Type generatorType) + { + 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]"""); + } + /// /// Writes a series of members separated by one line between each of them. /// From 3439d3ec05a5232551408df0b552581de5df4fef Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 30 Sep 2023 01:23:23 +0200 Subject: [PATCH 10/13] Add ImmutableHashSetBuilder type --- .../Helpers/ImmutableHashSetBuilder{T}.cs | 102 ++++++++++++++++++ 1 file changed, 102 insertions(+) create mode 100644 src/ComputeSharp.SourceGeneration/Helpers/ImmutableHashSetBuilder{T}.cs diff --git a/src/ComputeSharp.SourceGeneration/Helpers/ImmutableHashSetBuilder{T}.cs b/src/ComputeSharp.SourceGeneration/Helpers/ImmutableHashSetBuilder{T}.cs new file mode 100644 index 00000000..f9faaaca --- /dev/null +++ b/src/ComputeSharp.SourceGeneration/Helpers/ImmutableHashSetBuilder{T}.cs @@ -0,0 +1,102 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using System.Runtime.CompilerServices; + +namespace ComputeSharp.SourceGeneration.Helpers; + +/// +/// A helper type to build hash sets of values with pooled buffers. +/// +/// The type of items to create hash sets for. +internal struct ImmutableHashSetBuilder : IDisposable +{ + /// + /// The shared instance to share objects. + /// + private static readonly ObjectPool> SharedObjectPool = new(static () => new HashSet()); + + /// + /// The rented instance to use. + /// + private HashSet? set; + + /// + /// Creates a value with a pooled underlying data writer. + /// + /// A instance to write data to. + public static ImmutableHashSetBuilder Rent() + { + return new(SharedObjectPool.Allocate()); + } + + /// + /// Creates a new object with the specified parameters. + /// + /// The target instance to use. + private ImmutableHashSetBuilder(HashSet set) + { + this.set = set; + } + + /// + /// Gets the number of elements currently written in the current instance. + /// + public readonly int Count + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => this.set!.Count; + } + + /// + public readonly void Add(T item) + { + _ = this.set!.Add(item); + } + + /// + /// Gets an instance for the current builder. + /// + /// An instance for the current builder. + /// + /// The builder should not be mutated while an enumerator is in use. + /// + public readonly IEnumerable AsEnumerable() + { + return this.set!; + } + + /// + public readonly ImmutableArray ToImmutable() + { + T[] array = this.set!.ToArray(); + + return Unsafe.As>(ref array); + } + + /// + public readonly T[] ToArray() + { + return this.set!.ToArray(); + } + + /// + public void Dispose() + { + HashSet? writer = this.set; + + this.set = null; + + if (writer is not null) + { + writer.Clear(); + + SharedObjectPool.Free(writer); + } + } +} \ No newline at end of file From 4917d67d7db36a05b84090cafb272ff2607b23cd Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 30 Sep 2023 01:24:14 +0200 Subject: [PATCH 11/13] Move all generated types into private namespace --- ...InitializeFromDispatchDataMethod.Syntax.cs | 2 +- ....CreateInputDescriptionsProperty.Syntax.cs | 39 ++++++++++++++++--- ...nerator.CreateInputTypesProperty.Syntax.cs | 39 ++++++++++++------- ...nerator.CreateLoadBytecodeMethod.Syntax.cs | 36 +++++++++++------ ...tor.CreateLoadDispatchDataMethod.Syntax.cs | 24 ++++++++---- ...ourceTextureDescriptionsProperty.Syntax.cs | 23 +++++++++-- .../ID2D1ShaderGenerator.cs | 36 ++++++++++++++--- .../ComputeSharp.SourceGeneration.projitems | 1 + .../IndentedTextWriterExtensions.cs | 31 +++++++++++++-- .../Models/HierarchyInfo.cs | 14 +++++-- 10 files changed, 189 insertions(+), 56 deletions(-) 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("}"); + } } /// From 1be2ae1fc998a0d709c33f8219ee0975bfaa520c Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 30 Sep 2023 01:25:38 +0200 Subject: [PATCH 12/13] Remove unused methods --- .../ID2D1ShaderGenerator.Helpers.cs | 95 ------------------- 1 file changed, 95 deletions(-) diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.Helpers.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.Helpers.cs index 78ced89a..ff29a0e6 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.Helpers.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.Helpers.cs @@ -1,10 +1,4 @@ -using System.Collections.Generic; -using System.Linq; -using ComputeSharp.SourceGeneration.Models; using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Syntax; -using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; namespace ComputeSharp.D2D1.SourceGenerators; @@ -34,93 +28,4 @@ partial class ID2D1ShaderGenerator return false; } - - /// - /// Creates a instance wrapping the given method. - /// - /// The instance for the current type. - /// The items to insert. - /// Additional member declarations to also emit, if any. - /// A object wrapping . - private static CompilationUnitSyntax GetCompilationUnitFromMembers( - HierarchyInfo hierarchyInfo, - (MemberDeclarationSyntax Member, bool SkipLocalsInit)[] memberDeclarations, - params MemberDeclarationSyntax[] additionalMemberDeclarations) - { - // Method attributes - AttributeListSyntax[] attributes = - { - AttributeList(SingletonSeparatedList( - Attribute(IdentifierName("global::System.CodeDom.Compiler.GeneratedCode")).AddArgumentListArguments( - AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(ID2D1ShaderGenerator).FullName))), - AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(ID2D1ShaderGenerator).Assembly.GetName().Version.ToString())))))), - AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Diagnostics.DebuggerNonUserCode")))), - AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage")))), - AttributeList(SingletonSeparatedList( - Attribute(IdentifierName("global::System.ComponentModel.EditorBrowsable")).AddArgumentListArguments( - AttributeArgument(ParseExpression("global::System.ComponentModel.EditorBrowsableState.Never"))))), - AttributeList(SingletonSeparatedList( - Attribute(IdentifierName("global::System.Obsolete")).AddArgumentListArguments( - AttributeArgument(LiteralExpression( - SyntaxKind.StringLiteralExpression, - Literal("This method is not intended to be used directly by user code")))))) - }; - - MemberDeclarationSyntax[] membersToAdd = memberDeclarations.Select(item => - { - MemberDeclarationSyntax memberToAdd = item.Member.AddAttributeLists(attributes); - - // Add [SkipLocalsInit] if needed - if (item.SkipLocalsInit) - { - memberToAdd = memberToAdd.AddAttributeLists(AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Runtime.CompilerServices.SkipLocalsInit"))))); - } - - return memberToAdd; - }).ToArray(); - - return hierarchyInfo.GetSyntax(membersToAdd, additionalMemberDeclarations); - } - - /// - /// Creates a instance wrapping the given method. - /// - /// The instance for the current type. - /// The item to insert. - /// Whether [SkipLocalsInit] should also be generated. - /// Additional member declarations to also emit, if any. - /// A object wrapping . - private static CompilationUnitSyntax GetCompilationUnitFromMember( - HierarchyInfo hierarchyInfo, - MemberDeclarationSyntax memberDeclaration, - bool skipLocalsInit, - params MemberDeclarationSyntax[] additionalMemberDeclarations) - { - // Method attributes - List attributes = new() - { - AttributeList(SingletonSeparatedList( - Attribute(IdentifierName("global::System.CodeDom.Compiler.GeneratedCode")).AddArgumentListArguments( - AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(ID2D1ShaderGenerator).FullName))), - AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(ID2D1ShaderGenerator).Assembly.GetName().Version.ToString())))))), - AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Diagnostics.DebuggerNonUserCode")))), - AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage")))), - AttributeList(SingletonSeparatedList( - Attribute(IdentifierName("global::System.ComponentModel.EditorBrowsable")).AddArgumentListArguments( - AttributeArgument(ParseExpression("global::System.ComponentModel.EditorBrowsableState.Never"))))), - AttributeList(SingletonSeparatedList( - Attribute(IdentifierName("global::System.Obsolete")).AddArgumentListArguments( - AttributeArgument(LiteralExpression( - SyntaxKind.StringLiteralExpression, - Literal("This method is not intended to be used directly by user code")))))) - }; - - // Add [SkipLocalsInit] if needed - if (skipLocalsInit) - { - attributes.Add(AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Runtime.CompilerServices.SkipLocalsInit"))))); - } - - return hierarchyInfo.GetSyntax(new MemberDeclarationSyntax[] { memberDeclaration.AddAttributeLists(attributes.ToArray()) }, additionalMemberDeclarations); - } } \ No newline at end of file From fe385da3a04a5d6d1cf617fdecfb36ae0661b6ce Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 30 Sep 2023 03:10:02 +0200 Subject: [PATCH 13/13] Fix two issues with generated dispatching logic --- ...rGenerator.CreateInitializeFromDispatchDataMethod.Syntax.cs | 2 +- ...ID2D1ShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs | 3 +++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInitializeFromDispatchDataMethod.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInitializeFromDispatchDataMethod.Syntax.cs index 8c207652..e51cbcd2 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInitializeFromDispatchDataMethod.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInitializeFromDispatchDataMethod.Syntax.cs @@ -64,7 +64,7 @@ partial class ID2D1ShaderGenerator // global::System.Runtime.CompilerServices.Unsafe.AsRef(in this.)[N] = buffer.; for (int j = 0; j < matrix.Rows; j++) { - writer.WriteLine($"global::System.Runtime.CompilerServices.Unsafe.AsRef(in this.{fieldPath})[0] = buffer.{fieldNamePrefix}_{j};"); + writer.WriteLine($"global::System.Runtime.CompilerServices.Unsafe.AsRef(in this.{fieldPath})[{j}] = buffer.{fieldNamePrefix}_{j};"); } break; diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs index bb9dea1b..7ec8edb3 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs @@ -62,6 +62,9 @@ partial class ID2D1ShaderGenerator break; } } + + writer.WriteLine(); + writer.WriteLine("loader.LoadConstantBuffer(new global::System.ReadOnlySpan(&buffer, sizeof(global::ComputeSharp.D2D1.Generated.ConstantBuffer)));"); } } }