Generate EffectId from derived type identifiers

このコミットが含まれているのは:
Sergio Pedri committed 2023-09-27 14:04:04 +02:00
1 親 c31572f68f
コミット 3303c0f2f3
6ファイル変更
+163 -17

検索条件に一致するファイルはありません

@@ -1,8 +1,8 @@
using System;
using System.Text;
using ComputeSharp.D2D1.__Internals;
using ComputeSharp.D2D1.SourceGenerators.Models;
using ComputeSharp.SourceGeneration.Helpers;
using ComputeSharp.SourceGeneration.Models;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
@@ -22,10 +22,10 @@ partial class ID2D1ShaderGenerator
/// <summary>
/// Creates a <see cref="PropertyDeclarationSyntax"/> instance for the <c>EffectId</c> property.
/// </summary>
/// <param name="info">The input <see cref="HierarchyInfo"/> instance.</param>
/// <param name="info">The input <see cref="EffectIdInfo"/> instance.</param>
/// <param name="fixup">An opaque <see cref="Func{TResult}"/> instance to transform the final tree into text.</param>
/// <returns>The resulting <see cref="PropertyDeclarationSyntax"/> instance for the <c>EffectId</c> property.</returns>
public static PropertyDeclarationSyntax GetSyntax(HierarchyInfo info, out Func<SyntaxNode, SourceText> fixup)
public static PropertyDeclarationSyntax GetSyntax(EffectIdInfo info, out Func<SyntaxNode, SourceText> fixup)
{
// Create the local declaration:
//
@@ -48,7 +48,7 @@ partial class ID2D1ShaderGenerator
SingletonSeparatedList<ExpressionSyntax>(IdentifierName("__EMBEDDED_EFFECT_ID_BYTES"))))))));
// Prepare the initialization text
string effectIdLiterals = SyntaxFormattingHelper.BuildByteArrayInitializationExpressionString(new byte[] { 1, 2, 3, 4 }.AsSpan());
string effectIdLiterals = SyntaxFormattingHelper.BuildByteArrayInitializationExpressionString(info.Bytes.AsSpan());
// Set the fixup function
fixup = tree => SourceText.From(tree.ToFullString().Replace("__EMBEDDED_EFFECT_ID_BYTES", effectIdLiterals), Encoding.UTF8);
@@ -0,0 +1,77 @@
using System;
using System.Collections.Immutable;
using System.Runtime.CompilerServices;
using System.Security.Cryptography;
using System.Text;
using ComputeSharp.SourceGeneration.Extensions;
using ComputeSharp.SourceGeneration.Helpers;
using ComputeSharp.SourceGeneration.Models;
using Microsoft.CodeAnalysis;
namespace ComputeSharp.D2D1.SourceGenerators;
/// <inheritdoc/>
partial class ID2D1ShaderGenerator
{
/// <summary>
/// A helper with all logic to generate the <c>EffectId</c> property.
/// </summary>
private static partial class EffectId
{
/// <summary>
/// The <see cref="IncrementalHash"/> instance currently in use for the running thread, if any.
/// </summary>
[ThreadStatic]
private static IncrementalHash? incrementalHash;
/// <summary>
/// Extracts the effect id info for the current shader.
/// </summary>
/// <param name="diagnostics">The collection of produced <see cref="DiagnosticInfo"/> instances.</param>
/// <param name="structDeclarationSymbol">The <see cref="INamedTypeSymbol"/> for the shader type in use.</param>
/// <returns>The resulting effect id.</returns>
public static ImmutableArray<byte> GetInfo(ImmutableArrayBuilder<DiagnosticInfo> diagnostics, INamedTypeSymbol structDeclarationSymbol)
{
// Initialize an instance using the MD5 algorithm. We use this for several reasons:
// - We don't really need security, this is just to uniquely identify types
// - The hash size is 128 bits, which is exactly the size of a GUID.
IncrementalHash incrementalHash = EffectId.incrementalHash ??= IncrementalHash.CreateHash(HashAlgorithmName.MD5);
string assemblyName = structDeclarationSymbol.ContainingAssembly?.Name ?? string.Empty;
using ImmutableArrayBuilder<byte> byteBuffer = ImmutableArrayBuilder<byte>.Rent();
using ImmutableArrayBuilder<char> charBuffer = ImmutableArrayBuilder<char>.Rent();
// Format the fully qualified name into a pooled builder to avoid the string allocation
structDeclarationSymbol.AppendFullyQualifiedMetadataName(in charBuffer);
int maxTypeNameCharsLength = Encoding.UTF8.GetMaxByteCount(charBuffer.Count);
int maxAssemblyNameCharsLength = Encoding.UTF8.GetMaxByteCount(assemblyName.Length);
int maxEncodedCharsLength = Math.Max(maxTypeNameCharsLength, maxAssemblyNameCharsLength);
byteBuffer.EnsureCapacity(maxEncodedCharsLength);
// UTF8 encode the fully qualified name first
int typeNameCharsLength = Encoding.UTF8.GetBytes(charBuffer.WrittenSpan, byteBuffer.DangerousGetArray().AsSpan());
byteBuffer.Advance(typeNameCharsLength);
// Append the UTF8 fully qualified name to the MD5 hash
incrementalHash.AppendData(byteBuffer.DangerousGetArray(), 0, byteBuffer.Count);
// UTF8 encode the assembly name as well
int assemblyNameCharsLength = Encoding.UTF8.GetBytes(assemblyName.AsSpan(), byteBuffer.DangerousGetArray().AsSpan());
byteBuffer.Advance(assemblyNameCharsLength);
// Append the UTF8 assembly name to the MD5 hash
incrementalHash.AppendData(byteBuffer.DangerousGetArray(), 0, byteBuffer.Count);
// Get the resulting MD5 hash (128 bits)
byte[] hash = incrementalHash.GetHashAndReset();
// We own this buffer, so we can just reinterpret to an immutable array
return Unsafe.As<byte[], ImmutableArray<byte>>(ref hash);
}
}
}
+17 -8
ファイルの表示
@@ -52,6 +52,11 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator
using ImmutableArrayBuilder<DiagnosticInfo> diagnostics = ImmutableArrayBuilder<DiagnosticInfo>.Rent();
// EffectId info
ImmutableArray<byte> effectId = EffectId.GetInfo(diagnostics, typeSymbol);
token.ThrowIfCancellationRequested();
// LoadDispatchData() info
ImmutableArray<FieldInfo> fieldInfos = LoadDispatchData.GetInfo(
diagnostics,
@@ -115,6 +120,7 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator
return new D2D1ShaderInfo(
Hierarchy: HierarchyInfo.From(typeSymbol),
EffectId: new EffectIdInfo(effectId),
DispatchData: new DispatchDataInfo(fieldInfos, constantBufferSizeInBytes),
InputTypes: new InputTypesInfo(inputTypes),
ResourceTextureDescriptions: new ResourceTextureDescriptionsInfo(resourceTextureDescriptions),
@@ -136,10 +142,8 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator
shaderInfoWithErrors
.Select(static (item, _) => item.Diagnostcs));
// Get the EffectDisplayName and EffectId info (hierarchy)
IncrementalValuesProvider<HierarchyInfo> hierarchyInfo =
shaderInfoWithErrors
.Select(static (item, _) => item.Hierarchy);
// Get the EffectDisplayName info (hierarchy)
IncrementalValuesProvider<HierarchyInfo> hierarchyInfo = shaderInfoWithErrors.Select(static (item, _) => item.Hierarchy);
// Generate the EffectDisplayName properties
context.RegisterSourceOutput(hierarchyInfo, static (context, item) =>
@@ -150,14 +154,19 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator
context.AddSource($"{item.FullyQualifiedMetadataName}.{nameof(EffectDisplayName)}.g.cs", compilationUnit.GetText(Encoding.UTF8));
});
// Get the EffectId info (hierarchy and effect id info)
IncrementalValuesProvider<(HierarchyInfo Hierarchy, EffectIdInfo EffectId)> effectIdInfo =
shaderInfoWithErrors
.Select(static (item, _) => (item.Hierarchy, item.EffectId));
// Generate the EffectId properties
context.RegisterSourceOutput(hierarchyInfo, static (context, item) =>
context.RegisterSourceOutput(effectIdInfo, static (context, item) =>
{
PropertyDeclarationSyntax effectDisplayNameProperty = EffectId.GetSyntax(item, out Func<SyntaxNode, SourceText> fixup);
CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMember(item, effectDisplayNameProperty, canUseSkipLocalsInit: false);
PropertyDeclarationSyntax effectDisplayNameProperty = EffectId.GetSyntax(item.EffectId, out Func<SyntaxNode, SourceText> fixup);
CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMember(item.Hierarchy, effectDisplayNameProperty, canUseSkipLocalsInit: false);
SourceText text = fixup(compilationUnit);
context.AddSource($"{item.FullyQualifiedMetadataName}.{nameof(EffectId)}.g.cs", text);
context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.{nameof(EffectId)}.g.cs", text);
});
// Get the GetInputCount() info (hierarchy and input count)
+2
ファイルの表示
@@ -7,6 +7,7 @@ namespace ComputeSharp.D2D1.SourceGenerators.Models;
/// A model representing all necessary info for a full generation pass for a D2D1 shader.
/// </summary>
/// <param name="Hierarchy">The hierarchy info for the shader type.</param>
/// <param name="EffectId">The effect id info for the shader type.</param>
/// <param name="DispatchData">The gathered shader dispatch data.</param>
/// <param name="InputTypes">The gathered input types for the shader.</param>
/// <param name="ResourceTextureDescriptions">The gathered resource texture descriptions for the shader.</param>
@@ -17,6 +18,7 @@ namespace ComputeSharp.D2D1.SourceGenerators.Models;
/// <param name="Diagnostcs">The discovered diagnostics, if any.</param>
internal sealed record D2D1ShaderInfo(
HierarchyInfo Hierarchy,
EffectIdInfo EffectId,
DispatchDataInfo DispatchData,
InputTypesInfo InputTypes,
ResourceTextureDescriptionsInfo ResourceTextureDescriptions,
+9
ファイルの表示
@@ -0,0 +1,9 @@
using ComputeSharp.SourceGeneration.Helpers;
namespace ComputeSharp.D2D1.SourceGenerators.Models;
/// <summary>
/// A model representing info to use to generate an effect id for a shader.
/// </summary>
/// <param name="Bytes">The bytes for the processed effect id.</param>
internal sealed record EffectIdInfo(EquatableArray<byte> Bytes);
+54 -5
ファイルの表示
@@ -75,6 +75,33 @@ internal struct ImmutableArrayBuilder<T> : IDisposable
this.writer!.AddRange(items);
}
/// <summary>
/// Advances the current writer by the specified amount.
/// </summary>
/// <param name="count">The amoutn to advance by.</param>
public readonly void Advance(int count)
{
this.writer!.Advance(count);
}
/// <summary>
/// Gets the array currently in use (rented from the pool).
/// </summary>
/// <returns>The array currently in use.</returns>
public readonly T[] DangerousGetArray()
{
return this.writer!.DangerousGetArray();
}
/// <summary>
/// Ensures that the current instance has enough free space to contain a given number of new items.
/// </summary>
/// <param name="requestedSize">The minimum number of items to ensure space for.</param>
public readonly void EnsureCapacity(int requestedSize)
{
this.writer!.EnsureCapacity(requestedSize);
}
/// <summary>
/// Inserts an item to the builder at the specified index.
/// </summary>
@@ -177,6 +204,23 @@ internal struct ImmutableArrayBuilder<T> : IDisposable
this.index += items.Length;
}
/// <inheritdoc cref="ImmutableArrayBuilder{T}.Advance"/>
public void Advance(int count)
{
if (count > this.array.Length - this.index)
{
ImmutableArrayBuilder.ThrowArgumentOutOfRangeExceptionForCount();
}
this.index += count;
}
/// <inheritdoc cref="ImmutableArrayBuilder{T}.DangerousGetArray"/>
public T[] DangerousGetArray()
{
return this.array;
}
/// <inheritdoc cref="ImmutableArrayBuilder{T}.Insert"/>
public void Insert(int index, T item)
{
@@ -209,12 +253,9 @@ internal struct ImmutableArrayBuilder<T> : IDisposable
this.index = 0;
}
/// <summary>
/// Ensures that <see cref="array"/> has enough free space to contain a given number of new items.
/// </summary>
/// <param name="requestedSize">The minimum number of items to ensure space for in <see cref="array"/>.</param>
/// <inheritdoc cref="ImmutableArrayBuilder{T}.EnsureCapacity"/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void EnsureCapacity(int requestedSize)
public void EnsureCapacity(int requestedSize)
{
if (requestedSize > this.array.Length - this.index)
{
@@ -253,4 +294,12 @@ file static class ImmutableArrayBuilder
{
throw new ArgumentOutOfRangeException("index");
}
/// <summary>
/// Throws an <see cref="ArgumentOutOfRangeException"/> for <c>"count"</c>.
/// </summary>
public static void ThrowArgumentOutOfRangeExceptionForCount()
{
throw new ArgumentOutOfRangeException("count");
}
}