Merge pull request #673 from Sergio0694/dev/remove-auto-constructor

Remove [AutoConstructor] attribute and generator
このコミットが含まれているのは:
Sergio Pedri authored and GitHub committed 2023-11-24 02:47:17 +01:00
コミット f6f5a426ed
31ファイル変更
+63 -527

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

-1
ファイルの表示
@@ -512,7 +512,6 @@ Global
src\ComputeSharp.CodeFixing\ComputeSharp.CodeFixing.projitems*{9b4448b1-200f-4966-8a13-a508691b3003}*SharedItemsImports = 5
src\ComputeSharp.Win32.D2D1\ComputeSharp.Win32.D2D1.projitems*{9da1da9f-f8b2-4b25-be80-c21f773029e3}*SharedItemsImports = 13
samples\ComputeSharp.SwapChain.Shaders.D2D1.Shared\ComputeSharp.SwapChain.Shaders.D2D1.Shared.projitems*{9ea5ae9d-c39a-4f43-b03e-0a848ea2558a}*SharedItemsImports = 5
src\ComputeSharp.SourceGeneration\ComputeSharp.SourceGeneration.projitems*{bfb003d1-788b-48de-8065-39479c162cb0}*SharedItemsImports = 5
samples\ComputeSharp.SwapChain.Shaders.Shared\ComputeSharp.SwapChain.Shaders.Shared.projitems*{c12d7ace-98ed-4813-8118-6667c34f484f}*SharedItemsImports = 5
src\ComputeSharp.SourceGeneration.Hlsl\ComputeSharp.SourceGeneration.Hlsl.projitems*{e44053bd-a761-47fb-aa78-087a599672ea}*SharedItemsImports = 5
src\ComputeSharp.SourceGeneration\ComputeSharp.SourceGeneration.projitems*{e44053bd-a761-47fb-aa78-087a599672ea}*SharedItemsImports = 5
+4 -3
ファイルの表示
@@ -4,8 +4,6 @@
using System.Numerics;
using System.Runtime.CompilerServices;
#pragma warning disable IDE0022
namespace SixLabors.ImageSharp;
/// <summary>
@@ -30,5 +28,8 @@ internal struct ComplexVector4
/// <param name="b">The 'b' parameter, for the imaginary component</param>
/// <returns>The resulting <see cref="Vector4"/> value</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly Vector4 WeightedSum(float a, float b) => (this.Real * a) + (this.Imaginary * b);
public readonly Vector4 WeightedSum(float a, float b)
{
return (this.Real * a) + (this.Imaginary * b);
}
}
-149
ファイルの表示
@@ -1,149 +0,0 @@
using System.Linq;
using System.Text;
using ComputeSharp.Core.SourceGenerators.Models;
using ComputeSharp.SourceGeneration.Extensions;
using ComputeSharp.SourceGeneration.Helpers;
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, IDE0300
namespace ComputeSharp.Core.SourceGenerators;
/// <summary>
/// A source generator creating constructors for types annotated with <see cref="AutoConstructorAttribute"/>.
/// </summary>
[Generator(LanguageNames.CSharp)]
public sealed class AutoConstructorGenerator : IIncrementalGenerator
{
/// <inheritdoc/>
public void Initialize(IncrementalGeneratorInitializationContext context)
{
// Get all declared struct symbols with the [AutoConstructor] attribute and
// extract the type hierarchy and fields info for each of the annotated types
IncrementalValuesProvider<(HierarchyInfo Left, ConstructorInfo Right)> constructorInfo =
context.SyntaxProvider
.ForAttributeWithMetadataName(
typeof(AutoConstructorAttribute).FullName,
static (node, _) => node is StructDeclarationSyntax structDeclaration,
static (context, _) =>
{
INamedTypeSymbol typeSymbol = (INamedTypeSymbol)context.TargetSymbol;
ConstructorInfo constructorInfo = Ctor.GetData(typeSymbol);
// If the type has no parameters, just do nothing
if (constructorInfo.Parameters.IsEmpty)
{
return default;
}
HierarchyInfo hierarchyInfo = HierarchyInfo.From(typeSymbol);
return (Hierarchy: hierarchyInfo, constructorInfo);
})
.Where(static item => item.Hierarchy is not null);
// Generate the constructors
context.RegisterSourceOutput(constructorInfo, static (context, item) =>
{
CompilationUnitSyntax compilationUnit = Ctor.GetSyntax(item.Left, item.Right);
context.AddSource($"{item.Left.FullyQualifiedMetadataName}.Ctor.g.cs", compilationUnit.GetText(Encoding.UTF8));
});
}
/// <summary>
/// A helper with all logic to generate the constructor declarations.
/// </summary>
private static class Ctor
{
/// <summary>
/// Gets the sequence of <see cref="ParameterInfo"/> items for all fields in the input type.
/// </summary>
/// <param name="structDeclarationSymbol">The <see cref="INamedTypeSymbol"/> being inspected.</param>
/// <returns>The <see cref="ConstructorInfo"/> instance for <paramref name="structDeclarationSymbol"/>.</returns>
public static ConstructorInfo GetData(INamedTypeSymbol structDeclarationSymbol)
{
using ImmutableArrayBuilder<ParameterInfo> parameters = new();
using ImmutableArrayBuilder<string> defaulted = new();
foreach (IFieldSymbol fieldSymbol in structDeclarationSymbol.GetMembers().OfType<IFieldSymbol>())
{
// Skip fields that are not instance ones (and also ignore generated fields and fixed size buffers)
if (fieldSymbol is not { IsConst: false, IsStatic: false, IsFixedSizeBuffer: false, IsImplicitlyDeclared: false })
{
continue;
}
// Check whether the field is annotated to have a special behavior
if (fieldSymbol.Type.TryGetAttributeWithFullyQualifiedMetadataName("ComputeSharp.AutoConstructorBehaviorAttribute", out AttributeData? usageData) &&
usageData.ConstructorArguments is [{ Value: (int)AutoConstructorBehavior.IgnoreAndSetToDefault }])
{
defaulted.Add(fieldSymbol.Name);
}
else
{
// Track the field normally
string typeName = fieldSymbol.Type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat);
parameters.Add(new ParameterInfo(typeName, fieldSymbol.Name));
}
}
return new(parameters.ToImmutable(), defaulted.ToImmutable());
}
/// <summary>
/// Gets the <see cref="CompilationUnitSyntax"/> instance for a given type and sequence of parameters.
/// </summary>
/// <param name="hierarchyInfo">The type hierarchy info.</param>
/// <param name="constructorInfo">The <see cref="ConstructorInfo"/> instance with the info for the constructor to generate.</param>
/// <returns>A <see cref="CompilationUnitSyntax"/> instance for a specified type.</returns>
public static CompilationUnitSyntax GetSyntax(HierarchyInfo hierarchyInfo, ConstructorInfo constructorInfo)
{
// Create the constructor declaration for the type. This will
// produce a constructor with simple initialization of all variables:
//
// public MyType(Foo a, Bar b, Baz c, ...)
// {
// this.a = a;
// this.b = b;
// this.c = c;
// ...
// this.ignored1 = default;
// this.ignored2 = default;
// this.ignored3 = default;
// ...
// }
ConstructorDeclarationSyntax constructorDeclaration =
ConstructorDeclaration(hierarchyInfo.Hierarchy[0].QualifiedName)
.AddModifiers(Token(SyntaxKind.PublicKeyword))
.AddParameterListParameters(constructorInfo.Parameters.Select(field => Parameter(Identifier(field.Name)).WithType(IdentifierName(field.Type))).ToArray())
.AddBodyStatements(constructorInfo.Parameters.Select(field => ParseStatement($"this.{field.Name} = {field.Name};")).ToArray())
.AddBodyStatements(constructorInfo.DefaultedFields.Select(field => ParseStatement($"this.{field} = default;")).ToArray());
// Add the unsafe modifier, if needed
if (constructorInfo.Parameters.Any(static param => param.Type.Contains("*")))
{
constructorDeclaration = constructorDeclaration.AddModifiers(Token(SyntaxKind.UnsafeKeyword));
}
// Constructor attributes
AttributeListSyntax[] attributes =
{
AttributeList(SingletonSeparatedList(
Attribute(IdentifierName("global::System.CodeDom.Compiler.GeneratedCode")).AddArgumentListArguments(
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(AutoConstructorGenerator).FullName))),
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(AutoConstructorGenerator).Assembly.GetName().Version.ToString())))))),
AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Diagnostics.DebuggerNonUserCode")))),
AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage"))))
};
return hierarchyInfo.GetSyntax(constructorDeclaration.AddAttributeLists(attributes));
}
}
}
-12
ファイルの表示
@@ -2,15 +2,6 @@
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
</PropertyGroup>
<!--The source generator cannot contain package references or project references, so instead we're just
manually linking the source files from ComputeSharp\Core in here. We only need them to extract metadata
and to match members based on full name, so the types being in the generator assembly are not an issue.-->
<ItemGroup>
<Compile Include="..\ComputeSharp.Core\Attributes\AutoConstructorAttribute.cs" Link="ComputeSharp.Core\Attributes\AutoConstructorAttribute.cs" />
<Compile Include="..\ComputeSharp.Core\Attributes\Internals\AutoConstructorBehaviorAttribute.cs" Link="ComputeSharp.Core\Attributes\Internals\AutoConstructorBehaviorAttribute.cs" />
<Compile Include="..\ComputeSharp.Core\Attributes\Internals\AutoConstructorBehavior.cs" Link="ComputeSharp.Core\Attributes\Internals\AutoConstructorBehavior.cs" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.8.0" PrivateAssets="all" Pack="false" />
@@ -20,7 +11,4 @@
<AdditionalFiles Include="AnalyzerReleases.Shipped.md" />
<AdditionalFiles Include="AnalyzerReleases.Unshipped.md" />
</ItemGroup>
<!-- Shared project with common helpers -->
<Import Project="..\ComputeSharp.SourceGeneration\ComputeSharp.SourceGeneration.projitems" Label="Shared" />
</Project>
-10
ファイルの表示
@@ -1,10 +0,0 @@
using ComputeSharp.SourceGeneration.Helpers;
namespace ComputeSharp.Core.SourceGenerators.Models;
/// <summary>
/// A model containiing information on a constructor to generate.
/// </summary>
/// <param name="Parameters">The <see cref="ParameterInfo"/> values for the constructor.</param>
/// <param name="DefaultedFields">The names of ignored fields that should be defaulted.</param>
internal sealed record ConstructorInfo(EquatableArray<ParameterInfo> Parameters, EquatableArray<string> DefaultedFields);
-8
ファイルの表示
@@ -1,8 +0,0 @@
namespace ComputeSharp.Core.SourceGenerators.Models;
/// <summary>
/// A model describing info on a constructor parameter.
/// </summary>
/// <param name="Type">The fully qualified type name.</param>
/// <param name="Name">The parameter name.</param>
internal sealed record ParameterInfo(string Type, string Name);
-17
ファイルの表示
@@ -1,17 +0,0 @@
using System;
using System.ComponentModel;
namespace ComputeSharp;
/// <summary>
/// An attribute that indicates that a target shader type should get an automatic constructor for all fields.
/// </summary>
[AttributeUsage(AttributeTargets.Struct, AllowMultiple = false)]
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete(
"This API (and its accompanying source generator) is being removed in a future version of ComputeSharp. " +
"If you're relying on this functionality, consider switching to primary constructors, once they are supported. " +
"Otherwise, consider using alternative source generators providing similar functionality available on NuGet.")]
public sealed class AutoConstructorAttribute : Attribute
{
}
-12
ファイルの表示
@@ -1,12 +0,0 @@
namespace ComputeSharp;
/// <summary>
/// Indicates the behavior of fields annotated with <see cref="AutoConstructorBehaviorAttribute"/>.
/// </summary>
internal enum AutoConstructorBehavior
{
/// <summary>
/// Causes <see cref="AutoConstructorAttribute"/> to ignore fields and set their values to <see langword="default"/>.
/// </summary>
IgnoreAndSetToDefault
}
-26
ファイルの表示
@@ -1,26 +0,0 @@
using System;
#pragma warning disable IDE0290
namespace ComputeSharp;
/// <summary>
/// An attribute that indicates that a target shader type should get an automatic constructor for all fields.
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = false)]
internal sealed class AutoConstructorBehaviorAttribute : Attribute
{
/// <summary>
/// Creates a new <see cref="AutoConstructorBehaviorAttribute"/> instance with the specified parameters.
/// </summary>
/// <param name="behavior">The <see cref="AutoConstructorBehavior"/> value for the current instance.</param>
public AutoConstructorBehaviorAttribute(AutoConstructorBehavior behavior)
{
Behavior = behavior;
}
/// <summary>
/// Gets the <see cref="AutoConstructorBehavior"/> value for the current instance.
/// </summary>
public AutoConstructorBehavior Behavior { get; }
}
-1
ファイルの表示
@@ -7,7 +7,6 @@ namespace ComputeSharp.D2D1;
/// This can be used from D2D1 pixel shaders to be able to pass arbitrary inputs to them.
/// </summary>
/// <typeparam name="T">The type of items stored on the texture (only <see langword="float"/> and <see cref="Float4"/> are supported).</typeparam>
[AutoConstructorBehavior(AutoConstructorBehavior.IgnoreAndSetToDefault)]
public readonly struct D2D1ResourceTexture1D<T>
where T : unmanaged
{
-1
ファイルの表示
@@ -7,7 +7,6 @@ namespace ComputeSharp.D2D1;
/// This can be used from D2D1 pixel shaders to be able to pass arbitrary inputs to them.
/// </summary>
/// <typeparam name="T">The type of items stored on the texture (only <see langword="float"/> and <see cref="Float4"/> are supported).</typeparam>
[AutoConstructorBehavior(AutoConstructorBehavior.IgnoreAndSetToDefault)]
public readonly struct D2D1ResourceTexture2D<T>
where T : unmanaged
{
-1
ファイルの表示
@@ -7,7 +7,6 @@ namespace ComputeSharp.D2D1;
/// This can be used from D2D1 pixel shaders to be able to pass arbitrary inputs to them.
/// </summary>
/// <typeparam name="T">The type of items stored on the texture (only <see langword="float"/> and <see cref="Float4"/> are supported).</typeparam>
[AutoConstructorBehavior(AutoConstructorBehavior.IgnoreAndSetToDefault)]
public readonly struct D2D1ResourceTexture3D<T>
where T : unmanaged
{
+1
ファイルの表示
@@ -8,6 +8,7 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="AutoConstructor" Version="5.1.0" PrivateAssets="all" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.8.0" />
<PackageReference Include="MSTest.TestAdapter" Version="3.1.1" />
<PackageReference Include="MSTest.TestFramework" Version="3.1.1" />
+2 -9
ファイルの表示
@@ -2,7 +2,6 @@ using System;
using System.Buffers;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using ComputeSharp;
using ComputeSharp.D2D1;
using ComputeSharp.D2D1.Interop;
using ComputeSharp.D2D1.Tests.Effects;
@@ -323,7 +322,6 @@ namespace ComputeSharp.D2D1.Tests
[D2DInputComplex(3)]
[D2DShaderProfile(D2D1ShaderProfile.PixelShader50)]
[D2DGeneratedPixelShaderDescriptor]
[AutoConstructor]
internal partial struct ShaderWithoutResourceTextures : ID2D1PixelShader
{
public Float4 Execute()
@@ -335,7 +333,6 @@ namespace ComputeSharp.D2D1.Tests
[D2DInputCount(0)]
[D2DShaderProfile(D2D1ShaderProfile.PixelShader50)]
[D2DGeneratedPixelShaderDescriptor]
[AutoConstructor]
internal readonly partial struct ShaderWithJustOneResourceTextures : ID2D1PixelShader
{
[D2DResourceTextureIndex(0)]
@@ -354,11 +351,8 @@ namespace ComputeSharp.D2D1.Tests
[D2DInputComplex(3)]
[D2DShaderProfile(D2D1ShaderProfile.PixelShader50)]
[D2DGeneratedPixelShaderDescriptor]
[AutoConstructor]
internal readonly partial struct ShaderWithResourceTextures : ID2D1PixelShader
internal readonly partial struct ShaderWithResourceTextures(float number) : ID2D1PixelShader
{
readonly float number;
[D2DResourceTextureIndex(4)]
readonly D2D1ResourceTexture1D<float4> myTexture1;
@@ -381,7 +375,7 @@ namespace ComputeSharp.D2D1.Tests
float4 pixel6 = this.myTexture3.Sample(0.4f, 0.5f, 0.6f);
float number1 = this.myTexture4[0, 2];
float number2 = this.myTexture4.Sample(0.4f, 0.6f);
float number3 = this.number;
float number3 = number;
return 0;
}
@@ -1128,7 +1122,6 @@ namespace ComputeSharp.D2D1.Tests
{
[D2DInputCount(0)]
[D2DGeneratedPixelShaderDescriptor]
[AutoConstructor]
public readonly partial struct DeeplyNestedShader : ID2D1PixelShader
{
public float4 Execute()
+6 -12
ファイルの表示
@@ -535,11 +535,8 @@ public partial class D2D1ResourceTextureManagerTests
[D2DInputCount(0)]
[D2DRequiresScenePosition]
[D2DGeneratedPixelShaderDescriptor]
[AutoConstructor]
internal readonly partial struct IndexFrom3DResourceTextureShader : ID2D1PixelShader
internal readonly partial struct IndexFrom3DResourceTextureShader(float height) : ID2D1PixelShader
{
private readonly int height;
[D2DResourceTextureIndex(0)]
private readonly D2D1ResourceTexture3D<float4> source;
@@ -548,8 +545,8 @@ public partial class D2D1ResourceTextureManagerTests
int2 xy = (int2)D2D.GetScenePosition().XY;
int x = xy.X;
int y = (int)((uint)xy.Y % (uint)this.height);
int z = (int)((uint)xy.Y / (uint)this.height);
int y = (int)((uint)xy.Y % (uint)height);
int z = (int)((uint)xy.Y / (uint)height);
return this.source[x, y, z];
}
@@ -895,11 +892,8 @@ public partial class D2D1ResourceTextureManagerTests
[D2DInputCount(0)]
[D2DRequiresScenePosition]
[D2DGeneratedPixelShaderDescriptor]
[AutoConstructor]
internal readonly partial struct CopyFromResourceTexture3DShader : ID2D1PixelShader
internal readonly partial struct CopyFromResourceTexture3DShader(float height) : ID2D1PixelShader
{
private readonly int height;
[D2DResourceTextureIndex(0)]
private readonly D2D1ResourceTexture3D<float> source;
@@ -908,8 +902,8 @@ public partial class D2D1ResourceTextureManagerTests
int2 xy = (int2)D2D.GetScenePosition().XY;
int x = xy.X;
int y = (int)((uint)xy.Y % (uint)this.height);
int z = (int)((uint)xy.Y / (uint)this.height);
int y = (int)((uint)xy.Y % (uint)height);
int z = (int)((uint)xy.Y / (uint)height);
return this.source[x, y, z];
}
+8 -11
ファイルの表示
@@ -493,10 +493,9 @@ public sealed partial class BokehBlurEffect
[D2DShaderProfile(D2D1ShaderProfile.PixelShader50)]
[D2DRequiresScenePosition]
[D2DGeneratedPixelShaderDescriptor]
[AutoConstructor]
public readonly partial struct Shader : ID2D1PixelShader
public readonly partial struct Shader(int kernelLength) : ID2D1PixelShader
{
public readonly int kernelLength;
public readonly int kernelLength = kernelLength;
[D2DResourceTextureIndex(1)]
private readonly D2D1ResourceTexture1D<float> kernel;
@@ -543,12 +542,12 @@ public sealed partial class BokehBlurEffect
[D2DShaderProfile(D2D1ShaderProfile.PixelShader50)]
[D2DRequiresScenePosition]
[D2DGeneratedPixelShaderDescriptor]
[AutoConstructor]
public readonly partial struct Shader : ID2D1PixelShader
public readonly partial struct Shader(
int kernelLength,
float z,
float w) : ID2D1PixelShader
{
public readonly int kernelLength;
private readonly float z;
private readonly float w;
public readonly int kernelLength = kernelLength;
[D2DResourceTextureIndex(2)]
private readonly D2D1ResourceTexture1D<float> kernelReals;
@@ -574,7 +573,7 @@ public sealed partial class BokehBlurEffect
result.Imaginary += (Vector4)((realFactor * sourceImaginary) + (imaginaryFactor * sourceReal));
}
return result.WeightedSum(this.z, this.w);
return result.WeightedSum(z, w);
}
}
}
@@ -588,7 +587,6 @@ public sealed partial class BokehBlurEffect
[D2DOutputBuffer(D2D1BufferPrecision.Float32, D2D1ChannelDepth.Four)]
[D2DShaderProfile(D2D1ShaderProfile.PixelShader50)]
[D2DGeneratedPixelShaderDescriptor]
[AutoConstructor]
internal readonly partial struct GammaHighlight : ID2D1PixelShader
{
/// <inheritdoc/>
@@ -611,7 +609,6 @@ public sealed partial class BokehBlurEffect
[D2DOutputBuffer(D2D1BufferPrecision.Float32, D2D1ChannelDepth.Four)]
[D2DShaderProfile(D2D1ShaderProfile.PixelShader50)]
[D2DGeneratedPixelShaderDescriptor]
[AutoConstructor]
internal readonly partial struct InverseGammaHighlight : ID2D1PixelShader
{
/// <inheritdoc/>
+1
ファイルの表示
@@ -56,6 +56,7 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="AutoConstructor" Version="5.1.0" PrivateAssets="all" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.8.0" ExcludeAssets="build" />
<PackageReference Include="MSTest.TestAdapter" Version="3.1.1" />
<PackageReference Include="MSTest.TestFramework" Version="3.1.1" />
+1 -4
ファイルの表示
@@ -33,13 +33,10 @@ Trace.Assert(shaderInfo.BoundResourceCount == 2);
/// <summary>
/// A sample kernel that requires dynamic compilation, as it's not precompiled.
/// </summary>
[AutoConstructor]
[ThreadGroupSize(DefaultThreadGroupSizes.X)]
[GeneratedComputeShaderDescriptor]
internal readonly partial struct MultiplyByTwo : IComputeShader
internal readonly partial struct MultiplyByTwo(ReadWriteBuffer<float> buffer) : IComputeShader
{
public readonly ReadWriteBuffer<float> buffer;
/// <inheritdoc/>
public void Execute()
{
+1 -4
ファイルの表示
@@ -27,11 +27,8 @@ for (int i = 0; i < array.Length; i++)
/// </summary>
[ThreadGroupSize(DefaultThreadGroupSizes.X)]
[GeneratedComputeShaderDescriptor]
[AutoConstructor]
internal readonly partial struct MultiplyByTwo : IComputeShader
internal readonly partial struct MultiplyByTwo(ReadWriteBuffer<float> buffer) : IComputeShader
{
public readonly ReadWriteBuffer<float> buffer;
/// <inheritdoc/>
public void Execute()
{
+1 -4
ファイルの表示
@@ -33,11 +33,8 @@ for (int i = 0; i < array.Length; i++)
/// </summary>
[ThreadGroupSize(DefaultThreadGroupSizes.X)]
[GeneratedComputeShaderDescriptor]
[AutoConstructor]
internal readonly partial struct MultiplyByTwo : IComputeShader
internal readonly partial struct MultiplyByTwo(ReadWriteBuffer<float> buffer) : IComputeShader
{
public readonly ReadWriteBuffer<float> buffer;
/// <inheritdoc/>
public void Execute()
{
+1
ファイルの表示
@@ -10,6 +10,7 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="AutoConstructor" Version="5.1.0" PrivateAssets="all" />
<PackageReference Include="CommunityToolkit.Diagnostics" Version="8.2.2" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.8.0" />
<PackageReference Include="MSTest.TestAdapter" Version="3.1.1" />
@@ -5,6 +5,7 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="AutoConstructor" Version="5.1.0" PrivateAssets="all" />
<PackageReference Include="CommunityToolkit.Diagnostics" Version="8.2.2" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.8.0" />
<PackageReference Include="MSTest.TestAdapter" Version="3.1.1" />
+2 -5
ファイルの表示
@@ -21,13 +21,10 @@ if (!numbers.SequenceEqual(result))
Console.WriteLine("Test passed successfully!");
[AutoConstructor]
[ThreadGroupSize(DefaultThreadGroupSizes.X)]
[GeneratedComputeShaderDescriptor]
public readonly partial struct ApplyFunctionShader : IComputeShader
public readonly partial struct ApplyFunctionShader(ReadWriteBuffer<float> sourceTexture) : IComputeShader
{
private readonly ReadWriteBuffer<float> sourceTexture;
public static float AddHalf(float input)
{
return input + 0.5f;
@@ -35,6 +32,6 @@ public readonly partial struct ApplyFunctionShader : IComputeShader
public void Execute()
{
this.sourceTexture[ThreadIds.X] = AddHalf(this.sourceTexture[ThreadIds.X]);
sourceTexture[ThreadIds.X] = AddHalf(sourceTexture[ThreadIds.X]);
}
}
+1
ファイルの表示
@@ -5,6 +5,7 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="AutoConstructor" Version="5.1.0" PrivateAssets="all" />
<PackageReference Include="CommunityToolkit.Diagnostics" Version="8.2.2" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.8.0" />
<PackageReference Include="MSTest.TestAdapter" Version="3.1.1" />
+29 -29
ファイルの表示
@@ -16,7 +16,7 @@ public partial class ShaderDataLoaderTests
[GeneratedComputeShaderDescriptor]
public readonly partial struct CapturedResourceShader : IComputeShader
{
public readonly ReadWriteBuffer<float> _;
public readonly ReadWriteBuffer<float> _buffer;
public void Execute()
{
@@ -52,8 +52,8 @@ public partial class ShaderDataLoaderTests
[GeneratedComputeShaderDescriptor]
public readonly partial struct MultipleResourcesAndPrimitivesShader : IComputeShader
{
public readonly ReadWriteBuffer<float> _0;
public readonly ReadWriteBuffer<float> _1;
public readonly ReadWriteBuffer<float> _buffer0;
public readonly ReadWriteBuffer<float> _buffer1;
public readonly int a;
public readonly int b;
public readonly int c;
@@ -98,7 +98,7 @@ public partial class ShaderDataLoaderTests
[GeneratedComputeShaderDescriptor]
public readonly partial struct ScalarAndVectorTypesShader : IComputeShader
{
public readonly ReadWriteBuffer<float> _;
public readonly ReadWriteBuffer<float> _buffer;
public readonly float3 f3;
public readonly int a;
public readonly int b;
@@ -149,7 +149,7 @@ public partial class ShaderDataLoaderTests
[GeneratedComputeShaderDescriptor]
public readonly partial struct ScalarVectorAndMatrixTypesShader : IComputeShader
{
public readonly ReadWriteBuffer<float> _;
public readonly ReadWriteBuffer<float> _buffer;
public readonly float2x3 f2x3;
public readonly int a;
public readonly Int1x3 i1x3;
@@ -218,16 +218,16 @@ public partial class ShaderDataLoaderTests
}
[AutoConstructor]
public partial struct SimpleTypes
public readonly partial struct SimpleTypes
{
public float2x3 f2x3;
public int a;
public Int1x3 i1x3;
public double2 d2;
public int c;
public Int1x2 i1x2;
public int2x2 i2x2;
public int d;
public readonly float2x3 f2x3;
public readonly int a;
public readonly Int1x3 i1x3;
public readonly double2 d2;
public readonly int c;
public readonly Int1x2 i1x2;
public readonly int2x2 i2x2;
public readonly int d;
}
[AutoConstructor]
@@ -235,7 +235,7 @@ public partial class ShaderDataLoaderTests
[GeneratedComputeShaderDescriptor]
public readonly partial struct FlatCustomTypeShader : IComputeShader
{
public readonly ReadWriteBuffer<float> _0;
public readonly ReadWriteBuffer<float> _buffer0;
public readonly SimpleTypes a;
public void Execute()
@@ -298,28 +298,28 @@ public partial class ShaderDataLoaderTests
}
[AutoConstructor]
public partial struct CustomType1
public readonly partial struct CustomType1
{
public float3 a;
public SimpleTypes b;
public int c;
public CustomType2 d;
public CustomType3 e;
public readonly float3 a;
public readonly SimpleTypes b;
public readonly int c;
public readonly CustomType2 d;
public readonly CustomType3 e;
}
[AutoConstructor]
public partial struct CustomType2
public readonly partial struct CustomType2
{
public int a;
public float2 b;
public CustomType3 c;
public readonly int a;
public readonly float2 b;
public readonly CustomType3 c;
}
[AutoConstructor]
public partial struct CustomType3
public readonly partial struct CustomType3
{
public int a;
public float2 b;
public readonly int a;
public readonly float2 b;
}
[AutoConstructor]
@@ -327,7 +327,7 @@ public partial class ShaderDataLoaderTests
[GeneratedComputeShaderDescriptor]
public readonly partial struct NestedCustomTypesShader : IComputeShader
{
public readonly ReadWriteBuffer<float> _0;
public readonly ReadWriteBuffer<float> _buffer0;
public readonly CustomType1 a;
public void Execute()
-114
ファイルの表示
@@ -1,114 +0,0 @@
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using ComputeSharp.Core.SourceGenerators;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace ComputeSharp.Tests.SourceGenerators;
[TestClass]
[TestCategory("AutoConstructorGenerator")]
public class AutoConstructorGeneratorTests
{
[TestMethod]
public void GenerateConstructor()
{
const string source = """
using System.Numerics;
using ComputeSharp;
namespace ComputeSharp
{
public class ReadWriteBuffer<T> { }
}
namespace MyFancyApp.Sample
{
public partial class IFoo<T> : IFluff
where T : notnull, new()
{
public partial class Foo
{
[AutoConstructor]
public readonly partial struct Test
{
private readonly float a;
private readonly Vector2 b;
public readonly ReadWriteBuffer<Vector4> c;
public readonly ReadWriteBuffer<int> d;
}
}
}
}
""";
string expected = $$"""
// <auto-generated/>
#pragma warning disable
namespace MyFancyApp.Sample;
partial class IFoo<T>
{
partial class Foo
{
partial struct Test
{
[global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.Core.SourceGenerators.AutoConstructorGenerator", "{{typeof(AutoConstructorGenerator).Assembly.GetName().Version}}")]
[global::System.Diagnostics.DebuggerNonUserCode]
[global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
public Test(float a, global::System.Numerics.Vector2 b, global::ComputeSharp.ReadWriteBuffer<global::System.Numerics.Vector4> c, global::ComputeSharp.ReadWriteBuffer<int> d)
{
this.a = a;
this.b = b;
this.c = c;
this.d = d;
}
}
}
}
""";
VerifyGeneratedMethodLines<AutoConstructorGenerator>(source, 0, expected);
}
/// <summary>
/// Verifies the output of a source generator.
/// </summary>
/// <typeparam name="TGenerator">The generator type to use.</typeparam>
/// <param name="source">The input source to process.</param>
/// <param name="index">The target index to check in the resulting output.</param>
/// <param name="expectedBody">The expected body to compare with the generated code.</param>
private static void VerifyGeneratedMethodLines<TGenerator>(string source, int index, string expectedBody)
where TGenerator : class, IIncrementalGenerator, new()
{
SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(source);
IEnumerable<MetadataReference> references =
from assembly in AppDomain.CurrentDomain.GetAssemblies()
where !assembly.IsDynamic
let reference = MetadataReference.CreateFromFile(assembly.Location)
select reference;
CSharpCompilation compilation = CSharpCompilation.Create("original", new SyntaxTree[] { syntaxTree }, references, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
IIncrementalGenerator generator = new TGenerator();
CSharpGeneratorDriver driver = CSharpGeneratorDriver.Create(generator);
_ = driver.RunGeneratorsAndUpdateCompilation(compilation, out Compilation outputCompilation, out ImmutableArray<Diagnostic> diagnostics);
string outputBody = outputCompilation.SyntaxTrees.Skip(index + 1).First().ToString();
string[] outputLines = outputBody.Split('\n', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
string[] expectedLines = expectedBody.Replace("\r", "").Split('\n', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
Assert.AreEqual(expectedLines.Length, outputLines.Length);
for (int i = 0; i < outputLines.Length; i++)
{
Assert.AreEqual(expectedLines[i], outputLines[i]);
}
}
}
-89
ファイルの表示
@@ -1,89 +0,0 @@
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace ComputeSharp.Tests;
[TestClass]
[TestCategory("AutoConstructorAttribute")]
public unsafe partial class AutoConstructorAttributeTests
{
[AutoConstructor]
public partial struct StructWithFixedField
{
public int a;
public float b;
public byte* c;
public fixed byte d[16];
}
[TestMethod]
public void GenerateConstructorWithInheritedUnsafeContextAndIgnoredFixedField()
{
byte c = 123;
StructWithFixedField instance = new(42, 3.14f, &c);
Assert.AreEqual(instance.a, 42);
Assert.AreEqual(instance.b, 3.14f);
Assert.IsTrue(instance.c == &c);
}
public partial interface ISomeInterface
{
public partial record SomeRecord
{
public partial struct SomeStruct
{
[AutoConstructor]
public partial struct AnotherStruct
{
public int a;
public float b;
}
}
}
}
[TestMethod]
public void GenerateConstructorWithNestedTypes()
{
int a = 42;
float b = 3.14f;
ISomeInterface.SomeRecord.SomeStruct.AnotherStruct instance = new(a, b);
Assert.AreEqual(instance.a, a);
Assert.AreEqual(instance.b, b);
}
public partial interface IAnotherInterface
{
public int B { get; }
public void Foo();
}
[AutoConstructor]
public partial struct AnotherStruct : IAnotherInterface
{
public int a;
public float b;
int IAnotherInterface.B => 100;
void IAnotherInterface.Foo()
{
}
}
[TestMethod]
public void GenerateConstructorWithExplicitInterfaceMembers()
{
int a = 42;
float b = 3.14f;
AnotherStruct instance = new(a, b);
Assert.AreEqual(instance.a, a);
Assert.AreEqual(instance.b, b);
}
}
-1
ファイルの表示
@@ -1308,7 +1308,6 @@ public partial class ComputeContextTests
}
}
[AutoConstructor]
[ThreadGroupSize(DefaultThreadGroupSizes.XY)]
[GeneratedComputeShaderDescriptor]
internal readonly partial struct ClearPixelShader : IComputeShader<float4>
+1
ファイルの表示
@@ -10,6 +10,7 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="AutoConstructor" Version="5.1.0" PrivateAssets="all" />
<PackageReference Include="CommunityToolkit.Diagnostics" Version="8.2.2" />
<PackageReference Include="CommunityToolkit.HighPerformance" Version="8.2.2" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.8.0" />
-1
ファイルの表示
@@ -34,7 +34,6 @@ public partial class IPixelShaderTests
}
}
[AutoConstructor]
[ThreadGroupSize(DefaultThreadGroupSizes.XY)]
[GeneratedComputeShaderDescriptor]
internal readonly partial struct EarlyReturnShader : IComputeShader<float4>
+3 -3
ファイルの表示
@@ -230,10 +230,10 @@ namespace ComputeSharp.Tests
}
[AutoConstructor]
public partial struct CustomStructType
public readonly partial struct CustomStructType
{
public float2 a;
public int b;
public readonly float2 a;
public readonly int b;
}
[AutoConstructor]