参照されないプロジェクトを削除しビルド構成を整理
このコミットが含まれているのは:
1 親
902d1a50a3
コミット
67af7b667b
588ファイル変更
+3
-56403
検索条件に一致するファイルはありません
@@ -7,12 +7,6 @@
|
||||
<InternalsVisibleTo Include="ComputeSharp, PublicKey=$(AssemblySignPublicKey)" />
|
||||
<InternalsVisibleTo Include="ComputeSharp.D3D12MemoryAllocator, PublicKey=$(AssemblySignPublicKey)" />
|
||||
<InternalsVisibleTo Include="ComputeSharp.Dxc, PublicKey=$(AssemblySignPublicKey)" />
|
||||
<InternalsVisibleTo Include="ComputeSharp.Pix, PublicKey=$(AssemblySignPublicKey)" />
|
||||
<InternalsVisibleTo Include="ComputeSharp.Uwp, PublicKey=$(AssemblySignPublicKey)" />
|
||||
<InternalsVisibleTo Include="ComputeSharp.WinUI, PublicKey=$(AssemblySignPublicKey)" />
|
||||
<InternalsVisibleTo Include="ComputeSharp.D2D1, PublicKey=$(AssemblySignPublicKey)" />
|
||||
<InternalsVisibleTo Include="ComputeSharp.D2D1.Uwp, PublicKey=$(AssemblySignPublicKey)" />
|
||||
<InternalsVisibleTo Include="ComputeSharp.D2D1.WinUI, PublicKey=$(AssemblySignPublicKey)" />
|
||||
</ItemGroup>
|
||||
|
||||
<!-- T4 template generation service (the .tt/.g.cs files are resolved in the .targets file) -->
|
||||
|
||||
@@ -1,15 +0,0 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<TargetFramework>netstandard2.0</TargetFramework>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.Workspaces" Version="4.9.2" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\ComputeSharp.D2D1.SourceGenerators\ComputeSharp.D2D1.SourceGenerators.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<Import Project="..\ComputeSharp.CodeFixing\ComputeSharp.CodeFixing.projitems" Label="Shared" />
|
||||
</Project>
|
||||
@@ -1,48 +0,0 @@
|
||||
using System.Composition;
|
||||
using ComputeSharp.CodeFixing;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.CodeFixes;
|
||||
using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors;
|
||||
|
||||
namespace ComputeSharp.D2D1.CodeFixers;
|
||||
|
||||
/// <summary>
|
||||
/// A code fixer that adds the <c>[D2DGeneratedPixelShaderDescriptor]</c> to D2D1 shader types with no descriptor.
|
||||
/// </summary>
|
||||
[ExportCodeFixProvider(LanguageNames.CSharp)]
|
||||
[Shared]
|
||||
public sealed class MissingPixelShaderDescriptorOnPixelShaderCodeFixer : MissingAttributeCodeFixer
|
||||
{
|
||||
/// <summary>
|
||||
/// The set of type names for all D2D attributes that can be over shader types.
|
||||
/// </summary>
|
||||
private static readonly string[] D2DAttributeTypeNames =
|
||||
[
|
||||
"ComputeSharp.D2D1.D2DCompileOptionsAttribute",
|
||||
"ComputeSharp.D2D1.D2DEffectAuthorAttribute",
|
||||
"ComputeSharp.D2D1.D2DEffectCategoryAttribute",
|
||||
"ComputeSharp.D2D1.D2DEffectDescriptionAttribute",
|
||||
"ComputeSharp.D2D1.D2DEffectDisplayNameAttribute",
|
||||
"ComputeSharp.D2D1.D2DEffectIdAttribute",
|
||||
"ComputeSharp.D2D1.D2DInputComplexAttribute",
|
||||
"ComputeSharp.D2D1.D2DInputCountAttribute",
|
||||
"ComputeSharp.D2D1.D2DInputDescriptionAttribute",
|
||||
"ComputeSharp.D2D1.D2DInputSimpleAttribute",
|
||||
"ComputeSharp.D2D1.D2DOutputBufferAttribute",
|
||||
"ComputeSharp.D2D1.D2DPixelOptionsAttribute",
|
||||
"ComputeSharp.D2D1.D2DRequiresScenePositionAttribute",
|
||||
"ComputeSharp.D2D1.D2DShaderProfileAttribute"
|
||||
];
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="MissingAttributeCodeFixer"/> instance with the specified parameters.
|
||||
/// </summary>
|
||||
public MissingPixelShaderDescriptorOnPixelShaderCodeFixer()
|
||||
: base(
|
||||
diagnosticId: MissingPixelShaderDescriptorOnPixelShaderTypeId,
|
||||
codeActionTitle: "Add [D2DGeneratedPixelShaderDescriptor] attribute",
|
||||
attributeFullyQualifiedMetadataName: "ComputeSharp.D2D1.D2DGeneratedPixelShaderDescriptorAttribute",
|
||||
leadingAttributeFullyQualifiedMetadataNames: D2DAttributeTypeNames)
|
||||
{
|
||||
}
|
||||
}
|
||||
@@ -1,95 +0,0 @@
|
||||
; Shipped analyzer releases
|
||||
; https://github.com/dotnet/roslyn-analyzers/blob/master/src/Microsoft.CodeAnalysis.Analyzers/ReleaseTrackingAnalyzers.Help.md
|
||||
|
||||
## Release 1.0
|
||||
|
||||
### New Rules
|
||||
|
||||
Rule ID | Category | Severity | Notes
|
||||
--------|----------|----------|-------
|
||||
CMPSD2D0001 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
CMPSD2D0002 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
CMPSD2D0003 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
CMPSD2D0004 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
CMPSD2D0005 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
CMPSD2D0006 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
CMPSD2D0007 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
CMPSD2D0008 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
CMPSD2D0009 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
CMPSD2D0010 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
CMPSD2D0011 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
CMPSD2D0012 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
CMPSD2D0013 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
CMPSD2D0014 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
CMPSD2D0015 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
CMPSD2D0016 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
CMPSD2D0017 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
CMPSD2D0018 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
CMPSD2D0019 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
CMPSD2D0020 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
CMPSD2D0021 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
CMPSD2D0022 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
CMPSD2D0023 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
CMPSD2D0024 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
CMPSD2D0025 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
CMPSD2D0026 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
CMPSD2D0027 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
CMPSD2D0028 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
CMPSD2D0029 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
CMPSD2D0030 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
CMPSD2D0031 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
CMPSD2D0032 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
CMPSD2D0033 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
CMPSD2D0034 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
CMPSD2D0035 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
CMPSD2D0036 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
CMPSD2D0037 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
CMPSD2D0038 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
CMPSD2D0039 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
CMPSD2D0040 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
CMPSD2D0041 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
CMPSD2D0042 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
CMPSD2D0043 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
CMPSD2D0044 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
CMPSD2D0045 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
CMPSD2D0046 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
CMPSD2D0047 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
CMPSD2D0048 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
CMPSD2D0049 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
CMPSD2D0050 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
CMPSD2D0051 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
CMPSD2D0052 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
CMPSD2D0053 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
CMPSD2D0054 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
CMPSD2D0055 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
CMPSD2D0056 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
CMPSD2D0057 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
CMPSD2D0058 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
CMPSD2D0059 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
CMPSD2D0060 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
CMPSD2D0061 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
CMPSD2D0062 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
CMPSD2D0063 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
CMPSD2D0064 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
CMPSD2D0065 | ComputeSharp.D2D1.Shaders | Warning | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
CMPSD2D0066 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
CMPSD2D0067 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
CMPSD2D0068 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
CMPSD2D0069 | ComputeSharp.D2D1.Shaders | Warning | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
CMPSD2D0070 | ComputeSharp.D2D1.Shaders | Warning | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
CMPSD2D0071 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
CMPSD2D0072 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
CMPSD2D0073 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
CMPSD2D0074 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
CMPSD2D0075 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
CMPSD2D0076 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
CMPSD2D0077 | ComputeSharp.D2D1.Shaders | Info | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
CMPSD2D0078 | ComputeSharp.D2D1.Shaders | Warning | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
CMPSD2D0079 | ComputeSharp.D2D1.Shaders | Warning | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
CMPSD2D0080 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
CMPSD2D0081 | ComputeSharp.D2D1.Shaders | Warning | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
CMPSD2D0082 | ComputeSharp.D2D1.Shaders | Warning | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
CMPSD2D0083 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
CMPSD2D0084 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
CMPSD2D0085 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
CMPSD2D0086 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
@@ -1,2 +0,0 @@
|
||||
; Unshipped analyzer release
|
||||
; https://github.com/dotnet/roslyn-analyzers/blob/master/src/Microsoft.CodeAnalysis.Analyzers/ReleaseTrackingAnalyzers.Help.md
|
||||
@@ -1,99 +0,0 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<TargetFramework>netstandard2.0</TargetFramework>
|
||||
<DefineConstants>$(DefineConstants);D2D1_SOURCE_GENERATOR</DefineConstants>
|
||||
</PropertyGroup>
|
||||
|
||||
<PropertyGroup>
|
||||
|
||||
<!-- Ignore warnings for ambiguous XML cref attributes (due to some CSharpLang/CsWin32 signature differences) -->
|
||||
<NoWarn>$(NoWarn);CS0419</NoWarn>
|
||||
|
||||
<!-- Ignore warnings for unresolved XML cref attributes (for imported types, same as in the D3D12 generator) -->
|
||||
<NoWarn>$(NoWarn);CS1574</NoWarn>
|
||||
|
||||
<!-- Ignore warnings for redundant casts (needed in some imported enum types due to CSharpLang/CsWin32 type differences) -->
|
||||
<NoWarn>$(NoWarn);IDE0004</NoWarn>
|
||||
</PropertyGroup>
|
||||
|
||||
<!-- Same setup as ComputeSharp.Core.SourceGenerators, just with also APIs from ComputeSharp -->
|
||||
<ItemGroup>
|
||||
|
||||
<!-- ComputeSharp.Core APIs -->
|
||||
<Compile Include="..\ComputeSharp.Core\Exceptions\InvalidExecutionContextException.cs" Link="ComputeSharp.Core\Exceptions\InvalidExecutionContextException.cs" />
|
||||
<Compile Include="..\ComputeSharp.Core\Intrinsics\Attributes\HlslIntrinsicNameAttribute.cs" Link="ComputeSharp.Core\Intrinsics\Attributes\HlslIntrinsicNameAttribute.cs" />
|
||||
<Compile Include="..\ComputeSharp.Core\Intrinsics\Hlsl.Casts.g.cs" Link="ComputeSharp.Core\Intrinsics\Hlsl.Casts.g.cs" />
|
||||
<Compile Include="..\ComputeSharp.Core\Intrinsics\Hlsl.cs" Link="ComputeSharp.Core\Intrinsics\Hlsl.cs" />
|
||||
<Compile Include="..\ComputeSharp.Core\Intrinsics\Hlsl.g.cs" Link="ComputeSharp.Core\Intrinsics\Hlsl.g.cs" />
|
||||
<Compile Include="..\ComputeSharp.Core\Intrinsics\Hlsl.Void.g.cs" Link="ComputeSharp.Core\Intrinsics\Hlsl.Void.g.cs" />
|
||||
<Compile Include="..\ComputeSharp.Core\Primitives\Bool\Bool.cs" Link="ComputeSharp.Core\Primitives\Bool\Bool.cs" />
|
||||
<Compile Include="..\ComputeSharp.Core\Primitives\Bool\Bool2.g.cs" Link="ComputeSharp.Core\Primitives\Bool\Bool2.g.cs" />
|
||||
<Compile Include="..\ComputeSharp.Core\Primitives\Bool\Bool3.g.cs" Link="ComputeSharp.Core\Primitives\Bool\Bool3.g.cs" />
|
||||
<Compile Include="..\ComputeSharp.Core\Primitives\Bool\Bool4.g.cs" Link="ComputeSharp.Core\Primitives\Bool\Bool4.g.cs" />
|
||||
<Compile Include="..\ComputeSharp.Core\Primitives\Bool\BoolMxN.g.cs" Link="ComputeSharp.Core\Primitives\Bool\BoolMxN.g.cs" />
|
||||
<Compile Include="..\ComputeSharp.Core\Primitives\Double\Double2.g.cs" Link="ComputeSharp.Core\Primitives\Double\Double2.g.cs" />
|
||||
<Compile Include="..\ComputeSharp.Core\Primitives\Double\Double3.g.cs" Link="ComputeSharp.Core\Primitives\Double\Double3.g.cs" />
|
||||
<Compile Include="..\ComputeSharp.Core\Primitives\Double\Double4.g.cs" Link="ComputeSharp.Core\Primitives\Double\Double4.g.cs" />
|
||||
<Compile Include="..\ComputeSharp.Core\Primitives\Double\DoubleMxN.g.cs" Link="ComputeSharp.Core\Primitives\Double\DoubleMxN.g.cs" />
|
||||
<Compile Include="..\ComputeSharp.Core\Primitives\Float\Float2.g.cs" Link="ComputeSharp.Core\Primitives\Float\Float2.g.cs" />
|
||||
<Compile Include="..\ComputeSharp.Core\Primitives\Float\Float3.g.cs" Link="ComputeSharp.Core\Primitives\Float\Float3.g.cs" />
|
||||
<Compile Include="..\ComputeSharp.Core\Primitives\Float\Float4.g.cs" Link="ComputeSharp.Core\Primitives\Float\Float4.g.cs" />
|
||||
<Compile Include="..\ComputeSharp.Core\Primitives\Float\FloatMxN.g.cs" Link="ComputeSharp.Core\Primitives\Float\FloatMxN.g.cs" />
|
||||
<Compile Include="..\ComputeSharp.Core\Primitives\Int\Int2.g.cs" Link="ComputeSharp.Core\Primitives\Int\Int2.g.cs" />
|
||||
<Compile Include="..\ComputeSharp.Core\Primitives\Int\Int3.g.cs" Link="ComputeSharp.Core\Primitives\Int\Int3.g.cs" />
|
||||
<Compile Include="..\ComputeSharp.Core\Primitives\Int\Int4.g.cs" Link="ComputeSharp.Core\Primitives\Int\Int4.g.cs" />
|
||||
<Compile Include="..\ComputeSharp.Core\Primitives\Int\IntMxN.g.cs" Link="ComputeSharp.Core\Primitives\Int\IntMxN.g.cs" />
|
||||
<Compile Include="..\ComputeSharp.Core\Primitives\Internals\UndefinedData.cs" Link="ComputeSharp.Core\Primitives\Internals\UndefinedData.cs" />
|
||||
<Compile Include="..\ComputeSharp.Core\Primitives\UInt\UInt2.g.cs" Link="ComputeSharp.Core\Primitives\UInt\UInt2.g.cs" />
|
||||
<Compile Include="..\ComputeSharp.Core\Primitives\UInt\UInt3.g.cs" Link="ComputeSharp.Core\Primitives\UInt\UInt3.g.cs" />
|
||||
<Compile Include="..\ComputeSharp.Core\Primitives\UInt\UInt4.g.cs" Link="ComputeSharp.Core\Primitives\UInt\UInt4.g.cs" />
|
||||
<Compile Include="..\ComputeSharp.Core\Primitives\UInt\UIntMxN.g.cs" Link="ComputeSharp.Core\Primitives\UInt\UIntMxN.g.cs" />
|
||||
<Compile Include="..\ComputeSharp.Core\Primitives\MatrixIndex.cs" Link="ComputeSharp.Core\Primitives\MatrixIndex.cs" />
|
||||
|
||||
<!-- ComputeSharp APIs -->
|
||||
<Compile Include="..\ComputeSharp\Graphics\Helpers\AlignmentHelper.cs" Link="ComputeSharp\Graphics\Helpers\AlignmentHelper.cs" />
|
||||
|
||||
<!-- ComputeSharp.D2D1 APIs -->
|
||||
<Compile Include="..\ComputeSharp.D2D1\Attributes\Enums\D2D1ShaderProfile.cs" Link="ComputeSharp.D2D1\Attributes\Enums\D2D1ShaderProfile.cs" />
|
||||
<Compile Include="..\ComputeSharp.D2D1\Attributes\Enums\D2D1BufferPrecision.cs" Link="ComputeSharp.D2D1\Attributes\Enums\D2D1BufferPrecision.cs" />
|
||||
<Compile Include="..\ComputeSharp.D2D1\Attributes\Enums\D2D1ChannelDepth.cs" Link="ComputeSharp.D2D1\Attributes\Enums\D2D1ChannelDepth.cs" />
|
||||
<Compile Include="..\ComputeSharp.D2D1\Attributes\Enums\D2D1CompileOptions.cs" Link="ComputeSharp.D2D1\Attributes\Enums\D2D1CompileOptions.cs" />
|
||||
<Compile Include="..\ComputeSharp.D2D1\Attributes\Enums\D2D1Filter.cs" Link="ComputeSharp.D2D1\Attributes\Enums\D2D1Filter.cs" />
|
||||
<Compile Include="..\ComputeSharp.D2D1\Attributes\Enums\D2D1PixelOptions.cs" Link="ComputeSharp.D2D1\Attributes\Enums\D2D1PixelOptions.cs" />
|
||||
<Compile Include="..\ComputeSharp.D2D1\Intrinsics\D2D.cs" Link="ComputeSharp.D2D1\Intrinsics\D2D.cs" />
|
||||
<Compile Include="..\ComputeSharp.D2D1\Intrinsics\Attributes\HlslD2DIntrinsicInputTypeAttribute.cs" Link="ComputeSharp.D2D1\Intrinsics\Attributes\HlslD2DIntrinsicInputTypeAttribute.cs" />
|
||||
<Compile Include="..\ComputeSharp.D2D1\Shaders\Exceptions\FxcCompilationException.cs" Link="ComputeSharp.D2D1\Shaders\Exceptions\FxcCompilationException.cs" />
|
||||
<Compile Include="..\ComputeSharp.D2D1\Shaders\Interop\D2D1PixelShaderInputType.cs" Link="ComputeSharp.D2D1\Shaders\Interop\D2D1PixelShaderInputType.cs" />
|
||||
<Compile Include="..\ComputeSharp.D2D1\Shaders\Interop\Helpers\D2D1AssemblyAssociatedMemory.cs" Link="ComputeSharp.D2D1\Shaders\Interop\Helpers\D2D1AssemblyAssociatedMemory.cs" />
|
||||
<Compile Include="..\ComputeSharp.D2D1\Shaders\Translation\ASCII.cs" Link="ComputeSharp.D2D1\Shaders\Translation\ASCII.cs" />
|
||||
<Compile Include="..\ComputeSharp.D2D1\Shaders\Translation\D3DCompiler.cs" Link="ComputeSharp.D2D1\Shaders\Translation\D3DCompiler.cs" />
|
||||
<Compile Include="..\ComputeSharp.D2D1\Shaders\Translation\D3DCompiler.ID3DInclude.cs" Link="ComputeSharp.D2D1\Shaders\Translation\D3DCompiler.ID3DInclude.cs" />
|
||||
<Compile Include="..\ComputeSharp.D2D1\Shaders\Translation\Headers\D2D1EffectHelpers.cs" Link="ComputeSharp.D2D1\Shaders\Translation\Headers\D2D1EffectHelpers.cs" />
|
||||
|
||||
<!-- ComPtr<T> and HRESULT extension from D3D12 generator -->
|
||||
<Compile Include="..\ComputeSharp.SourceGenerators\Dxc\Windows.Win32\ComPtr{T}.cs" Link="Fxc\Windows.Win32\ComPtr{T}.cs" />
|
||||
<Compile Include="..\ComputeSharp.SourceGenerators\Dxc\Windows.Win32\HRESULT.cs" Link="Fxc\Windows.Win32\HRESULT.cs" />
|
||||
|
||||
<!-- Shared JSON config for CsWin32 from D3D12 generator -->
|
||||
<AdditionalFiles Include="..\ComputeSharp.SourceGenerators\NativeMethods.json" Link="NativeMethods.json" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.9.2" PrivateAssets="all" Pack="false" />
|
||||
<PackageReference Include="Microsoft.Windows.CsWin32" Version="0.3.106" PrivateAssets="all" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<AdditionalFiles Include="AnalyzerReleases.Shipped.md" />
|
||||
<AdditionalFiles Include="AnalyzerReleases.Unshipped.md" />
|
||||
</ItemGroup>
|
||||
|
||||
<!-- Shared projects with common helpers -->
|
||||
<Import Project="..\ComputeSharp.SourceGeneration\ComputeSharp.SourceGeneration.projitems" Label="Shared" />
|
||||
<Import Project="..\ComputeSharp.SourceGeneration.Hlsl\ComputeSharp.SourceGeneration.Hlsl.projitems" Label="Shared" />
|
||||
|
||||
<!-- Give access to the code fixers project for the exported diagnostic ids and properties -->
|
||||
<ItemGroup>
|
||||
<InternalsVisibleTo Include="ComputeSharp.D2D1.CodeFixers, PublicKey=$(AssemblySignPublicKey)" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
-117
@@ -1,117 +0,0 @@
|
||||
using System.Collections.Immutable;
|
||||
using ComputeSharp.D2D1.SourceGenerators.Models;
|
||||
using ComputeSharp.SourceGeneration.Extensions;
|
||||
using ComputeSharp.SourceGeneration.Helpers;
|
||||
using ComputeSharp.SourceGeneration.Models;
|
||||
using ComputeSharp.SourceGeneration.SyntaxProcessors;
|
||||
using Microsoft.CodeAnalysis;
|
||||
|
||||
namespace ComputeSharp.D2D1.SourceGenerators;
|
||||
|
||||
/// <inheritdoc/>
|
||||
partial class D2DPixelShaderDescriptorGenerator
|
||||
{
|
||||
/// <summary>
|
||||
/// A helper with all logic to generate the constant buffer marshalling methods and additional types.
|
||||
/// </summary>
|
||||
private static class ConstantBuffer
|
||||
{
|
||||
/// <inheritdoc cref="ConstantBufferSyntaxProcessor.GetInfo"/>
|
||||
/// <param name="compilation"><inheritdoc cref="ConstantBufferSyntaxProcessor.GetInfo" path="/param[@name='compilation']/node()"/></param>
|
||||
/// <param name="structDeclarationSymbol"><inheritdoc cref="ConstantBufferSyntaxProcessor.GetInfo" path="/param[@name='structDeclarationSymbol']/node()"/></param>
|
||||
/// <param name="constantBufferSizeInBytes"><inheritdoc cref="ConstantBufferSyntaxProcessor.GetInfo" path="/param[@name='constantBufferSizeInBytes']/node()"/></param>
|
||||
/// <param name="fields"><inheritdoc cref="ConstantBufferSyntaxProcessor.GetInfo" path="/param[@name='fields']/node()"/></param>
|
||||
public static void GetInfo(
|
||||
Compilation compilation,
|
||||
ITypeSymbol structDeclarationSymbol,
|
||||
out int constantBufferSizeInBytes,
|
||||
out ImmutableArray<FieldInfo> fields)
|
||||
{
|
||||
constantBufferSizeInBytes = 0;
|
||||
|
||||
ConstantBufferSyntaxProcessor.GetInfo(
|
||||
compilation,
|
||||
structDeclarationSymbol,
|
||||
ref constantBufferSizeInBytes,
|
||||
out fields);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes the <c>LoadConstantBuffer</c> method.
|
||||
/// </summary>
|
||||
/// <param name="info">The input <see cref="D2D1ShaderInfo"/> instance with gathered shader info.</param>
|
||||
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
|
||||
public static void WriteLoadConstantBufferSyntax(D2D1ShaderInfo info, IndentedTextWriter writer)
|
||||
{
|
||||
string typeName = info.Hierarchy.Hierarchy[0].QualifiedName;
|
||||
|
||||
writer.WriteLine("/// <inheritdoc/>");
|
||||
writer.WriteGeneratedAttributes(GeneratorName);
|
||||
writer.WriteLine("[global::System.Runtime.CompilerServices.SkipLocalsInit]");
|
||||
|
||||
// Write the method declaration (we only need unsafe blocks if we have any values in the constant buffer)
|
||||
writer.Write("static ");
|
||||
writer.WriteIf(!info.Fields.IsEmpty, "unsafe ");
|
||||
writer.WriteLine($"void global::ComputeSharp.D2D1.Descriptors.ID2D1PixelShaderDescriptor<{typeName}>.LoadConstantBuffer<TLoader>(in {typeName} shader, ref TLoader loader)");
|
||||
|
||||
using (writer.WriteBlock())
|
||||
{
|
||||
// If there are no fields, just load an empty buffer
|
||||
if (info.Fields.IsEmpty)
|
||||
{
|
||||
writer.WriteLine("loader.LoadConstantBuffer(default);");
|
||||
}
|
||||
else
|
||||
{
|
||||
// Because D2D (and possibly other consumers) will do a bitwise check on the constant buffer to check for changes,
|
||||
// it is important that the padding space between aligned elements in the generated constant buffer type are also
|
||||
// cleared, and not filled with random data (which might be the case if no special care is taken). We cannot just
|
||||
// rely on the default zero-ing performed by the JIT, because there is no guarantee that the padding space in types
|
||||
// representing unions will also be zero-ed. So instead we create an uninitialized instance and manually clear it
|
||||
// with 'NativeMemory.Clear' (which can also be unrolled by the JIT). This still maintains good performance, and
|
||||
// makes it possible for downstream consumers to further improve performance by implementing better caching strategies.
|
||||
writer.WriteLine("global::System.Runtime.CompilerServices.Unsafe.SkipInit(out global::ComputeSharp.D2D1.Generated.ConstantBuffer buffer);");
|
||||
writer.WriteLine();
|
||||
writer.WriteLine("global::System.Runtime.InteropServices.NativeMemory.Clear(&buffer, (uint)sizeof(global::ComputeSharp.D2D1.Generated.ConstantBuffer));");
|
||||
writer.WriteLine();
|
||||
|
||||
// Otherwise, pass a span into the marshalled native layout buffer
|
||||
writer.WriteLine("global::ComputeSharp.D2D1.Generated.ConstantBufferMarshaller.FromManaged(in shader, out buffer);");
|
||||
writer.WriteLine();
|
||||
writer.WriteLine("loader.LoadConstantBuffer(new global::System.ReadOnlySpan<byte>(&buffer, sizeof(global::ComputeSharp.D2D1.Generated.ConstantBuffer)));");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes the <c>CreateFromConstantBuffer</c> method.
|
||||
/// </summary>
|
||||
/// <param name="info">The input <see cref="D2D1ShaderInfo"/> instance with gathered shader info.</param>
|
||||
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
|
||||
public static void WriteCreateFromConstantBufferSyntax(D2D1ShaderInfo info, IndentedTextWriter writer)
|
||||
{
|
||||
string typeName = info.Hierarchy.Hierarchy[0].QualifiedName;
|
||||
|
||||
writer.WriteLine("/// <inheritdoc/>");
|
||||
writer.WriteGeneratedAttributes(GeneratorName);
|
||||
writer.WriteLine("[global::System.Runtime.CompilerServices.SkipLocalsInit]");
|
||||
writer.WriteLine($"static {typeName} global::ComputeSharp.D2D1.Descriptors.ID2D1PixelShaderDescriptor<{typeName}>.CreateFromConstantBuffer(global::System.ReadOnlySpan<byte> data)");
|
||||
|
||||
using (writer.WriteBlock())
|
||||
{
|
||||
// If there are no fields, just return an empty shader
|
||||
if (info.Fields.IsEmpty)
|
||||
{
|
||||
writer.WriteLine("return default;");
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// Get a reference to the data through the generated native layout type and define the shader
|
||||
writer.WriteLine("ref readonly global::ComputeSharp.D2D1.Generated.ConstantBuffer buffer = ref global::System.Runtime.InteropServices.MemoryMarshal.AsRef<global::ComputeSharp.D2D1.Generated.ConstantBuffer>(data);");
|
||||
writer.WriteLine();
|
||||
writer.WriteLine("return global::ComputeSharp.D2D1.Generated.ConstantBufferMarshaller.ToManaged(in buffer);");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
-46
@@ -1,46 +0,0 @@
|
||||
using ComputeSharp.D2D1.SourceGenerators.Models;
|
||||
using ComputeSharp.SourceGeneration.Extensions;
|
||||
using ComputeSharp.SourceGeneration.Helpers;
|
||||
|
||||
namespace ComputeSharp.D2D1.SourceGenerators;
|
||||
|
||||
/// <inheritdoc/>
|
||||
partial class D2DPixelShaderDescriptorGenerator
|
||||
{
|
||||
/// <summary>
|
||||
/// A helper with all logic to generate the <c>EffectFactory</c> property.
|
||||
/// </summary>
|
||||
private static class EffectFactory
|
||||
{
|
||||
/// <summary>
|
||||
/// Writes the <c>EffectFactory</c> property.
|
||||
/// </summary>
|
||||
/// <param name="info">The input <see cref="D2D1ShaderInfo"/> instance with gathered shader info.</param>
|
||||
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
|
||||
public static void WriteSyntax(D2D1ShaderInfo info, IndentedTextWriter writer)
|
||||
{
|
||||
writer.WriteLine("/// <inheritdoc/>");
|
||||
writer.WriteGeneratedAttributes(GeneratorName);
|
||||
writer.WriteLine($"static unsafe nint global::ComputeSharp.D2D1.Descriptors.ID2D1PixelShaderDescriptor<{info.Hierarchy.Hierarchy[0].QualifiedName}>.EffectFactory");
|
||||
|
||||
using (writer.WriteBlock())
|
||||
{
|
||||
writer.WriteLine("[global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]");
|
||||
writer.WriteLine("get");
|
||||
|
||||
using (writer.WriteBlock())
|
||||
{
|
||||
writer.WriteLine($$"""
|
||||
[global::System.Runtime.InteropServices.UnmanagedCallersOnly(CallConvs = [typeof(global::System.Runtime.CompilerServices.CallConvStdcall)])]
|
||||
static int EffectFactory(void** effectImpl)
|
||||
{
|
||||
return global::ComputeSharp.D2D1.Interop.D2D1PixelShaderEffect.CreateEffectUnsafe<{{info.Hierarchy.Hierarchy[0].QualifiedName}}>(effectImpl);
|
||||
}
|
||||
|
||||
return (nint)(delegate* unmanaged[Stdcall]<void**, int>)&EffectFactory;
|
||||
""", isMultiline: true);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
-71
@@ -1,71 +0,0 @@
|
||||
using ComputeSharp.D2D1.SourceGenerators.Models;
|
||||
using ComputeSharp.SourceGeneration.Extensions;
|
||||
using ComputeSharp.SourceGeneration.Helpers;
|
||||
|
||||
namespace ComputeSharp.D2D1.SourceGenerators;
|
||||
|
||||
/// <inheritdoc/>
|
||||
partial class D2DPixelShaderDescriptorGenerator
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
partial class EffectId
|
||||
{
|
||||
/// <summary>
|
||||
/// Writes the <c>EffectId</c> property.
|
||||
/// </summary>
|
||||
/// <param name="info">The input <see cref="D2D1ShaderInfo"/> instance with gathered shader info.</param>
|
||||
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
|
||||
public static void WriteSyntax(D2D1ShaderInfo info, IndentedTextWriter writer)
|
||||
{
|
||||
writer.WriteLine("/// <inheritdoc/>");
|
||||
writer.WriteGeneratedAttributes(GeneratorName);
|
||||
writer.WriteLine($"static ref readonly global::System.Guid global::ComputeSharp.D2D1.Descriptors.ID2D1PixelShaderDescriptor<{info.Hierarchy.Hierarchy[0].QualifiedName}>.EffectId");
|
||||
|
||||
using (writer.WriteBlock())
|
||||
{
|
||||
writer.WriteLine("[global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]");
|
||||
writer.WriteLine("get");
|
||||
|
||||
using (writer.WriteBlock())
|
||||
{
|
||||
writer.WriteLine("global::System.ReadOnlySpan<byte> bytes =");
|
||||
writer.WriteLine("[");
|
||||
writer.IncreaseIndent();
|
||||
|
||||
// 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<byte, global::System.Guid>(ref global::System.Runtime.InteropServices.MemoryMarshal.GetReference(bytes));");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,132 +0,0 @@
|
||||
using System;
|
||||
using System.Buffers;
|
||||
using System.Collections.Immutable;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using ComputeSharp.SourceGeneration.Extensions;
|
||||
using ComputeSharp.SourceGeneration.Helpers;
|
||||
using Microsoft.CodeAnalysis;
|
||||
|
||||
namespace ComputeSharp.D2D1.SourceGenerators;
|
||||
|
||||
/// <inheritdoc/>
|
||||
partial class D2DPixelShaderDescriptorGenerator
|
||||
{
|
||||
/// <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="compilation">The input <see cref="Compilation"/> object currently in use.</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(Compilation compilation, INamedTypeSymbol structDeclarationSymbol)
|
||||
{
|
||||
if (TryGetDefinedEffectId(compilation, structDeclarationSymbol, out ImmutableArray<byte> effectId))
|
||||
{
|
||||
return effectId;
|
||||
}
|
||||
|
||||
return CreateDefaultEffectId(structDeclarationSymbol);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Tries to get the defined effect id for a given shader type.
|
||||
/// </summary>
|
||||
/// <param name="compilation">The input <see cref="Compilation"/> object currently in use.</param>
|
||||
/// <param name="typeSymbol">The input <see cref="INamedTypeSymbol"/> instance.</param>
|
||||
/// <param name="effectId">The resulting defined effect id, if found.</param>
|
||||
/// <returns>Whether or not a defined effect id could be found.</returns>
|
||||
private static bool TryGetDefinedEffectId(Compilation compilation, INamedTypeSymbol typeSymbol, out ImmutableArray<byte> effectId)
|
||||
{
|
||||
INamedTypeSymbol effectIdAttributeSymbol = compilation.GetTypeByMetadataName("ComputeSharp.D2D1.D2DEffectIdAttribute")!;
|
||||
|
||||
foreach (AttributeData attributeData in typeSymbol.GetAttributes())
|
||||
{
|
||||
// Check that the attribute is [D2DEffectId] and with a valid parameter
|
||||
if (SymbolEqualityComparer.Default.Equals(attributeData.AttributeClass, effectIdAttributeSymbol) &&
|
||||
attributeData.ConstructorArguments is [{ Value: string value }] &&
|
||||
Guid.TryParse(value, out Guid guid))
|
||||
{
|
||||
byte[] bytes = guid.ToByteArray();
|
||||
|
||||
effectId = Unsafe.As<byte[], ImmutableArray<byte>>(ref bytes);
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
effectId = default;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates the default effect id for a given type symbol.
|
||||
/// </summary>
|
||||
/// <param name="typeSymbol">The input <see cref="INamedTypeSymbol"/> instance.</param>
|
||||
/// <returns>The resulting effect id.</returns>
|
||||
private static unsafe ImmutableArray<byte> CreateDefaultEffectId(INamedTypeSymbol typeSymbol)
|
||||
{
|
||||
try
|
||||
{
|
||||
// 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 = typeSymbol.ContainingAssembly?.Name ?? string.Empty;
|
||||
|
||||
using ImmutableArrayBuilder<char> charBuffer = new();
|
||||
|
||||
// Format the fully qualified name into a pooled builder to avoid the string allocation
|
||||
typeSymbol.AppendFullyQualifiedMetadataName(in charBuffer);
|
||||
|
||||
int maxTypeNameByteCount = Encoding.UTF8.GetMaxByteCount(charBuffer.Count);
|
||||
int maxAssemblyNameByteCount = Encoding.UTF8.GetMaxByteCount(assemblyName.Length);
|
||||
int maxEncodedByteCount = Math.Max(maxTypeNameByteCount, maxAssemblyNameByteCount);
|
||||
|
||||
byte[] bufferUtf8 = ArrayPool<byte>.Shared.Rent(maxEncodedByteCount);
|
||||
|
||||
// UTF8 encode the fully qualified name first
|
||||
int typeNameBytesWritten = Encoding.UTF8.GetBytes(charBuffer.WrittenSpan, bufferUtf8);
|
||||
|
||||
// Append the UTF8 fully qualified name to the MD5 hash
|
||||
incrementalHash.AppendData(bufferUtf8, 0, typeNameBytesWritten);
|
||||
|
||||
// UTF8 encode the assembly name as well
|
||||
int assemblyNameBytesWritten = Encoding.UTF8.GetBytes(assemblyName.AsSpan(), bufferUtf8);
|
||||
|
||||
// Append the UTF8 assembly name to the MD5 hash
|
||||
incrementalHash.AppendData(bufferUtf8, 0, assemblyNameBytesWritten);
|
||||
|
||||
// The state is now fully in the incremental hash, we can return the array
|
||||
ArrayPool<byte>.Shared.Return(bufferUtf8);
|
||||
|
||||
// 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);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Something went wrong, throw away the current incremental hash.
|
||||
// Realistically speaking, this should just never happen.
|
||||
incrementalHash = null;
|
||||
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
-77
@@ -1,77 +0,0 @@
|
||||
using ComputeSharp.D2D1.SourceGenerators.Models;
|
||||
using ComputeSharp.SourceGeneration.Extensions;
|
||||
using ComputeSharp.SourceGeneration.Helpers;
|
||||
|
||||
namespace ComputeSharp.D2D1.SourceGenerators;
|
||||
|
||||
/// <inheritdoc/>
|
||||
partial class D2DPixelShaderDescriptorGenerator
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
partial class EffectMetadata
|
||||
{
|
||||
/// <summary>
|
||||
/// Writes the <c>EffectDisplayName</c> property.
|
||||
/// </summary>
|
||||
/// <param name="info">The input <see cref="D2D1ShaderInfo"/> instance with gathered shader info.</param>
|
||||
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
|
||||
public static void WriteEffectDisplayNameSyntax(D2D1ShaderInfo info, IndentedTextWriter writer)
|
||||
{
|
||||
WriteEffectMetadataSyntax(info.Hierarchy.Hierarchy[0].QualifiedName, "EffectDisplayName", info.EffectDisplayName, writer);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes the <c>EffectDescription</c> property.
|
||||
/// </summary>
|
||||
/// <param name="info">The input <see cref="D2D1ShaderInfo"/> instance with gathered shader info.</param>
|
||||
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
|
||||
public static void WriteEffectDescriptionSyntax(D2D1ShaderInfo info, IndentedTextWriter writer)
|
||||
{
|
||||
WriteEffectMetadataSyntax(info.Hierarchy.Hierarchy[0].QualifiedName, "EffectDescription", info.EffectDescription, writer);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes the <c>EffectCategory</c> property.
|
||||
/// </summary>
|
||||
/// <param name="info">The input <see cref="D2D1ShaderInfo"/> instance with gathered shader info.</param>
|
||||
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
|
||||
public static void WriteEffectCategorySyntax(D2D1ShaderInfo info, IndentedTextWriter writer)
|
||||
{
|
||||
WriteEffectMetadataSyntax(info.Hierarchy.Hierarchy[0].QualifiedName, "EffectCategory", info.EffectCategory, writer);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes the <c>EffectAuthor</c> property.
|
||||
/// </summary>
|
||||
/// <param name="info">The input <see cref="D2D1ShaderInfo"/> instance with gathered shader info.</param>
|
||||
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
|
||||
public static void WriteEffectAuthorSyntax(D2D1ShaderInfo info, IndentedTextWriter writer)
|
||||
{
|
||||
WriteEffectMetadataSyntax(info.Hierarchy.Hierarchy[0].QualifiedName, "EffectAuthor", info.EffectAuthor, writer);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes a specified metadata property.
|
||||
/// </summary>
|
||||
/// <param name="qualifiedName">The qualified name of the shader type.</param>
|
||||
/// <param name="propertyName">The property name to generate.</param>
|
||||
/// <param name="metadataValue">The input effect metadata value, if available.</param>
|
||||
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
|
||||
private static void WriteEffectMetadataSyntax(string qualifiedName, string propertyName, string? metadataValue, IndentedTextWriter writer)
|
||||
{
|
||||
writer.WriteLine("/// <inheritdoc/>");
|
||||
writer.WriteGeneratedAttributes(GeneratorName);
|
||||
writer.Write($"static string? global::ComputeSharp.D2D1.Descriptors.ID2D1PixelShaderDescriptor<{qualifiedName}>.{propertyName} => ");
|
||||
|
||||
// Append null or the metadata value as a string literal
|
||||
if (metadataValue is null)
|
||||
{
|
||||
writer.WriteLine("null;");
|
||||
}
|
||||
else
|
||||
{
|
||||
writer.WriteLine($"\"{metadataValue}\";");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
-98
@@ -1,98 +0,0 @@
|
||||
using ComputeSharp.D2D1.SourceGenerators.Helpers;
|
||||
using Microsoft.CodeAnalysis;
|
||||
|
||||
namespace ComputeSharp.D2D1.SourceGenerators;
|
||||
|
||||
/// <inheritdoc/>
|
||||
partial class D2DPixelShaderDescriptorGenerator
|
||||
{
|
||||
/// <summary>
|
||||
/// A helper with all logic to generate the effect metadata properties.
|
||||
/// </summary>
|
||||
private static partial class EffectMetadata
|
||||
{
|
||||
/// <summary>
|
||||
/// Extracts the effect display name info for the current shader.
|
||||
/// </summary>
|
||||
/// <param name="compilation">The input <see cref="Compilation"/> object currently in use.</param>
|
||||
/// <param name="structDeclarationSymbol">The <see cref="INamedTypeSymbol"/> for the shader type in use.</param>
|
||||
/// <returns>The resulting effect display name, if available.</returns>
|
||||
public static string? GetEffectDisplayNameInfo(Compilation compilation, INamedTypeSymbol structDeclarationSymbol)
|
||||
{
|
||||
if (D2D1EffectMetadataParser.TryGetEffectMetadataName(
|
||||
compilation,
|
||||
structDeclarationSymbol,
|
||||
"ComputeSharp.D2D1.D2DEffectDisplayNameAttribute",
|
||||
isAssemblyLevelAttributeSupported: false,
|
||||
out string? effectDisplayName))
|
||||
{
|
||||
return effectDisplayName;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Extracts the effect description info for the current shader.
|
||||
/// </summary>
|
||||
/// <param name="compilation">The input <see cref="Compilation"/> object currently in use.</param>
|
||||
/// <param name="structDeclarationSymbol">The <see cref="INamedTypeSymbol"/> for the shader type in use.</param>
|
||||
/// <returns>The resulting effect description, if available.</returns>
|
||||
public static string? GetEffectDescriptionInfo(Compilation compilation, INamedTypeSymbol structDeclarationSymbol)
|
||||
{
|
||||
if (D2D1EffectMetadataParser.TryGetEffectMetadataName(
|
||||
compilation,
|
||||
structDeclarationSymbol,
|
||||
"ComputeSharp.D2D1.D2DEffectDescriptionAttribute",
|
||||
isAssemblyLevelAttributeSupported: false,
|
||||
out string? effectDescription))
|
||||
{
|
||||
return effectDescription;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Extracts the effect category info for the current shader.
|
||||
/// </summary>
|
||||
/// <param name="compilation">The input <see cref="Compilation"/> object currently in use.</param>
|
||||
/// <param name="structDeclarationSymbol">The <see cref="INamedTypeSymbol"/> for the shader type in use.</param>
|
||||
/// <returns>The resulting effect category, if available.</returns>
|
||||
public static string? GetEffectCategoryInfo(Compilation compilation, INamedTypeSymbol structDeclarationSymbol)
|
||||
{
|
||||
if (D2D1EffectMetadataParser.TryGetEffectMetadataName(
|
||||
compilation,
|
||||
structDeclarationSymbol,
|
||||
"ComputeSharp.D2D1.D2DEffectCategoryAttribute",
|
||||
isAssemblyLevelAttributeSupported: true,
|
||||
out string? effectCategory))
|
||||
{
|
||||
return effectCategory;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Extracts the effect author info for the current shader.
|
||||
/// </summary>
|
||||
/// <param name="compilation">The input <see cref="Compilation"/> object currently in use.</param>
|
||||
/// <param name="structDeclarationSymbol">The <see cref="INamedTypeSymbol"/> for the shader type in use.</param>
|
||||
/// <returns>The resulting effect author, if available.</returns>
|
||||
public static string? GetEffectAuthorInfo(Compilation compilation, INamedTypeSymbol structDeclarationSymbol)
|
||||
{
|
||||
if (D2D1EffectMetadataParser.TryGetEffectMetadataName(
|
||||
compilation,
|
||||
structDeclarationSymbol,
|
||||
"ComputeSharp.D2D1.D2DEffectAuthorAttribute",
|
||||
isAssemblyLevelAttributeSupported: true,
|
||||
out string? effectAuthor))
|
||||
{
|
||||
return effectAuthor;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
-158
@@ -1,158 +0,0 @@
|
||||
using System.Linq;
|
||||
using ComputeSharp.D2D1.SourceGenerators.Models;
|
||||
using ComputeSharp.SourceGeneration.Extensions;
|
||||
using ComputeSharp.SourceGeneration.Helpers;
|
||||
using ComputeSharp.SourceGeneration.Models;
|
||||
using Microsoft.CodeAnalysis;
|
||||
|
||||
namespace ComputeSharp.D2D1.SourceGenerators;
|
||||
|
||||
/// <inheritdoc/>
|
||||
partial class D2DPixelShaderDescriptorGenerator
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
partial class HlslBytecode
|
||||
{
|
||||
/// <summary>
|
||||
/// Writes the <c>ShaderProfile</c> property.
|
||||
/// </summary>
|
||||
/// <param name="info">The input <see cref="D2D1ShaderInfo"/> instance with gathered shader info.</param>
|
||||
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
|
||||
public static void WriteShaderProfileSyntax(D2D1ShaderInfo info, IndentedTextWriter writer)
|
||||
{
|
||||
writer.WriteLine("/// <inheritdoc/>");
|
||||
writer.WriteGeneratedAttributes(GeneratorName);
|
||||
writer.WriteLine($"static ComputeSharp.D2D1.D2D1ShaderProfile global::ComputeSharp.D2D1.Descriptors.ID2D1PixelShaderDescriptor<{info.Hierarchy.Hierarchy[0].QualifiedName}>.ShaderProfile => global::ComputeSharp.D2D1.D2D1ShaderProfile.{info.HlslInfoKey.ShaderProfile};");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes the <c>CompileOptions</c> property.
|
||||
/// </summary>
|
||||
/// <param name="info">The input <see cref="D2D1ShaderInfo"/> instance with gathered shader info.</param>
|
||||
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
|
||||
public static void WriteCompileOptionsSyntax(D2D1ShaderInfo info, IndentedTextWriter writer)
|
||||
{
|
||||
// Get a formatted representation of the compile options being used
|
||||
string compileOptionsExpression =
|
||||
info.HlslInfoKey.CompileOptions
|
||||
.ToString()
|
||||
.Split(',')
|
||||
.Select(static name => $"global::ComputeSharp.D2D1.D2D1CompileOptions.{name.Trim()}")
|
||||
.Aggregate("", static (left, right) => left.Length > 0 ? $"{left} | {right}" : right);
|
||||
|
||||
writer.WriteLine("/// <inheritdoc/>");
|
||||
writer.WriteGeneratedAttributes(GeneratorName);
|
||||
writer.WriteLine($"static ComputeSharp.D2D1.D2D1CompileOptions global::ComputeSharp.D2D1.Descriptors.ID2D1PixelShaderDescriptor<{info.Hierarchy.Hierarchy[0].QualifiedName}>.CompileOptions => {compileOptionsExpression};");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes the <c>HlslBytecode</c> property.
|
||||
/// </summary>
|
||||
/// <param name="info">The input <see cref="D2D1ShaderInfo"/> instance with gathered shader info.</param>
|
||||
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
|
||||
public static void WriteHlslBytecodeSyntax(D2D1ShaderInfo info, IndentedTextWriter writer)
|
||||
{
|
||||
writer.WriteLine("/// <inheritdoc/>");
|
||||
writer.WriteGeneratedAttributes(GeneratorName);
|
||||
writer.Write($"static global::System.ReadOnlyMemory<byte> global::ComputeSharp.D2D1.Descriptors.ID2D1PixelShaderDescriptor<{info.Hierarchy.Hierarchy[0].QualifiedName}>.HlslBytecode => ");
|
||||
|
||||
// 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)
|
||||
{
|
||||
writer.WriteLine("default;");
|
||||
}
|
||||
else
|
||||
{
|
||||
writer.WriteLine("global::ComputeSharp.D2D1.Generated.HlslBytecodeMemoryManager.Instance.Memory;");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registers a callback to generate additional types, if needed.
|
||||
/// </summary>
|
||||
/// <param name="info">The input <see cref="D2D1ShaderInfo"/> instance with gathered shader info.</param>
|
||||
/// <param name="callbacks">The registered callbacks to generate additional types.</param>
|
||||
/// <param name="usingDirectives">The using directives needed by the generated code.</param>
|
||||
public static void RegisterAdditionalTypesSyntax(
|
||||
D2D1ShaderInfo info,
|
||||
ImmutableArrayBuilder<IndentedTextWriter.Callback<D2D1ShaderInfo>> callbacks,
|
||||
ImmutableHashSetBuilder<string> usingDirectives)
|
||||
{
|
||||
// If there is no bytecode, no memory manager is needed
|
||||
if (info.HlslInfo is not HlslBytecodeInfo.Success)
|
||||
{
|
||||
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($$"""/// <summary>""");
|
||||
writer.WriteLine($$"""/// <see cref="MemoryManager{T}"/> implementation to get the HLSL bytecode.""");
|
||||
writer.WriteLine($$"""/// </summary>""");
|
||||
writer.WriteGeneratedAttributes(GeneratorName, useFullyQualifiedTypeNames: false);
|
||||
writer.WriteLine($$"""file sealed class HlslBytecodeMemoryManager : MemoryManager<byte>""");
|
||||
|
||||
using (writer.WriteBlock())
|
||||
{
|
||||
// Static singleton instance (to avoid the static constructor, just like with the input types)
|
||||
writer.WriteLine($$"""/// <summary>The singleton <see cref="HlslBytecodeMemoryManager"/> instance to use.</summary>""");
|
||||
writer.WriteLine($$"""public static readonly HlslBytecodeMemoryManager Instance = new();""");
|
||||
|
||||
// RVA field (with the compiled HLSL bytecode, on a single line)
|
||||
writer.WriteLine();
|
||||
writer.WriteLine("/// <summary>The RVA data with the HLSL bytecode.</summary>");
|
||||
writer.Write("private static ReadOnlySpan<byte> Data => [");
|
||||
|
||||
SyntaxFormattingHelper.WriteByteArrayInitializationExpressions(((HlslBytecodeInfo.Success)info.HlslInfo).Bytecode.AsSpan(), writer);
|
||||
|
||||
writer.WriteLine("];");
|
||||
writer.WriteLine();
|
||||
|
||||
// Add the remaining members for the memory manager
|
||||
writer.WriteLine("""
|
||||
/// <inheritdoc/>
|
||||
public override unsafe Span<byte> GetSpan()
|
||||
{
|
||||
return new(Unsafe.AsPointer(ref MemoryMarshal.GetReference(Data)), Data.Length);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override Memory<byte> Memory
|
||||
{
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
get => CreateMemory(Data.Length);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override unsafe MemoryHandle Pin(int elementIndex)
|
||||
{
|
||||
return new(Unsafe.AsPointer(ref Unsafe.AsRef(in Data[elementIndex])), pinnable: this);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override void Unpin()
|
||||
{
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
}
|
||||
""", isMultiline: true);
|
||||
}
|
||||
}
|
||||
|
||||
callbacks.Add(Callback);
|
||||
}
|
||||
}
|
||||
}
|
||||
-86
@@ -1,86 +0,0 @@
|
||||
using ComputeSharp.SourceGeneration.Extensions;
|
||||
using Microsoft.CodeAnalysis;
|
||||
|
||||
namespace ComputeSharp.D2D1.SourceGenerators;
|
||||
|
||||
/// <inheritdoc/>
|
||||
partial class D2DPixelShaderDescriptorGenerator
|
||||
{
|
||||
/// <summary>
|
||||
/// A helper with all logic to generate the HLSL bytecode properties.
|
||||
/// </summary>
|
||||
internal static partial class HlslBytecode
|
||||
{
|
||||
/// <summary>
|
||||
/// Extracts the requested shader profile for the current shader.
|
||||
/// </summary>
|
||||
/// <param name="structDeclarationSymbol">The input <see cref="INamedTypeSymbol"/> instance to process.</param>
|
||||
/// <returns>The requested shader profile to use to compile the shader, if present.</returns>
|
||||
public static D2D1ShaderProfile? GetRequestedShaderProfile(INamedTypeSymbol structDeclarationSymbol)
|
||||
{
|
||||
if (structDeclarationSymbol.TryGetAttributeWithFullyQualifiedMetadataName("ComputeSharp.D2D1.D2DShaderProfileAttribute", out AttributeData? attributeData))
|
||||
{
|
||||
return (D2D1ShaderProfile)attributeData.ConstructorArguments[0].Value!;
|
||||
}
|
||||
|
||||
if (structDeclarationSymbol.ContainingAssembly.TryGetAttributeWithFullyQualifiedMetadataName("ComputeSharp.D2D1.D2DShaderProfileAttribute", out attributeData))
|
||||
{
|
||||
return (D2D1ShaderProfile)attributeData.ConstructorArguments[0].Value!;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Extracts the requested compile options for the current shader.
|
||||
/// </summary>
|
||||
/// <param name="structDeclarationSymbol">The input <see cref="INamedTypeSymbol"/> instance to process.</param>
|
||||
/// <returns>The requested compile options to use to compile the shader, if present.</returns>
|
||||
public static D2D1CompileOptions? GetRequestedCompileOptions(INamedTypeSymbol structDeclarationSymbol)
|
||||
{
|
||||
if (structDeclarationSymbol.TryGetAttributeWithFullyQualifiedMetadataName("ComputeSharp.D2D1.D2DCompileOptionsAttribute", out AttributeData? attributeData))
|
||||
{
|
||||
D2D1CompileOptions options = (D2D1CompileOptions)attributeData.ConstructorArguments[0].Value!;
|
||||
|
||||
// PackMatrixRowMajor is always automatically enabled. If by any chance the attribute is requesting
|
||||
// column major packing, the analyzer will emit a diagnostic (same as for the assembly-level case).
|
||||
return options | D2D1CompileOptions.PackMatrixRowMajor;
|
||||
}
|
||||
|
||||
if (structDeclarationSymbol.ContainingAssembly.TryGetAttributeWithFullyQualifiedMetadataName("ComputeSharp.D2D1.D2DCompileOptionsAttribute", out attributeData))
|
||||
{
|
||||
// No need to validate against PackMatrixColumnMajor as that's checked separately
|
||||
return (D2D1CompileOptions)attributeData.ConstructorArguments[0].Value! | D2D1CompileOptions.PackMatrixRowMajor;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the effective shader profile to use.
|
||||
/// </summary>
|
||||
/// <param name="shaderProfile">The requested shader profile.</param>
|
||||
/// <param name="isCompilationEnabled">Whether compilation should be performed with the input profile.</param>
|
||||
/// <returns>The effective shader profile.</returns>
|
||||
public static D2D1ShaderProfile GetEffectiveShaderProfile(D2D1ShaderProfile? shaderProfile, out bool isCompilationEnabled)
|
||||
{
|
||||
// Compilation is only enabled if the user explicitly selected a shader profile
|
||||
isCompilationEnabled = shaderProfile is not null;
|
||||
|
||||
// The effective shader profile is either be the requested one, or the default value (which maps to PS5.0)
|
||||
return shaderProfile ?? D2D1ShaderProfile.PixelShader50;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the effective compile options to use.
|
||||
/// </summary>
|
||||
/// <param name="compileOptions">The requested compile options.</param>
|
||||
/// <returns>The effective compile options.</returns>
|
||||
public static D2D1CompileOptions GetEffectiveCompileOptions(D2D1CompileOptions? compileOptions)
|
||||
{
|
||||
// If an explicit set of compile options is provided, use that directly. Otherwise, use the default
|
||||
// options plus the option to enable linking only if the shader can potentially support it.
|
||||
return compileOptions ?? D2D1CompileOptions.Default;
|
||||
}
|
||||
}
|
||||
}
|
||||
-31
@@ -1,31 +0,0 @@
|
||||
using ComputeSharp.D2D1.SourceGenerators.Models;
|
||||
using ComputeSharp.SourceGeneration.Extensions;
|
||||
using ComputeSharp.SourceGeneration.Helpers;
|
||||
|
||||
namespace ComputeSharp.D2D1.SourceGenerators;
|
||||
|
||||
/// <inheritdoc/>
|
||||
partial class D2DPixelShaderDescriptorGenerator
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
partial class HlslSource
|
||||
{
|
||||
/// <summary>
|
||||
/// Writes the <c>HlslSource</c> property.
|
||||
/// </summary>
|
||||
/// <param name="info">The input <see cref="D2D1ShaderInfo"/> instance with gathered shader info.</param>
|
||||
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
|
||||
public static void WriteSyntax(D2D1ShaderInfo info, IndentedTextWriter writer)
|
||||
{
|
||||
writer.WriteLine("/// <inheritdoc/>");
|
||||
writer.WriteGeneratedAttributes(GeneratorName);
|
||||
writer.WriteLine($"static string global::ComputeSharp.D2D1.Descriptors.ID2D1PixelShaderDescriptor<{info.Hierarchy.Hierarchy[0].QualifiedName}>.HlslSource =>");
|
||||
writer.IncreaseIndent();
|
||||
writer.WriteLine("\"\"\"");
|
||||
writer.Write(info.HlslInfoKey.HlslSource, isMultiline: true);
|
||||
writer.WriteLine(skipIfPresent: true);
|
||||
writer.WriteLine("\"\"\";");
|
||||
writer.DecreaseIndent();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,539 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Immutable;
|
||||
using System.Threading;
|
||||
using ComputeSharp.SourceGeneration.Extensions;
|
||||
using ComputeSharp.SourceGeneration.Helpers;
|
||||
using ComputeSharp.SourceGeneration.Mappings;
|
||||
using ComputeSharp.SourceGeneration.Models;
|
||||
using ComputeSharp.SourceGeneration.SyntaxProcessors;
|
||||
using ComputeSharp.SourceGeneration.SyntaxRewriters;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.CSharp;
|
||||
using Microsoft.CodeAnalysis.CSharp.Syntax;
|
||||
using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors;
|
||||
|
||||
namespace ComputeSharp.D2D1.SourceGenerators;
|
||||
|
||||
/// <inheritdoc/>
|
||||
partial class D2DPixelShaderDescriptorGenerator
|
||||
{
|
||||
/// <summary>
|
||||
/// A helper with all logic to generate the <c>HlslSource</c> property.
|
||||
/// </summary>
|
||||
private static partial class HlslSource
|
||||
{
|
||||
/// <summary>
|
||||
/// Gathers all necessary information on a transpiled HLSL source for a given shader type.
|
||||
/// </summary>
|
||||
/// <param name="diagnostics">The collection of produced <see cref="DiagnosticInfo"/> instances.</param>
|
||||
/// <param name="compilation">The input <see cref="Compilation"/> object currently in use.</param>
|
||||
/// <param name="structDeclarationSymbol">The <see cref="INamedTypeSymbol"/> for the shader type.</param>
|
||||
/// <param name="shaderInterfaceType">The shader interface type implemented by the shader type.</param>
|
||||
/// <param name="inputCount">The number of inputs for the shader.</param>
|
||||
/// <param name="inputSimpleIndices">The indices of the simple shader inputs.</param>
|
||||
/// <param name="inputComplexIndices">The indices of the complex shader inputs.</param>
|
||||
/// <param name="token">The <see cref="CancellationToken"/> used to cancel the operation, if needed.</param>
|
||||
/// <returns>The HLSL source for the shader.</returns>
|
||||
public static string GetHlslSource(
|
||||
ImmutableArrayBuilder<DiagnosticInfo> diagnostics,
|
||||
Compilation compilation,
|
||||
INamedTypeSymbol structDeclarationSymbol,
|
||||
INamedTypeSymbol shaderInterfaceType,
|
||||
int inputCount,
|
||||
ImmutableArray<int> inputSimpleIndices,
|
||||
ImmutableArray<int> inputComplexIndices,
|
||||
CancellationToken token)
|
||||
{
|
||||
// Detect any invalid properties
|
||||
HlslDefinitionsSyntaxProcessor.DetectAndReportInvalidPropertyDeclarations(diagnostics, structDeclarationSymbol);
|
||||
|
||||
token.ThrowIfCancellationRequested();
|
||||
|
||||
// We need to sets to track all discovered custom types and static methods
|
||||
HashSet<INamedTypeSymbol> discoveredTypes = new(SymbolEqualityComparer.Default);
|
||||
Dictionary<IMethodSymbol, MethodDeclarationSyntax> staticMethods = new(SymbolEqualityComparer.Default);
|
||||
Dictionary<IMethodSymbol, MethodDeclarationSyntax> instanceMethods = new(SymbolEqualityComparer.Default);
|
||||
Dictionary<IMethodSymbol, (MethodDeclarationSyntax, MethodDeclarationSyntax)> constructors = new(SymbolEqualityComparer.Default);
|
||||
Dictionary<IFieldSymbol, string> constantDefinitions = new(SymbolEqualityComparer.Default);
|
||||
Dictionary<IFieldSymbol, HlslStaticField> staticFieldDefinitions = new(SymbolEqualityComparer.Default);
|
||||
|
||||
token.ThrowIfCancellationRequested();
|
||||
|
||||
// Extract information on all captured fields
|
||||
GetInstanceFields(
|
||||
diagnostics,
|
||||
structDeclarationSymbol,
|
||||
discoveredTypes,
|
||||
out ImmutableArray<HlslValueField> valueFields,
|
||||
out ImmutableArray<HlslResourceTextureField> resourceTextureFields);
|
||||
|
||||
token.ThrowIfCancellationRequested();
|
||||
|
||||
SemanticModelProvider semanticModelProvider = new(compilation);
|
||||
|
||||
// Explore the syntax tree and extract the processed info
|
||||
(string entryPoint, ImmutableArray<HlslMethod> processedMethods) = GetProcessedMethods(
|
||||
diagnostics,
|
||||
structDeclarationSymbol,
|
||||
shaderInterfaceType,
|
||||
semanticModelProvider,
|
||||
discoveredTypes,
|
||||
staticMethods,
|
||||
instanceMethods,
|
||||
constructors,
|
||||
constantDefinitions,
|
||||
staticFieldDefinitions,
|
||||
token,
|
||||
out bool methodsNeedD2D1RequiresScenePosition);
|
||||
|
||||
token.ThrowIfCancellationRequested();
|
||||
|
||||
ImmutableArray<HlslStaticField> staticFields = GetStaticFields(
|
||||
diagnostics,
|
||||
semanticModelProvider,
|
||||
structDeclarationSymbol,
|
||||
discoveredTypes,
|
||||
constantDefinitions,
|
||||
staticFieldDefinitions,
|
||||
token,
|
||||
out bool fieldsNeedD2D1RequiresScenePosition);
|
||||
|
||||
token.ThrowIfCancellationRequested();
|
||||
|
||||
// Process the discovered types and constants
|
||||
HlslDefinitionsSyntaxProcessor.GetDeclaredTypes(
|
||||
diagnostics,
|
||||
structDeclarationSymbol,
|
||||
discoveredTypes,
|
||||
instanceMethods,
|
||||
constructors,
|
||||
out ImmutableArray<HlslUserType> typeDeclarations,
|
||||
out ImmutableArray<string> typeMethodDeclarations);
|
||||
|
||||
token.ThrowIfCancellationRequested();
|
||||
|
||||
ImmutableArray<HlslConstant> definedConstants = HlslDefinitionsSyntaxProcessor.GetDefinedConstants(constantDefinitions);
|
||||
|
||||
token.ThrowIfCancellationRequested();
|
||||
|
||||
// Check whether the scene position is required
|
||||
bool requiresScenePosition = GetD2DRequiresScenePositionInfo(structDeclarationSymbol);
|
||||
|
||||
// Emit diagnostics for incorrect scene position uses
|
||||
ReportInvalidD2DRequiresScenePositionUse(
|
||||
diagnostics,
|
||||
structDeclarationSymbol,
|
||||
requiresScenePosition,
|
||||
methodsNeedD2D1RequiresScenePosition || fieldsNeedD2D1RequiresScenePosition);
|
||||
|
||||
token.ThrowIfCancellationRequested();
|
||||
|
||||
// Get the HLSL source
|
||||
return GetHlslSource(
|
||||
definedConstants,
|
||||
valueFields,
|
||||
resourceTextureFields,
|
||||
staticFields,
|
||||
processedMethods,
|
||||
typeDeclarations,
|
||||
typeMethodDeclarations,
|
||||
entryPoint,
|
||||
inputCount,
|
||||
inputSimpleIndices,
|
||||
inputComplexIndices,
|
||||
requiresScenePosition);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a sequence of captured fields and their mapped names.
|
||||
/// </summary>
|
||||
/// <param name="diagnostics">The collection of produced <see cref="DiagnosticInfo"/> instances.</param>
|
||||
/// <param name="structDeclarationSymbol">The input <see cref="INamedTypeSymbol"/> instance to process.</param>
|
||||
/// <param name="types">The collection of currently discovered types.</param>
|
||||
/// <param name="valueFields">The sequence of captured fields in <paramref name="structDeclarationSymbol"/>.</param>
|
||||
/// <param name="resourceTextureFields">The sequence of captured resource textures in <paramref name="structDeclarationSymbol"/>.</param>
|
||||
private static void GetInstanceFields(
|
||||
ImmutableArrayBuilder<DiagnosticInfo> diagnostics,
|
||||
INamedTypeSymbol structDeclarationSymbol,
|
||||
ICollection<INamedTypeSymbol> types,
|
||||
out ImmutableArray<HlslValueField> valueFields,
|
||||
out ImmutableArray<HlslResourceTextureField> resourceTextureFields)
|
||||
{
|
||||
using ImmutableArrayBuilder<HlslValueField> values = new();
|
||||
using ImmutableArrayBuilder<HlslResourceTextureField> resourceTextures = new();
|
||||
|
||||
foreach (ISymbol memberSymbol in structDeclarationSymbol.GetMembers())
|
||||
{
|
||||
// Skip constants and static fields, we only care about instance ones here
|
||||
if (memberSymbol is not IFieldSymbol { IsConst: false, IsStatic: false } fieldSymbol)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
// Try to get the actual field name
|
||||
if (!ConstantBufferSyntaxProcessor.TryGetFieldAccessorName(fieldSymbol, out string? fieldName, out _))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
// Captured fields must be named type symbols
|
||||
if (fieldSymbol.Type is not INamedTypeSymbol typeSymbol)
|
||||
{
|
||||
diagnostics.Add(InvalidShaderField, fieldSymbol, structDeclarationSymbol, fieldName, fieldSymbol.Type);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
string metadataName = typeSymbol.GetFullyQualifiedMetadataName();
|
||||
string typeName = HlslKnownTypes.GetMappedName(typeSymbol);
|
||||
|
||||
_ = HlslKnownKeywords.TryGetMappedName(fieldName, out string? mapping);
|
||||
|
||||
// Handle resource textures as a special case
|
||||
if (HlslKnownTypes.IsResourceTextureType(metadataName))
|
||||
{
|
||||
ITypeSymbol resourceTextureTypeArgumentSymbol = typeSymbol.TypeArguments[0];
|
||||
|
||||
// Validate that the type argument is only either float or float4
|
||||
if (!resourceTextureTypeArgumentSymbol.HasFullyQualifiedMetadataName("System.Single") &&
|
||||
!resourceTextureTypeArgumentSymbol.HasFullyQualifiedMetadataName("ComputeSharp.Float4"))
|
||||
{
|
||||
diagnostics.Add(
|
||||
InvalidResourceTextureElementType,
|
||||
fieldSymbol,
|
||||
fieldName,
|
||||
structDeclarationSymbol,
|
||||
fieldSymbol.Type);
|
||||
}
|
||||
|
||||
int index = 0;
|
||||
|
||||
// If [D2DResourceTextureIndex] is present, get the resource texture index.
|
||||
// This generator doesn't need to emit diagnostics, as that's handled separately
|
||||
// by the logic handling the info gathering for LoadResourceTextureDescriptions.
|
||||
if (fieldSymbol.TryGetAttributeWithFullyQualifiedMetadataName("ComputeSharp.D2D1.D2DResourceTextureIndexAttribute", out AttributeData? attributeData))
|
||||
{
|
||||
_ = attributeData.TryGetConstructorArgument(0, out index);
|
||||
}
|
||||
|
||||
resourceTextures.Add((mapping ?? fieldName, typeName, index));
|
||||
}
|
||||
else if (typeSymbol.IsUnmanagedType)
|
||||
{
|
||||
// Allowed fields must be unmanaged values.
|
||||
// Also, track the type if it's a custom struct.
|
||||
if (!HlslKnownTypes.IsKnownHlslType(metadataName))
|
||||
{
|
||||
types.Add(typeSymbol);
|
||||
}
|
||||
|
||||
values.Add((mapping ?? fieldName, typeName));
|
||||
}
|
||||
else
|
||||
{
|
||||
diagnostics.Add(InvalidShaderField, fieldSymbol, structDeclarationSymbol, fieldName, typeSymbol);
|
||||
}
|
||||
}
|
||||
|
||||
valueFields = values.ToImmutable();
|
||||
resourceTextureFields = resourceTextures.ToImmutable();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a sequence of shader static fields and their mapped names.
|
||||
/// </summary>
|
||||
/// <param name="diagnostics">The collection of produced <see cref="DiagnosticInfo"/> instances.</param>
|
||||
/// <param name="semanticModel">The <see cref="SemanticModelProvider"/> instance for the type to process.</param>
|
||||
/// <param name="structDeclarationSymbol">The type symbol for the shader type.</param>
|
||||
/// <param name="discoveredTypes">The collection of currently discovered types.</param>
|
||||
/// <param name="constantDefinitions">The collection of discovered constant definitions.</param>
|
||||
/// <param name="staticFieldDefinitions">The collection of discovered static field definitions.</param>
|
||||
/// <param name="token">The <see cref="CancellationToken"/> used to cancel the operation, if needed.</param>
|
||||
/// <param name="needsD2D1RequiresScenePosition">Whether or not the shader needs the <c>[D2DRequiresScenePosition]</c> annotation.</param>
|
||||
/// <returns>A sequence of static constant fields in <paramref name="structDeclarationSymbol"/>.</returns>
|
||||
private static ImmutableArray<HlslStaticField> GetStaticFields(
|
||||
ImmutableArrayBuilder<DiagnosticInfo> diagnostics,
|
||||
SemanticModelProvider semanticModel,
|
||||
INamedTypeSymbol structDeclarationSymbol,
|
||||
ICollection<INamedTypeSymbol> discoveredTypes,
|
||||
IDictionary<IFieldSymbol, string> constantDefinitions,
|
||||
IDictionary<IFieldSymbol, HlslStaticField> staticFieldDefinitions,
|
||||
CancellationToken token,
|
||||
out bool needsD2D1RequiresScenePosition)
|
||||
{
|
||||
using ImmutableArrayBuilder<HlslStaticField> builder = new();
|
||||
|
||||
needsD2D1RequiresScenePosition = false;
|
||||
|
||||
foreach (ISymbol memberSymbol in structDeclarationSymbol.GetMembers())
|
||||
{
|
||||
if (memberSymbol is not IFieldSymbol fieldSymbol)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (HlslDefinitionsSyntaxProcessor.TryGetStaticField(
|
||||
structDeclarationSymbol,
|
||||
fieldSymbol,
|
||||
semanticModel,
|
||||
discoveredTypes,
|
||||
constantDefinitions,
|
||||
staticFieldDefinitions,
|
||||
diagnostics,
|
||||
token,
|
||||
out string? name,
|
||||
out string? typeDeclaration,
|
||||
out string? assignmentExpression,
|
||||
out StaticFieldRewriter? staticFieldRewriter))
|
||||
{
|
||||
needsD2D1RequiresScenePosition |= staticFieldRewriter.NeedsD2DRequiresScenePositionAttribute;
|
||||
|
||||
builder.Add((name, typeDeclaration, assignmentExpression));
|
||||
}
|
||||
}
|
||||
|
||||
// Also gather the external static fields (same as in the DX12 generator)
|
||||
foreach (HlslStaticField externalField in staticFieldDefinitions.Values)
|
||||
{
|
||||
builder.Add(externalField);
|
||||
}
|
||||
|
||||
return builder.ToImmutable();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a sequence of processed methods declared within a given type.
|
||||
/// </summary>
|
||||
/// <param name="diagnostics">The collection of produced <see cref="DiagnosticInfo"/> instances.</param>
|
||||
/// <param name="structDeclarationSymbol">The type symbol for the shader type.</param>
|
||||
/// <param name="shaderInterfaceType">The shader interface type implemented by the shader type.</param>
|
||||
/// <param name="semanticModel">The <see cref="SemanticModelProvider"/> instance for the type to process.</param>
|
||||
/// <param name="discoveredTypes">The collection of currently discovered types.</param>
|
||||
/// <param name="staticMethods">The set of discovered and processed static methods.</param>
|
||||
/// <param name="instanceMethods">The collection of discovered instance methods for custom struct types.</param>
|
||||
/// <param name="constructors">The collection of discovered constructors for custom struct types.</param>
|
||||
/// <param name="constantDefinitions">The collection of discovered constant definitions.</param>
|
||||
/// <param name="staticFieldDefinitions">The collection of discovered static field definitions.</param>
|
||||
/// <param name="needsD2D1RequiresScenePosition">Whether or not the shader needs the <c>[D2DRequiresScenePosition]</c> annotation.</param>
|
||||
/// <param name="token">The <see cref="CancellationToken"/> used to cancel the operation, if needed.</param>
|
||||
/// <returns>A sequence of processed methods in <paramref name="structDeclarationSymbol"/>, and the entry point.</returns>
|
||||
private static (string EntryPoint, ImmutableArray<HlslMethod> Methods) GetProcessedMethods(
|
||||
ImmutableArrayBuilder<DiagnosticInfo> diagnostics,
|
||||
INamedTypeSymbol structDeclarationSymbol,
|
||||
INamedTypeSymbol shaderInterfaceType,
|
||||
SemanticModelProvider semanticModel,
|
||||
ICollection<INamedTypeSymbol> discoveredTypes,
|
||||
IDictionary<IMethodSymbol, MethodDeclarationSyntax> staticMethods,
|
||||
IDictionary<IMethodSymbol, MethodDeclarationSyntax> instanceMethods,
|
||||
IDictionary<IMethodSymbol, (MethodDeclarationSyntax, MethodDeclarationSyntax)> constructors,
|
||||
IDictionary<IFieldSymbol, string> constantDefinitions,
|
||||
IDictionary<IFieldSymbol, HlslStaticField> staticFieldDefinitions,
|
||||
CancellationToken token,
|
||||
out bool needsD2D1RequiresScenePosition)
|
||||
{
|
||||
using ImmutableArrayBuilder<HlslMethod> methods = new();
|
||||
|
||||
IMethodSymbol entryPointInterfaceMethod = shaderInterfaceType.GetMethod("Execute")!;
|
||||
string? entryPoint = null;
|
||||
|
||||
// By default, the scene position is not required. We will set this while
|
||||
// rewriting HLSL, if any method we traverse ends up requiring the position.
|
||||
needsD2D1RequiresScenePosition = false;
|
||||
|
||||
foreach (ISymbol memberSymbol in structDeclarationSymbol.GetMembers())
|
||||
{
|
||||
// Find all declared methods in the type
|
||||
if (memberSymbol is not IMethodSymbol { IsImplicitlyDeclared: false, } methodSymbol)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
// Ensure that we have accessible source information
|
||||
if (!methodSymbol.TryGetSyntaxNode(token, out MethodDeclarationSyntax? methodDeclaration))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
// Check whether the current method is the entry point (ie. it's implementing 'Execute').
|
||||
// This is the same logic as in the DX12 generator for compute shaders and pixel shaders.
|
||||
bool isShaderEntryPoint = SymbolEqualityComparer.Default.Equals(
|
||||
structDeclarationSymbol.FindImplementationForInterfaceMember(entryPointInterfaceMethod),
|
||||
methodSymbol);
|
||||
|
||||
// Except for the entry point, ignore explicit interface implementations
|
||||
if (!isShaderEntryPoint && !methodSymbol.ExplicitInterfaceImplementations.IsDefaultOrEmpty)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
token.ThrowIfCancellationRequested();
|
||||
|
||||
// Create the source rewriter for the current method
|
||||
ShaderSourceRewriter shaderSourceRewriter = new(
|
||||
structDeclarationSymbol,
|
||||
semanticModel,
|
||||
discoveredTypes,
|
||||
staticMethods,
|
||||
instanceMethods,
|
||||
constructors,
|
||||
constantDefinitions,
|
||||
staticFieldDefinitions,
|
||||
diagnostics,
|
||||
token,
|
||||
isShaderEntryPoint);
|
||||
|
||||
// Rewrite the method syntax tree
|
||||
MethodDeclarationSyntax? processedMethod = shaderSourceRewriter.Visit(methodDeclaration)!.WithoutTrivia();
|
||||
|
||||
token.ThrowIfCancellationRequested();
|
||||
|
||||
// Update the position requirement
|
||||
needsD2D1RequiresScenePosition |= shaderSourceRewriter.NeedsD2DRequiresScenePositionAttribute;
|
||||
|
||||
// Emit the extracted local functions first
|
||||
foreach (KeyValuePair<string, LocalFunctionStatementSyntax> localFunction in shaderSourceRewriter.LocalFunctions)
|
||||
{
|
||||
methods.Add((
|
||||
localFunction.Value.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(),
|
||||
localFunction.Value.NormalizeWhitespace(eol: "\n").ToFullString()));
|
||||
}
|
||||
|
||||
// If the method is the shader entry point, do additional processing
|
||||
if (isShaderEntryPoint)
|
||||
{
|
||||
string entryPointDeclaration = processedMethod.NormalizeWhitespace(eol: "\n").ToFullString();
|
||||
string adjustedEntryPointDeclaration = entryPointDeclaration.Replace("float4 Execute()", "D2D_PS_ENTRY(Execute)");
|
||||
|
||||
entryPoint = adjustedEntryPointDeclaration;
|
||||
}
|
||||
else
|
||||
{
|
||||
methods.Add((
|
||||
processedMethod.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(),
|
||||
processedMethod.NormalizeWhitespace(eol: "\n").ToFullString()));
|
||||
}
|
||||
}
|
||||
|
||||
token.ThrowIfCancellationRequested();
|
||||
|
||||
// Process static methods as well
|
||||
foreach (MethodDeclarationSyntax staticMethod in staticMethods.Values)
|
||||
{
|
||||
methods.Add((
|
||||
staticMethod.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(),
|
||||
staticMethod.NormalizeWhitespace(eol: "\n").ToFullString()));
|
||||
}
|
||||
|
||||
return (entryPoint!, methods.ToImmutable());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reports diagnostics for invalid uses of <c>[D2DRequiresScenePosition]</c> in a shader.
|
||||
/// </summary>
|
||||
/// <param name="diagnostics">The collection of produced <see cref="DiagnosticInfo"/> instances.</param>
|
||||
/// <param name="structDeclarationSymbol">The input <see cref="INamedTypeSymbol"/> instance to process.</param>
|
||||
/// <param name="requiresScenePosition">Whether the shader type is declaring the need for scene position.</param>
|
||||
/// <param name="usesPositionDependentMethods">Whether the shader is using APIs that rely on scene position.</param>
|
||||
private static void ReportInvalidD2DRequiresScenePositionUse(
|
||||
ImmutableArrayBuilder<DiagnosticInfo> diagnostics,
|
||||
INamedTypeSymbol structDeclarationSymbol,
|
||||
bool requiresScenePosition,
|
||||
bool usesPositionDependentMethods)
|
||||
{
|
||||
if (!requiresScenePosition && usesPositionDependentMethods)
|
||||
{
|
||||
diagnostics.Add(MissingD2DRequiresScenePositionAttribute, structDeclarationSymbol, structDeclarationSymbol);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets whether or not a given shader requires the scene position.
|
||||
/// </summary>
|
||||
/// <param name="structDeclarationSymbol">The input <see cref="INamedTypeSymbol"/> instance to process.</param>
|
||||
/// <remarks>Whether <paramref name="structDeclarationSymbol"/> requires the scene position.</remarks>
|
||||
private static bool GetD2DRequiresScenePositionInfo(INamedTypeSymbol structDeclarationSymbol)
|
||||
{
|
||||
return structDeclarationSymbol.TryGetAttributeWithFullyQualifiedMetadataName("ComputeSharp.D2D1.D2DRequiresScenePositionAttribute", out _);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Produces the series of statements to build the current HLSL source.
|
||||
/// </summary>
|
||||
/// <param name="definedConstants"><inheritdoc cref="HlslSourceSyntaxProcessor.WriteTopDeclarations" path="/param[@name='definedConstants']/node()"/></param>
|
||||
/// <param name="valueFields"><inheritdoc cref="HlslSourceSyntaxProcessor.WriteCapturedFields" path="/param[@name='valueFields']/node()"/></param>
|
||||
/// <param name="resourceTextureFields">The sequence of captured resource textures for the current shader.</param>
|
||||
/// <param name="staticFields"><inheritdoc cref="HlslSourceSyntaxProcessor.WriteTopDeclarations" path="/param[@name='staticFields']/node()"/></param>
|
||||
/// <param name="processedMethods"><inheritdoc cref="HlslSourceSyntaxProcessor.WriteTopDeclarations" path="/param[@name='processedMethods']/node()"/></param>
|
||||
/// <param name="typeDeclarations"><inheritdoc cref="HlslSourceSyntaxProcessor.WriteTopDeclarations" path="/param[@name='typeDeclarations']/node()"/></param>
|
||||
/// <param name="typeMethodDeclarations"><inheritdoc cref="HlslSourceSyntaxProcessor.WriteMethodDeclarations" path="/param[@name='typeMethodDeclarations']/node()"/></param>
|
||||
/// <param name="executeMethod">The body of the entry point of the shader.</param>
|
||||
/// <param name="inputCount">The number of shader inputs to declare.</param>
|
||||
/// <param name="inputSimpleIndices">The indices of the simple shader inputs.</param>
|
||||
/// <param name="inputComplexIndices">The indices of the complex shader inputs.</param>
|
||||
/// <param name="requiresScenePosition">Whether the shader requires the scene position.</param>
|
||||
/// <returns>The series of statements to build the HLSL source to compile to execute the current shader.</returns>
|
||||
private static string GetHlslSource(
|
||||
ImmutableArray<HlslConstant> definedConstants,
|
||||
ImmutableArray<HlslValueField> valueFields,
|
||||
ImmutableArray<HlslResourceTextureField> resourceTextureFields,
|
||||
ImmutableArray<HlslStaticField> staticFields,
|
||||
ImmutableArray<HlslMethod> processedMethods,
|
||||
ImmutableArray<HlslUserType> typeDeclarations,
|
||||
ImmutableArray<string> typeMethodDeclarations,
|
||||
string executeMethod,
|
||||
int inputCount,
|
||||
ImmutableArray<int> inputSimpleIndices,
|
||||
ImmutableArray<int> inputComplexIndices,
|
||||
bool requiresScenePosition)
|
||||
{
|
||||
using IndentedTextWriter writer = new();
|
||||
|
||||
// Shader metadata
|
||||
writer.WriteLine($"#define D2D_INPUT_COUNT {inputCount}");
|
||||
|
||||
foreach (int simpleInput in inputSimpleIndices)
|
||||
{
|
||||
writer.WriteLine($"#define D2D_INPUT{simpleInput}_SIMPLE");
|
||||
}
|
||||
|
||||
foreach (int complexInput in inputComplexIndices)
|
||||
{
|
||||
writer.WriteLine($"#define D2D_INPUT{complexInput}_COMPLEX");
|
||||
}
|
||||
|
||||
writer.WriteLineIf(requiresScenePosition, "#define D2D_REQUIRES_SCENE_POSITION");
|
||||
|
||||
// Add the "d2d1effecthelpers.hlsli" header
|
||||
writer.WriteLine();
|
||||
writer.WriteLine("#include \"d2d1effecthelpers.hlsli\"");
|
||||
writer.WriteLine();
|
||||
|
||||
// The FXC compiler does not support type forward declarations
|
||||
HlslSourceSyntaxProcessor.WriteTopDeclarations(
|
||||
writer,
|
||||
definedConstants,
|
||||
staticFields,
|
||||
processedMethods,
|
||||
typeDeclarations,
|
||||
includeTypeForwardDeclarations: false);
|
||||
|
||||
HlslSourceSyntaxProcessor.WriteCapturedFields(writer, valueFields);
|
||||
|
||||
// Resource textures
|
||||
foreach (HlslResourceTextureField field in resourceTextureFields)
|
||||
{
|
||||
writer.WriteLine(skipIfPresent: true);
|
||||
writer.WriteLine($"{field.Type} {field.Name} : register(t{field.Index});");
|
||||
writer.WriteLine($"SamplerState __sampler__{field.Name} : register(s{field.Index});");
|
||||
}
|
||||
|
||||
HlslSourceSyntaxProcessor.WriteMethodDeclarations(writer, processedMethods, typeMethodDeclarations);
|
||||
|
||||
// Entry point
|
||||
writer.WriteLine(executeMethod);
|
||||
|
||||
return writer.ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
-145
@@ -1,145 +0,0 @@
|
||||
using ComputeSharp.D2D1.SourceGenerators.Models;
|
||||
using ComputeSharp.SourceGeneration.Extensions;
|
||||
using ComputeSharp.SourceGeneration.Helpers;
|
||||
|
||||
#pragma warning disable IDE0053
|
||||
|
||||
namespace ComputeSharp.D2D1.SourceGenerators;
|
||||
|
||||
/// <inheritdoc/>
|
||||
partial class D2DPixelShaderDescriptorGenerator
|
||||
{
|
||||
/// <inheritoc/>
|
||||
private static partial class InputDescriptions
|
||||
{
|
||||
/// <summary>
|
||||
/// Writes the <c>InputDescriptions</c> property.
|
||||
/// </summary>
|
||||
/// <param name="info">The input <see cref="D2D1ShaderInfo"/> instance with gathered shader info.</param>
|
||||
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
|
||||
public static void WriteSyntax(D2D1ShaderInfo info, IndentedTextWriter writer)
|
||||
{
|
||||
writer.WriteLine("/// <inheritdoc/>");
|
||||
writer.WriteGeneratedAttributes(GeneratorName);
|
||||
writer.Write($"static global::System.ReadOnlyMemory<global::ComputeSharp.D2D1.Interop.D2D1InputDescription> global::ComputeSharp.D2D1.Descriptors.ID2D1PixelShaderDescriptor<{info.Hierarchy.Hierarchy[0].QualifiedName}>.InputDescriptions => ");
|
||||
|
||||
// If there are no input descriptions, just return a default expression.
|
||||
// Otherwise, return the shared array with cached input descriptions.
|
||||
if (info.InputDescriptions.IsEmpty)
|
||||
{
|
||||
writer.WriteLine("default;");
|
||||
}
|
||||
else
|
||||
{
|
||||
writer.WriteLine("global::ComputeSharp.D2D1.Generated.Data.InputDescriptions;");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registers a callback to generate additional types, if needed.
|
||||
/// </summary>
|
||||
/// <param name="info">The input <see cref="D2D1ShaderInfo"/> instance with gathered shader info.</param>
|
||||
/// <param name="callbacks">The registered callbacks to generate additional types.</param>
|
||||
/// <param name="usingDirectives">The using directives needed by the generated code.</param>
|
||||
public static void RegisterAdditionalTypesSyntax(
|
||||
D2D1ShaderInfo info,
|
||||
ImmutableArrayBuilder<IndentedTextWriter.Callback<D2D1ShaderInfo>> callbacks,
|
||||
ImmutableHashSetBuilder<string> usingDirectives)
|
||||
{
|
||||
// If there are no necessary data members, stop here
|
||||
if (info.InputDescriptions.IsEmpty &&
|
||||
info.ResourceTextureDescriptions.IsEmpty)
|
||||
{
|
||||
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($$"""/// <summary>""");
|
||||
writer.WriteLine($$"""/// A container type for additional data needed by the shader.""");
|
||||
writer.WriteLine($$"""/// </summary>""");
|
||||
writer.WriteGeneratedAttributes(GeneratorName, useFullyQualifiedTypeNames: false);
|
||||
writer.WriteLine($$"""file static class Data""");
|
||||
|
||||
using (writer.WriteBlock())
|
||||
{
|
||||
using ImmutableArrayBuilder<IndentedTextWriter.Callback<D2D1ShaderInfo>> dataMembers = new();
|
||||
|
||||
RegisterAdditionalDataMemberSyntax(info, dataMembers);
|
||||
ResourceTextureDescriptions.RegisterAdditionalDataMemberSyntax(info, dataMembers);
|
||||
|
||||
for (int i = 0; i < dataMembers.WrittenSpan.Length; i++)
|
||||
{
|
||||
dataMembers.WrittenSpan[i](info, writer);
|
||||
|
||||
if (i < dataMembers.WrittenSpan.Length - 1)
|
||||
{
|
||||
writer.WriteLine();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
callbacks.Add(Callback);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds any using directives for the additional data member, if needed.
|
||||
/// </summary>
|
||||
/// <param name="info">The input <see cref="D2D1ShaderInfo"/> instance with gathered shader info.</param>
|
||||
/// <param name="usingDirectives">The using directives needed by the generated code.</param>
|
||||
private static void AddAdditionalDataMemberUsingDirectives(D2D1ShaderInfo info, ImmutableHashSetBuilder<string> usingDirectives)
|
||||
{
|
||||
if (info.InputDescriptions.IsEmpty)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_ = usingDirectives.Add("global::ComputeSharp.D2D1");
|
||||
_ = usingDirectives.Add("global::ComputeSharp.D2D1.Interop");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registers a callback to generate an additional data member, if needed.
|
||||
/// </summary>
|
||||
/// <param name="info">The input <see cref="D2D1ShaderInfo"/> instance with gathered shader info.</param>
|
||||
/// <param name="callbacks">The registered callbacks to generate additional data members.</param>
|
||||
private static void RegisterAdditionalDataMemberSyntax(D2D1ShaderInfo info, ImmutableArrayBuilder<IndentedTextWriter.Callback<D2D1ShaderInfo>> callbacks)
|
||||
{
|
||||
// If there are no input descriptions, there is nothing to di
|
||||
if (info.InputDescriptions.IsEmpty)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Declare the shared array with input descriptions
|
||||
static void Callback(D2D1ShaderInfo info, IndentedTextWriter writer)
|
||||
{
|
||||
writer.WriteLine("""/// <summary>The singleton <see cref="D2D1InputDescription"/> array instance.</summary>""");
|
||||
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 D2D1InputDescription({{description.Index}}, D2D1Filter.{{description.Filter}}) { LevelOfDetailCount = {{description.LevelOfDetailCount}} }""");
|
||||
});
|
||||
|
||||
writer.DecreaseIndent();
|
||||
writer.WriteLine();
|
||||
writer.WriteLine("];");
|
||||
}
|
||||
|
||||
callbacks.Add(Callback);
|
||||
}
|
||||
}
|
||||
}
|
||||
-44
@@ -1,44 +0,0 @@
|
||||
using System.Collections.Immutable;
|
||||
using ComputeSharp.D2D1.SourceGenerators.Models;
|
||||
using ComputeSharp.SourceGeneration.Extensions;
|
||||
using ComputeSharp.SourceGeneration.Helpers;
|
||||
using Microsoft.CodeAnalysis;
|
||||
|
||||
namespace ComputeSharp.D2D1.SourceGenerators;
|
||||
|
||||
/// <inheritdoc/>
|
||||
partial class D2DPixelShaderDescriptorGenerator
|
||||
{
|
||||
/// <summary>
|
||||
/// A helper with all logic to generate the <c>InputDescriptions</c> property.
|
||||
/// </summary>
|
||||
private static partial class InputDescriptions
|
||||
{
|
||||
/// <summary>
|
||||
/// Extracts the input descriptions for the current shader.
|
||||
/// </summary>
|
||||
/// <param name="structDeclarationSymbol">The input <see cref="INamedTypeSymbol"/> instance to process.</param>
|
||||
/// <param name="inputDescriptions">The produced input descriptions for the shader.</param>
|
||||
public static void GetInfo(
|
||||
INamedTypeSymbol structDeclarationSymbol,
|
||||
out ImmutableArray<InputDescription> inputDescriptions)
|
||||
{
|
||||
using ImmutableArrayBuilder<InputDescription> builder = new();
|
||||
|
||||
foreach (AttributeData attributeData in structDeclarationSymbol.GetAttributes())
|
||||
{
|
||||
if (attributeData.AttributeClass?.HasFullyQualifiedMetadataName("ComputeSharp.D2D1.D2DInputDescriptionAttribute") == true)
|
||||
{
|
||||
int index = (int)attributeData.ConstructorArguments[0].Value!;
|
||||
D2D1Filter filter = (D2D1Filter)attributeData.ConstructorArguments[1].Value!;
|
||||
|
||||
_ = attributeData.TryGetNamedArgument("LevelOfDetailCount", out int levelOfDetailCount);
|
||||
|
||||
builder.Add(new InputDescription(index, filter, levelOfDetailCount));
|
||||
}
|
||||
}
|
||||
|
||||
inputDescriptions = builder.ToImmutable();
|
||||
}
|
||||
}
|
||||
}
|
||||
-133
@@ -1,133 +0,0 @@
|
||||
using ComputeSharp.D2D1.SourceGenerators.Models;
|
||||
using ComputeSharp.SourceGeneration.Extensions;
|
||||
using ComputeSharp.SourceGeneration.Helpers;
|
||||
|
||||
namespace ComputeSharp.D2D1.SourceGenerators;
|
||||
|
||||
/// <inheritdoc/>
|
||||
partial class D2DPixelShaderDescriptorGenerator
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
partial class InputTypes
|
||||
{
|
||||
/// <summary>
|
||||
/// Writes the <c>InputTypes</c> property.
|
||||
/// </summary>
|
||||
/// <param name="info">The input <see cref="D2D1ShaderInfo"/> instance with gathered shader info.</param>
|
||||
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
|
||||
public static void WriteSyntax(D2D1ShaderInfo info, IndentedTextWriter writer)
|
||||
{
|
||||
writer.WriteLine("/// <inheritdoc/>");
|
||||
writer.WriteGeneratedAttributes(GeneratorName);
|
||||
writer.Write($"static global::System.ReadOnlyMemory<global::ComputeSharp.D2D1.Interop.D2D1PixelShaderInputType> global::ComputeSharp.D2D1.Descriptors.ID2D1PixelShaderDescriptor<{info.Hierarchy.Hierarchy[0].QualifiedName}>.InputTypes => ");
|
||||
|
||||
// If there are no inputs, simply return a default expression. Otherwise, create
|
||||
// a ReadOnlyMemory<D2D1PixelShaderInputType> instance from the memory manager.
|
||||
if (info.InputTypes.IsEmpty)
|
||||
{
|
||||
writer.WriteLine("default;");
|
||||
}
|
||||
else
|
||||
{
|
||||
writer.WriteLine("global::ComputeSharp.D2D1.Generated.InputTypesMemoryManager.Instance.Memory;");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registers a callback to generate additional types, if needed.
|
||||
/// </summary>
|
||||
/// <param name="info">The input <see cref="D2D1ShaderInfo"/> instance with gathered shader info.</param>
|
||||
/// <param name="callbacks">The registered callbacks to generate additional types.</param>
|
||||
/// <param name="usingDirectives">The using directives needed by the generated code.</param>
|
||||
public static void RegisterAdditionalTypesSyntax(
|
||||
D2D1ShaderInfo info,
|
||||
ImmutableArrayBuilder<IndentedTextWriter.Callback<D2D1ShaderInfo>> callbacks,
|
||||
ImmutableHashSetBuilder<string> usingDirectives)
|
||||
{
|
||||
// If there are no inputs, no memory manager is needed
|
||||
if (info.InputTypes.IsEmpty)
|
||||
{
|
||||
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($$"""/// <summary>""");
|
||||
writer.WriteLine($$"""/// A <see cref="MemoryManager{T}"/> implementation to get the input types.""");
|
||||
writer.WriteLine($$"""/// </summary>""");
|
||||
writer.WriteGeneratedAttributes(GeneratorName, useFullyQualifiedTypeNames: false);
|
||||
writer.WriteLine($$"""file sealed class InputTypesMemoryManager : MemoryManager<D2D1PixelShaderInputType>""");
|
||||
|
||||
using (writer.WriteBlock())
|
||||
{
|
||||
// Static singleton instance (the object goes in the frozen heap, so there's no static constructor)
|
||||
writer.WriteLine($$"""/// <summary>The singleton <see cref="InputTypesMemoryManager"/> instance to use.</summary>""");
|
||||
writer.WriteLine($$"""public static readonly InputTypesMemoryManager Instance = new();""");
|
||||
|
||||
// RVA field
|
||||
writer.WriteLine();
|
||||
writer.WriteLine("/// <summary>The RVA data with the input type info.</summary>");
|
||||
writer.WriteLine("private static ReadOnlySpan<D2D1PixelShaderInputType> Data =>");
|
||||
writer.WriteLine("[");
|
||||
writer.IncreaseIndent();
|
||||
|
||||
// Input types, one per line in the RVA field initializer
|
||||
writer.WriteInitializationExpressions(info.InputTypes.AsSpan(), static (type, writer) =>
|
||||
{
|
||||
writer.Write("D2D1PixelShaderInputType.");
|
||||
writer.Write(type == 0 ? "Simple" : "Complex");
|
||||
});
|
||||
|
||||
writer.DecreaseIndent();
|
||||
writer.WriteLine();
|
||||
writer.WriteLine("];");
|
||||
writer.WriteLine();
|
||||
|
||||
// Add the remaining members for the memory manager
|
||||
writer.WriteLine("""
|
||||
/// <inheritdoc/>
|
||||
public override unsafe Span<D2D1PixelShaderInputType> GetSpan()
|
||||
{
|
||||
return new(Unsafe.AsPointer(ref MemoryMarshal.GetReference(Data)), Data.Length);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override Memory<D2D1PixelShaderInputType> Memory
|
||||
{
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
get => CreateMemory(Data.Length);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override unsafe MemoryHandle Pin(int elementIndex)
|
||||
{
|
||||
return new(Unsafe.AsPointer(ref Unsafe.AsRef(in Data[elementIndex])), pinnable: this);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override void Unpin()
|
||||
{
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
}
|
||||
""", isMultiline: true);
|
||||
}
|
||||
}
|
||||
|
||||
callbacks.Add(Callback);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,93 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Immutable;
|
||||
using System.Runtime.CompilerServices;
|
||||
using ComputeSharp.SourceGeneration.Extensions;
|
||||
using ComputeSharp.SourceGeneration.Helpers;
|
||||
using Microsoft.CodeAnalysis;
|
||||
|
||||
namespace ComputeSharp.D2D1.SourceGenerators;
|
||||
|
||||
/// <inheritdoc/>
|
||||
partial class D2DPixelShaderDescriptorGenerator
|
||||
{
|
||||
/// <summary>
|
||||
/// A helper with all logic to generate the <c>InputTypes</c> properties.
|
||||
/// </summary>
|
||||
internal static partial class InputTypes
|
||||
{
|
||||
/// <summary>
|
||||
/// Extracts the input info for the current shader.
|
||||
/// </summary>
|
||||
/// <param name="structDeclarationSymbol">The input <see cref="INamedTypeSymbol"/> instance to process.</param>
|
||||
/// <param name="inputCount">The number of shader inputs to declare.</param>
|
||||
/// <param name="inputSimpleIndices">The indicess of the simple shader inputs.</param>
|
||||
/// <param name="inputComplexIndices">The indices of the complex shader inputs.</param>
|
||||
/// <param name="combinedInputTypes">The combined and serialized input types for each available input.</param>
|
||||
public static void GetInfo(
|
||||
INamedTypeSymbol structDeclarationSymbol,
|
||||
out int inputCount,
|
||||
out ImmutableArray<int> inputSimpleIndices,
|
||||
out ImmutableArray<int> inputComplexIndices,
|
||||
out ImmutableArray<uint> combinedInputTypes)
|
||||
{
|
||||
// Note: this logic is shared with InvalidD2DResourceTextureIndexAttributeUseAnalyzer.
|
||||
// If any changes are made here, they should be reflected in that analyzer as well.
|
||||
inputCount = 0;
|
||||
|
||||
using ImmutableArrayBuilder<int> inputSimpleIndicesBuilder = new();
|
||||
using ImmutableArrayBuilder<int> inputComplexIndicesBuilder = new();
|
||||
|
||||
foreach (AttributeData attributeData in structDeclarationSymbol.GetAttributes())
|
||||
{
|
||||
using ImmutableArrayBuilder<char> builder = new();
|
||||
|
||||
attributeData.AttributeClass?.AppendFullyQualifiedMetadataName(in builder);
|
||||
|
||||
switch (builder.WrittenSpan)
|
||||
{
|
||||
case "ComputeSharp.D2D1.D2DInputCountAttribute":
|
||||
|
||||
// We ignore negative values here to avoid the rest of the generator crashing due
|
||||
// to out of bound exceptions or other issues. The analyzer will detect this and
|
||||
// emit a diagnostic if that's the case, so it is safe to ignore that from here.
|
||||
inputCount = Math.Max((int)attributeData.ConstructorArguments[0].Value!, 0);
|
||||
break;
|
||||
case "ComputeSharp.D2D1.D2DInputSimpleAttribute":
|
||||
inputSimpleIndicesBuilder.Add((int)attributeData.ConstructorArguments[0].Value!);
|
||||
break;
|
||||
case "ComputeSharp.D2D1.D2DInputComplexAttribute":
|
||||
inputComplexIndicesBuilder.Add((int)attributeData.ConstructorArguments[0].Value!);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
inputSimpleIndices = inputSimpleIndicesBuilder.ToImmutable();
|
||||
inputComplexIndices = inputComplexIndicesBuilder.ToImmutable();
|
||||
|
||||
uint[] inputTypes = new uint[inputCount];
|
||||
|
||||
// The D2D_INPUT<N>_SIMPLE define is optional, and if omitted, the corresponding input
|
||||
// will automatically be of complex type. For the same reason, D2D_INPUT<N>_COMPLEX is
|
||||
// also essentially redundant. So we can do the following to compute the input types:
|
||||
// - Create an array with as many inputs as the declared number of inputs
|
||||
// - Fill it with 1 (ie. D2D1PixelShaderInputType.Complex), as that's the default
|
||||
// - Traverse the declared simple inputs once, and update their corresponding values
|
||||
inputTypes.AsSpan().Fill(1);
|
||||
|
||||
foreach (int index in inputSimpleIndicesBuilder.WrittenSpan)
|
||||
{
|
||||
// Simply ignore any out of range indices here, to avoid throwing an exception.
|
||||
// The analyzer will detect all of these cases and correctly issue a diagnostic.
|
||||
if ((uint)index < inputCount)
|
||||
{
|
||||
inputTypes[index] = 0;
|
||||
}
|
||||
}
|
||||
|
||||
// We own the array, so we can just reinterpret it here
|
||||
combinedInputTypes = Unsafe.As<uint[], ImmutableArray<uint>>(ref inputTypes);
|
||||
}
|
||||
}
|
||||
}
|
||||
-51
@@ -1,51 +0,0 @@
|
||||
using ComputeSharp.D2D1.SourceGenerators.Models;
|
||||
using ComputeSharp.SourceGeneration.Extensions;
|
||||
using ComputeSharp.SourceGeneration.Helpers;
|
||||
|
||||
namespace ComputeSharp.D2D1.SourceGenerators;
|
||||
|
||||
/// <inheritdoc/>
|
||||
partial class D2DPixelShaderDescriptorGenerator
|
||||
{
|
||||
/// <summary>
|
||||
/// A helper with all logic to generate the available numeric properties.
|
||||
/// </summary>
|
||||
private static class NumericProperties
|
||||
{
|
||||
/// <summary>
|
||||
/// Writes the <c>ConstantBufferSize</c> property.
|
||||
/// </summary>
|
||||
/// <param name="info">The input <see cref="D2D1ShaderInfo"/> instance with gathered shader info.</param>
|
||||
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
|
||||
public static void WriteConstantBufferSizeSyntax(D2D1ShaderInfo info, IndentedTextWriter writer)
|
||||
{
|
||||
writer.WriteLine("/// <inheritdoc/>");
|
||||
writer.WriteGeneratedAttributes(GeneratorName);
|
||||
writer.WriteLine($"static int global::ComputeSharp.D2D1.Descriptors.ID2D1PixelShaderDescriptor<{info.Hierarchy.Hierarchy[0].QualifiedName}>.ConstantBufferSize => {info.ConstantBufferSizeInBytes};");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes the <c>InputCount</c> property.
|
||||
/// </summary>
|
||||
/// <param name="info">The input <see cref="D2D1ShaderInfo"/> instance with gathered shader info.</param>
|
||||
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
|
||||
public static void WriteInputCountSyntax(D2D1ShaderInfo info, IndentedTextWriter writer)
|
||||
{
|
||||
writer.WriteLine("/// <inheritdoc/>");
|
||||
writer.WriteGeneratedAttributes(GeneratorName);
|
||||
writer.WriteLine($"static int global::ComputeSharp.D2D1.Descriptors.ID2D1PixelShaderDescriptor<{info.Hierarchy.Hierarchy[0].QualifiedName}>.InputCount => {info.InputTypes.Length};");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes the <c>ResourceTextureCount</c> property.
|
||||
/// </summary>
|
||||
/// <param name="info">The input <see cref="D2D1ShaderInfo"/> instance with gathered shader info.</param>
|
||||
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
|
||||
public static void WriteResourceTextureCountSyntax(D2D1ShaderInfo info, IndentedTextWriter writer)
|
||||
{
|
||||
writer.WriteLine("/// <inheritdoc/>");
|
||||
writer.WriteGeneratedAttributes(GeneratorName);
|
||||
writer.WriteLine($"static int global::ComputeSharp.D2D1.Descriptors.ID2D1PixelShaderDescriptor<{info.Hierarchy.Hierarchy[0].QualifiedName}>.ResourceTextureCount => {info.ResourceTextureDescriptions.Length};");
|
||||
}
|
||||
}
|
||||
}
|
||||
-53
@@ -1,53 +0,0 @@
|
||||
using System;
|
||||
using ComputeSharp.D2D1.SourceGenerators.Models;
|
||||
using ComputeSharp.SourceGeneration.Extensions;
|
||||
using ComputeSharp.SourceGeneration.Helpers;
|
||||
|
||||
namespace ComputeSharp.D2D1.SourceGenerators;
|
||||
|
||||
/// <inheritdoc/>
|
||||
partial class D2DPixelShaderDescriptorGenerator
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
partial class OutputBuffer
|
||||
{
|
||||
/// <summary>
|
||||
/// Writes the <c>BufferPrecision</c> property.
|
||||
/// </summary>
|
||||
/// <param name="info">The input <see cref="D2D1ShaderInfo"/> instance with gathered shader info.</param>
|
||||
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
|
||||
public static void WriteBufferPrecisionSyntax(D2D1ShaderInfo info, IndentedTextWriter writer)
|
||||
{
|
||||
// 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
|
||||
{
|
||||
true => $"global::ComputeSharp.D2D1.D2D1BufferPrecision.{info.BufferPrecision}",
|
||||
false => "default"
|
||||
};
|
||||
|
||||
writer.WriteLine("/// <inheritdoc/>");
|
||||
writer.WriteGeneratedAttributes(GeneratorName);
|
||||
writer.WriteLine($"static ComputeSharp.D2D1.D2D1BufferPrecision global::ComputeSharp.D2D1.Descriptors.ID2D1PixelShaderDescriptor<{info.Hierarchy.Hierarchy[0].QualifiedName}>.BufferPrecision => {bufferPrecisionExpression};");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes the <c>ChannelDepth</c> property.
|
||||
/// </summary>
|
||||
/// <param name="info">The input <see cref="D2D1ShaderInfo"/> instance with gathered shader info.</param>
|
||||
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
|
||||
public static void WriteChannelDepthSyntax(D2D1ShaderInfo info, IndentedTextWriter writer)
|
||||
{
|
||||
// Set the right expression if the buffer options are valid
|
||||
string channelDepthExpression = Enum.IsDefined(typeof(D2D1ChannelDepth), info.ChannelDepth) switch
|
||||
{
|
||||
true => $"global::ComputeSharp.D2D1.D2D1ChannelDepth.{info.ChannelDepth}",
|
||||
false => "default"
|
||||
};
|
||||
|
||||
writer.WriteLine("/// <inheritdoc/>");
|
||||
writer.WriteGeneratedAttributes(GeneratorName);
|
||||
writer.WriteLine($"static ComputeSharp.D2D1.D2D1ChannelDepth global::ComputeSharp.D2D1.Descriptors.ID2D1PixelShaderDescriptor<{info.Hierarchy.Hierarchy[0].QualifiedName}>.ChannelDepth => {channelDepthExpression};");
|
||||
}
|
||||
}
|
||||
}
|
||||
-62
@@ -1,62 +0,0 @@
|
||||
using ComputeSharp.SourceGeneration.Extensions;
|
||||
using Microsoft.CodeAnalysis;
|
||||
|
||||
namespace ComputeSharp.D2D1.SourceGenerators;
|
||||
|
||||
/// <inheritdoc/>
|
||||
partial class D2DPixelShaderDescriptorGenerator
|
||||
{
|
||||
/// <summary>
|
||||
/// A helper with all logic to generate the output buffer properties.
|
||||
/// </summary>
|
||||
private static partial class OutputBuffer
|
||||
{
|
||||
/// <summary>
|
||||
/// Extracts the output buffer info for the current shader.
|
||||
/// </summary>
|
||||
/// <param name="structDeclarationSymbol">The input <see cref="INamedTypeSymbol"/> instance to process.</param>
|
||||
/// <param name="bufferPrecision">The output buffer precision for the shader.</param>
|
||||
/// <param name="channelDepth">The output buffer channel depth for the shader.</param>
|
||||
public static void GetInfo(
|
||||
INamedTypeSymbol structDeclarationSymbol,
|
||||
out D2D1BufferPrecision bufferPrecision,
|
||||
out D2D1ChannelDepth channelDepth)
|
||||
{
|
||||
// Try to get the [D2DOutputBuffer] attribute
|
||||
if (!structDeclarationSymbol.TryGetAttributeWithFullyQualifiedMetadataName("ComputeSharp.D2D1.D2DOutputBufferAttribute", out AttributeData? attributeData))
|
||||
{
|
||||
bufferPrecision = D2D1BufferPrecision.Unknown;
|
||||
channelDepth = D2D1ChannelDepth.Default;
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// Extract the buffer precision and channel depth, if available
|
||||
if (attributeData.ConstructorArguments.Length == 1)
|
||||
{
|
||||
if (attributeData.AttributeConstructor is IMethodSymbol { Parameters.Length: 1 } constructorSymbol &&
|
||||
constructorSymbol.Parameters[0].Type.HasFullyQualifiedMetadataName("ComputeSharp.D2D1.D2D1BufferPrecision"))
|
||||
{
|
||||
bufferPrecision = (D2D1BufferPrecision)attributeData.ConstructorArguments[0].Value!;
|
||||
channelDepth = D2D1ChannelDepth.Default;
|
||||
}
|
||||
else
|
||||
{
|
||||
bufferPrecision = D2D1BufferPrecision.Unknown;
|
||||
channelDepth = (D2D1ChannelDepth)attributeData.ConstructorArguments[0].Value!;
|
||||
}
|
||||
}
|
||||
else if (attributeData.ConstructorArguments.Length == 2)
|
||||
{
|
||||
bufferPrecision = (D2D1BufferPrecision)attributeData.ConstructorArguments[0].Value!;
|
||||
channelDepth = (D2D1ChannelDepth)attributeData.ConstructorArguments[1].Value!;
|
||||
}
|
||||
else
|
||||
{
|
||||
// The syntax tree is likely invalid, so just ignore it for now
|
||||
bufferPrecision = D2D1BufferPrecision.Unknown;
|
||||
channelDepth = D2D1ChannelDepth.Default;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
-52
@@ -1,52 +0,0 @@
|
||||
using ComputeSharp.D2D1.SourceGenerators.Models;
|
||||
using ComputeSharp.SourceGeneration.Extensions;
|
||||
using ComputeSharp.SourceGeneration.Helpers;
|
||||
using Microsoft.CodeAnalysis;
|
||||
|
||||
namespace ComputeSharp.D2D1.SourceGenerators;
|
||||
|
||||
/// <inheritdoc/>
|
||||
partial class D2DPixelShaderDescriptorGenerator
|
||||
{
|
||||
/// <summary>
|
||||
/// A helper with all logic to generate the <c>PixelOptions</c> property.
|
||||
/// </summary>
|
||||
private static class PixelOptions
|
||||
{
|
||||
/// <summary>
|
||||
/// Extracts the pixel options for the current shader.
|
||||
/// </summary>
|
||||
/// <param name="structDeclarationSymbol">The input <see cref="INamedTypeSymbol"/> instance to process.</param>
|
||||
/// <param name="pixelOptions">The pixel options for the shader.</param>
|
||||
public static void GetInfo(INamedTypeSymbol structDeclarationSymbol, out D2D1PixelOptions pixelOptions)
|
||||
{
|
||||
if (structDeclarationSymbol.TryGetAttributeWithFullyQualifiedMetadataName("ComputeSharp.D2D1.D2DPixelOptionsAttribute", out AttributeData? attributeData))
|
||||
{
|
||||
pixelOptions = (D2D1PixelOptions)attributeData.ConstructorArguments[0].Value!;
|
||||
}
|
||||
else
|
||||
{
|
||||
pixelOptions = D2D1PixelOptions.None;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes the <c>PixelOptions</c> property.
|
||||
/// </summary>
|
||||
/// <param name="info">The input <see cref="D2D1ShaderInfo"/> instance with gathered shader info.</param>
|
||||
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
|
||||
public static void WriteSyntax(D2D1ShaderInfo info, IndentedTextWriter writer)
|
||||
{
|
||||
// Set the right expression if the pixel options are valid
|
||||
string pixelOptionsExpression = (info.PixelOptions is D2D1PixelOptions.None or D2D1PixelOptions.TrivialSampling) switch
|
||||
{
|
||||
true => $"global::ComputeSharp.D2D1.D2D1PixelOptions.{info.PixelOptions}",
|
||||
false => "default"
|
||||
};
|
||||
|
||||
writer.WriteLine("/// <inheritdoc/>");
|
||||
writer.WriteGeneratedAttributes(GeneratorName);
|
||||
writer.WriteLine($"static ComputeSharp.D2D1.D2D1PixelOptions global::ComputeSharp.D2D1.Descriptors.ID2D1PixelShaderDescriptor<{info.Hierarchy.Hierarchy[0].QualifiedName}>.PixelOptions => {pixelOptionsExpression};");
|
||||
}
|
||||
}
|
||||
}
|
||||
-88
@@ -1,88 +0,0 @@
|
||||
using ComputeSharp.D2D1.SourceGenerators.Models;
|
||||
using ComputeSharp.SourceGeneration.Extensions;
|
||||
using ComputeSharp.SourceGeneration.Helpers;
|
||||
|
||||
#pragma warning disable IDE0053
|
||||
|
||||
namespace ComputeSharp.D2D1.SourceGenerators;
|
||||
|
||||
/// <inheritdoc/>
|
||||
partial class D2DPixelShaderDescriptorGenerator
|
||||
{
|
||||
/// <inheritoc/>
|
||||
private static partial class ResourceTextureDescriptions
|
||||
{
|
||||
/// <summary>
|
||||
/// Writes the <c>ResourceTextureDescriptions</c> property.
|
||||
/// </summary>
|
||||
/// <param name="info">The input <see cref="D2D1ShaderInfo"/> instance with gathered shader info.</param>
|
||||
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
|
||||
public static void WriteSyntax(D2D1ShaderInfo info, IndentedTextWriter writer)
|
||||
{
|
||||
writer.WriteLine("/// <inheritdoc/>");
|
||||
writer.WriteGeneratedAttributes(GeneratorName);
|
||||
writer.Write($"static global::System.ReadOnlyMemory<global::ComputeSharp.D2D1.Interop.D2D1ResourceTextureDescription> global::ComputeSharp.D2D1.Descriptors.ID2D1PixelShaderDescriptor<{info.Hierarchy.Hierarchy[0].QualifiedName}>.ResourceTextureDescriptions => ");
|
||||
|
||||
// If there are no resource texture descriptions, just return a default expression.
|
||||
// Otherwise, return a memory instance from the generated static readonly array.
|
||||
if (info.ResourceTextureDescriptions.IsEmpty)
|
||||
{
|
||||
writer.WriteLine("default;");
|
||||
}
|
||||
else
|
||||
{
|
||||
writer.WriteLine("global::ComputeSharp.D2D1.Generated.Data.ResourceTextureDescriptions;");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds any using directives for the additional data member, if needed.
|
||||
/// </summary>
|
||||
/// <param name="info">The input <see cref="D2D1ShaderInfo"/> instance with gathered shader info.</param>
|
||||
/// <param name="usingDirectives">The using directives needed by the generated code.</param>
|
||||
public static void AddAdditionalDataMemberUsingDirectives(D2D1ShaderInfo info, ImmutableHashSetBuilder<string> usingDirectives)
|
||||
{
|
||||
if (info.ResourceTextureDescriptions.IsEmpty)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_ = usingDirectives.Add("global::ComputeSharp.D2D1.Interop");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registers a callback to generate an additional data member, if needed.
|
||||
/// </summary>
|
||||
/// <param name="info">The input <see cref="D2D1ShaderInfo"/> instance with gathered shader info.</param>
|
||||
/// <param name="callbacks">The registered callbacks to generate additional data members.</param>
|
||||
public static void RegisterAdditionalDataMemberSyntax(D2D1ShaderInfo info, ImmutableArrayBuilder<IndentedTextWriter.Callback<D2D1ShaderInfo>> callbacks)
|
||||
{
|
||||
// If there are no resource texture descriptions, there is nothing to di
|
||||
if (info.ResourceTextureDescriptions.IsEmpty)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Declare the shared array with resource texture descriptions
|
||||
static void Callback(D2D1ShaderInfo info, IndentedTextWriter writer)
|
||||
{
|
||||
writer.WriteLine("""/// <summary>The singleton <see cref="D2D1ResourceTextureDescription"/> array instance.</summary>""");
|
||||
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 D2D1ResourceTextureDescription({description.Index}, {description.Rank})");
|
||||
});
|
||||
|
||||
writer.DecreaseIndent();
|
||||
writer.WriteLine();
|
||||
writer.WriteLine("];");
|
||||
}
|
||||
|
||||
callbacks.Add(Callback);
|
||||
}
|
||||
}
|
||||
}
|
||||
-67
@@ -1,67 +0,0 @@
|
||||
using System.Collections.Immutable;
|
||||
using ComputeSharp.D2D1.SourceGenerators.Models;
|
||||
using ComputeSharp.SourceGeneration.Extensions;
|
||||
using ComputeSharp.SourceGeneration.Helpers;
|
||||
using ComputeSharp.SourceGeneration.Mappings;
|
||||
using Microsoft.CodeAnalysis;
|
||||
|
||||
namespace ComputeSharp.D2D1.SourceGenerators;
|
||||
|
||||
/// <inheritdoc/>
|
||||
partial class D2DPixelShaderDescriptorGenerator
|
||||
{
|
||||
/// <summary>
|
||||
/// A helper with all logic to generate the <c>ResourceTextureDescriptions</c> property.
|
||||
/// </summary>
|
||||
private static partial class ResourceTextureDescriptions
|
||||
{
|
||||
/// <summary>
|
||||
/// Extracts the resource texture descriptions for the current shader.
|
||||
/// </summary>
|
||||
/// <param name="structDeclarationSymbol">The input <see cref="INamedTypeSymbol"/> instance to process.</param>
|
||||
/// <param name="resourceTextureDescriptions">The produced resource texture descriptions for the shader.</param>
|
||||
public static void GetInfo(
|
||||
INamedTypeSymbol structDeclarationSymbol,
|
||||
out ImmutableArray<ResourceTextureDescription> resourceTextureDescriptions)
|
||||
{
|
||||
using ImmutableArrayBuilder<ResourceTextureDescription> builder = new();
|
||||
|
||||
foreach (ISymbol memberSymbol in structDeclarationSymbol.GetMembers().OfType<IFieldSymbol>())
|
||||
{
|
||||
// Only look for fields of a named type symbol (diagnostics is emitted by the HLSL rewriter if it's not the case).
|
||||
// We're only looking for instance fields of unmanaged types in this case (as resource textures are structs).
|
||||
if (memberSymbol is not IFieldSymbol { IsStatic: false, Type: INamedTypeSymbol { IsUnmanagedType: true, IsGenericType: true } typeSymbol } fieldSymbol)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
string metadataName = typeSymbol.GetFullyQualifiedMetadataName();
|
||||
|
||||
// Check that the field is a resource texture type (if not, it will be processed by the HLSL rewriter too)
|
||||
if (HlslKnownTypes.IsResourceTextureType(metadataName))
|
||||
{
|
||||
// The type name will be ComputeSharp.D2D1.D2D1ResourceTexture1D`1 or the 2D/3D versions.
|
||||
// To avoid the intermediate string and the parsing, we can rely on the fact the metadata
|
||||
// has already been validated here, so we can get the rank by offsetting the characters.
|
||||
int rank = metadataName[^4] - '0';
|
||||
int? index = null;
|
||||
|
||||
// Get the index from the [D2DResourceTextureIndex] attribute over the field
|
||||
if (fieldSymbol.TryGetAttributeWithFullyQualifiedMetadataName("ComputeSharp.D2D1.D2DResourceTextureIndexAttribute", out AttributeData? attributeData))
|
||||
{
|
||||
// If the constructor argument isn't available, it means the code is invalid. Just do nothing then, as the
|
||||
// user will have to fix that to get the code to compile anyway. This way the generator won't crash too.
|
||||
if (attributeData.TryGetConstructorArgument(0, out int resourceIndex))
|
||||
{
|
||||
index = resourceIndex;
|
||||
}
|
||||
}
|
||||
|
||||
builder.Add(new ResourceTextureDescription(index ?? 0, rank));
|
||||
}
|
||||
}
|
||||
|
||||
resourceTextureDescriptions = builder.ToImmutable();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,278 +0,0 @@
|
||||
using System.Collections.Immutable;
|
||||
using System.ComponentModel;
|
||||
using System.Linq;
|
||||
using ComputeSharp.D2D1.SourceGenerators.Models;
|
||||
using ComputeSharp.SourceGeneration.Constants;
|
||||
using ComputeSharp.SourceGeneration.Extensions;
|
||||
using ComputeSharp.SourceGeneration.Helpers;
|
||||
using ComputeSharp.SourceGeneration.Models;
|
||||
using ComputeSharp.SourceGeneration.SyntaxProcessors;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.CSharp.Syntax;
|
||||
|
||||
namespace ComputeSharp.D2D1.SourceGenerators;
|
||||
|
||||
/// <summary>
|
||||
/// A source generator creating pixel shader descriptors for annotated D2D1 pixel shader types.
|
||||
/// </summary>
|
||||
[Generator(LanguageNames.CSharp)]
|
||||
public sealed partial class D2DPixelShaderDescriptorGenerator : IIncrementalGenerator
|
||||
{
|
||||
/// <summary>
|
||||
/// The name of generator to include in the generated code.
|
||||
/// </summary>
|
||||
private const string GeneratorName = "ComputeSharp.D2D1.D2DPixelShaderDescriptorGenerator";
|
||||
|
||||
/// <inheritdoc/>
|
||||
public void Initialize(IncrementalGeneratorInitializationContext context)
|
||||
{
|
||||
// Discover all shader types and extract all the necessary info from each of them
|
||||
IncrementalValuesProvider<D2D1ShaderInfo> shaderInfo =
|
||||
context.SyntaxProvider
|
||||
.ForAttributeWithMetadataName(
|
||||
"ComputeSharp.D2D1.D2DGeneratedPixelShaderDescriptorAttribute",
|
||||
static (node, _) => node.IsTypeDeclarationWithOrPotentiallyWithBaseTypes<StructDeclarationSyntax>(),
|
||||
static (context, token) =>
|
||||
{
|
||||
// The source generator requires unsafe blocks to be enabled (eg. for pointers, [SkipLocalsInit], etc.)
|
||||
if (!context.SemanticModel.Compilation.IsAllowUnsafeBlocksEnabled())
|
||||
{
|
||||
return default;
|
||||
}
|
||||
|
||||
// If the type symbol doesn't have at least one interface, it can't possibly be a shader type.
|
||||
// Also check for generic types, just like with DX12 shaders (including nesting inside generics).
|
||||
if (context.TargetSymbol is not INamedTypeSymbol { AllInterfaces.Length: > 0, IsGenericType: false } typeSymbol)
|
||||
{
|
||||
return default;
|
||||
}
|
||||
|
||||
// Immediately bail if the target type doesn't have internal accessibility
|
||||
if (!typeSymbol.IsAccessibleFromContainingAssembly(context.SemanticModel.Compilation))
|
||||
{
|
||||
return default;
|
||||
}
|
||||
|
||||
INamedTypeSymbol shaderInterfaceType = context.SemanticModel.Compilation.GetTypeByMetadataName("ComputeSharp.D2D1.ID2D1PixelShader")!;
|
||||
|
||||
// Check that the shader implements the ID2D1PixelShader interface
|
||||
if (!typeSymbol.HasInterfaceWithType(shaderInterfaceType))
|
||||
{
|
||||
return default;
|
||||
}
|
||||
|
||||
// EffectId info
|
||||
ImmutableArray<byte> effectId = EffectId.GetInfo(context.SemanticModel.Compilation, typeSymbol);
|
||||
|
||||
token.ThrowIfCancellationRequested();
|
||||
|
||||
// EffectDisplayName info
|
||||
string? effectDisplayName = EffectMetadata.GetEffectDisplayNameInfo(context.SemanticModel.Compilation, typeSymbol);
|
||||
|
||||
token.ThrowIfCancellationRequested();
|
||||
|
||||
// EffectDescription info
|
||||
string? effectDescription = EffectMetadata.GetEffectDescriptionInfo(context.SemanticModel.Compilation, typeSymbol);
|
||||
|
||||
token.ThrowIfCancellationRequested();
|
||||
|
||||
// EffectCategory info
|
||||
string? effectCategory = EffectMetadata.GetEffectCategoryInfo(context.SemanticModel.Compilation, typeSymbol);
|
||||
|
||||
token.ThrowIfCancellationRequested();
|
||||
|
||||
// EffectAuthor info
|
||||
string? effectAuthor = EffectMetadata.GetEffectAuthorInfo(context.SemanticModel.Compilation, typeSymbol);
|
||||
|
||||
token.ThrowIfCancellationRequested();
|
||||
|
||||
// Constant buffer info
|
||||
ConstantBuffer.GetInfo(
|
||||
context.SemanticModel.Compilation,
|
||||
typeSymbol,
|
||||
out int constantBufferSizeInBytes,
|
||||
out ImmutableArray<FieldInfo> fieldInfos);
|
||||
|
||||
token.ThrowIfCancellationRequested();
|
||||
|
||||
// Get the input info for InputTypes
|
||||
InputTypes.GetInfo(
|
||||
typeSymbol,
|
||||
out int inputCount,
|
||||
out ImmutableArray<int> inputSimpleIndices,
|
||||
out ImmutableArray<int> inputComplexIndices,
|
||||
out ImmutableArray<uint> inputTypes);
|
||||
|
||||
token.ThrowIfCancellationRequested();
|
||||
|
||||
// Get the resource texture info for ResourceTextureDescriptions
|
||||
ResourceTextureDescriptions.GetInfo(
|
||||
typeSymbol,
|
||||
out ImmutableArray<ResourceTextureDescription> resourceTextureDescriptions);
|
||||
|
||||
token.ThrowIfCancellationRequested();
|
||||
|
||||
// Get the info for the output buffer properties
|
||||
OutputBuffer.GetInfo(typeSymbol, out D2D1BufferPrecision bufferPrecision, out D2D1ChannelDepth channelDepth);
|
||||
|
||||
token.ThrowIfCancellationRequested();
|
||||
|
||||
// Get the info for InputDescriptions
|
||||
InputDescriptions.GetInfo(
|
||||
typeSymbol,
|
||||
out ImmutableArray<InputDescription> inputDescriptions);
|
||||
|
||||
token.ThrowIfCancellationRequested();
|
||||
|
||||
// Get the info for PixelOptions
|
||||
PixelOptions.GetInfo(typeSymbol, out D2D1PixelOptions pixelOptions);
|
||||
|
||||
token.ThrowIfCancellationRequested();
|
||||
|
||||
// Get the shader profile and linking info for the HLSL bytecode properties
|
||||
D2D1ShaderProfile? requestedShaderProfile = HlslBytecode.GetRequestedShaderProfile(typeSymbol);
|
||||
D2D1CompileOptions? requestedCompileOptions = HlslBytecode.GetRequestedCompileOptions(typeSymbol);
|
||||
D2D1ShaderProfile effectiveShaderProfile = HlslBytecode.GetEffectiveShaderProfile(requestedShaderProfile, out bool isCompilationEnabled);
|
||||
D2D1CompileOptions effectiveCompileOptions = HlslBytecode.GetEffectiveCompileOptions(requestedCompileOptions);
|
||||
|
||||
token.ThrowIfCancellationRequested();
|
||||
|
||||
using ImmutableArrayBuilder<DiagnosticInfo> diagnostics = new();
|
||||
|
||||
// Get HLSL source for HlslSource
|
||||
string hlslSource = HlslSource.GetHlslSource(
|
||||
diagnostics,
|
||||
context.SemanticModel.Compilation,
|
||||
typeSymbol,
|
||||
shaderInterfaceType,
|
||||
inputCount,
|
||||
inputSimpleIndices,
|
||||
inputComplexIndices,
|
||||
token);
|
||||
|
||||
token.ThrowIfCancellationRequested();
|
||||
|
||||
// As the last steps in the pipeline, try to compile the shader if needed.
|
||||
// This is done last so that it can be skipped if any errors happened before.
|
||||
HlslBytecodeInfoKey hlslInfoKey = new(
|
||||
hlslSource,
|
||||
effectiveShaderProfile,
|
||||
effectiveCompileOptions,
|
||||
isCompilationEnabled);
|
||||
|
||||
// Get the existing compiled shader, or compile the processed HLSL code
|
||||
HlslBytecodeInfo hlslInfo = HlslBytecodeSyntaxProcessor.GetInfo(ref hlslInfoKey, token);
|
||||
|
||||
token.ThrowIfCancellationRequested();
|
||||
|
||||
// Append any diagnostic for the shader compilation
|
||||
HlslBytecodeSyntaxProcessor.GetInfoDiagnostics(typeSymbol, hlslInfo, diagnostics);
|
||||
HlslBytecodeSyntaxProcessor.GetDoublePrecisionSupportDiagnostics(typeSymbol, hlslInfo, diagnostics);
|
||||
|
||||
token.ThrowIfCancellationRequested();
|
||||
|
||||
// Finally, get the hierarchy too
|
||||
HierarchyInfo hierarchyInfo = HierarchyInfo.From(typeSymbol);
|
||||
|
||||
token.ThrowIfCancellationRequested();
|
||||
|
||||
return new D2D1ShaderInfo(
|
||||
Hierarchy: hierarchyInfo,
|
||||
EffectId: effectId,
|
||||
EffectDisplayName: effectDisplayName,
|
||||
EffectDescription: effectDescription,
|
||||
EffectCategory: effectCategory,
|
||||
EffectAuthor: effectAuthor,
|
||||
ConstantBufferSizeInBytes: constantBufferSizeInBytes,
|
||||
InputTypes: inputTypes,
|
||||
InputDescriptions: inputDescriptions,
|
||||
ResourceTextureDescriptions: resourceTextureDescriptions,
|
||||
Fields: fieldInfos,
|
||||
BufferPrecision: bufferPrecision,
|
||||
ChannelDepth: channelDepth,
|
||||
PixelOptions: pixelOptions,
|
||||
HlslInfoKey: hlslInfoKey,
|
||||
HlslInfo: hlslInfo,
|
||||
Diagnostcs: diagnostics.ToImmutable());
|
||||
})
|
||||
.WithTrackingName(WellKnownTrackingNames.Execute)
|
||||
.Where(static item => item is not null)!;
|
||||
|
||||
// We need to create two more incremental steps to ensure we correctly emit diagnostics and re-generate sources.
|
||||
// First, select an incremental provider with just the diagnostics, which will trigger every time any of them changes.
|
||||
IncrementalValuesProvider<EquatableArray<DiagnosticInfo>> diagnosticInfo =
|
||||
shaderInfo
|
||||
.Select(static (item, _) => item.Diagnostcs)
|
||||
.WithTrackingName(WellKnownTrackingNames.Diagnostics)
|
||||
.Where(static item => !item.IsEmpty);
|
||||
|
||||
// Next, select one with just the shader info (and no diagnostics), so that changes there don't trigger generation unnecessarily
|
||||
IncrementalValuesProvider<D2D1ShaderInfo> outputInfo =
|
||||
shaderInfo
|
||||
.Select(static (item, _) => item with { Diagnostcs = default })
|
||||
.WithTrackingName(WellKnownTrackingNames.Output);
|
||||
|
||||
// Output the diagnostics, if any
|
||||
context.ReportDiagnostics(diagnosticInfo);
|
||||
|
||||
// Generate the source files, if any
|
||||
context.RegisterSourceOutput(outputInfo, static (context, item) =>
|
||||
{
|
||||
using ImmutableArrayBuilder<IndentedTextWriter.Callback<D2D1ShaderInfo>> declaredMembers = new();
|
||||
|
||||
declaredMembers.Add(EffectId.WriteSyntax);
|
||||
declaredMembers.Add(EffectMetadata.WriteEffectDisplayNameSyntax);
|
||||
declaredMembers.Add(EffectMetadata.WriteEffectDescriptionSyntax);
|
||||
declaredMembers.Add(EffectMetadata.WriteEffectCategorySyntax);
|
||||
declaredMembers.Add(EffectMetadata.WriteEffectAuthorSyntax);
|
||||
declaredMembers.Add(EffectFactory.WriteSyntax);
|
||||
declaredMembers.Add(NumericProperties.WriteConstantBufferSizeSyntax);
|
||||
declaredMembers.Add(NumericProperties.WriteInputCountSyntax);
|
||||
declaredMembers.Add(NumericProperties.WriteResourceTextureCountSyntax);
|
||||
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(HlslBytecode.WriteShaderProfileSyntax);
|
||||
declaredMembers.Add(HlslBytecode.WriteCompileOptionsSyntax);
|
||||
declaredMembers.Add(HlslSource.WriteSyntax);
|
||||
declaredMembers.Add(HlslBytecode.WriteHlslBytecodeSyntax);
|
||||
declaredMembers.Add(ConstantBuffer.WriteCreateFromConstantBufferSyntax);
|
||||
declaredMembers.Add(ConstantBuffer.WriteLoadConstantBufferSyntax);
|
||||
|
||||
using ImmutableArrayBuilder<IndentedTextWriter.Callback<D2D1ShaderInfo>> additionalTypes = new();
|
||||
using ImmutableHashSetBuilder<string> usingDirectives = new();
|
||||
|
||||
ConstantBufferSyntaxProcessor.RegisterAdditionalTypesSyntax(GeneratorName, BindingDirection.TwoWay, item, additionalTypes, usingDirectives);
|
||||
InputDescriptions.RegisterAdditionalTypesSyntax(item, additionalTypes, usingDirectives);
|
||||
InputTypes.RegisterAdditionalTypesSyntax(item, additionalTypes, usingDirectives);
|
||||
HlslBytecode.RegisterAdditionalTypesSyntax(item, additionalTypes, usingDirectives);
|
||||
|
||||
using IndentedTextWriter writer = new();
|
||||
|
||||
item.Hierarchy.WriteSyntax(
|
||||
state: item,
|
||||
writer: writer,
|
||||
baseTypes: [$"global::ComputeSharp.D2D1.Descriptors.ID2D1PixelShaderDescriptor<{item.Hierarchy.Hierarchy[0].QualifiedName}>"],
|
||||
memberCallbacks: declaredMembers.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");
|
||||
|
||||
using (writer.WriteBlock())
|
||||
{
|
||||
writer.WriteSortedUsingDirectives(usingDirectives.AsEnumerable());
|
||||
writer.WriteLineSeparatedMembers(additionalTypes.WrittenSpan, (callback, writer) => callback(item, writer));
|
||||
}
|
||||
}
|
||||
|
||||
context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.g.cs", writer.ToString());
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,180 +0,0 @@
|
||||
using System.Collections.Immutable;
|
||||
using ComputeSharp.D2D1.SourceGenerators.Models;
|
||||
using ComputeSharp.SourceGeneration.Extensions;
|
||||
using ComputeSharp.SourceGeneration.Helpers;
|
||||
using ComputeSharp.SourceGeneration.Models;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.CSharp;
|
||||
using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors;
|
||||
|
||||
namespace ComputeSharp.D2D1.SourceGenerators;
|
||||
|
||||
/// <inheritdoc/>
|
||||
partial class D2DPixelShaderSourceGenerator
|
||||
{
|
||||
/// <summary>
|
||||
/// A container for all the logic for <see cref="D2DPixelShaderSourceGenerator"/>.
|
||||
/// </summary>
|
||||
private static partial class Execute
|
||||
{
|
||||
/// <summary>
|
||||
/// Validates that the return type of the annotated method is valid and returns the type name.
|
||||
/// </summary>
|
||||
/// <param name="methodSymbol">The input <see cref="IMethodSymbol"/> instance to process.</param>
|
||||
/// <returns>The fully qualified type name, if invalid.</returns>
|
||||
public static string? GetInvalidReturnType(IMethodSymbol methodSymbol)
|
||||
{
|
||||
if (methodSymbol.ReturnType is not INamedTypeSymbol
|
||||
{
|
||||
Name: "ReadOnlySpan",
|
||||
ContainingNamespace.Name: "System",
|
||||
IsGenericType: true,
|
||||
TypeArguments: [{ SpecialType: SpecialType.System_Byte }]
|
||||
})
|
||||
{
|
||||
return methodSymbol.ReturnType.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Extracts the HLSL source from an annotated method.
|
||||
/// </summary>
|
||||
/// <param name="methodSymbol">The input <see cref="IMethodSymbol"/> instance to process.</param>
|
||||
/// <returns>The HLSL source to compile, if present.</returns>
|
||||
public static string? GetHlslSource(IMethodSymbol methodSymbol)
|
||||
{
|
||||
if (methodSymbol.TryGetAttributeWithFullyQualifiedMetadataName("ComputeSharp.D2D1.D2DPixelShaderSourceAttribute", out AttributeData? attributeData) &&
|
||||
attributeData!.TryGetConstructorArgument(0, out string? hlslSource))
|
||||
{
|
||||
return hlslSource;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Extracts the shader profile for a target method, if present.
|
||||
/// </summary>
|
||||
/// <param name="methodSymbol">The input <see cref="IMethodSymbol"/> instance to process.</param>
|
||||
/// <returns>The shader profile to use to compile the shader, if present.</returns>
|
||||
public static D2D1ShaderProfile? GetShaderProfile(IMethodSymbol methodSymbol)
|
||||
{
|
||||
if (methodSymbol.TryGetAttributeWithFullyQualifiedMetadataName("ComputeSharp.D2D1.D2DShaderProfileAttribute", out AttributeData? attributeData))
|
||||
{
|
||||
return (D2D1ShaderProfile)attributeData.ConstructorArguments[0].Value!;
|
||||
}
|
||||
|
||||
if (methodSymbol.ContainingAssembly.TryGetAttributeWithFullyQualifiedMetadataName("ComputeSharp.D2D1.D2DShaderProfileAttribute", out attributeData))
|
||||
{
|
||||
return (D2D1ShaderProfile)attributeData.ConstructorArguments[0].Value!;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Extracts the compile options for the current shader.
|
||||
/// </summary>
|
||||
/// <param name="methodSymbol">The input <see cref="IMethodSymbol"/> instance to process.</param>
|
||||
/// <returns>The compile options to use to compile the shader, if present.</returns>
|
||||
public static D2D1CompileOptions GetCompileOptions(IMethodSymbol methodSymbol)
|
||||
{
|
||||
if (methodSymbol.TryGetAttributeWithFullyQualifiedMetadataName("ComputeSharp.D2D1.D2DCompileOptionsAttribute", out AttributeData? attributeData))
|
||||
{
|
||||
return (D2D1CompileOptions)attributeData.ConstructorArguments[0].Value!;
|
||||
}
|
||||
|
||||
if (methodSymbol.ContainingAssembly.TryGetAttributeWithFullyQualifiedMetadataName("ComputeSharp.D2D1.D2DCompileOptionsAttribute", out attributeData))
|
||||
{
|
||||
return (D2D1CompileOptions)attributeData.ConstructorArguments[0].Value!;
|
||||
}
|
||||
|
||||
return D2D1CompileOptions.Default;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets any diagnostics from a processed <see cref="HlslBytecodeInfo"/> instance.
|
||||
/// </summary>
|
||||
/// <param name="methodSymbol">The input <see cref="IMethodSymbol"/> instance to process.</param>
|
||||
/// <param name="info">The source <see cref="HlslBytecodeInfo"/> instance.</param>
|
||||
/// <returns>The collection of produced <see cref="DiagnosticInfo"/> instances.</returns>
|
||||
public static ImmutableArray<DiagnosticInfo> GetInfoDiagnostics(IMethodSymbol methodSymbol, HlslBytecodeInfo info)
|
||||
{
|
||||
if (info is HlslBytecodeInfo.Win32Error win32Error)
|
||||
{
|
||||
DiagnosticInfo diagnostic = DiagnosticInfo.Create(
|
||||
D2DPixelShaderSourceCompilationFailedWithWin32Exception,
|
||||
methodSymbol,
|
||||
methodSymbol,
|
||||
methodSymbol.ContainingType,
|
||||
win32Error.HResult,
|
||||
win32Error.Message);
|
||||
|
||||
return [diagnostic];
|
||||
}
|
||||
else if (info is HlslBytecodeInfo.CompilerError fxcError)
|
||||
{
|
||||
DiagnosticInfo diagnostic = DiagnosticInfo.Create(
|
||||
D2DPixelShaderSourceCompilationFailedWithFxcCompilationException,
|
||||
methodSymbol,
|
||||
methodSymbol,
|
||||
methodSymbol.ContainingType,
|
||||
fxcError.Message);
|
||||
|
||||
return [diagnostic];
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes the generated method for the compiled HLSL bytecode.
|
||||
/// </summary>
|
||||
/// <param name="info">The input <see cref="D2D1PixelShaderSourceInfo"/> instance with gathered shader info.</param>
|
||||
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
|
||||
public static void WriteSyntax(D2D1PixelShaderSourceInfo info, IndentedTextWriter writer)
|
||||
{
|
||||
writer.WriteLine("/// <inheritdoc/>");
|
||||
writer.WriteGeneratedAttributes(GeneratorName);
|
||||
|
||||
// Write the modifiers, if any
|
||||
foreach (uint modifier in info.Modifiers)
|
||||
{
|
||||
writer.Write(SyntaxFacts.GetText((SyntaxKind)modifier));
|
||||
writer.Write(" ");
|
||||
}
|
||||
|
||||
// Write the return type
|
||||
if (info.InvalidReturnType is string invalidReturnType)
|
||||
{
|
||||
writer.Write(invalidReturnType);
|
||||
writer.Write(" ");
|
||||
}
|
||||
else
|
||||
{
|
||||
writer.Write("global::System.ReadOnlySpan<byte> ");
|
||||
}
|
||||
|
||||
writer.WriteLine($"{info.MethodName}()");
|
||||
|
||||
// Write the bytecode expression
|
||||
using (writer.WriteBlock())
|
||||
{
|
||||
if (info.HlslInfo is HlslBytecodeInfo.Success success)
|
||||
{
|
||||
writer.Write("return [");
|
||||
|
||||
SyntaxFormattingHelper.WriteByteArrayInitializationExpressions(success.Bytecode.AsSpan(), writer);
|
||||
|
||||
writer.WriteLine("];");
|
||||
}
|
||||
else
|
||||
{
|
||||
writer.Write("return default;");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,117 +0,0 @@
|
||||
using System.Collections.Immutable;
|
||||
using System.Linq;
|
||||
using ComputeSharp.D2D1.SourceGenerators.Models;
|
||||
using ComputeSharp.SourceGeneration.Constants;
|
||||
using ComputeSharp.SourceGeneration.Extensions;
|
||||
using ComputeSharp.SourceGeneration.Helpers;
|
||||
using ComputeSharp.SourceGeneration.Models;
|
||||
using ComputeSharp.SourceGeneration.SyntaxProcessors;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.CSharp;
|
||||
using Microsoft.CodeAnalysis.CSharp.Syntax;
|
||||
|
||||
namespace ComputeSharp.D2D1.SourceGenerators;
|
||||
|
||||
/// <summary>
|
||||
/// A source generator compiling methods annotated with <see cref="D2DPixelShaderSourceAttribute"/>.
|
||||
/// </summary>
|
||||
[Generator(LanguageNames.CSharp)]
|
||||
public sealed partial class D2DPixelShaderSourceGenerator : IIncrementalGenerator
|
||||
{
|
||||
/// <inheritdoc cref="D2DPixelShaderDescriptorGenerator.GeneratorName"/>
|
||||
private const string GeneratorName = "ComputeSharp.D2D1.D2DPixelShaderSourceGenerator";
|
||||
|
||||
/// <inheritdoc/>
|
||||
public void Initialize(IncrementalGeneratorInitializationContext context)
|
||||
{
|
||||
// Get all method declarations with the [D2DPixelShaderSource] attribute and gather all necessary info
|
||||
IncrementalValuesProvider<D2D1PixelShaderSourceInfo> methodInfo =
|
||||
context.SyntaxProvider
|
||||
.ForAttributeWithMetadataName(
|
||||
"ComputeSharp.D2D1.D2DPixelShaderSourceAttribute",
|
||||
static (node, _) => node is MethodDeclarationSyntax,
|
||||
static (context, token) =>
|
||||
{
|
||||
MethodDeclarationSyntax methodDeclaration = (MethodDeclarationSyntax)context.TargetNode;
|
||||
IMethodSymbol methodSymbol = (IMethodSymbol)context.TargetSymbol;
|
||||
|
||||
// Get the remaining info for the current shader
|
||||
ImmutableArray<ushort> modifiers = methodDeclaration.Modifiers.Select(token => (ushort)token.Kind()).ToImmutableArray();
|
||||
string methodName = methodSymbol.Name;
|
||||
string? invalidReturnType = Execute.GetInvalidReturnType(methodSymbol);
|
||||
string? requestedHlslSource = Execute.GetHlslSource(methodSymbol);
|
||||
string effectiveHlslSource = requestedHlslSource ?? "";
|
||||
D2D1CompileOptions compileOptions = Execute.GetCompileOptions(methodSymbol);
|
||||
|
||||
// For the shader profile, reuse the same logic as in D2D1PixelShaderDescriptorGenerator.
|
||||
// The only difference is that in this case, we also skip if the source is null.
|
||||
D2D1ShaderProfile? requestedShaderProfile = Execute.GetShaderProfile(methodSymbol);
|
||||
D2D1ShaderProfile effectiveShaderProfile = requestedShaderProfile ?? D2D1ShaderProfile.PixelShader50;
|
||||
bool isCompilationEnabled = requestedHlslSource is not null && requestedShaderProfile is not null;
|
||||
|
||||
token.ThrowIfCancellationRequested();
|
||||
|
||||
// Prepare the key to cache the bytecode (just like the main D2D1 generator)
|
||||
HlslBytecodeInfoKey hlslInfoKey = new(
|
||||
effectiveHlslSource,
|
||||
effectiveShaderProfile,
|
||||
compileOptions,
|
||||
isCompilationEnabled);
|
||||
|
||||
// Get the existing compiled shader, or compile the processed HLSL code
|
||||
HlslBytecodeInfo hlslInfo = HlslBytecodeSyntaxProcessor.GetInfo(ref hlslInfoKey, token);
|
||||
|
||||
token.ThrowIfCancellationRequested();
|
||||
|
||||
// Get any diagnostics for the shader compilation
|
||||
ImmutableArray<DiagnosticInfo> diagnostics = Execute.GetInfoDiagnostics(methodSymbol, hlslInfo);
|
||||
|
||||
token.ThrowIfCancellationRequested();
|
||||
|
||||
// Finally, get the hierarchy too
|
||||
HierarchyInfo hierarchyInfo = HierarchyInfo.From(methodSymbol.ContainingType!);
|
||||
|
||||
token.ThrowIfCancellationRequested();
|
||||
|
||||
return new D2D1PixelShaderSourceInfo(
|
||||
Hierarchy: hierarchyInfo,
|
||||
Modifiers: modifiers,
|
||||
MethodName: methodName,
|
||||
InvalidReturnType: invalidReturnType,
|
||||
HlslInfoKey: hlslInfoKey,
|
||||
HlslInfo: hlslInfo,
|
||||
Diagnostcs: diagnostics);
|
||||
})
|
||||
.WithTrackingName(WellKnownTrackingNames.Execute);
|
||||
|
||||
// Get the diagnostic incremental collection with filtering (same as in the D2D1 generator)
|
||||
IncrementalValuesProvider<EquatableArray<DiagnosticInfo>> diagnosticInfo =
|
||||
methodInfo
|
||||
.Select(static (item, _) => item.Diagnostcs)
|
||||
.WithTrackingName(WellKnownTrackingNames.Diagnostics)
|
||||
.Where(static item => !item.IsEmpty);
|
||||
|
||||
// Also get the comparison-friendly incremental collection for the output (same as above)
|
||||
IncrementalValuesProvider<D2D1PixelShaderSourceInfo> outputInfo =
|
||||
methodInfo
|
||||
.Select(static (item, _) => item with { Diagnostcs = default })
|
||||
.WithTrackingName(WellKnownTrackingNames.Output);
|
||||
|
||||
// Output the diagnostics, if any
|
||||
context.ReportDiagnostics(diagnosticInfo);
|
||||
|
||||
// Generate the shader bytecode methods
|
||||
context.RegisterSourceOutput(outputInfo, static (context, item) =>
|
||||
{
|
||||
using IndentedTextWriter writer = new();
|
||||
|
||||
item.Hierarchy.WriteSyntax(
|
||||
state: item,
|
||||
writer: writer,
|
||||
baseTypes: [],
|
||||
memberCallbacks: [Execute.WriteSyntax]);
|
||||
|
||||
context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.{item.MethodName}.g.cs", writer.ToString());
|
||||
});
|
||||
}
|
||||
}
|
||||
-39
@@ -1,39 +0,0 @@
|
||||
using System.Collections.Immutable;
|
||||
using ComputeSharp.SourceGeneration.Extensions;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.Diagnostics;
|
||||
using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors;
|
||||
|
||||
namespace ComputeSharp.D2D1.SourceGenerators;
|
||||
|
||||
/// <summary>
|
||||
/// A diagnostic analyzer that generates diagnostics for the [D2DEnableRuntimeCompilation] attribute, when used on an assembly.
|
||||
/// </summary>
|
||||
[DiagnosticAnalyzer(LanguageNames.CSharp)]
|
||||
public sealed class D2DEnableRuntimeCompilationOnAssemblyAnalyzer : DiagnosticAnalyzer
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = [D2DRuntimeCompilationOnAssemblyNotNecessary];
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override void Initialize(AnalysisContext context)
|
||||
{
|
||||
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics);
|
||||
context.EnableConcurrentExecution();
|
||||
|
||||
context.RegisterCompilationAction(static context =>
|
||||
{
|
||||
IAssemblySymbol assemblySymbol = context.Compilation.Assembly;
|
||||
|
||||
// Emit a diagnostic if an assembly has both [D2DShaderProfile] and [D2DEnableRuntimeCompilation] (the latter is useless)
|
||||
if (assemblySymbol.TryGetAttributeWithFullyQualifiedMetadataName("ComputeSharp.D2D1.D2DShaderProfileAttribute", out _) &&
|
||||
assemblySymbol.TryGetAttributeWithFullyQualifiedMetadataName("ComputeSharp.D2D1.D2DEnableRuntimeCompilationAttribute", out AttributeData? attributeData))
|
||||
{
|
||||
context.ReportDiagnostic(Diagnostic.Create(
|
||||
D2DRuntimeCompilationOnAssemblyNotNecessary,
|
||||
attributeData.GetLocation(),
|
||||
assemblySymbol));
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
-94
@@ -1,94 +0,0 @@
|
||||
using System.Collections.Immutable;
|
||||
using System.Linq;
|
||||
using ComputeSharp.SourceGeneration.Extensions;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.Diagnostics;
|
||||
using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors;
|
||||
|
||||
namespace ComputeSharp.D2D1.SourceGenerators;
|
||||
|
||||
/// <summary>
|
||||
/// A diagnostic analyzer that generates diagnostics for the [D2DEnableRuntimeCompilation] attribute, when used on a type.
|
||||
/// </summary>
|
||||
[DiagnosticAnalyzer(LanguageNames.CSharp)]
|
||||
public sealed class D2DEnableRuntimeCompilationOnTypeAnalyzer : DiagnosticAnalyzer
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = [D2DRuntimeCompilationDisabled, D2DRuntimeCompilationAlreadyEnabled, D2DRuntimeCompilationOnTypeNotNecessary];
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override void Initialize(AnalysisContext context)
|
||||
{
|
||||
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics);
|
||||
context.EnableConcurrentExecution();
|
||||
|
||||
context.RegisterCompilationStartAction(static context =>
|
||||
{
|
||||
// Get the [D2DShaderProfile], [D2DEnableRuntimeCompilation] and [D2DGeneratedPixelShaderDescriptor] symbols
|
||||
if (context.Compilation.GetTypeByMetadataName("ComputeSharp.D2D1.D2DShaderProfileAttribute") is not { } d2DShaderProfileAttributeSymbol ||
|
||||
context.Compilation.GetTypeByMetadataName("ComputeSharp.D2D1.D2DEnableRuntimeCompilationAttribute") is not { } d2DEnableRuntimeCompilationAttributeSymbol ||
|
||||
context.Compilation.GetTypeByMetadataName("ComputeSharp.D2D1.D2DGeneratedPixelShaderDescriptorAttribute") is not { } d2DGeneratedPixelShaderDescriptorAttributeSymbol)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
context.RegisterSymbolAction(context =>
|
||||
{
|
||||
// Only struct types are possible targets
|
||||
if (context.Symbol is not INamedTypeSymbol { TypeKind: TypeKind.Struct } typeSymbol)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Skip the type if it's not a generated shader descriptor target
|
||||
if (!typeSymbol.HasAttributeWithType(d2DGeneratedPixelShaderDescriptorAttributeSymbol))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// This analyzer will detect the following cases:
|
||||
// 1) Shader not precompiled, and missing [D2DEnableRuntimeCompilation] (D2DRuntimeCompilationDisabled)
|
||||
// 2) Shader with [D2DEnableRuntimeCompilation] on the assembly and also on the shader type (D2DRuntimeCompilationAlreadyEnabled)
|
||||
// 3) Shader being precompiled, but also with [D2DEnableRuntimeCompilation] (D2DRuntimeCompilationNotNecessary)
|
||||
bool hasD2DShaderProfileAttributeOnAssembly = typeSymbol.ContainingAssembly.HasAttributeWithType(d2DShaderProfileAttributeSymbol);
|
||||
bool hasD2DShaderProfileAttributeOnType = typeSymbol.HasAttributeWithType(d2DShaderProfileAttributeSymbol);
|
||||
bool hasD2DEnableRuntimeCompilationAttributeOnAssembly = typeSymbol.ContainingAssembly.HasAttributeWithType(d2DEnableRuntimeCompilationAttributeSymbol);
|
||||
bool hasD2DEnableRuntimeCompilationAttributeOnType = typeSymbol.TryGetAttributeWithType(
|
||||
d2DEnableRuntimeCompilationAttributeSymbol,
|
||||
out AttributeData? d2DEnableRuntimeCompilationAttributeData);
|
||||
|
||||
// If [D2DEnableRuntimeCompilation] is present on the type and also on the assembly, emit a diagnostic (2)
|
||||
if (hasD2DEnableRuntimeCompilationAttributeOnAssembly && hasD2DEnableRuntimeCompilationAttributeOnType)
|
||||
{
|
||||
context.ReportDiagnostic(Diagnostic.Create(
|
||||
D2DRuntimeCompilationAlreadyEnabled,
|
||||
d2DEnableRuntimeCompilationAttributeData!.GetLocation(),
|
||||
typeSymbol));
|
||||
}
|
||||
|
||||
// Check if the shader is precompiled:
|
||||
// - If it is, we should check that it's not annotated with [D2DEnableRuntimeCompilation]
|
||||
// - If it is not, we should check that it is annotated with [D2DEnableRuntimeCompilation]
|
||||
if (hasD2DShaderProfileAttributeOnType || hasD2DShaderProfileAttributeOnAssembly)
|
||||
{
|
||||
// Emit a diagnostic if [D2DEnableRuntimeCompilation] is present on the type (3)
|
||||
if (hasD2DEnableRuntimeCompilationAttributeOnType)
|
||||
{
|
||||
context.ReportDiagnostic(Diagnostic.Create(
|
||||
D2DRuntimeCompilationOnTypeNotNecessary,
|
||||
d2DEnableRuntimeCompilationAttributeData!.GetLocation(),
|
||||
typeSymbol));
|
||||
}
|
||||
}
|
||||
else if (!hasD2DEnableRuntimeCompilationAttributeOnType && !hasD2DEnableRuntimeCompilationAttributeOnAssembly)
|
||||
{
|
||||
// Emit a diagnostic if there is no [D2DEnableRuntimeCompilation] set anywhere (1)
|
||||
context.ReportDiagnostic(Diagnostic.Create(
|
||||
D2DRuntimeCompilationDisabled,
|
||||
typeSymbol.Locations.FirstOrDefault(),
|
||||
typeSymbol));
|
||||
}
|
||||
}, SymbolKind.NamedType);
|
||||
});
|
||||
}
|
||||
}
|
||||
-73
@@ -1,73 +0,0 @@
|
||||
using System.Collections.Immutable;
|
||||
using System.Linq;
|
||||
using ComputeSharp.SourceGeneration.Extensions;
|
||||
using ComputeSharp.SourceGeneration.SyntaxProcessors;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.Diagnostics;
|
||||
using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors;
|
||||
|
||||
namespace ComputeSharp.D2D1.SourceGenerators;
|
||||
|
||||
/// <summary>
|
||||
/// A diagnostic analyzer that generates errors when a D2D pixel shader exceeds the maximum dispatch data size.
|
||||
/// </summary>
|
||||
[DiagnosticAnalyzer(LanguageNames.CSharp)]
|
||||
public sealed class ExceededPixelShaderDispatchDataSizeAnalyzer : DiagnosticAnalyzer
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = [ExceededDispatchDataSize];
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override void Initialize(AnalysisContext context)
|
||||
{
|
||||
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics);
|
||||
context.EnableConcurrentExecution();
|
||||
|
||||
context.RegisterCompilationStartAction(static context =>
|
||||
{
|
||||
// Get the ID2D1PixelShader symbol
|
||||
if (context.Compilation.GetTypeByMetadataName("ComputeSharp.D2D1.ID2D1PixelShader") is not { } d2D1PixelShaderSymbol)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
context.RegisterSymbolAction(context =>
|
||||
{
|
||||
// We're validating all struct types (since they're the possible shader types)
|
||||
if (context.Symbol is not INamedTypeSymbol { TypeKind: TypeKind.Struct } typeSymbol)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Only validate fields for shader types (even without a generated descriptor)
|
||||
if (!typeSymbol.HasInterfaceWithType(d2D1PixelShaderSymbol))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
int constantBufferSizeInBytes = 0;
|
||||
|
||||
// Run the fast-path constant buffer processor logic.
|
||||
// This only extracts the constant buffer size.
|
||||
ConstantBufferSyntaxProcessor.GetInfo(
|
||||
context.Compilation,
|
||||
typeSymbol,
|
||||
ref constantBufferSizeInBytes);
|
||||
|
||||
// The maximum size for a constant buffer is 64KB
|
||||
const int D3D11_REQ_CONSTANT_BUFFER_ELEMENT_COUNT = 4096;
|
||||
const int MaximumConstantBufferSize = D3D11_REQ_CONSTANT_BUFFER_ELEMENT_COUNT * 4 * sizeof(float);
|
||||
|
||||
// Emit a diagnostic if the shader constant buffer is too large
|
||||
if (constantBufferSizeInBytes > MaximumConstantBufferSize)
|
||||
{
|
||||
context.ReportDiagnostic(Diagnostic.Create(
|
||||
ExceededDispatchDataSize,
|
||||
typeSymbol.Locations.First(),
|
||||
typeSymbol,
|
||||
constantBufferSizeInBytes));
|
||||
}
|
||||
}, SymbolKind.NamedType);
|
||||
});
|
||||
}
|
||||
}
|
||||
-48
@@ -1,48 +0,0 @@
|
||||
using System.Collections.Immutable;
|
||||
using ComputeSharp.SourceGeneration.Extensions;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.Diagnostics;
|
||||
using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors;
|
||||
|
||||
namespace ComputeSharp.D2D1.SourceGenerators;
|
||||
|
||||
/// <summary>
|
||||
/// A diagnostic analyzer that generates an error whenever invalid options are used in an assembly-level [D2D1CompileOptions] attribute.
|
||||
/// </summary>
|
||||
[DiagnosticAnalyzer(LanguageNames.CSharp)]
|
||||
public sealed class InvalidAssemblyLevelCompileOptionsAnalyzer : DiagnosticAnalyzer
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = [InvalidPackMatrixColumnMajorOption];
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override void Initialize(AnalysisContext context)
|
||||
{
|
||||
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics);
|
||||
context.EnableConcurrentExecution();
|
||||
|
||||
context.RegisterCompilationAction(static context =>
|
||||
{
|
||||
IAssemblySymbol assemblySymbol = context.Compilation.Assembly;
|
||||
|
||||
// In order to emit diagnostics for [D2D1CompileOptions] attributes at the assembly level, the following is needed:
|
||||
// - The type symbol for the assembly, to get the AttributeData object for the [D2D1CompileOptions] attribute, if used.
|
||||
// - The syntax node representing the attribute targeting the assembly, to get a location (this is retrieved from the AttributeData).
|
||||
// - The input D2D1CompileOptions value, which can be retrieved from the constructor arguments of the AttributeData object.
|
||||
if (assemblySymbol.TryGetAttributeWithFullyQualifiedMetadataName("ComputeSharp.D2D1.D2DCompileOptionsAttribute", out AttributeData? attributeData))
|
||||
{
|
||||
D2D1CompileOptions options = (D2D1CompileOptions)attributeData.ConstructorArguments[0].Value!;
|
||||
|
||||
if ((options & D2D1CompileOptions.PackMatrixColumnMajor) != 0)
|
||||
{
|
||||
Diagnostic diagnostic = Diagnostic.Create(
|
||||
InvalidPackMatrixColumnMajorOption,
|
||||
attributeData.ApplicationSyntaxReference?.GetSyntax(context.CancellationToken).GetLocation(),
|
||||
assemblySymbol);
|
||||
|
||||
context.ReportDiagnostic(diagnostic);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
-120
@@ -1,120 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Immutable;
|
||||
using ComputeSharp.SourceGeneration.Extensions;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.Diagnostics;
|
||||
using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors;
|
||||
|
||||
namespace ComputeSharp.D2D1.SourceGenerators;
|
||||
|
||||
/// <summary>
|
||||
/// A diagnostic analyzer that generates an error whenever [D2DPixelOptions] is used on a shader type to incorrectly request trivial sampling.
|
||||
/// </summary>
|
||||
[DiagnosticAnalyzer(LanguageNames.CSharp)]
|
||||
public sealed class InvalidD2D1PixelOptionsTrivialSamplingOnShaderTypeAnalyzer : DiagnosticAnalyzer
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = [InvalidD2D1PixelOptionsTrivialSamplingOnShaderType];
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override void Initialize(AnalysisContext context)
|
||||
{
|
||||
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics);
|
||||
context.EnableConcurrentExecution();
|
||||
|
||||
context.RegisterCompilationStartAction(static context =>
|
||||
{
|
||||
// Get the [D2DPixelOptions], [D2DInputCount] and [D2DInputSimple] symbols
|
||||
if (context.Compilation.GetTypeByMetadataName("ComputeSharp.D2D1.D2DPixelOptionsAttribute") is not { } d2DPixelOptionsAttributeSymbol ||
|
||||
context.Compilation.GetTypeByMetadataName("ComputeSharp.D2D1.D2DInputCountAttribute") is not { } d2DInputCountAttributeSymbol ||
|
||||
context.Compilation.GetTypeByMetadataName("ComputeSharp.D2D1.D2DInputSimpleAttribute") is not { } d2DInputSimpleAttributeSymbol)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
context.RegisterSymbolAction(context =>
|
||||
{
|
||||
// Only struct types are possible targets
|
||||
if (context.Symbol is not INamedTypeSymbol { TypeKind: TypeKind.Struct } typeSymbol)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// If the type is not using [D2DPixelOptions] with D2D1PixelOptions.TrivialSampling, there's nothing to do
|
||||
if (!typeSymbol.TryGetAttributeWithType(d2DPixelOptionsAttributeSymbol, out AttributeData? pixelOptionsAttribute) ||
|
||||
!((D2D1PixelOptions)pixelOptionsAttribute.ConstructorArguments[0].Value!).HasFlag(D2D1PixelOptions.TrivialSampling))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Make sure we have the [D2DInputCount] (if not present, the shader is invalid anyway) and with a valid value
|
||||
if (!typeSymbol.TryGetAttributeWithType(d2DInputCountAttributeSymbol, out AttributeData? inputCountAttribute) ||
|
||||
inputCountAttribute.ConstructorArguments is not [{ Value: >= 0 and < 8 and int inputCount }])
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Emit a diagnostic if the compile options are not valid for the shader type
|
||||
if (!IsSimpleInputShader(typeSymbol, d2DInputSimpleAttributeSymbol, inputCount))
|
||||
{
|
||||
context.ReportDiagnostic(Diagnostic.Create(
|
||||
InvalidD2D1PixelOptionsTrivialSamplingOnShaderType,
|
||||
pixelOptionsAttribute.GetLocation(),
|
||||
typeSymbol));
|
||||
}
|
||||
}, SymbolKind.NamedType);
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks whether a given shader only has simple inputs.
|
||||
/// </summary>
|
||||
/// <param name="structDeclarationSymbol">The input <see cref="INamedTypeSymbol"/> instance to process.</param>
|
||||
/// <param name="d2DInputSimpleSymbolAttributeSymbol">The symbol for the <c>[D2DInputSimple]</c> attribute.</param>
|
||||
/// <param name="inputCount">The number of inputs for the shader.</param>
|
||||
/// <returns>Whether the shader only has simple inputs.</returns>
|
||||
private static unsafe bool IsSimpleInputShader(
|
||||
INamedTypeSymbol structDeclarationSymbol,
|
||||
INamedTypeSymbol d2DInputSimpleSymbolAttributeSymbol,
|
||||
int inputCount)
|
||||
{
|
||||
// We cannot trust the input count to be valid at this point (it may be invalid and
|
||||
// with diagnostic already emitted for it). So first, just clamp it in the right range.
|
||||
inputCount = Math.Max(0, Math.Min(8, inputCount));
|
||||
|
||||
// If there are no inputs, the shader is as if only had simple inputs
|
||||
if (inputCount == 0)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
// Build a map of all simple inputs (unmarked inputs default to being complex).
|
||||
// We can never have more than 8 inputs, and if there are it means the shader is
|
||||
// not valid. Just ignore them, and the generator will emit a separate diagnostic.
|
||||
Span<bool> simpleInputsMap = stackalloc bool[8];
|
||||
|
||||
// We first start with all inputs marked as complex (ie. not simple)
|
||||
simpleInputsMap.Clear();
|
||||
|
||||
foreach (AttributeData attributeData in structDeclarationSymbol.GetAttributes())
|
||||
{
|
||||
// Only retrieve indices of simple inputs that are in range. If an input is out of
|
||||
// range, the diagnostic for it will already be emitted by a previous generator step.
|
||||
if (SymbolEqualityComparer.Default.Equals(attributeData.AttributeClass, d2DInputSimpleSymbolAttributeSymbol) &&
|
||||
attributeData.ConstructorArguments is [{ Value: >= 0 and < 8 and int index }])
|
||||
{
|
||||
simpleInputsMap[index] = true;
|
||||
}
|
||||
}
|
||||
|
||||
bool isSimpleInputShader = true;
|
||||
|
||||
// Validate all inputs in our range (filtered by the allowed one)
|
||||
foreach (bool isSimpleInput in simpleInputsMap[..inputCount])
|
||||
{
|
||||
isSimpleInputShader &= isSimpleInput;
|
||||
}
|
||||
|
||||
return isSimpleInputShader;
|
||||
}
|
||||
}
|
||||
-58
@@ -1,58 +0,0 @@
|
||||
using System.Collections.Immutable;
|
||||
using ComputeSharp.SourceGeneration.Extensions;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.Diagnostics;
|
||||
using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors;
|
||||
|
||||
namespace ComputeSharp.D2D1.SourceGenerators;
|
||||
|
||||
/// <summary>
|
||||
/// A diagnostic analyzer that generates an error whenever the [D2DGeneratedPixelShaderDescriptor] attribute is used on an invalid target type.
|
||||
/// </summary>
|
||||
[DiagnosticAnalyzer(LanguageNames.CSharp)]
|
||||
public sealed class InvalidD2DGeneratedPixelShaderDescriptorAttributeTargetAnalyzer : DiagnosticAnalyzer
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = [InvalidD2DGeneratedPixelShaderDescriptorAttributeTarget];
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override void Initialize(AnalysisContext context)
|
||||
{
|
||||
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics);
|
||||
context.EnableConcurrentExecution();
|
||||
|
||||
context.RegisterCompilationStartAction(static context =>
|
||||
{
|
||||
// Get the ID2D1PixelShader and [D2DGeneratedPixelShaderDescriptor] symbols
|
||||
if (context.Compilation.GetTypeByMetadataName("ComputeSharp.D2D1.ID2D1PixelShader") is not { } d2D1PixelShaderSymbol ||
|
||||
context.Compilation.GetTypeByMetadataName("ComputeSharp.D2D1.D2DGeneratedPixelShaderDescriptorAttribute") is not { } d2DGeneratedPixelShaderDescriptorAttributeSymbol)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
context.RegisterSymbolAction(context =>
|
||||
{
|
||||
// Only struct types are possible targets
|
||||
if (context.Symbol is not INamedTypeSymbol { TypeKind: TypeKind.Struct } typeSymbol)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// If the type does not have [D2DGeneratedPixelShaderDescriptor], we can stop here
|
||||
if (!typeSymbol.TryGetAttributeWithType(d2DGeneratedPixelShaderDescriptorAttributeSymbol, out AttributeData? attribute))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Emit a diagnostic if the target type is generic or does not implement ID2D1PixelShader
|
||||
if (typeSymbol.IsGenericType || !typeSymbol.HasInterfaceWithType(d2D1PixelShaderSymbol))
|
||||
{
|
||||
context.ReportDiagnostic(Diagnostic.Create(
|
||||
InvalidD2DGeneratedPixelShaderDescriptorAttributeTarget,
|
||||
attribute.GetLocation(),
|
||||
typeSymbol));
|
||||
}
|
||||
}, SymbolKind.NamedType);
|
||||
});
|
||||
}
|
||||
}
|
||||
-202
@@ -1,202 +0,0 @@
|
||||
using System.Collections.Immutable;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Reflection;
|
||||
using ComputeSharp.D2D1.Interop;
|
||||
using ComputeSharp.D2D1.Intrinsics;
|
||||
using ComputeSharp.SourceGeneration.Extensions;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.CSharp;
|
||||
using Microsoft.CodeAnalysis.Diagnostics;
|
||||
using Microsoft.CodeAnalysis.Operations;
|
||||
using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors;
|
||||
|
||||
namespace ComputeSharp.D2D1.SourceGenerators;
|
||||
|
||||
/// <summary>
|
||||
/// A diagnostic analyzer that generates an error whenever an invocation to a D2D intrinsic references an out of range or invalid shader input.
|
||||
/// </summary>
|
||||
[DiagnosticAnalyzer(LanguageNames.CSharp)]
|
||||
public sealed class InvalidD2DInputArgumentAnalyzer : DiagnosticAnalyzer
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } =
|
||||
[
|
||||
IndexOutOfRangeForD2DIntrinsic,
|
||||
InvalidInputTypeForD2DIntrinsic,
|
||||
InvalidIndexSyntaxForD2DIntrinsic
|
||||
];
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override void Initialize(AnalysisContext context)
|
||||
{
|
||||
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
|
||||
context.EnableConcurrentExecution();
|
||||
|
||||
context.RegisterCompilationStartAction(static context =>
|
||||
{
|
||||
// If we can't get the D2D methods map, we have to stop right away
|
||||
if (!TryBuildMethodSymbolMap(context.Compilation, out ImmutableDictionary<IMethodSymbol, D2D1PixelShaderInputType?>? methodSymbols))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
context.CancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
// Get the '[D2DInputCount]' symbol, which we need to validate the source input arguments
|
||||
if (context.Compilation.GetTypeByMetadataName("ComputeSharp.D2D1.D2DInputCountAttribute") is not { } d2DInputCountAttributeSymbol)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// We want to register a callback for each method invocation, as all 'D2D' intrinsics would map to one
|
||||
context.RegisterOperationAction(context =>
|
||||
{
|
||||
IInvocationOperation operation = (IInvocationOperation)context.Operation;
|
||||
|
||||
// Cheap initial filter: we only care about static methods from the 'D2D' type
|
||||
if (operation.TargetMethod is not { IsStatic: true, ContainingType.Name: "D2D" } targetMethodSymbol)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Second cheap inital filter: we only care about invocations with a constant 'int' argument in first position.
|
||||
// While we're validating this, let's also get the 'index' parameter, since we need to validate it anyway.
|
||||
if (operation.Arguments is not [{ Value.ConstantValue: { HasValue: true, Value: int index } } firstArgument, ..])
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// We only want to kick in when the target parameter is an 'int' (same as in 'NonConstantD2DInputArgumentAnalyzer')
|
||||
if (firstArgument.Parameter is not { Type.SpecialType: SpecialType.System_Int32 } parameterSymbol)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Validate that the target method is one of the ones we care about, and get the target input type
|
||||
if (!methodSymbols.TryGetValue(targetMethodSymbol, out D2D1PixelShaderInputType? targetInputType))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Also check that the actual syntax for the index argument is valid (only literals and direct constant field references
|
||||
// are valid). For parenthesized expressions, we need to check the parent syntax node (the operation just ignores it).
|
||||
if (firstArgument.Value is not (ILiteralOperation or IFieldReferenceOperation))
|
||||
{
|
||||
context.ReportDiagnostic(Diagnostic.Create(
|
||||
InvalidIndexSyntaxForD2DIntrinsic,
|
||||
firstArgument.Syntax.GetLocation(),
|
||||
parameterSymbol.Name,
|
||||
targetMethodSymbol.Name));
|
||||
}
|
||||
else if (firstArgument.Syntax.Parent.IsKind(SyntaxKind.ParenthesizedExpression))
|
||||
{
|
||||
// In this case, we pass the parent syntax node for the location, so that we can
|
||||
// include the parentheses as well. Otherwise we'd just underline the inner value.
|
||||
context.ReportDiagnostic(Diagnostic.Create(
|
||||
InvalidIndexSyntaxForD2DIntrinsic,
|
||||
firstArgument.Syntax.Parent.GetLocation(),
|
||||
parameterSymbol.Name,
|
||||
targetMethodSymbol.Name));
|
||||
}
|
||||
|
||||
// We have matched a target symbol, so let's try to get the parent shader
|
||||
if (context.ContainingSymbol.FirstAncestorOrSelf<INamedTypeSymbol>() is not { TypeKind: TypeKind.Struct } typeSymbol)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// We found a containing type, make sure it has '[D2DInputCount]'
|
||||
if (!typeSymbol.HasAttributeWithType(d2DInputCountAttributeSymbol))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// At this point we can assume the shader type is mostly valid: let's get the actual input counts and types
|
||||
D2DPixelShaderDescriptorGenerator.InputTypes.GetInfo(
|
||||
typeSymbol,
|
||||
out int inputCount,
|
||||
out _,
|
||||
out _,
|
||||
out ImmutableArray<uint> inputTypes);
|
||||
|
||||
// First validation: the index must be in range
|
||||
if ((uint)index >= (uint)inputCount)
|
||||
{
|
||||
context.ReportDiagnostic(Diagnostic.Create(
|
||||
IndexOutOfRangeForD2DIntrinsic,
|
||||
firstArgument.Syntax.GetLocation(),
|
||||
targetMethodSymbol.Name,
|
||||
index,
|
||||
typeSymbol,
|
||||
inputCount));
|
||||
}
|
||||
else if (targetInputType is not null && (D2D1PixelShaderInputType)inputTypes[index] != targetInputType)
|
||||
{
|
||||
// Second validation: the input type must match
|
||||
context.ReportDiagnostic(Diagnostic.Create(
|
||||
InvalidInputTypeForD2DIntrinsic,
|
||||
firstArgument.Syntax.GetLocation(),
|
||||
targetMethodSymbol.Name,
|
||||
index));
|
||||
}
|
||||
}, OperationKind.Invocation);
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Tries to build a map of <see cref="IMethodSymbol"/> instances for all D2D intrinsics and their associated D2D input type.
|
||||
/// </summary>
|
||||
/// <param name="compilation">The <see cref="Compilation"/> to consider for analysis.</param>
|
||||
/// <param name="methodSymbols">The resulting mapping of resolved <see cref="IMethodSymbol"/> instances.</param>
|
||||
/// <returns>Whether all requested <see cref="IMethodSymbol"/> instances could be resolved.</returns>
|
||||
private static bool TryBuildMethodSymbolMap(Compilation compilation, [NotNullWhen(true)] out ImmutableDictionary<IMethodSymbol, D2D1PixelShaderInputType?>? methodSymbols)
|
||||
{
|
||||
// Get the 'D2D' symbol, to get methods from it
|
||||
if (compilation.GetTypeByMetadataName("ComputeSharp.D2D1.D2D") is not { } d2DSymbol)
|
||||
{
|
||||
methodSymbols = null;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
// These are all the 'D2D' intrinsic methods that take a target shader input index
|
||||
string[] d2DMethodNames =
|
||||
[
|
||||
nameof(D2D.GetInput),
|
||||
nameof(D2D.GetInputCoordinate),
|
||||
nameof(D2D.SampleInput),
|
||||
nameof(D2D.SampleInputAtOffset),
|
||||
nameof(D2D.SampleInputAtPosition)
|
||||
];
|
||||
|
||||
ImmutableDictionary<IMethodSymbol, D2D1PixelShaderInputType?>.Builder inputTypeMethodMap = ImmutableDictionary.CreateBuilder<IMethodSymbol, D2D1PixelShaderInputType?>(SymbolEqualityComparer.Default);
|
||||
|
||||
// Validate all methods and build the map
|
||||
foreach (string d2DMethodName in d2DMethodNames)
|
||||
{
|
||||
// If we can't resolve a symbol (shouldn't really ever happen), just stop here
|
||||
if (d2DSymbol.GetMethod(d2DMethodName) is not { } d2DMethodSymbol)
|
||||
{
|
||||
methodSymbols = null;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
// Lookup the attribute to get the D2D input type (the attribute only exists on the 'D2D' type loaded in the analyzer)
|
||||
if (typeof(D2D).GetMethod(d2DMethodSymbol.Name).GetCustomAttribute<HlslD2DIntrinsicInputTypeAttribute>() is { } hlslD2DIntrinsicInputTypeAttribute)
|
||||
{
|
||||
inputTypeMethodMap.Add(d2DMethodSymbol, hlslD2DIntrinsicInputTypeAttribute.InputType);
|
||||
}
|
||||
else
|
||||
{
|
||||
// If the method is not annotated, we stil track it, but we will not indicate any exclusive input type.
|
||||
// This means that the input index validation logic will still work, but we'll skip the input type checks.
|
||||
inputTypeMethodMap.Add(d2DMethodSymbol, null);
|
||||
}
|
||||
}
|
||||
|
||||
methodSymbols = inputTypeMethodMap.ToImmutable();
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
-122
@@ -1,122 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Immutable;
|
||||
using System.Linq;
|
||||
using ComputeSharp.SourceGeneration.Extensions;
|
||||
using ComputeSharp.SourceGeneration.Helpers;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.Diagnostics;
|
||||
using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors;
|
||||
|
||||
namespace ComputeSharp.D2D1.SourceGenerators;
|
||||
|
||||
/// <summary>
|
||||
/// A diagnostic analyzer that generates errors for all invalid uses of the [D2DInputDescription] attribute.
|
||||
/// </summary>
|
||||
[DiagnosticAnalyzer(LanguageNames.CSharp)]
|
||||
public sealed class InvalidD2DInputDescriptionAttributeUseAnalyzer : DiagnosticAnalyzer
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = [OutOfRangeInputDescriptionIndex, RepeatedD2DInputDescriptionIndices];
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override unsafe void Initialize(AnalysisContext context)
|
||||
{
|
||||
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics);
|
||||
context.EnableConcurrentExecution();
|
||||
|
||||
context.RegisterCompilationStartAction(static context =>
|
||||
{
|
||||
// Get the [D2DInputDescription], [D2DInputCount] and ID2D1PixelShader symbols
|
||||
if (context.Compilation.GetTypeByMetadataName("ComputeSharp.D2D1.D2DInputDescriptionAttribute") is not { } d2DInputDescriptionAttributeSymbol ||
|
||||
context.Compilation.GetTypeByMetadataName("ComputeSharp.D2D1.D2DInputCountAttribute") is not { } d2DInputCountAttributeSymbol ||
|
||||
context.Compilation.GetTypeByMetadataName("ComputeSharp.D2D1.ID2D1PixelShader") is not { } d2D1PixelShaderSymbol)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
context.RegisterSymbolAction(context =>
|
||||
{
|
||||
// We're validating all struct types (since they're the possible shader types)
|
||||
if (context.Symbol is not INamedTypeSymbol { TypeKind: TypeKind.Struct } typeSymbol)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Only validate fields for shader types (same as for resource textures)
|
||||
if (!typeSymbol.HasInterfaceWithType(d2D1PixelShaderSymbol))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Immediately bail if [D2DInputCount] is not present. If that's the case, there's no way to properly
|
||||
// validate the indices of the input descriptions anyway. Another analyzer will catch these cases.
|
||||
if (!typeSymbol.TryGetAttributeWithType(d2DInputCountAttributeSymbol, out AttributeData? inputCountData))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
int inputCount = (int)inputCountData.ConstructorArguments[0].Value!;
|
||||
|
||||
// Just like in the resource texture analyzer, also bail if the input count is invalid (for the same reason)
|
||||
if (inputCount is not (>= 0 and <= 8))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
using ImmutableArrayBuilder<int> inputDescriptionIndices = new();
|
||||
|
||||
// Collect all indices of available input descriptions (there's no validation for the other properties)
|
||||
foreach (AttributeData attributeData in typeSymbol.GetAttributes())
|
||||
{
|
||||
if (SymbolEqualityComparer.Default.Equals(attributeData.AttributeClass, d2DInputDescriptionAttributeSymbol))
|
||||
{
|
||||
inputDescriptionIndices.Add((int)attributeData.ConstructorArguments[0].Value!);
|
||||
}
|
||||
}
|
||||
|
||||
// All simple indices must be in range
|
||||
foreach (int index in inputDescriptionIndices.WrittenSpan)
|
||||
{
|
||||
if (index >= inputCount)
|
||||
{
|
||||
context.ReportDiagnostic(Diagnostic.Create(
|
||||
OutOfRangeInputDescriptionIndex,
|
||||
typeSymbol.Locations.First(),
|
||||
typeSymbol));
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
Span<bool> selectedInputDescriptionIndices = stackalloc bool[8];
|
||||
|
||||
selectedInputDescriptionIndices.Clear();
|
||||
|
||||
// All input description indices must be unique
|
||||
foreach (int index in inputDescriptionIndices.WrittenSpan)
|
||||
{
|
||||
// Skip this path for invalid indices (just like with resource textures again).
|
||||
// This would just throw when accessing the span anyway (also it's unlikely).
|
||||
if (index >= 8)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
ref bool isInputDescriptionIndexUsed = ref selectedInputDescriptionIndices[index];
|
||||
|
||||
if (isInputDescriptionIndexUsed)
|
||||
{
|
||||
context.ReportDiagnostic(Diagnostic.Create(
|
||||
RepeatedD2DInputDescriptionIndices,
|
||||
typeSymbol.Locations.First(),
|
||||
typeSymbol));
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
isInputDescriptionIndexUsed = true;
|
||||
}
|
||||
}, SymbolKind.NamedType);
|
||||
});
|
||||
}
|
||||
}
|
||||
-59
@@ -1,59 +0,0 @@
|
||||
using System.Collections.Immutable;
|
||||
using System.Linq;
|
||||
using ComputeSharp.SourceGeneration.Extensions;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.Diagnostics;
|
||||
using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors;
|
||||
|
||||
namespace ComputeSharp.D2D1.SourceGenerators;
|
||||
|
||||
/// <summary>
|
||||
/// A diagnostic analyzer that generates diagnostics when a method is using [D2DPixelShaderSource] with an invalid argument.
|
||||
/// </summary>
|
||||
[DiagnosticAnalyzer(LanguageNames.CSharp)]
|
||||
public sealed class InvalidD2DPixelShaderSourceAttributeUseAnalyzer : DiagnosticAnalyzer
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = [InvalidD2DPixelShaderSource];
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override void Initialize(AnalysisContext context)
|
||||
{
|
||||
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics);
|
||||
context.EnableConcurrentExecution();
|
||||
|
||||
context.RegisterCompilationStartAction(static context =>
|
||||
{
|
||||
// Get the [D2DPixelShaderSource] symbol
|
||||
if (context.Compilation.GetTypeByMetadataName("ComputeSharp.D2D1.D2DPixelShaderSourceAttribute") is not { } d2DPixelShaderSourceAttributeSymbol)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
context.RegisterSymbolAction(context =>
|
||||
{
|
||||
// Only partial definition methods are possible targets
|
||||
if (context.Symbol is not IMethodSymbol { IsPartialDefinition: true } methodSymbol)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Ignore methods without [D2DPixelShaderSource]
|
||||
if (!methodSymbol.TryGetAttributeWithType(d2DPixelShaderSourceAttributeSymbol, out AttributeData? attributeData))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Emit a diagnostic if there is no valid HLSL source argument
|
||||
if (!attributeData.TryGetConstructorArgument(0, out string? hlslSource))
|
||||
{
|
||||
context.ReportDiagnostic(Diagnostic.Create(
|
||||
InvalidD2DPixelShaderSource,
|
||||
methodSymbol.Locations.First(),
|
||||
methodSymbol.Name,
|
||||
methodSymbol.ContainingType));
|
||||
}
|
||||
}, SymbolKind.Method);
|
||||
});
|
||||
}
|
||||
}
|
||||
-65
@@ -1,65 +0,0 @@
|
||||
using System.Collections.Immutable;
|
||||
using System.Linq;
|
||||
using ComputeSharp.SourceGeneration.Extensions;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.Diagnostics;
|
||||
using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors;
|
||||
|
||||
namespace ComputeSharp.D2D1.SourceGenerators;
|
||||
|
||||
/// <summary>
|
||||
/// A diagnostic analyzer that generates diagnostics when [D2DPixelShaderSource] is used on a method with an incorrect return type.
|
||||
/// </summary>
|
||||
[DiagnosticAnalyzer(LanguageNames.CSharp)]
|
||||
public sealed class InvalidD2DPixelShaderSourceMethodReturnTypeAnalyzer : DiagnosticAnalyzer
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = [InvalidD2DPixelShaderSourceMethodReturnType];
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override void Initialize(AnalysisContext context)
|
||||
{
|
||||
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics);
|
||||
context.EnableConcurrentExecution();
|
||||
|
||||
context.RegisterCompilationStartAction(static context =>
|
||||
{
|
||||
// Get the [D2DPixelShaderSource] symbol
|
||||
if (context.Compilation.GetTypeByMetadataName("ComputeSharp.D2D1.D2DPixelShaderSourceAttribute") is not { } d2DPixelShaderSourceAttributeSymbol)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Also get the constructed ReadOnlySpan<byte> type
|
||||
INamedTypeSymbol readOnlySpanSymbol = context.Compilation.GetTypeByMetadataName("System.ReadOnlySpan`1")!;
|
||||
INamedTypeSymbol byteSymbol = context.Compilation.GetSpecialType(SpecialType.System_Byte);
|
||||
INamedTypeSymbol readOnlySpanOfByteSymbol = readOnlySpanSymbol.Construct(byteSymbol);
|
||||
|
||||
context.RegisterSymbolAction(context =>
|
||||
{
|
||||
// Only partial definition methods are possible targets
|
||||
if (context.Symbol is not IMethodSymbol { IsPartialDefinition: true } methodSymbol)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Ignore methods without [D2DPixelShaderSource]
|
||||
if (!methodSymbol.HasAttributeWithType(d2DPixelShaderSourceAttributeSymbol))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Emit a diagnostic if the return type is not ReadOnlySpan<byte>
|
||||
if (!SymbolEqualityComparer.Default.Equals(methodSymbol.ReturnType, readOnlySpanOfByteSymbol))
|
||||
{
|
||||
context.ReportDiagnostic(Diagnostic.Create(
|
||||
InvalidD2DPixelShaderSourceMethodReturnType,
|
||||
methodSymbol.Locations.First(),
|
||||
methodSymbol.Name,
|
||||
methodSymbol.ContainingType,
|
||||
methodSymbol.ReturnType));
|
||||
}
|
||||
}, SymbolKind.Method);
|
||||
});
|
||||
}
|
||||
}
|
||||
-66
@@ -1,66 +0,0 @@
|
||||
using System.Collections.Immutable;
|
||||
using ComputeSharp.SourceGeneration.Extensions;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.Diagnostics;
|
||||
using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors;
|
||||
|
||||
namespace ComputeSharp.D2D1.SourceGenerators;
|
||||
|
||||
/// <summary>
|
||||
/// A diagnostic analyzer that generates diagnostics when [D2DRequiresDoublePrecisionSupport] is used incorrectly.
|
||||
/// </summary>
|
||||
[DiagnosticAnalyzer(LanguageNames.CSharp)]
|
||||
public sealed class InvalidD2DRequiresDoublePrecisionSupportAnalyzer : DiagnosticAnalyzer
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = [InvalidD2DRequiresDoublePrecisionSupportAttribute];
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override void Initialize(AnalysisContext context)
|
||||
{
|
||||
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics);
|
||||
context.EnableConcurrentExecution();
|
||||
|
||||
context.RegisterCompilationStartAction(static context =>
|
||||
{
|
||||
// Get the [D2DRequiresDoublePrecisionSupport], [D2DShaderProfile] and [D2DGeneratedPixelShaderDescriptor] symbols
|
||||
if (context.Compilation.GetTypeByMetadataName("ComputeSharp.D2D1.D2DRequiresDoublePrecisionSupportAttribute") is not { } d2DRequiresDoublePrecisionSupportAttributeSymbol ||
|
||||
context.Compilation.GetTypeByMetadataName("ComputeSharp.D2D1.D2DShaderProfileAttribute") is not { } d2DShaderProfileAttributeSymbol ||
|
||||
context.Compilation.GetTypeByMetadataName("ComputeSharp.D2D1.D2DGeneratedPixelShaderDescriptorAttribute") is not { } d2DGeneratedPixelShaderDescriptorAttributeSymbol)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
context.RegisterSymbolAction(context =>
|
||||
{
|
||||
// Only struct types are possible targets
|
||||
if (context.Symbol is not INamedTypeSymbol { TypeKind: TypeKind.Struct } typeSymbol)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Skip the type if it's not a generated shader descriptor target
|
||||
if (!typeSymbol.HasAttributeWithType(d2DGeneratedPixelShaderDescriptorAttributeSymbol))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// If the shader is precompiled, there is nothing left to do
|
||||
if (typeSymbol.HasAttributeWithType(d2DShaderProfileAttributeSymbol) ||
|
||||
typeSymbol.ContainingAssembly.HasAttributeWithType(d2DShaderProfileAttributeSymbol))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Emit a diagnostic if the type is not precompiled and has [D2DRequiresDoublePrecisionSupport]
|
||||
if (typeSymbol.TryGetAttributeWithType(d2DRequiresDoublePrecisionSupportAttributeSymbol, out AttributeData? attributeData))
|
||||
{
|
||||
context.ReportDiagnostic(Diagnostic.Create(
|
||||
InvalidD2DRequiresDoublePrecisionSupportAttribute,
|
||||
attributeData.GetLocation(),
|
||||
typeSymbol));
|
||||
}
|
||||
}, SymbolKind.NamedType);
|
||||
});
|
||||
}
|
||||
}
|
||||
-64
@@ -1,64 +0,0 @@
|
||||
using System.Collections.Immutable;
|
||||
using System.Linq;
|
||||
using ComputeSharp.SourceGeneration.Extensions;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.Diagnostics;
|
||||
using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors;
|
||||
|
||||
namespace ComputeSharp.D2D1.SourceGenerators;
|
||||
|
||||
/// <summary>
|
||||
/// A diagnostic analyzer that generates an error whenever [D2DResourceTextureIndex] is used incorrectly to annotate a field.
|
||||
/// </summary>
|
||||
[DiagnosticAnalyzer(LanguageNames.CSharp)]
|
||||
public sealed class InvalidD2DResourceTextureIndexAttributeLocationAnalyzer : DiagnosticAnalyzer
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = [InvalidD2DResourceTextureIndexAttributeLocation];
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override void Initialize(AnalysisContext context)
|
||||
{
|
||||
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics);
|
||||
context.EnableConcurrentExecution();
|
||||
|
||||
context.RegisterCompilationStartAction(static context =>
|
||||
{
|
||||
// Get the [D2DResourceTextureIndex] symbol, and the ones for the D2D resource texture types
|
||||
if (context.Compilation.GetTypeByMetadataName("ComputeSharp.D2D1.D2DResourceTextureIndexAttribute") is not { } d2DResourceTextureIndexAttributeSymbol ||
|
||||
context.Compilation.GetTypeByMetadataName("ComputeSharp.D2D1.D2D1ResourceTexture1D`1") is not { } d2D1ResourceTexture1DSymbol ||
|
||||
context.Compilation.GetTypeByMetadataName("ComputeSharp.D2D1.D2D1ResourceTexture2D`1") is not { } d2D1ResourceTexture2DSymbol ||
|
||||
context.Compilation.GetTypeByMetadataName("ComputeSharp.D2D1.D2D1ResourceTexture3D`1") is not { } d2D1ResourceTexture3DSymbol)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Inspect all fields to make sure they're not using the attribute incorrectly
|
||||
context.RegisterSymbolAction(context =>
|
||||
{
|
||||
IFieldSymbol fieldSymbol = (IFieldSymbol)context.Symbol;
|
||||
|
||||
if (fieldSymbol.HasAttributeWithType(d2DResourceTextureIndexAttributeSymbol))
|
||||
{
|
||||
// If the field is using [D2DResourceTextureIndex], it must be a D2D resource texture. We can first
|
||||
// just check that the field type is a generic named type (since that's the case if it's indeed of
|
||||
// a D2D resource texture type). Past that, we just check that it's one of the three possible types.
|
||||
if (fieldSymbol.Type is not INamedTypeSymbol { IsGenericType: true } typeSymbol ||
|
||||
!(SymbolEqualityComparer.Default.Equals(typeSymbol.ConstructedFrom, d2D1ResourceTexture1DSymbol) ||
|
||||
SymbolEqualityComparer.Default.Equals(typeSymbol.ConstructedFrom, d2D1ResourceTexture2DSymbol) ||
|
||||
SymbolEqualityComparer.Default.Equals(typeSymbol.ConstructedFrom, d2D1ResourceTexture3DSymbol)))
|
||||
{
|
||||
Diagnostic diagnostic = Diagnostic.Create(
|
||||
InvalidD2DResourceTextureIndexAttributeLocation,
|
||||
fieldSymbol.Locations.First(),
|
||||
fieldSymbol.Name,
|
||||
fieldSymbol.ContainingType,
|
||||
fieldSymbol.Type);
|
||||
|
||||
context.ReportDiagnostic(diagnostic);
|
||||
}
|
||||
}
|
||||
}, SymbolKind.Field);
|
||||
});
|
||||
}
|
||||
}
|
||||
-193
@@ -1,193 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Immutable;
|
||||
using System.Linq;
|
||||
using ComputeSharp.SourceGeneration.Extensions;
|
||||
using ComputeSharp.SourceGeneration.Helpers;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.Diagnostics;
|
||||
using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors;
|
||||
|
||||
namespace ComputeSharp.D2D1.SourceGenerators;
|
||||
|
||||
/// <summary>
|
||||
/// A diagnostic analyzer that generates errors for all invalid uses of the [D2DResourceTextureIndex] attribute.
|
||||
/// </summary>
|
||||
[DiagnosticAnalyzer(LanguageNames.CSharp)]
|
||||
public sealed class InvalidD2DResourceTextureIndexAttributeUseAnalyzer : DiagnosticAnalyzer
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } =
|
||||
[
|
||||
MissingD2DResourceTextureIndexAttribute,
|
||||
ResourceTextureIndexOverlappingWithInputIndex,
|
||||
OutOfRangeResourceTextureIndex,
|
||||
RepeatedD2DResourceTextureIndices,
|
||||
];
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override unsafe void Initialize(AnalysisContext context)
|
||||
{
|
||||
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics);
|
||||
context.EnableConcurrentExecution();
|
||||
|
||||
context.RegisterCompilationStartAction(static context =>
|
||||
{
|
||||
// Get all necessary symbols (we need a whole bunch of them here)
|
||||
if (context.Compilation.GetTypeByMetadataName("ComputeSharp.D2D1.D2DResourceTextureIndexAttribute") is not { } d2DResourceTextureIndexAttributeSymbol ||
|
||||
context.Compilation.GetTypeByMetadataName("ComputeSharp.D2D1.D2D1ResourceTexture1D`1") is not { } d2D1ResourceTexture1DSymbol ||
|
||||
context.Compilation.GetTypeByMetadataName("ComputeSharp.D2D1.D2D1ResourceTexture2D`1") is not { } d2D1ResourceTexture2DSymbol ||
|
||||
context.Compilation.GetTypeByMetadataName("ComputeSharp.D2D1.D2D1ResourceTexture3D`1") is not { } d2D1ResourceTexture3DSymbol ||
|
||||
context.Compilation.GetTypeByMetadataName("ComputeSharp.D2D1.D2DInputCountAttribute") is not { } d2DInputCountAttributeSymbol ||
|
||||
context.Compilation.GetTypeByMetadataName("ComputeSharp.D2D1.ID2D1PixelShader") is not { } d2D1PixelShaderSymbol)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
context.RegisterSymbolAction(context =>
|
||||
{
|
||||
// We're validating all struct types (since they're the possible shader types)
|
||||
if (context.Symbol is not INamedTypeSymbol { TypeKind: TypeKind.Struct } typeSymbol)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Only validate fields for shader types (even without a generated descriptor)
|
||||
if (!typeSymbol.HasInterfaceWithType(d2D1PixelShaderSymbol))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
using ImmutableArrayBuilder<(int? Index, int Rank)> resourceTextureInfos = new();
|
||||
|
||||
foreach (ISymbol memberSymbol in typeSymbol.GetMembers())
|
||||
{
|
||||
// Only look for valid candidate fields (same logic as in D2DPixelShaderDescriptorGenerator.InputTypes)
|
||||
if (memberSymbol is not IFieldSymbol { IsStatic: false, Type: INamedTypeSymbol { IsUnmanagedType: true } } fieldSymbol)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
// Specifically check that the type is generic and grab the source one
|
||||
if (fieldSymbol.Type is not INamedTypeSymbol { ConstructedFrom: { } nonGenericFieldTypeSymbol })
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
// Check that the field is a D2D resource texture and get the rank
|
||||
int rank = nonGenericFieldTypeSymbol switch
|
||||
{
|
||||
_ when SymbolEqualityComparer.Default.Equals(d2D1ResourceTexture1DSymbol, nonGenericFieldTypeSymbol) => 1,
|
||||
_ when SymbolEqualityComparer.Default.Equals(d2D1ResourceTexture2DSymbol, nonGenericFieldTypeSymbol) => 2,
|
||||
_ when SymbolEqualityComparer.Default.Equals(d2D1ResourceTexture3DSymbol, nonGenericFieldTypeSymbol) => 3,
|
||||
_ => 0
|
||||
};
|
||||
|
||||
// The field is not a D2D resource texture, just skip it
|
||||
if (rank == 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
int? index = null;
|
||||
|
||||
// Try to get the annotated index for the D2D texture, and track it. This
|
||||
// logic is also in sync with D2DPixelShaderDescriptorGenerator.InputTypes.
|
||||
if (fieldSymbol.TryGetAttributeWithType(d2DResourceTextureIndexAttributeSymbol, out AttributeData? textureIndexData))
|
||||
{
|
||||
if (textureIndexData.TryGetConstructorArgument(0, out int resourceIndex))
|
||||
{
|
||||
index = resourceIndex;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// If the attribute is missing, emit a diagnostic
|
||||
context.ReportDiagnostic(Diagnostic.Create(
|
||||
MissingD2DResourceTextureIndexAttribute,
|
||||
fieldSymbol.Locations.First(),
|
||||
fieldSymbol.Name,
|
||||
typeSymbol));
|
||||
}
|
||||
|
||||
resourceTextureInfos.Add((index, rank));
|
||||
}
|
||||
|
||||
int inputCount = 0;
|
||||
|
||||
// Same logic as in D2DPixelShaderDescriptorGenerator.InputTypes (see there for reference).
|
||||
// Keeping this in sync to ensure a consistent behavior (this should be updated if that changes).
|
||||
if (typeSymbol.TryGetAttributeWithType(d2DInputCountAttributeSymbol, out AttributeData? inputCountData))
|
||||
{
|
||||
inputCount = Math.Max((int)inputCountData.ConstructorArguments[0].Value!, 0);
|
||||
}
|
||||
|
||||
// If the input count is invalid, do nothing and avoid emitting potentially incorrect diagnostics
|
||||
// based on the resource texture indices with respect to the input count. The generator for the
|
||||
// InputType property has already emitted diagnostic for this error, so this analyzer can just
|
||||
// wait for users to go back and fix that issue before proceeding.
|
||||
if (inputCount is not (>= 0 and <= 8))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Validate that the resource texture indices don't overlap with the shader inputs
|
||||
foreach ((int? index, _) in resourceTextureInfos.WrittenSpan)
|
||||
{
|
||||
if (index < inputCount)
|
||||
{
|
||||
context.ReportDiagnostic(Diagnostic.Create(
|
||||
ResourceTextureIndexOverlappingWithInputIndex,
|
||||
typeSymbol.Locations.First(),
|
||||
typeSymbol));
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Validate that no resource texture has an index greater than or equal to 16
|
||||
foreach ((int? index, _) in resourceTextureInfos.WrittenSpan)
|
||||
{
|
||||
if (index >= 16)
|
||||
{
|
||||
context.ReportDiagnostic(Diagnostic.Create(
|
||||
OutOfRangeResourceTextureIndex,
|
||||
typeSymbol.Locations.First(),
|
||||
typeSymbol));
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
Span<bool> selectedResourceTextureIndices = stackalloc bool[16];
|
||||
|
||||
selectedResourceTextureIndices.Clear();
|
||||
|
||||
// All input description indices must be unique
|
||||
foreach ((int? index, _) in resourceTextureInfos.WrittenSpan)
|
||||
{
|
||||
// Skip this path for invalid indices, as those will receive other diagnostics.
|
||||
// We have to do this to avoid generating false positives for the default value.
|
||||
// Because indices could be out of range, we also have to skip any of those.
|
||||
if (index is null or >= 16)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
ref bool isResourceTextureIndexUsed = ref selectedResourceTextureIndices[index ?? 0];
|
||||
|
||||
if (isResourceTextureIndexUsed)
|
||||
{
|
||||
context.ReportDiagnostic(Diagnostic.Create(
|
||||
RepeatedD2DResourceTextureIndices,
|
||||
typeSymbol.Locations.First(),
|
||||
typeSymbol));
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
isResourceTextureIndexUsed = true;
|
||||
}
|
||||
}, SymbolKind.NamedType);
|
||||
});
|
||||
}
|
||||
}
|
||||
-63
@@ -1,63 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Immutable;
|
||||
using ComputeSharp.SourceGeneration.Extensions;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.Diagnostics;
|
||||
using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors;
|
||||
|
||||
namespace ComputeSharp.D2D1.SourceGenerators;
|
||||
|
||||
/// <summary>
|
||||
/// A diagnostic analyzer that generates an error whenever [D2DEffectId] is used with an invalid value.
|
||||
/// </summary>
|
||||
[DiagnosticAnalyzer(LanguageNames.CSharp)]
|
||||
public sealed class InvalidEffectIdValueAnalyzer : DiagnosticAnalyzer
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = [InvalidD2DEffectIdAttributeValue];
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override void Initialize(AnalysisContext context)
|
||||
{
|
||||
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics);
|
||||
context.EnableConcurrentExecution();
|
||||
|
||||
context.RegisterCompilationStartAction(static context =>
|
||||
{
|
||||
// Get the [D2DEffectId] symbol
|
||||
if (context.Compilation.GetTypeByMetadataName("ComputeSharp.D2D1.D2DEffectIdAttribute") is not { } d2DEffectIdAttributeSymbol)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
context.RegisterSymbolAction(context =>
|
||||
{
|
||||
// Only struct types are possible targets
|
||||
if (context.Symbol is not INamedTypeSymbol { TypeKind: TypeKind.Struct } typeSymbol)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
foreach (AttributeData attributeData in typeSymbol.GetAttributes())
|
||||
{
|
||||
// Look for the [D2DEffectId] use
|
||||
if (!SymbolEqualityComparer.Default.Equals(attributeData.AttributeClass, d2DEffectIdAttributeSymbol))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
// Validate the GUID text and emit a diagnostic if needed
|
||||
if (attributeData.ConstructorArguments is not [{ Value: string value }] ||
|
||||
!Guid.TryParse(value, out _))
|
||||
{
|
||||
context.ReportDiagnostic(Diagnostic.Create(
|
||||
InvalidD2DEffectIdAttributeValue,
|
||||
attributeData.GetLocation()));
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
}, SymbolKind.NamedType);
|
||||
});
|
||||
}
|
||||
}
|
||||
-92
@@ -1,92 +0,0 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Immutable;
|
||||
using ComputeSharp.D2D1.SourceGenerators.Helpers;
|
||||
using ComputeSharp.SourceGeneration.Extensions;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.Diagnostics;
|
||||
using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors;
|
||||
|
||||
namespace ComputeSharp.D2D1.SourceGenerators;
|
||||
|
||||
/// <summary>
|
||||
/// A diagnostic analyzer that generates an error whenever any shader metadata value attributes are used with an invalid value.
|
||||
/// </summary>
|
||||
[DiagnosticAnalyzer(LanguageNames.CSharp)]
|
||||
public sealed class InvalidEffectMetadataValueAnalyzer : DiagnosticAnalyzer
|
||||
{
|
||||
/// <summary>
|
||||
/// The set of type names for all metadata attributes.
|
||||
/// </summary>
|
||||
private static readonly ImmutableArray<string> MetadataAttributeTypeNames =
|
||||
[
|
||||
"ComputeSharp.D2D1.D2DEffectDisplayNameAttribute",
|
||||
"ComputeSharp.D2D1.D2DEffectDescriptionAttribute",
|
||||
"ComputeSharp.D2D1.D2DEffectCategoryAttribute",
|
||||
"ComputeSharp.D2D1.D2DEffectAuthorAttribute",
|
||||
];
|
||||
|
||||
/// <summary>
|
||||
/// The mapping of diagnostics to their attribute type names.
|
||||
/// </summary>
|
||||
private static readonly ImmutableDictionary<string, DiagnosticDescriptor> AttributeTypeNameToDiagnosticMapping = ImmutableDictionary.CreateRange(
|
||||
[
|
||||
new KeyValuePair<string, DiagnosticDescriptor>("D2DEffectDisplayNameAttribute", InvalidD2DEffectDisplayNameAttributeValue),
|
||||
new KeyValuePair<string, DiagnosticDescriptor>("D2DEffectDescriptionAttribute", InvalidD2DEffectDescriptionAttributeValue),
|
||||
new KeyValuePair<string, DiagnosticDescriptor>("D2DEffectCategoryAttribute", InvalidD2DEffectCategoryAttributeValue),
|
||||
new KeyValuePair<string, DiagnosticDescriptor>("D2DEffectAuthorAttribute", InvalidD2DEffectAuthorAttributeValue)
|
||||
]);
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } =
|
||||
[
|
||||
InvalidD2DEffectDisplayNameAttributeValue,
|
||||
InvalidD2DEffectDescriptionAttributeValue,
|
||||
InvalidD2DEffectCategoryAttributeValue,
|
||||
InvalidD2DEffectAuthorAttributeValue,
|
||||
];
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override void Initialize(AnalysisContext context)
|
||||
{
|
||||
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics);
|
||||
context.EnableConcurrentExecution();
|
||||
|
||||
context.RegisterCompilationStartAction(static context =>
|
||||
{
|
||||
// Get the metadata attribute symbols
|
||||
if (!context.Compilation.TryBuildNamedTypeSymbolSet(MetadataAttributeTypeNames, out ImmutableHashSet<INamedTypeSymbol>? typeSymbols))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
context.RegisterSymbolAction(context =>
|
||||
{
|
||||
// Only struct types and assemblies are possible targets
|
||||
if (context.Symbol is not (INamedTypeSymbol { TypeKind: TypeKind.Struct } or IAssemblySymbol))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
foreach (AttributeData attributeData in context.Symbol.GetAttributes())
|
||||
{
|
||||
// Only check attributes we care about
|
||||
if (attributeData.AttributeClass is not INamedTypeSymbol attributeSymbol ||
|
||||
!typeSymbols.Contains(attributeSymbol))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
// Validate the effect display name
|
||||
if (!D2D1EffectMetadataParser.IsValidEffectMetadataName(attributeData))
|
||||
{
|
||||
context.ReportDiagnostic(Diagnostic.Create(
|
||||
AttributeTypeNameToDiagnosticMapping[attributeSymbol.MetadataName],
|
||||
attributeData.GetLocation()));
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
}, SymbolKind.NamedType | SymbolKind.Assembly);
|
||||
});
|
||||
}
|
||||
}
|
||||
-59
@@ -1,59 +0,0 @@
|
||||
using System.Collections.Immutable;
|
||||
using ComputeSharp.SourceGeneration.Extensions;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.Diagnostics;
|
||||
using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors;
|
||||
|
||||
namespace ComputeSharp.D2D1.SourceGenerators;
|
||||
|
||||
/// <summary>
|
||||
/// A diagnostic analyzer that generates an error whenever invalid options are used in a [D2D1CompileOptions] attribute over a shader type.
|
||||
/// </summary>
|
||||
[DiagnosticAnalyzer(LanguageNames.CSharp)]
|
||||
public sealed class InvalidShaderTypeCompileOptionsAnalyzer : DiagnosticAnalyzer
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = [InvalidPackMatrixColumnMajorOption];
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override void Initialize(AnalysisContext context)
|
||||
{
|
||||
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics);
|
||||
context.EnableConcurrentExecution();
|
||||
|
||||
context.RegisterCompilationStartAction(static context =>
|
||||
{
|
||||
// Get the [D2DCompileOptions] attribute type
|
||||
if (context.Compilation.GetTypeByMetadataName("ComputeSharp.D2D1.D2DCompileOptionsAttribute") is not { } d2DCompileOptionsAttributeSymbol)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
context.RegisterSymbolAction(context =>
|
||||
{
|
||||
// We're validating all struct types (since they're the possible shader types)
|
||||
if (context.Symbol is not INamedTypeSymbol { TypeKind: TypeKind.Struct } typeSymbol)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Check that the type is using [D2DCompileOptions]
|
||||
if (!typeSymbol.TryGetAttributeWithFullyQualifiedMetadataName("ComputeSharp.D2D1.D2DCompileOptionsAttribute", out AttributeData? attributeData))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
D2D1CompileOptions options = (D2D1CompileOptions)attributeData.ConstructorArguments[0].Value!;
|
||||
|
||||
// Same validation and diagnostic as in the assembly-level analyzer
|
||||
if ((options & D2D1CompileOptions.PackMatrixColumnMajor) != 0)
|
||||
{
|
||||
context.ReportDiagnostic(Diagnostic.Create(
|
||||
InvalidPackMatrixColumnMajorOption,
|
||||
attributeData.ApplicationSyntaxReference?.GetSyntax(context.CancellationToken).GetLocation(),
|
||||
typeSymbol));
|
||||
}
|
||||
}, SymbolKind.NamedType);
|
||||
});
|
||||
}
|
||||
}
|
||||
-212
@@ -1,212 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Immutable;
|
||||
using System.Linq;
|
||||
using ComputeSharp.SourceGeneration.Extensions;
|
||||
using ComputeSharp.SourceGeneration.Helpers;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.Diagnostics;
|
||||
using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors;
|
||||
|
||||
namespace ComputeSharp.D2D1.SourceGenerators;
|
||||
|
||||
/// <summary>
|
||||
/// A diagnostic analyzer that generates errors whenever a shader type is declaring invalid inputs.
|
||||
/// </summary>
|
||||
[DiagnosticAnalyzer(LanguageNames.CSharp)]
|
||||
public sealed class InvalidShaderTypeInputsAnalyzer : DiagnosticAnalyzer
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } =
|
||||
[
|
||||
MissingD2DInputCountAttribute,
|
||||
InvalidD2DInputCount,
|
||||
OutOfRangeInputIndex,
|
||||
RepeatedD2DInputSimpleIndices,
|
||||
RepeatedD2DInputComplexIndices,
|
||||
InvalidSimpleAndComplexIndicesCombination,
|
||||
];
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override unsafe void Initialize(AnalysisContext context)
|
||||
{
|
||||
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics);
|
||||
context.EnableConcurrentExecution();
|
||||
|
||||
context.RegisterCompilationStartAction(static context =>
|
||||
{
|
||||
// Get the [D2DInputCount], [D2DInputSimple], [D2DInputComplex] and ID2D1PixelShader symbols
|
||||
if (context.Compilation.GetTypeByMetadataName("ComputeSharp.D2D1.D2DInputCountAttribute") is not { } d2DInputCountAttributeSymbol ||
|
||||
context.Compilation.GetTypeByMetadataName("ComputeSharp.D2D1.D2DInputSimpleAttribute") is not { } d2DInputSimpleAttributeSymbol ||
|
||||
context.Compilation.GetTypeByMetadataName("ComputeSharp.D2D1.D2DInputComplexAttribute") is not { } d2DInputComplexAttributeSymbol ||
|
||||
context.Compilation.GetTypeByMetadataName("ComputeSharp.D2D1.ID2D1PixelShader") is not { } d2D1PixelShaderSymbol)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
context.RegisterSymbolAction(context =>
|
||||
{
|
||||
// We're validating all struct types (since they're the possible shader types)
|
||||
if (context.Symbol is not INamedTypeSymbol { TypeKind: TypeKind.Struct } typeSymbol)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Only validate fields for shader types (same as for resource textures)
|
||||
if (!typeSymbol.HasInterfaceWithType(d2D1PixelShaderSymbol))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// If there is no [D2DInputCount], we must stop here, but also emit a diagnostic (as it's mandatory)
|
||||
if (!typeSymbol.TryGetAttributeWithType(d2DInputCountAttributeSymbol, out AttributeData? inputCountData))
|
||||
{
|
||||
context.ReportDiagnostic(Diagnostic.Create(
|
||||
MissingD2DInputCountAttribute,
|
||||
typeSymbol.Locations.First(),
|
||||
typeSymbol));
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
int inputCount = (int)inputCountData.ConstructorArguments[0].Value!;
|
||||
|
||||
// Validate the input count
|
||||
if (inputCount is not (>= 0 and <= 8))
|
||||
{
|
||||
context.ReportDiagnostic(Diagnostic.Create(
|
||||
InvalidD2DInputCount,
|
||||
typeSymbol.Locations.First(),
|
||||
typeSymbol,
|
||||
inputCount));
|
||||
}
|
||||
|
||||
// If we input is not valid, we can just clamp it to ensure it's nor negative, and
|
||||
// continue to validate the rest normally. This will avoid some false positives.
|
||||
inputCount = Math.Max(inputCount, 0);
|
||||
|
||||
using ImmutableArrayBuilder<int> inputSimpleIndices = new();
|
||||
using ImmutableArrayBuilder<int> inputComplexIndices = new();
|
||||
|
||||
// Gather the indices of all explicitly declared simple and complex inputs
|
||||
foreach (AttributeData attributeData in typeSymbol.GetAttributes())
|
||||
{
|
||||
if (SymbolEqualityComparer.Default.Equals(attributeData.AttributeClass, d2DInputSimpleAttributeSymbol))
|
||||
{
|
||||
inputSimpleIndices.Add((int)attributeData.ConstructorArguments[0].Value!);
|
||||
}
|
||||
else if (SymbolEqualityComparer.Default.Equals(attributeData.AttributeClass, d2DInputComplexAttributeSymbol))
|
||||
{
|
||||
inputComplexIndices.Add((int)attributeData.ConstructorArguments[0].Value!);
|
||||
}
|
||||
}
|
||||
|
||||
// All simple indices must be in range
|
||||
foreach (int index in inputSimpleIndices.WrittenSpan)
|
||||
{
|
||||
if ((uint)index >= inputCount)
|
||||
{
|
||||
context.ReportDiagnostic(Diagnostic.Create(
|
||||
OutOfRangeInputIndex,
|
||||
typeSymbol.Locations.First(),
|
||||
typeSymbol));
|
||||
|
||||
goto AfterOutOfRangeInputValidation;
|
||||
}
|
||||
}
|
||||
|
||||
// All complex indices must also be in range (of course)
|
||||
foreach (int index in inputComplexIndices.WrittenSpan)
|
||||
{
|
||||
if ((uint)index >= inputCount)
|
||||
{
|
||||
context.ReportDiagnostic(Diagnostic.Create(
|
||||
OutOfRangeInputIndex,
|
||||
typeSymbol.Locations.First(),
|
||||
typeSymbol));
|
||||
|
||||
goto AfterOutOfRangeInputValidation;
|
||||
}
|
||||
}
|
||||
|
||||
AfterOutOfRangeInputValidation:
|
||||
|
||||
Span<bool> selectedSimpleInputIndices = stackalloc bool[8];
|
||||
Span<bool> selectedComplexInputIndices = stackalloc bool[8];
|
||||
|
||||
selectedSimpleInputIndices.Clear();
|
||||
selectedComplexInputIndices.Clear();
|
||||
|
||||
bool hasReportedRepeatedD2DinputSimpleIndex = false;
|
||||
bool hasReportedRepeatedD2DinputComplexIndex = false;
|
||||
|
||||
// All simple indices must be unique
|
||||
foreach (int index in inputSimpleIndices.WrittenSpan)
|
||||
{
|
||||
// Skip this path for invalid indices (just like with resource textures again).
|
||||
// This same exact pattern is also used when validating input descriptions.
|
||||
if ((uint)index >= 8)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
ref bool isInputIndexUsed = ref selectedSimpleInputIndices[index];
|
||||
|
||||
// If we detect a repeated index, we emit the diagnostic (only at most once), but
|
||||
// then we also continue processing all remaining items. This is done to make sure
|
||||
// that all used indices are correctly marked, so that the detection of invalid
|
||||
// combinations at the end of the analyzer doesn't risk having false negatives.
|
||||
if (isInputIndexUsed && !hasReportedRepeatedD2DinputSimpleIndex)
|
||||
{
|
||||
context.ReportDiagnostic(Diagnostic.Create(
|
||||
RepeatedD2DInputSimpleIndices,
|
||||
typeSymbol.Locations.First(),
|
||||
typeSymbol));
|
||||
|
||||
hasReportedRepeatedD2DinputSimpleIndex = true;
|
||||
}
|
||||
|
||||
isInputIndexUsed = true;
|
||||
}
|
||||
|
||||
// All complex indices must be unique as well (again, of course)
|
||||
foreach (int index in inputComplexIndices.WrittenSpan)
|
||||
{
|
||||
if ((uint)index >= 8)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
ref bool isInputIndexUsed = ref selectedComplexInputIndices[index];
|
||||
|
||||
if (isInputIndexUsed && !hasReportedRepeatedD2DinputComplexIndex)
|
||||
{
|
||||
context.ReportDiagnostic(Diagnostic.Create(
|
||||
RepeatedD2DInputComplexIndices,
|
||||
typeSymbol.Locations.First(),
|
||||
typeSymbol));
|
||||
|
||||
hasReportedRepeatedD2DinputComplexIndex = true;
|
||||
}
|
||||
|
||||
isInputIndexUsed = true;
|
||||
}
|
||||
|
||||
// Simple and complex indices can't have indices in common. We just validate
|
||||
// the entire temporary spans, so that even if some values are out of range,
|
||||
// we still also detect that some are conflicting.
|
||||
for (int i = 0; i < 8; i++)
|
||||
{
|
||||
if (selectedSimpleInputIndices[i] && selectedComplexInputIndices[i])
|
||||
{
|
||||
context.ReportDiagnostic(Diagnostic.Create(
|
||||
InvalidSimpleAndComplexIndicesCombination,
|
||||
typeSymbol.Locations.First(),
|
||||
typeSymbol));
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
}, SymbolKind.NamedType);
|
||||
});
|
||||
}
|
||||
}
|
||||
-19
@@ -1,19 +0,0 @@
|
||||
using ComputeSharp.SourceGeneration.Diagnostics;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.Diagnostics;
|
||||
using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors;
|
||||
|
||||
namespace ComputeSharp.D2D1.SourceGenerators;
|
||||
|
||||
/// <inheritdoc/>
|
||||
[DiagnosticAnalyzer(LanguageNames.CSharp)]
|
||||
public sealed class MissingAllowUnsafeBlocksCompilationOptionAnalyzer : MissingAllowUnsafeBlocksCompilationOptionAnalyzerBase
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="MissingAllowUnsafeBlocksCompilationOptionAnalyzer"/> instance.
|
||||
/// </summary>
|
||||
public MissingAllowUnsafeBlocksCompilationOptionAnalyzer()
|
||||
: base(MissingAllowUnsafeBlocksOption, "ComputeSharp.D2D1.D2DGeneratedPixelShaderDescriptorAttribute")
|
||||
{
|
||||
}
|
||||
}
|
||||
-61
@@ -1,61 +0,0 @@
|
||||
using System.Collections.Immutable;
|
||||
using System.Linq;
|
||||
using ComputeSharp.SourceGeneration.Extensions;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.Diagnostics;
|
||||
using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors;
|
||||
|
||||
namespace ComputeSharp.D2D1.SourceGenerators;
|
||||
|
||||
/// <summary>
|
||||
/// A diagnostic analyzer that generates diagnostics when a method with [D2DPixelShaderSource] isn't using [D2DCompileOptions].
|
||||
/// </summary>
|
||||
[DiagnosticAnalyzer(LanguageNames.CSharp)]
|
||||
public sealed class MissingD2DCompileOptionsOnD2DPixelShaderSourceMethodAnalyzer : DiagnosticAnalyzer
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = [MissingCompileOptionsForD2DPixelShaderSource];
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override void Initialize(AnalysisContext context)
|
||||
{
|
||||
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics);
|
||||
context.EnableConcurrentExecution();
|
||||
|
||||
context.RegisterCompilationStartAction(static context =>
|
||||
{
|
||||
// Get the [D2DPixelShaderSource] and [D2DShaderProfile] symbols
|
||||
if (context.Compilation.GetTypeByMetadataName("ComputeSharp.D2D1.D2DPixelShaderSourceAttribute") is not { } d2DPixelShaderSourceAttributeSymbol ||
|
||||
context.Compilation.GetTypeByMetadataName("ComputeSharp.D2D1.D2DCompileOptionsAttribute") is not { } d2DCompileOptionsAttributeSymbol)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
context.RegisterSymbolAction(context =>
|
||||
{
|
||||
// Only partial definition methods are possible targets
|
||||
if (context.Symbol is not IMethodSymbol { IsPartialDefinition: true } methodSymbol)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Ignore methods without [D2DPixelShaderSource]
|
||||
if (!methodSymbol.HasAttributeWithType(d2DPixelShaderSourceAttributeSymbol))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Emit a diagnostic if there is no compile options available at any level
|
||||
if (!methodSymbol.HasAttributeWithType(d2DCompileOptionsAttributeSymbol) &&
|
||||
!methodSymbol.ContainingAssembly.HasAttributeWithType(d2DCompileOptionsAttributeSymbol))
|
||||
{
|
||||
context.ReportDiagnostic(Diagnostic.Create(
|
||||
MissingCompileOptionsForD2DPixelShaderSource,
|
||||
methodSymbol.Locations.First(),
|
||||
methodSymbol.Name,
|
||||
methodSymbol.ContainingType));
|
||||
}
|
||||
}, SymbolKind.Method);
|
||||
});
|
||||
}
|
||||
}
|
||||
-61
@@ -1,61 +0,0 @@
|
||||
using System.Collections.Immutable;
|
||||
using System.Linq;
|
||||
using ComputeSharp.SourceGeneration.Extensions;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.Diagnostics;
|
||||
using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors;
|
||||
|
||||
namespace ComputeSharp.D2D1.SourceGenerators;
|
||||
|
||||
/// <summary>
|
||||
/// A diagnostic analyzer that generates diagnostics when a method with [D2DPixelShaderSource] isn't using [D2DShaderProfile].
|
||||
/// </summary>
|
||||
[DiagnosticAnalyzer(LanguageNames.CSharp)]
|
||||
public sealed class MissingD2DShaderProfileOnD2DPixelShaderSourceMethodAnalyzer : DiagnosticAnalyzer
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = [MissingShaderProfileForD2DPixelShaderSource];
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override void Initialize(AnalysisContext context)
|
||||
{
|
||||
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics);
|
||||
context.EnableConcurrentExecution();
|
||||
|
||||
context.RegisterCompilationStartAction(static context =>
|
||||
{
|
||||
// Get the [D2DPixelShaderSource] and [D2DShaderProfile] symbols
|
||||
if (context.Compilation.GetTypeByMetadataName("ComputeSharp.D2D1.D2DPixelShaderSourceAttribute") is not { } d2DPixelShaderSourceAttributeSymbol ||
|
||||
context.Compilation.GetTypeByMetadataName("ComputeSharp.D2D1.D2DShaderProfileAttribute") is not { } d2DShaderProfileAttributeSymbol)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
context.RegisterSymbolAction(context =>
|
||||
{
|
||||
// Only partial definition methods are possible targets
|
||||
if (context.Symbol is not IMethodSymbol { IsPartialDefinition: true } methodSymbol)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Ignore methods without [D2DPixelShaderSource]
|
||||
if (!methodSymbol.HasAttributeWithType(d2DPixelShaderSourceAttributeSymbol))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Emit a diagnostic if there is no shader profile available at any level
|
||||
if (!methodSymbol.HasAttributeWithType(d2DShaderProfileAttributeSymbol) &&
|
||||
!methodSymbol.ContainingAssembly.HasAttributeWithType(d2DShaderProfileAttributeSymbol))
|
||||
{
|
||||
context.ReportDiagnostic(Diagnostic.Create(
|
||||
MissingShaderProfileForD2DPixelShaderSource,
|
||||
methodSymbol.Locations.First(),
|
||||
methodSymbol.Name,
|
||||
methodSymbol.ContainingType));
|
||||
}
|
||||
}, SymbolKind.Method);
|
||||
});
|
||||
}
|
||||
}
|
||||
-80
@@ -1,80 +0,0 @@
|
||||
using System.Collections.Immutable;
|
||||
using System.Linq;
|
||||
using ComputeSharp.SourceGeneration.Extensions;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.Diagnostics;
|
||||
using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors;
|
||||
|
||||
namespace ComputeSharp.D2D1.SourceGenerators;
|
||||
|
||||
/// <summary>
|
||||
/// A diagnostic analyzer that generates a warning whenever a D2D1 shader type does not have an associated descriptor.
|
||||
/// </summary>
|
||||
[DiagnosticAnalyzer(LanguageNames.CSharp)]
|
||||
public sealed class MissingPixelShaderDescriptorOnPixelShaderAnalyzer : DiagnosticAnalyzer
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = [MissingPixelShaderDescriptorOnPixelShaderType];
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override void Initialize(AnalysisContext context)
|
||||
{
|
||||
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics);
|
||||
context.EnableConcurrentExecution();
|
||||
|
||||
context.RegisterCompilationStartAction(static context =>
|
||||
{
|
||||
// Get the ID2D1PixelShader, ID2D1PixelShaderDescriptor<T> and [D2DGeneratedPixelShaderDescriptor] symbols
|
||||
if (context.Compilation.GetTypeByMetadataName("ComputeSharp.D2D1.ID2D1PixelShader") is not { } d2D1PixelShaderSymbol ||
|
||||
context.Compilation.GetTypeByMetadataName("ComputeSharp.D2D1.Descriptors.ID2D1PixelShaderDescriptor`1") is not { } d2D1PixelShaderDescriptorSymbol ||
|
||||
context.Compilation.GetTypeByMetadataName("ComputeSharp.D2D1.D2DGeneratedPixelShaderDescriptorAttribute") is not { } d2DGeneratedPixelShaderDescriptorAttributeSymbol)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
context.RegisterSymbolAction(context =>
|
||||
{
|
||||
// Only struct types are possible targets
|
||||
if (context.Symbol is not INamedTypeSymbol { TypeKind: TypeKind.Struct } typeSymbol)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// If the type is not a pixel shader type, immediately bail out
|
||||
if (!typeSymbol.HasInterfaceWithType(d2D1PixelShaderSymbol))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Emit a diagnostic if the descriptor is missing for the shader type
|
||||
if (!HasD2D1PixelShaderDescriptorInterface(typeSymbol, d2D1PixelShaderDescriptorSymbol) &&
|
||||
!typeSymbol.HasAttributeWithType(d2DGeneratedPixelShaderDescriptorAttributeSymbol))
|
||||
{
|
||||
context.ReportDiagnostic(Diagnostic.Create(
|
||||
MissingPixelShaderDescriptorOnPixelShaderType,
|
||||
typeSymbol.Locations.FirstOrDefault(),
|
||||
typeSymbol));
|
||||
}
|
||||
}, SymbolKind.NamedType);
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks whether a given type implements the shader descriptor interface.
|
||||
/// </summary>
|
||||
/// <param name="typeSymbol">The type to check.</param>
|
||||
/// <param name="d2D1PixelShaderDescriptorSymbol">The type symbol for <c>ID2D1PixelShaderDescriptor<T></c>.</param>
|
||||
/// <returns></returns>
|
||||
private static bool HasD2D1PixelShaderDescriptorInterface(INamedTypeSymbol typeSymbol, INamedTypeSymbol d2D1PixelShaderDescriptorSymbol)
|
||||
{
|
||||
foreach (INamedTypeSymbol interfaceSymbol in typeSymbol.AllInterfaces)
|
||||
{
|
||||
if (SymbolEqualityComparer.Default.Equals(interfaceSymbol.ConstructedFrom, d2D1PixelShaderDescriptorSymbol))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
-133
@@ -1,133 +0,0 @@
|
||||
using System.Collections.Immutable;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using ComputeSharp.SourceGeneration.Extensions;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.Diagnostics;
|
||||
using Microsoft.CodeAnalysis.Operations;
|
||||
using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors;
|
||||
|
||||
namespace ComputeSharp.D2D1.SourceGenerators;
|
||||
|
||||
/// <summary>
|
||||
/// A diagnostic analyzer that generates an error whenever an invocation to a D2D intrinsic is using an argument that is not constant for the source shader input.
|
||||
/// </summary>
|
||||
[DiagnosticAnalyzer(LanguageNames.CSharp)]
|
||||
public sealed class NonConstantD2DInputArgumentAnalyzer : DiagnosticAnalyzer
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = [NonConstantSourceInputIndexForD2DIntrinsic];
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override void Initialize(AnalysisContext context)
|
||||
{
|
||||
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
|
||||
context.EnableConcurrentExecution();
|
||||
|
||||
context.RegisterCompilationStartAction(static context =>
|
||||
{
|
||||
// Ensure we can get all methods, or stop immediately
|
||||
if (!TryBuildMethodSymbolSet(context.Compilation, out ImmutableHashSet<IMethodSymbol>? methodSymbols))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
context.CancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
// Register a callback for each argument we want to validate
|
||||
context.RegisterOperationAction(context =>
|
||||
{
|
||||
IArgumentOperation operation = (IArgumentOperation)context.Operation;
|
||||
|
||||
// Ensure the argument is for an invocation, and get its first argument
|
||||
if (operation.Parent is not IInvocationOperation { Arguments: [{ } firstArgument, ..] } invocationOperation)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// We also want to verify that the argument is the first one (that's the only one that should be constant)
|
||||
if (operation != firstArgument)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Ensure the argument is for a 'D2D' method (ignore all other arguments, ie. almost all of them)
|
||||
if (invocationOperation is not { TargetMethod: { IsStatic: true, ContainingType.Name: "D2D" } targetMethodSymbol })
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// We only want to kick in when the target parameter is an 'int'
|
||||
if (operation is not { Parameter: { Type.SpecialType: SpecialType.System_Int32 } parameterSymbol })
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// This analyzer should also only kick in when the argument is not constant
|
||||
if (operation.Value.ConstantValue.HasValue)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Now we can actually verify that the target method is indeed one we care about (this should always match)
|
||||
if (!methodSymbols.Contains(targetMethodSymbol))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Finally, we can emit the diagnostic
|
||||
context.ReportDiagnostic(Diagnostic.Create(
|
||||
NonConstantSourceInputIndexForD2DIntrinsic,
|
||||
operation.Syntax.GetLocation(),
|
||||
parameterSymbol.Name,
|
||||
targetMethodSymbol.Name));
|
||||
}, OperationKind.Argument);
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Tries to build a set of <see cref="IMethodSymbol"/> instances for all D2D intrinsics targeting a specific shader input.
|
||||
/// </summary>
|
||||
/// <param name="compilation">The <see cref="Compilation"/> to consider for analysis.</param>
|
||||
/// <param name="methodSymbols">The resulting set of resolved <see cref="IMethodSymbol"/> instances.</param>
|
||||
/// <returns>Whether all requested <see cref="IMethodSymbol"/> instances could be resolved.</returns>
|
||||
private static bool TryBuildMethodSymbolSet(Compilation compilation, [NotNullWhen(true)] out ImmutableHashSet<IMethodSymbol>? methodSymbols)
|
||||
{
|
||||
// Get the 'D2D' symbol, to get methods from it
|
||||
if (compilation.GetTypeByMetadataName("ComputeSharp.D2D1.D2D") is not { } d2DSymbol)
|
||||
{
|
||||
methodSymbols = null;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
// All 'D2D' intrinsics targeting an input (see 'InvalidD2DInputArgumentAnalyzer')
|
||||
string[] d2DMethodNames =
|
||||
[
|
||||
nameof(D2D.GetInput),
|
||||
nameof(D2D.GetInputCoordinate),
|
||||
nameof(D2D.SampleInput),
|
||||
nameof(D2D.SampleInputAtOffset),
|
||||
nameof(D2D.SampleInputAtPosition)
|
||||
];
|
||||
|
||||
ImmutableHashSet<IMethodSymbol>.Builder inputTypeMethodSet = ImmutableHashSet.CreateBuilder<IMethodSymbol>(SymbolEqualityComparer.Default);
|
||||
|
||||
// Validate all methods and build the map
|
||||
foreach (string d2DMethodName in d2DMethodNames)
|
||||
{
|
||||
// Ensure we can find the target method symbol (again just like in 'InvalidD2DInputArgumentAnalyzer')
|
||||
if (d2DSymbol.GetMethod(d2DMethodName) is not { } d2DMethodSymbol)
|
||||
{
|
||||
methodSymbols = null;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
_ = inputTypeMethodSet.Add(d2DMethodSymbol);
|
||||
}
|
||||
|
||||
methodSymbols = inputTypeMethodSet.ToImmutable();
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
-19
@@ -1,19 +0,0 @@
|
||||
using ComputeSharp.SourceGeneration.Diagnostics;
|
||||
using Microsoft.CodeAnalysis.Diagnostics;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors;
|
||||
|
||||
namespace ComputeSharp.D2D1.SourceGenerators;
|
||||
|
||||
/// <inheritdoc/>
|
||||
[DiagnosticAnalyzer(LanguageNames.CSharp)]
|
||||
public sealed class NotAccessibleD2DGeneratedPixelShaderDescriptorAttributeTargetAnalyzer : NotAccessibleGeneratedShaderDescriptorAttributeTargetAnalyzerBase
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="NotAccessibleD2DGeneratedPixelShaderDescriptorAttributeTargetAnalyzer"/> instance.
|
||||
/// </summary>
|
||||
public NotAccessibleD2DGeneratedPixelShaderDescriptorAttributeTargetAnalyzer()
|
||||
: base(NotAccessibleTargetTypeForD2DGeneratedPixelShaderDescriptorAttribute, "ComputeSharp.D2D1.D2DGeneratedPixelShaderDescriptorAttribute")
|
||||
{
|
||||
}
|
||||
}
|
||||
-19
@@ -1,19 +0,0 @@
|
||||
using ComputeSharp.SourceGeneration.Diagnostics;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.Diagnostics;
|
||||
using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors;
|
||||
|
||||
namespace ComputeSharp.D2D1.SourceGenerators;
|
||||
|
||||
/// <inheritdoc/>
|
||||
[DiagnosticAnalyzer(LanguageNames.CSharp)]
|
||||
public sealed class NotAccessibleFieldTypeInD2DGeneratedShaderDescriptorAttributeTargetAnalyzer : NotAccessibleFieldTypeInGeneratedShaderDescriptorAttributeTargetAnalyzerBase
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="NotAccessibleFieldTypeInD2DGeneratedShaderDescriptorAttributeTargetAnalyzer"/> instance.
|
||||
/// </summary>
|
||||
public NotAccessibleFieldTypeInD2DGeneratedShaderDescriptorAttributeTargetAnalyzer()
|
||||
: base(NotAccessibleFieldTypeInTargetTypeForD2DGeneratedPixelShaderDescriptorAttribute, "ComputeSharp.D2D1.D2DGeneratedPixelShaderDescriptorAttribute")
|
||||
{
|
||||
}
|
||||
}
|
||||
-19
@@ -1,19 +0,0 @@
|
||||
using ComputeSharp.SourceGeneration.Diagnostics;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.Diagnostics;
|
||||
using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors;
|
||||
|
||||
namespace ComputeSharp.D2D1.SourceGenerators;
|
||||
|
||||
/// <inheritdoc/>
|
||||
[DiagnosticAnalyzer(LanguageNames.CSharp)]
|
||||
public sealed class NotReadOnlyPixelShaderTypeWithFieldsAnalyzer : NotReadOnlyShaderTypeWithFieldsAnalyzerBase
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="NotReadOnlyPixelShaderTypeWithFieldsAnalyzer"/> instance.
|
||||
/// </summary>
|
||||
public NotReadOnlyPixelShaderTypeWithFieldsAnalyzer()
|
||||
: base(NotReadOnlyShaderType, ["ComputeSharp.D2D1.ID2D1PixelShader"])
|
||||
{
|
||||
}
|
||||
}
|
||||
ファイル差分が大きすぎるため表示されません。
差分を読み込み
@@ -1,17 +0,0 @@
|
||||
using Microsoft.CodeAnalysis;
|
||||
|
||||
namespace ComputeSharp.D2D1.SourceGenerators.Diagnostics;
|
||||
|
||||
/// <summary>
|
||||
/// A container for all <see cref="SuppressionDescriptors"/> instances for suppressed diagnostics by analyzers in this project.
|
||||
/// </summary>
|
||||
internal static class SuppressionDescriptors
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets a <see cref="SuppressionDescriptor"/> for an uninitialized D2D1 resource texture field.
|
||||
/// </summary>
|
||||
public static readonly SuppressionDescriptor UninitializedD2D1ResourceTextureField = new(
|
||||
id: "CMPSD2DSPR0001",
|
||||
suppressedDiagnosticId: "CS0649",
|
||||
justification: "Fields of type D2D1ResourceTexture1D<T>, D2D1ResourceTexture2D<T> and D2D1ResourceTexture3D<T> are implicitly mapped to resource texture objects into the resulting D2D1 pixel shader for their containing type, and don't need to be initialized");
|
||||
}
|
||||
-69
@@ -1,69 +0,0 @@
|
||||
using System.Collections.Immutable;
|
||||
using ComputeSharp.SourceGeneration.Extensions;
|
||||
using ComputeSharp.SourceGeneration.Mappings;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.Diagnostics;
|
||||
using static ComputeSharp.D2D1.SourceGenerators.Diagnostics.SuppressionDescriptors;
|
||||
|
||||
namespace ComputeSharp.D2D1.SourceGenerators;
|
||||
|
||||
/// <summary>
|
||||
/// <para>
|
||||
/// A diagnostic suppressor to suppress CS0649 warnings for uninitialized D2D1 resource texture fields.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// That is, this diagnostic suppressor will suppress the following diagnostic:
|
||||
/// <code>
|
||||
/// public struct MyShader : ID2D1PixelShader
|
||||
/// {
|
||||
/// [D2DResourceTextureIndex(0)]
|
||||
/// private D2D1ResourceTexture1D<float4> texture;
|
||||
///
|
||||
/// public float4 Execute()
|
||||
/// {
|
||||
/// return texture[0];
|
||||
/// }
|
||||
/// }
|
||||
/// </code>
|
||||
/// </para>
|
||||
/// </summary>
|
||||
[DiagnosticAnalyzer(LanguageNames.CSharp)]
|
||||
public sealed class D2D1ResourceTextureUninitializedFieldDiagnosticSuppressor : DiagnosticSuppressor
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
public override ImmutableArray<SuppressionDescriptor> SupportedSuppressions => [UninitializedD2D1ResourceTextureField];
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override void ReportSuppressions(SuppressionAnalysisContext context)
|
||||
{
|
||||
foreach (Diagnostic diagnostic in context.ReportedDiagnostics)
|
||||
{
|
||||
SyntaxNode? syntaxNode = diagnostic.Location.SourceTree?.GetRoot(context.CancellationToken).FindNode(diagnostic.Location.SourceSpan);
|
||||
|
||||
if (syntaxNode is not null)
|
||||
{
|
||||
SemanticModel semanticModel = context.GetSemanticModel(syntaxNode.SyntaxTree);
|
||||
|
||||
// Get the field symbol
|
||||
ISymbol? declaredSymbol = semanticModel.GetDeclaredSymbol(syntaxNode, context.CancellationToken);
|
||||
|
||||
// Check if the field is in a struct and it's of a D2D1 resource texture type
|
||||
if (declaredSymbol is IFieldSymbol { ContainingType: { TypeKind: TypeKind.Struct } structSymbol } fieldSymbol &&
|
||||
HlslKnownTypes.IsResourceTextureType(fieldSymbol.Type.GetFullyQualifiedMetadataName()))
|
||||
{
|
||||
// Get the ID2D1PixelShader interface symbol to the check the containing type of the field
|
||||
if (semanticModel.Compilation.GetTypeByMetadataName("ComputeSharp.D2D1.ID2D1PixelShader") is not { } d2D1PixelShaderSymbol)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
// Also check if the containing type is in fact a D2D1 pixel shader type
|
||||
if (structSymbol.HasInterfaceWithType(d2D1PixelShaderSymbol))
|
||||
{
|
||||
context.ReportSuppression(Suppression.Create(UninitializedD2D1ResourceTextureField, diagnostic));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
using System;
|
||||
using Windows.Win32;
|
||||
using Windows.Win32.Graphics.Direct3D;
|
||||
using Windows.Win32.Graphics.Direct3D11;
|
||||
using DirectX = Windows.Win32.PInvoke;
|
||||
|
||||
namespace ComputeSharp.D2D1.Shaders.Translation;
|
||||
|
||||
/// <inheritdoc/>
|
||||
partial class D3DCompiler
|
||||
{
|
||||
/// <summary>
|
||||
/// Checks whether double precision support is required.
|
||||
/// </summary>
|
||||
/// <param name="d3DBlob">The input HLSL bytecode to inspect.</param>
|
||||
/// <returns>Whether double precision support is required for <paramref name="d3DBlob"/>.</returns>
|
||||
public static unsafe bool IsDoublePrecisionSupportRequired(ID3DBlob* d3DBlob)
|
||||
{
|
||||
using ComPtr<ID3D11ShaderReflection> d3D11ShaderReflection = default;
|
||||
|
||||
Guid iidOfID3D11ShaderReflection = ID3D11ShaderReflection.IID_Guid;
|
||||
|
||||
DirectX.D3DReflect(
|
||||
pSrcData: d3DBlob->GetBufferPointer(),
|
||||
SrcDataSize: d3DBlob->GetBufferSize(),
|
||||
pInterface: &iidOfID3D11ShaderReflection,
|
||||
ppReflector: (void**)d3D11ShaderReflection.GetAddressOf()).Assert();
|
||||
|
||||
const ulong doublePrecisionFlags = DirectX.D3D_SHADER_REQUIRES_DOUBLES | DirectX.D3D_SHADER_REQUIRES_11_1_DOUBLE_EXTENSIONS;
|
||||
|
||||
return (d3D11ShaderReflection.Get()->GetRequiresFlags() & doublePrecisionFlags) != 0;
|
||||
}
|
||||
}
|
||||
@@ -1,105 +0,0 @@
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Security;
|
||||
using System.Text.RegularExpressions;
|
||||
using ComputeSharp.SourceGeneration.Extensions;
|
||||
using Microsoft.CodeAnalysis;
|
||||
|
||||
namespace ComputeSharp.D2D1.SourceGenerators.Helpers;
|
||||
|
||||
/// <summary>
|
||||
/// A helper class to parse D2D metadata values.
|
||||
/// </summary>
|
||||
internal static class D2D1EffectMetadataParser
|
||||
{
|
||||
/// <summary>
|
||||
/// A <see cref="Regex"/> instance to find all newlines.
|
||||
/// </summary>
|
||||
private static readonly Regex NewLinesRegex = new("[\r\n\v]", RegexOptions.Compiled);
|
||||
|
||||
/// <summary>
|
||||
/// Checks whether a given <see cref="AttributeData"/> value contains a valid effect metadata name.
|
||||
/// </summary>
|
||||
/// <param name="attributeData">The input <see cref="AttributeData"/> object to inspect.</param>
|
||||
/// <returns>Whether <paramref name="attributeData"/> contains a valid effect metadata name.</returns>
|
||||
public static bool IsValidEffectMetadataName(AttributeData attributeData)
|
||||
{
|
||||
if (attributeData.ConstructorArguments is [{ Value: string { Length: > 0 } value }])
|
||||
{
|
||||
// Remove new lines (the values cannot span multiple lines in XML)
|
||||
string singleLineValue = NewLinesRegex.Replace(value, string.Empty);
|
||||
|
||||
// Trim directly and check that (no need to escape, as that wouldn't change things)
|
||||
return singleLineValue.AsSpan().Trim().Length > 0;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Tries to get the defined effect metadata name for a given shader type.
|
||||
/// </summary>
|
||||
/// <param name="compilation">The input <see cref="Compilation"/> object currently in use.</param>
|
||||
/// <param name="typeSymbol">The input <see cref="INamedTypeSymbol"/> instance.</param>
|
||||
/// <param name="attributeFullyQualifiedMetadataName">The fully qualified metadata name of the target attribute.</param>
|
||||
/// <param name="isAssemblyLevelAttributeSupported">Whether the attribute can also be on the assembly.</param>
|
||||
/// <param name="effectMetadataName">The resulting defined effect metadata name, if found.</param>
|
||||
/// <returns>Whether or not a defined effect metadata name could be found.</returns>
|
||||
public static bool TryGetEffectMetadataName(
|
||||
Compilation compilation,
|
||||
INamedTypeSymbol typeSymbol,
|
||||
string attributeFullyQualifiedMetadataName,
|
||||
bool isAssemblyLevelAttributeSupported,
|
||||
[NotNullWhen(true)] out string? effectMetadataName)
|
||||
{
|
||||
INamedTypeSymbol metadataAttributeSymbol = compilation.GetTypeByMetadataName(attributeFullyQualifiedMetadataName)!;
|
||||
|
||||
// Always check the attributes on the type first
|
||||
if (typeSymbol.TryGetAttributeWithType(metadataAttributeSymbol, out AttributeData? attributeData))
|
||||
{
|
||||
return TryGetEffectMetadataName(attributeData, out effectMetadataName);
|
||||
}
|
||||
|
||||
// Check assembly-level attributes next, if needed
|
||||
if (isAssemblyLevelAttributeSupported &&
|
||||
typeSymbol.ContainingAssembly!.TryGetAttributeWithType(metadataAttributeSymbol, out attributeData))
|
||||
{
|
||||
return TryGetEffectMetadataName(attributeData, out effectMetadataName);
|
||||
}
|
||||
|
||||
effectMetadataName = default;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Tries to get the defined effect metadata name for a given attribute.
|
||||
/// </summary>
|
||||
/// <param name="attributeData">The input <see cref="AttributeData"/> object to inspect.</param>
|
||||
/// <param name="effectMetadataName">The resulting defined effect metadata name, if found.</param>
|
||||
/// <returns>Whether or not a defined effect metadata name could be found.</returns>
|
||||
public static bool TryGetEffectMetadataName(AttributeData attributeData, [NotNullWhen(true)] out string? effectMetadataName)
|
||||
{
|
||||
// Check that the attribute has a valid parameter
|
||||
if (attributeData.ConstructorArguments is [{ Value: string { Length: > 0 } value }])
|
||||
{
|
||||
// Remove new lines (the values cannot span multiple lines in XML)
|
||||
string singleLineValue = NewLinesRegex.Replace(value, string.Empty);
|
||||
|
||||
// Make sure to escape any invalid XML characters
|
||||
string escapedValue = SecurityElement.Escape(singleLineValue);
|
||||
|
||||
// Trim the display name as well
|
||||
if (escapedValue.AsSpan().Trim() is { Length: > 0 } trimmedValue)
|
||||
{
|
||||
effectMetadataName = trimmedValue.ToString();
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
effectMetadataName = default;
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Reflection;
|
||||
using ComputeSharp.Core.Intrinsics;
|
||||
using ComputeSharp.D2D1;
|
||||
|
||||
namespace ComputeSharp.SourceGeneration.Mappings;
|
||||
|
||||
/// <inheritdoc/>
|
||||
partial class HlslKnownKeywords
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
static partial void AddKnownKeywords(ICollection<string> knownKeywords)
|
||||
{
|
||||
// D2D1 intrinsics method names
|
||||
foreach (MethodInfo? method in typeof(D2D).GetMethods(BindingFlags.Public | BindingFlags.Static))
|
||||
{
|
||||
string name = method.GetCustomAttribute<HlslIntrinsicNameAttribute>()?.Name ?? method.Name;
|
||||
|
||||
knownKeywords.Add(name);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,53 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using ComputeSharp.Core.Intrinsics;
|
||||
using ComputeSharp.D2D1;
|
||||
|
||||
namespace ComputeSharp.SourceGeneration.Mappings;
|
||||
|
||||
/// <inheritdoc/>
|
||||
partial class HlslKnownMethods
|
||||
{
|
||||
/// <summary>
|
||||
/// Checks whether or not a method name (previous matched with <see cref="TryGetMappedName(string, out string?)"/>
|
||||
/// needs the <c>[D2DRequiresScenePosition]</c> annotation on its containing shader in order to be used.
|
||||
/// </summary>
|
||||
/// <param name="name">The fully qualified metadata name.</param>
|
||||
/// <returns>Whether the method needs the <c>[D2DRequiresScenePosition]</c> annotation.</returns>
|
||||
public static bool NeedsD2DRequiresScenePositionAttribute(string name)
|
||||
{
|
||||
return name is "ComputeSharp.D2D1.D2D.GetScenePosition" or "ComputeSharp.D2D1.D2D.SampleInputAtPosition";
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
private static partial Dictionary<string, string?> BuildKnownResourceSamplers()
|
||||
{
|
||||
return new()
|
||||
{
|
||||
[$"ComputeSharp.D2D1.D2D1ResourceTexture1D`1.Sample({typeof(float).FullName})"] = null,
|
||||
[$"ComputeSharp.D2D1.D2D1ResourceTexture2D`1.Sample({typeof(float).FullName}, {typeof(float).FullName})"] = "float2",
|
||||
[$"ComputeSharp.D2D1.D2D1ResourceTexture2D`1.Sample({typeof(Float2).FullName})"] = null,
|
||||
[$"ComputeSharp.D2D1.D2D1ResourceTexture3D`1.Sample({typeof(float).FullName}, {typeof(float).FullName}, {typeof(float).FullName})"] = "float3",
|
||||
[$"ComputeSharp.D2D1.D2D1ResourceTexture3D`1.Sample({typeof(Float3).FullName})"] = null
|
||||
};
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
|
||||
static partial void AddKnownMethods(IDictionary<string, string> knownMethods)
|
||||
{
|
||||
// Programmatically load mappings from the D2D1 class as well
|
||||
foreach (MethodInfo? method in
|
||||
from method in typeof(D2D).GetMethods(BindingFlags.Public | BindingFlags.Static)
|
||||
group method by method.Name
|
||||
into groups
|
||||
select groups.First())
|
||||
{
|
||||
string hlslName = method.GetCustomAttribute<HlslIntrinsicNameAttribute>()?.Name ?? method.Name;
|
||||
|
||||
knownMethods.Add($"{typeof(D2D).FullName}{Type.Delimiter}{method.Name}", hlslName);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace ComputeSharp.SourceGeneration.Mappings;
|
||||
|
||||
/// <inheritdoc/>
|
||||
partial class HlslKnownProperties
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
private static partial Dictionary<string, string> BuildKnownResourceIndexers()
|
||||
{
|
||||
return new()
|
||||
{
|
||||
[$"ComputeSharp.D2D1.D2D1ResourceTexture2D`1.this[{typeof(int).FullName}, {typeof(int).FullName}]"] = "int2",
|
||||
[$"ComputeSharp.D2D1.D2D1ResourceTexture3D`1.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3"
|
||||
};
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
private static partial Dictionary<string, (int Rank, int Axis)> BuildKnownSizeAccessors()
|
||||
{
|
||||
return new()
|
||||
{
|
||||
["ComputeSharp.D2D1.D2D1ResourceTexture1D`1.Width"] = (1, 0),
|
||||
["ComputeSharp.D2D1.D2D1ResourceTexture2D`1.Width"] = (2, 0),
|
||||
["ComputeSharp.D2D1.D2D1ResourceTexture2D`1.Height"] = (2, 1),
|
||||
["ComputeSharp.D2D1.D2D1ResourceTexture3D`1.Width"] = (3, 0),
|
||||
["ComputeSharp.D2D1.D2D1ResourceTexture3D`1.Height"] = (3, 1),
|
||||
["ComputeSharp.D2D1.D2D1ResourceTexture3D`1.Depth"] = (3, 2)
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,57 +0,0 @@
|
||||
using System;
|
||||
using ComputeSharp.SourceGeneration.Extensions;
|
||||
using Microsoft.CodeAnalysis;
|
||||
|
||||
namespace ComputeSharp.SourceGeneration.Mappings;
|
||||
|
||||
/// <inheritdoc/>
|
||||
partial class HlslKnownTypes
|
||||
{
|
||||
/// <summary>
|
||||
/// Checks whether or not a given type name matches a resource texture type.
|
||||
/// </summary>
|
||||
/// <param name="typeName">The input type name to check.</param>
|
||||
/// <returns>Whether or not <paramref name="typeName"/> represents a readonly typed resource type.</returns>
|
||||
public static bool IsResourceTextureType(string typeName)
|
||||
{
|
||||
return typeName switch
|
||||
{
|
||||
"ComputeSharp.D2D1.D2D1ResourceTexture1D`1" or
|
||||
"ComputeSharp.D2D1.D2D1ResourceTexture2D`1" or
|
||||
"ComputeSharp.D2D1.D2D1ResourceTexture3D`1" => true,
|
||||
_ => false
|
||||
};
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public static partial string GetMappedName(INamedTypeSymbol typeSymbol)
|
||||
{
|
||||
string typeName = typeSymbol.GetFullyQualifiedMetadataName();
|
||||
|
||||
// Special case for resource texture types
|
||||
if (IsResourceTextureType(typeName))
|
||||
{
|
||||
string genericArgumentName = ((INamedTypeSymbol)typeSymbol.TypeArguments[0]).GetFullyQualifiedMetadataName();
|
||||
|
||||
// Get the HLSL name for the type argument (it can only be either float or float4)
|
||||
_ = KnownHlslTypeMetadataNames.TryGetValue(genericArgumentName, out string? mappedElementType);
|
||||
|
||||
return typeName switch
|
||||
{
|
||||
"ComputeSharp.D2D1.D2D1ResourceTexture1D`1" => $"Texture1D<{mappedElementType}>",
|
||||
"ComputeSharp.D2D1.D2D1ResourceTexture2D`1" => $"Texture2D<{mappedElementType}>",
|
||||
"ComputeSharp.D2D1.D2D1ResourceTexture3D`1" => $"Texture3D<{mappedElementType}>",
|
||||
_ => throw new ArgumentException()
|
||||
};
|
||||
}
|
||||
|
||||
// The captured field is of an HLSL primitive type
|
||||
if (KnownHlslTypeMetadataNames.TryGetValue(typeName, out string? mappedType))
|
||||
{
|
||||
return mappedType;
|
||||
}
|
||||
|
||||
// The captured field is of a custom struct type
|
||||
return typeName.ToHlslIdentifierName();
|
||||
}
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
using ComputeSharp.SourceGeneration.Helpers;
|
||||
using ComputeSharp.SourceGeneration.Models;
|
||||
|
||||
namespace ComputeSharp.D2D1.SourceGenerators.Models;
|
||||
|
||||
/// <summary>
|
||||
/// A model representing all necessary info for a full generation pass for a [D2D1PixelShaderSource] attribute.
|
||||
/// </summary>
|
||||
/// <param name="Hierarchy">The hierarchy info for the shader type.</param>
|
||||
/// <param name="Modifiers">The modifiers for the annotated method (these are <see cref="Microsoft.CodeAnalysis.CSharp.SyntaxKind"/> values, which can't be equated directly).</param>
|
||||
/// <param name="MethodName">The name of the annotated method.</param>
|
||||
/// <param name="InvalidReturnType">The fully qualified name of the return type, if invalid.</param>
|
||||
/// <param name="HlslInfoKey">The key with processed info on the shader.</param>
|
||||
/// <param name="HlslInfo">The value with processed info on the shader.</param>
|
||||
/// <param name="Diagnostcs">The discovered diagnostics, if any.</param>
|
||||
internal sealed record D2D1PixelShaderSourceInfo(
|
||||
HierarchyInfo Hierarchy,
|
||||
EquatableArray<ushort> Modifiers,
|
||||
string MethodName,
|
||||
string? InvalidReturnType,
|
||||
HlslBytecodeInfoKey HlslInfoKey,
|
||||
HlslBytecodeInfo HlslInfo,
|
||||
EquatableArray<DiagnosticInfo> Diagnostcs);
|
||||
@@ -1,43 +0,0 @@
|
||||
using ComputeSharp.SourceGeneration.Helpers;
|
||||
using ComputeSharp.SourceGeneration.Models;
|
||||
|
||||
namespace ComputeSharp.D2D1.SourceGenerators.Models;
|
||||
|
||||
/// <summary>
|
||||
/// 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 GUID bytes for the effect id.</param>
|
||||
/// <param name="EffectDisplayName">The effect display name for the shader type, if available.</param>
|
||||
/// <param name="EffectDescription">The effect description for the shader type, if available.</param>
|
||||
/// <param name="EffectCategory">The effect category for the shader type, if available.</param>
|
||||
/// <param name="EffectAuthor">The effect author for the shader type, if available.</param>
|
||||
/// <param name="ConstantBufferSizeInBytes">The size of the shader constant buffer.</param>
|
||||
/// <param name="InputTypes">The gathered input types for the shader.</param>
|
||||
/// <param name="InputDescriptions">The gathered input descriptions for the shader.</param>
|
||||
/// <param name="ResourceTextureDescriptions">The gathered resource texture descriptions for the shader.</param>
|
||||
/// <param name="Fields">The description on shader instance fields.</param>
|
||||
/// <param name="BufferPrecision">The buffer precision for the resulting output buffer.</param>
|
||||
/// <param name="ChannelDepth">The channel depth for the resulting output buffer.</param>
|
||||
/// <param name="PixelOptions">The pixel options used by the shader.</param>
|
||||
/// <param name="HlslInfoKey">The key with processed info on the shader.</param>
|
||||
/// <param name="HlslInfo">The value with processed info on the shader.</param>
|
||||
/// <param name="Diagnostcs">The discovered diagnostics, if any.</param>
|
||||
internal sealed record D2D1ShaderInfo(
|
||||
HierarchyInfo Hierarchy,
|
||||
EquatableArray<byte> EffectId,
|
||||
string? EffectDisplayName,
|
||||
string? EffectDescription,
|
||||
string? EffectCategory,
|
||||
string? EffectAuthor,
|
||||
int ConstantBufferSizeInBytes,
|
||||
EquatableArray<uint> InputTypes,
|
||||
EquatableArray<InputDescription> InputDescriptions,
|
||||
EquatableArray<ResourceTextureDescription> ResourceTextureDescriptions,
|
||||
EquatableArray<FieldInfo> Fields,
|
||||
D2D1BufferPrecision BufferPrecision,
|
||||
D2D1ChannelDepth ChannelDepth,
|
||||
D2D1PixelOptions PixelOptions,
|
||||
HlslBytecodeInfoKey HlslInfoKey,
|
||||
HlslBytecodeInfo HlslInfo,
|
||||
EquatableArray<DiagnosticInfo> Diagnostcs) : IConstantBufferInfo;
|
||||
@@ -1,14 +0,0 @@
|
||||
namespace ComputeSharp.D2D1.SourceGenerators.Models;
|
||||
|
||||
/// <summary>
|
||||
/// A model with info to be a unique key for <see cref="HlslBytecodeInfo"/> instances.
|
||||
/// </summary>
|
||||
/// <param name="HlslSource">The input HLSL source code.</param>
|
||||
/// <param name="ShaderProfile">The shader profile.</param>
|
||||
/// <param name="CompileOptions">The compile options.</param>
|
||||
/// <param name="IsCompilationEnabled">Whether compilation should be attempted for the current info.</param>
|
||||
internal sealed record HlslBytecodeInfoKey(
|
||||
string HlslSource,
|
||||
D2D1ShaderProfile ShaderProfile,
|
||||
D2D1CompileOptions CompileOptions,
|
||||
bool IsCompilationEnabled);
|
||||
@@ -1,9 +0,0 @@
|
||||
namespace ComputeSharp.D2D1.SourceGenerators.Models;
|
||||
|
||||
/// <summary>
|
||||
/// A model representing an input description for a shader.
|
||||
/// </summary>
|
||||
/// <param name="Index">The index of the input resource the description is for.</param>
|
||||
/// <param name="Filter">The input filter to use.</param>
|
||||
/// <param name="LevelOfDetailCount">The level of detail to use.</param>
|
||||
internal sealed record InputDescription(int Index, D2D1Filter Filter, int LevelOfDetailCount);
|
||||
@@ -1,8 +0,0 @@
|
||||
namespace ComputeSharp.D2D1.SourceGenerators.Models;
|
||||
|
||||
/// <summary>
|
||||
/// A model representing a resource texture description for a shader.
|
||||
/// </summary>
|
||||
/// <param name="Index">The index of the resource texture resource the description is for.</param>
|
||||
/// <param name="Rank">The rank of the resource texture.</param>
|
||||
internal sealed record ResourceTextureDescription(int Index, int Rank);
|
||||
@@ -1,30 +0,0 @@
|
||||
D3DCompile
|
||||
D3DReflect
|
||||
D3DSetBlobPart
|
||||
D3DStripShader
|
||||
D2D1_BUFFER_PRECISION
|
||||
D2D1_CHANNEL_DEPTH
|
||||
D2D1_FILTER
|
||||
D2D1_PIXEL_OPTIONS
|
||||
D3DCOMPILE_DEBUG
|
||||
D3DCOMPILE_SKIP_VALIDATION
|
||||
D3DCOMPILE_SKIP_OPTIMIZATION
|
||||
D3DCOMPILE_PACK_MATRIX_ROW_MAJOR
|
||||
D3DCOMPILE_PACK_MATRIX_COLUMN_MAJOR
|
||||
D3DCOMPILE_PARTIAL_PRECISION
|
||||
D3DCOMPILE_AVOID_FLOW_CONTROL
|
||||
D3DCOMPILE_ENABLE_STRICTNESS
|
||||
D3DCOMPILE_IEEE_STRICTNESS
|
||||
D3DCOMPILE_ENABLE_BACKWARDS_COMPATIBILITY
|
||||
D3DCOMPILE_OPTIMIZATION_LEVEL0
|
||||
D3DCOMPILE_OPTIMIZATION_LEVEL1
|
||||
D3DCOMPILE_OPTIMIZATION_LEVEL2
|
||||
D3DCOMPILE_OPTIMIZATION_LEVEL3
|
||||
D3DCOMPILE_WARNINGS_ARE_ERRORS
|
||||
D3DCOMPILER_STRIP_FLAGS
|
||||
D3D_SHADER_REQUIRES_DOUBLES
|
||||
D3D_SHADER_REQUIRES_11_1_DOUBLE_EXTENSIONS
|
||||
ID3D11ShaderReflection
|
||||
IUnknown
|
||||
S_OK
|
||||
S_FALSE
|
||||
@@ -1,23 +0,0 @@
|
||||
namespace System.Text;
|
||||
|
||||
/// <summary>
|
||||
/// Extensions for the <see cref="Encoding"/> type.
|
||||
/// </summary>
|
||||
internal static class EncodingExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Encodes into a span of bytes a set of characters from the specified read-only span.
|
||||
/// </summary>
|
||||
/// <param name="encoding">The input <see cref="Encoding"/> instance to use.</param>
|
||||
/// <param name="chars">The span containing the set of characters to encode.</param>
|
||||
/// <param name="bytes">The byte span to hold the encoded bytes.</param>
|
||||
/// <returns>The number of encoded bytes.</returns>
|
||||
public static unsafe int GetBytes(this Encoding encoding, ReadOnlySpan<char> chars, Span<byte> bytes)
|
||||
{
|
||||
fixed (char* charsPtr = chars)
|
||||
fixed (byte* bytesPtr = bytes)
|
||||
{
|
||||
return encoding.GetBytes(charsPtr, chars.Length, bytesPtr, bytes.Length);
|
||||
}
|
||||
}
|
||||
}
|
||||
-11
@@ -1,11 +0,0 @@
|
||||
namespace ComputeSharp.SourceGeneration.SyntaxProcessors;
|
||||
|
||||
/// <inheritdoc/>
|
||||
partial class ConstantBufferSyntaxProcessor
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
private static partial bool HasArtificialFields()
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
-40
@@ -1,40 +0,0 @@
|
||||
using System;
|
||||
using System.Threading;
|
||||
using ComputeSharp.D2D1.Shaders.Translation;
|
||||
using ComputeSharp.D2D1.SourceGenerators.Models;
|
||||
using Windows.Win32;
|
||||
using Windows.Win32.Graphics.Direct3D;
|
||||
|
||||
namespace ComputeSharp.SourceGeneration.SyntaxProcessors;
|
||||
|
||||
/// <inheritdoc/>
|
||||
partial class HlslBytecodeSyntaxProcessor
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
private static partial string GetRequiresDoublePrecisionSupportAttributeName()
|
||||
{
|
||||
return "ComputeSharp.D2D1.D2DRequiresDoublePrecisionSupportAttribute";
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
private static partial ComPtr<ID3DBlob> Compile(HlslBytecodeInfoKey key, CancellationToken token)
|
||||
{
|
||||
return D3DCompiler.Compile(
|
||||
key.HlslSource.AsSpan(),
|
||||
key.ShaderProfile,
|
||||
key.CompileOptions,
|
||||
token);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
private static unsafe partial bool IsDoublePrecisionSupportRequired(ID3DBlob* d3DBlob)
|
||||
{
|
||||
return D3DCompiler.IsDoublePrecisionSupportRequired(d3DBlob);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
private static partial string FixupErrorMessage(string message)
|
||||
{
|
||||
return D3DCompiler.PrettifyFxcErrorMessage(message);
|
||||
}
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
using ComputeSharp.SourceGeneration.Mappings;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.CSharp.Syntax;
|
||||
using Microsoft.CodeAnalysis.Operations;
|
||||
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
|
||||
|
||||
namespace ComputeSharp.SourceGeneration.SyntaxRewriters;
|
||||
|
||||
/// <inheritdoc/>
|
||||
partial class ShaderSourceRewriter
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets whether or not the shader needs the <c>[D2DRequiresScenePosition]</c> attribute.
|
||||
/// </summary>
|
||||
public bool NeedsD2DRequiresScenePositionAttribute { get; private set; }
|
||||
|
||||
/// <inheritdoc/>
|
||||
private partial SyntaxNode RewriteSampledTextureAccess(IInvocationOperation operation, ExpressionSyntax expression, ArgumentSyntax arguments)
|
||||
{
|
||||
string fieldName = (operation.Instance as IFieldReferenceOperation)?.Member.Name ?? "";
|
||||
|
||||
_ = HlslKnownKeywords.TryGetMappedName(fieldName, out string? mapped);
|
||||
|
||||
// Transform an indexer syntax into a sampling call with the implicit static linear sampler.
|
||||
// For instance: texture.Sample(uv) will be rewritten as texture.Sample(__sampler__texture, uv).
|
||||
return
|
||||
InvocationExpression(expression)
|
||||
.AddArgumentListArguments(Argument(IdentifierName($"__sampler__{mapped ?? fieldName}")), arguments);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
partial void TrackKnownMethodInvocation(string metadataName)
|
||||
{
|
||||
NeedsD2DRequiresScenePositionAttribute |= HlslKnownMethods.NeedsD2DRequiresScenePositionAttribute(metadataName);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
partial void TrackExternalStaticField(StaticFieldRewriter staticFieldRewriter)
|
||||
{
|
||||
NeedsD2DRequiresScenePositionAttribute |= staticFieldRewriter.NeedsD2DRequiresScenePositionAttribute;
|
||||
}
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
using ComputeSharp.SourceGeneration.Mappings;
|
||||
using Microsoft.CodeAnalysis.CSharp.Syntax;
|
||||
using Microsoft.CodeAnalysis.Operations;
|
||||
|
||||
namespace ComputeSharp.SourceGeneration.SyntaxRewriters;
|
||||
|
||||
/// <inheritdoc/>
|
||||
partial class StaticFieldRewriter
|
||||
{
|
||||
/// <inheritdoc cref="ShaderSourceRewriter.NeedsD2DRequiresScenePositionAttribute"/>
|
||||
public bool NeedsD2DRequiresScenePositionAttribute { get; private set; }
|
||||
|
||||
/// <inheritdoc/>
|
||||
private partial void TrackKnownPropertyAccess(IMemberReferenceOperation operation, MemberAccessExpressionSyntax node)
|
||||
{
|
||||
// No special tracking is needed for D2D1 shaders
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
private partial void TrackKnownMethodInvocation(string metadataName)
|
||||
{
|
||||
// Track whether the method needs [D2DRequiresScenePosition]
|
||||
if (HlslKnownMethods.NeedsD2DRequiresScenePositionAttribute(metadataName))
|
||||
{
|
||||
NeedsD2DRequiresScenePositionAttribute = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<PropertyGroup>
|
||||
<MSBuildAllProjects Condition="'$(MSBuildVersion)' == '' Or '$(MSBuildVersion)' < '16.0'">$(MSBuildAllProjects);$(MSBuildThisFileFullPath)</MSBuildAllProjects>
|
||||
<HasSharedItems>true</HasSharedItems>
|
||||
<SharedGUID>ce85dc5a-e455-42fe-9b64-0d5f0d7ee366</SharedGUID>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Label="Configuration">
|
||||
<Import_RootNamespace>ComputeSharp.D2D1.UI.CodeFixers</Import_RootNamespace>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<Compile Include="$(MSBuildThisFileDirectory)UseGeneratedCanvasEffectPropertyOnSemiAutoPropertyCodeFixer.cs" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -1,13 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<PropertyGroup Label="Globals">
|
||||
<ProjectGuid>ce85dc5a-e455-42fe-9b64-0d5f0d7ee366</ProjectGuid>
|
||||
<MinimumVisualStudioVersion>14.0</MinimumVisualStudioVersion>
|
||||
</PropertyGroup>
|
||||
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
|
||||
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.Common.Default.props" />
|
||||
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.Common.props" />
|
||||
<PropertyGroup />
|
||||
<Import Project="ComputeSharp.D2D1.UI.CodeFixers.projitems" Label="Shared" />
|
||||
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.CSharp.targets" />
|
||||
</Project>
|
||||
-350
@@ -1,350 +0,0 @@
|
||||
using System.Collections.Immutable;
|
||||
using System.Composition;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading.Tasks;
|
||||
#if WINDOWS_UWP
|
||||
using ComputeSharp.D2D1.Uwp.SourceGenerators.Constants;
|
||||
#else
|
||||
using ComputeSharp.D2D1.WinUI.SourceGenerators.Constants;
|
||||
#endif
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.CodeActions;
|
||||
using Microsoft.CodeAnalysis.CodeFixes;
|
||||
using Microsoft.CodeAnalysis.CSharp;
|
||||
using Microsoft.CodeAnalysis.CSharp.Syntax;
|
||||
using Microsoft.CodeAnalysis.Editing;
|
||||
using Microsoft.CodeAnalysis.Formatting;
|
||||
using Microsoft.CodeAnalysis.Simplification;
|
||||
using Microsoft.CodeAnalysis.Text;
|
||||
#if WINDOWS_UWP
|
||||
using static ComputeSharp.D2D1.Uwp.SourceGenerators.DiagnosticDescriptors;
|
||||
#else
|
||||
using static ComputeSharp.D2D1.WinUI.SourceGenerators.DiagnosticDescriptors;
|
||||
#endif
|
||||
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
|
||||
|
||||
#if WINDOWS_UWP
|
||||
namespace ComputeSharp.D2D1.Uwp.SourceGenerators;
|
||||
#else
|
||||
namespace ComputeSharp.D2D1.WinUI.SourceGenerators;
|
||||
#endif
|
||||
|
||||
/// <summary>
|
||||
/// A code fixer that converts manual properties into partial properties using <c>[GeneratedCanvasEffectProperty]</c>.
|
||||
/// </summary>
|
||||
[ExportCodeFixProvider(LanguageNames.CSharp)]
|
||||
[Shared]
|
||||
public sealed class UseGeneratedCanvasEffectPropertyOnSemiAutoPropertyCodeFixer : CodeFixProvider
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
public override ImmutableArray<string> FixableDiagnosticIds { get; } = [UseGeneratedCanvasEffectPropertyOnSemiAutoPropertyId];
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override Microsoft.CodeAnalysis.CodeFixes.FixAllProvider? GetFixAllProvider()
|
||||
{
|
||||
return new FixAllProvider();
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override async Task RegisterCodeFixesAsync(CodeFixContext context)
|
||||
{
|
||||
Diagnostic diagnostic = context.Diagnostics[0];
|
||||
TextSpan diagnosticSpan = context.Span;
|
||||
|
||||
// This code fixer needs the semantic model, so check that first
|
||||
if (!context.Document.SupportsSemanticModel)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Retrieve the properties passed by the analyzer
|
||||
if (!int.TryParse(diagnostic.Properties[UseGeneratedCanvasEffectPropertyOnSemiAutoPropertyAnalyzer.InvalidationTypePropertyName], out int invalidationType))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
SyntaxNode? root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);
|
||||
|
||||
// Get the property declaration from the target diagnostic
|
||||
if (root!.FindNode(diagnosticSpan) is PropertyDeclarationSyntax propertyDeclaration)
|
||||
{
|
||||
// Get the semantic model, as we need to resolve symbols
|
||||
SemanticModel semanticModel = (await context.Document.GetSemanticModelAsync(context.CancellationToken).ConfigureAwait(false))!;
|
||||
|
||||
// Register the code fix to update the semi-auto property to a partial property with [GeneratedCanvasEffectProperty]
|
||||
context.RegisterCodeFix(
|
||||
CodeAction.Create(
|
||||
title: "Use [GeneratedCanvasEffectProperty]",
|
||||
createChangedDocument: token => ConvertToPartialProperty(
|
||||
context.Document,
|
||||
semanticModel,
|
||||
root,
|
||||
propertyDeclaration,
|
||||
invalidationType),
|
||||
equivalenceKey: "Use [GeneratedCanvasEffectProperty]"),
|
||||
diagnostic);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Tries to get an <see cref="AttributeListSyntax"/> for the <c>[GeneratedCanvasEffectProperty]</c> attribute.
|
||||
/// </summary>
|
||||
/// <param name="document">The original document being fixed.</param>
|
||||
/// <param name="semanticModel">The <see cref="SemanticModel"/> instance for the current compilation.</param>
|
||||
/// <param name="generatedCanvasEffectPropertyAttributeList">The resulting attribute list, if successfully retrieved.</param>
|
||||
/// <returns>Whether <paramref name="generatedCanvasEffectPropertyAttributeList"/> could be retrieved successfully.</returns>
|
||||
private static bool TryGetGeneratedCanvasEffectPropertyAttributeList(
|
||||
Document document,
|
||||
SemanticModel semanticModel,
|
||||
[NotNullWhen(true)] out AttributeListSyntax? generatedCanvasEffectPropertyAttributeList)
|
||||
{
|
||||
// Make sure we can resolve the '[GeneratedCanvasEffectProperty]' attribute
|
||||
if (semanticModel.Compilation.GetTypeByMetadataName(WellKnownTypeNames.GeneratedCanvasEffectPropertyAttribute) is not INamedTypeSymbol attributeSymbol)
|
||||
{
|
||||
generatedCanvasEffectPropertyAttributeList = null;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
SyntaxGenerator syntaxGenerator = SyntaxGenerator.GetGenerator(document);
|
||||
|
||||
// Create the attribute syntax for the new '[GeneratedCanvasEffectProperty]' attribute here too
|
||||
SyntaxNode attributeTypeSyntax = syntaxGenerator.TypeExpression(attributeSymbol).WithAdditionalAnnotations(Simplifier.AddImportsAnnotation);
|
||||
|
||||
generatedCanvasEffectPropertyAttributeList = (AttributeListSyntax)syntaxGenerator.Attribute(attributeTypeSyntax);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Updates an <see cref="AttributeListSyntax"/> for the <c>[GeneratedCanvasEffectProperty]</c> attribute with the right default value.
|
||||
/// </summary>
|
||||
/// <param name="document">The original document being fixed.</param>
|
||||
/// <param name="semanticModel">The <see cref="SemanticModel"/> instance for the current compilation.</param>
|
||||
/// <param name="generatedCanvasEffectPropertyAttributeList">The <see cref="AttributeListSyntax"/> with the attribute to add.</param>
|
||||
/// <param name="invalidationType">The invalidation type to use.</param>
|
||||
/// <returns>The updated attribute syntax.</returns>
|
||||
private static AttributeListSyntax UpdateGeneratedCanvasEffectPropertyAttributeList(
|
||||
Document document,
|
||||
SemanticModel semanticModel,
|
||||
AttributeListSyntax generatedCanvasEffectPropertyAttributeList,
|
||||
int invalidationType)
|
||||
{
|
||||
// If the invalidation type is not the default, set it in the attribute.
|
||||
// We extract the generated attribute so we can add the new argument.
|
||||
// It's important to reuse it, as it has the "add usings" annotation.
|
||||
if (invalidationType == 1)
|
||||
{
|
||||
// Try to resolve the attribute type, if present (this should always be the case)
|
||||
if (semanticModel.Compilation.GetTypeByMetadataName(WellKnownTypeNames.CanvasEffectInvalidationType) is INamedTypeSymbol enumTypeSymbol)
|
||||
{
|
||||
SyntaxGenerator syntaxGenerator = SyntaxGenerator.GetGenerator(document);
|
||||
|
||||
// Create the identifier syntax for the enum type, with the right annotations
|
||||
SyntaxNode enumTypeSyntax = syntaxGenerator.TypeExpression(enumTypeSymbol).WithAdditionalAnnotations(Simplifier.AddImportsAnnotation);
|
||||
|
||||
// Create the member access expression for the target enum type.
|
||||
// We only ever take this path for the 'Creation' invalidation type.
|
||||
SyntaxNode enumMemberAccessExpressionSyntax = syntaxGenerator.MemberAccessExpression(enumTypeSyntax, "Creation");
|
||||
|
||||
// Create the attribute argument to insert
|
||||
SyntaxNode attributeArgumentSyntax = syntaxGenerator.AttributeArgument(enumMemberAccessExpressionSyntax);
|
||||
|
||||
// Actually add the argument to the existing attribute syntax
|
||||
return (AttributeListSyntax)syntaxGenerator.AddAttributeArguments(generatedCanvasEffectPropertyAttributeList, [attributeArgumentSyntax]);
|
||||
}
|
||||
|
||||
// This failed... For some reason. Use the fully qualified type name as a last resort.
|
||||
return
|
||||
AttributeList(SingletonSeparatedList(
|
||||
generatedCanvasEffectPropertyAttributeList.Attributes[0]
|
||||
.AddArgumentListArguments(
|
||||
AttributeArgument(ParseExpression(
|
||||
$"global::{WellKnownTypeNames.CanvasEffectInvalidationType}.Creation")))));
|
||||
}
|
||||
|
||||
// If we have no custom invalidation type, we can just reuse the attribute with no changes
|
||||
return generatedCanvasEffectPropertyAttributeList;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Applies the code fix to a target identifier and returns an updated document.
|
||||
/// </summary>
|
||||
/// <param name="document">The original document being fixed.</param>
|
||||
/// <param name="semanticModel">The <see cref="SemanticModel"/> instance for the current compilation.</param>
|
||||
/// <param name="root">The original tree root belonging to the current document.</param>
|
||||
/// <param name="propertyDeclaration">The <see cref="PropertyDeclarationSyntax"/> for the property being updated.</param>
|
||||
/// <param name="invalidationType">The invalidation type to use.</param>
|
||||
/// <returns>An updated document with the applied code fix, and <paramref name="propertyDeclaration"/> being replaced with a partial property.</returns>
|
||||
private static async Task<Document> ConvertToPartialProperty(
|
||||
Document document,
|
||||
SemanticModel semanticModel,
|
||||
SyntaxNode root,
|
||||
PropertyDeclarationSyntax propertyDeclaration,
|
||||
int invalidationType)
|
||||
{
|
||||
await Task.CompletedTask;
|
||||
|
||||
// If we can't generate the new attribute list, bail (this should never happen)
|
||||
if (!TryGetGeneratedCanvasEffectPropertyAttributeList(document, semanticModel, out AttributeListSyntax? generatedCanvasEffectPropertyAttributeList))
|
||||
{
|
||||
return document;
|
||||
}
|
||||
|
||||
// Create an editor to perform all mutations
|
||||
SyntaxEditor syntaxEditor = new(root, document.Project.Solution.Workspace.Services);
|
||||
|
||||
ConvertToPartialProperty(
|
||||
document,
|
||||
semanticModel,
|
||||
propertyDeclaration,
|
||||
generatedCanvasEffectPropertyAttributeList,
|
||||
syntaxEditor,
|
||||
invalidationType);
|
||||
|
||||
// Create the new document with the single change
|
||||
return document.WithSyntaxRoot(syntaxEditor.GetChangedRoot());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Applies the code fix to a target identifier and returns an updated document.
|
||||
/// </summary>
|
||||
/// <param name="document">The original document being fixed.</param>
|
||||
/// <param name="semanticModel">The <see cref="SemanticModel"/> instance for the current compilation.</param>
|
||||
/// <param name="propertyDeclaration">The <see cref="PropertyDeclarationSyntax"/> for the property being updated.</param>
|
||||
/// <param name="generatedCanvasEffectPropertyAttributeList">The <see cref="AttributeListSyntax"/> with the attribute to add.</param>
|
||||
/// <param name="syntaxEditor">The <see cref="SyntaxEditor"/> instance to use.</param>
|
||||
/// <param name="invalidationType">The invalidation type to use.</param>
|
||||
/// <returns>An updated document with the applied code fix, and <paramref name="propertyDeclaration"/> being replaced with a partial property.</returns>
|
||||
private static void ConvertToPartialProperty(
|
||||
Document document,
|
||||
SemanticModel semanticModel,
|
||||
PropertyDeclarationSyntax propertyDeclaration,
|
||||
AttributeListSyntax generatedCanvasEffectPropertyAttributeList,
|
||||
SyntaxEditor syntaxEditor,
|
||||
int invalidationType)
|
||||
{
|
||||
// Update the attribute to insert with the invalidation type, if needed
|
||||
generatedCanvasEffectPropertyAttributeList = UpdateGeneratedCanvasEffectPropertyAttributeList(
|
||||
document,
|
||||
semanticModel,
|
||||
generatedCanvasEffectPropertyAttributeList,
|
||||
invalidationType);
|
||||
|
||||
// Start setting up the updated attribute lists
|
||||
SyntaxList<AttributeListSyntax> attributeLists = propertyDeclaration.AttributeLists;
|
||||
|
||||
if (attributeLists is [AttributeListSyntax firstAttributeListSyntax, ..])
|
||||
{
|
||||
// Remove the trivia from the original first attribute
|
||||
attributeLists = attributeLists.Replace(
|
||||
nodeInList: firstAttributeListSyntax,
|
||||
newNode: firstAttributeListSyntax.WithoutTrivia());
|
||||
|
||||
// If the property has at least an attribute list, move the trivia from it to the new attribute
|
||||
generatedCanvasEffectPropertyAttributeList = generatedCanvasEffectPropertyAttributeList.WithTriviaFrom(firstAttributeListSyntax);
|
||||
|
||||
// Insert the new attribute
|
||||
attributeLists = attributeLists.Insert(0, generatedCanvasEffectPropertyAttributeList);
|
||||
}
|
||||
else
|
||||
{
|
||||
// Otherwise (there are no attribute lists), transfer the trivia to the new (only) attribute list
|
||||
generatedCanvasEffectPropertyAttributeList = generatedCanvasEffectPropertyAttributeList.WithTriviaFrom(propertyDeclaration);
|
||||
|
||||
// Save the new attribute list
|
||||
attributeLists = attributeLists.Add(generatedCanvasEffectPropertyAttributeList);
|
||||
}
|
||||
|
||||
// Get a new property that is partial and with semicolon token accessors
|
||||
PropertyDeclarationSyntax updatedPropertyDeclaration =
|
||||
propertyDeclaration
|
||||
.AddModifiers(Token(SyntaxKind.PartialKeyword))
|
||||
.WithoutLeadingTrivia()
|
||||
.WithAttributeLists(attributeLists)
|
||||
.WithAdditionalAnnotations(Formatter.Annotation)
|
||||
.WithAccessorList(AccessorList(List(
|
||||
[
|
||||
// Keep the accessors (so we can easily keep all trivia, modifiers, attributes, etc.) but make them semicolon only
|
||||
propertyDeclaration.AccessorList!.Accessors[0]
|
||||
.WithBody(null)
|
||||
.WithExpressionBody(null)
|
||||
.WithSemicolonToken(Token(SyntaxKind.SemicolonToken))
|
||||
.WithAdditionalAnnotations(Formatter.Annotation),
|
||||
propertyDeclaration.AccessorList!.Accessors[1]
|
||||
.WithBody(null)
|
||||
.WithExpressionBody(null)
|
||||
.WithSemicolonToken(Token(SyntaxKind.SemicolonToken))
|
||||
.WithTrailingTrivia(propertyDeclaration.AccessorList.Accessors[1].GetTrailingTrivia())
|
||||
.WithAdditionalAnnotations(Formatter.Annotation)
|
||||
])).WithTrailingTrivia(propertyDeclaration.AccessorList.GetTrailingTrivia()));
|
||||
|
||||
syntaxEditor.ReplaceNode(propertyDeclaration, updatedPropertyDeclaration);
|
||||
|
||||
// Find the parent type for the property
|
||||
TypeDeclarationSyntax typeDeclaration = propertyDeclaration.FirstAncestorOrSelf<TypeDeclarationSyntax>()!;
|
||||
|
||||
// Make sure it's partial (we create the updated node in the function to preserve the updated property declaration).
|
||||
// If we created it separately and replaced it, the whole tree would also be replaced, and we'd lose the new property.
|
||||
if (!typeDeclaration.Modifiers.Any(SyntaxKind.PartialKeyword))
|
||||
{
|
||||
syntaxEditor.ReplaceNode(typeDeclaration, static (node, generator) => generator.WithModifiers(node, generator.GetModifiers(node).WithPartial(true)));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A custom <see cref="FixAllProvider"/> with the logic from <see cref="UseGeneratedCanvasEffectPropertyOnSemiAutoPropertyCodeFixer"/>.
|
||||
/// </summary>
|
||||
private sealed class FixAllProvider : DocumentBasedFixAllProvider
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
protected override async Task<Document?> FixAllAsync(FixAllContext fixAllContext, Document document, ImmutableArray<Diagnostic> diagnostics)
|
||||
{
|
||||
// Get the semantic model, as we need to resolve symbols
|
||||
if (await document.GetSemanticModelAsync(fixAllContext.CancellationToken).ConfigureAwait(false) is not SemanticModel semanticModel)
|
||||
{
|
||||
return document;
|
||||
}
|
||||
|
||||
// Get the document root (this should always succeed)
|
||||
if (await document.GetSyntaxRootAsync(fixAllContext.CancellationToken).ConfigureAwait(false) is not SyntaxNode root)
|
||||
{
|
||||
return document;
|
||||
}
|
||||
|
||||
// If we can't generate the new attribute list, bail (this should never happen)
|
||||
if (!TryGetGeneratedCanvasEffectPropertyAttributeList(document, semanticModel, out AttributeListSyntax? generatedCanvasEffectPropertyAttributeList))
|
||||
{
|
||||
return document;
|
||||
}
|
||||
|
||||
// Create an editor to perform all mutations (across all edits in the file)
|
||||
SyntaxEditor syntaxEditor = new(root, fixAllContext.Solution.Services);
|
||||
|
||||
foreach (Diagnostic diagnostic in diagnostics)
|
||||
{
|
||||
// Get the current property declaration for the diagnostic
|
||||
if (root.FindNode(diagnostic.Location.SourceSpan) is not PropertyDeclarationSyntax propertyDeclaration)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
// Retrieve the properties passed by the analyzer
|
||||
if (!int.TryParse(diagnostic.Properties[UseGeneratedCanvasEffectPropertyOnSemiAutoPropertyAnalyzer.InvalidationTypePropertyName], out int invalidationType))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
ConvertToPartialProperty(
|
||||
document,
|
||||
semanticModel,
|
||||
propertyDeclaration,
|
||||
generatedCanvasEffectPropertyAttributeList,
|
||||
syntaxEditor,
|
||||
invalidationType);
|
||||
}
|
||||
|
||||
return document.WithSyntaxRoot(syntaxEditor.GetChangedRoot());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,258 +0,0 @@
|
||||
using System.Threading;
|
||||
#if WINDOWS_UWP
|
||||
using ComputeSharp.D2D1.Uwp.SourceGenerators.Constants;
|
||||
using ComputeSharp.D2D1.Uwp.SourceGenerators.Models;
|
||||
#else
|
||||
using ComputeSharp.D2D1.WinUI.SourceGenerators.Constants;
|
||||
using ComputeSharp.D2D1.WinUI.SourceGenerators.Models;
|
||||
#endif
|
||||
using ComputeSharp.SourceGeneration.Extensions;
|
||||
using ComputeSharp.SourceGeneration.Helpers;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.CSharp;
|
||||
using Microsoft.CodeAnalysis.CSharp.Syntax;
|
||||
|
||||
#if WINDOWS_UWP
|
||||
namespace ComputeSharp.D2D1.Uwp.SourceGenerators;
|
||||
#else
|
||||
namespace ComputeSharp.D2D1.WinUI.SourceGenerators;
|
||||
#endif
|
||||
|
||||
/// <inheritdoc/>
|
||||
partial class CanvasEffectPropertyGenerator
|
||||
{
|
||||
/// <summary>
|
||||
/// A container for all the logic for <see cref="CanvasEffectPropertyGenerator"/>.
|
||||
/// </summary>
|
||||
private static partial class Execute
|
||||
{
|
||||
/// <summary>
|
||||
/// Checks whether an input syntax node is a candidate property declaration for the generator.
|
||||
/// </summary>
|
||||
/// <param name="node">The input syntax node to check.</param>
|
||||
/// <param name="token">The <see cref="CancellationToken"/> used to cancel the operation, if needed.</param>
|
||||
/// <returns>Whether <paramref name="node"/> is a candidate property declaration.</returns>
|
||||
public static bool IsCandidatePropertyDeclaration(SyntaxNode node, CancellationToken token)
|
||||
{
|
||||
// The node must be a property declaration with two accessors
|
||||
if (node is not PropertyDeclarationSyntax { AccessorList.Accessors: { Count: 2 } accessors } property)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
// The property must be partial (we'll check that it's a declaration from its symbol)
|
||||
if (!property.Modifiers.Any(SyntaxKind.PartialKeyword))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
// Static properties are not supported
|
||||
if (property.Modifiers.Any(SyntaxKind.StaticKeyword))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
// The accessors must be a get and a set (with any accessibility)
|
||||
if (accessors[0].Kind() is not (SyntaxKind.GetAccessorDeclaration or SyntaxKind.SetAccessorDeclaration) ||
|
||||
accessors[1].Kind() is not (SyntaxKind.GetAccessorDeclaration or SyntaxKind.SetAccessorDeclaration))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
token.ThrowIfCancellationRequested();
|
||||
|
||||
// The property must be in a type with a base type (as it must derive from CanvasEffect)
|
||||
return node.Parent?.IsTypeDeclarationWithOrPotentiallyWithBaseTypes<ClassDeclarationSyntax>() == true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Tries to get the accessibility of the property and accessors, if possible.
|
||||
/// </summary>
|
||||
/// <param name="node">The input <see cref="PropertyDeclarationSyntax"/> node.</param>
|
||||
/// <param name="symbol">The input <see cref="IPropertySymbol"/> instance.</param>
|
||||
/// <param name="declaredAccessibility">The accessibility of the property, if available.</param>
|
||||
/// <param name="getterAccessibility">The accessibility of the <see langword="get"/> accessor, if available.</param>
|
||||
/// <param name="setterAccessibility">The accessibility of the <see langword="set"/> accessor, if available.</param>
|
||||
/// <returns>Whether the property was valid and the accessibilities could be retrieved.</returns>
|
||||
public static bool TryGetAccessibilityModifiers(
|
||||
PropertyDeclarationSyntax node,
|
||||
IPropertySymbol symbol,
|
||||
out Accessibility declaredAccessibility,
|
||||
out Accessibility getterAccessibility,
|
||||
out Accessibility setterAccessibility)
|
||||
{
|
||||
declaredAccessibility = Accessibility.NotApplicable;
|
||||
getterAccessibility = Accessibility.NotApplicable;
|
||||
setterAccessibility = Accessibility.NotApplicable;
|
||||
|
||||
// Ensure that we have a getter and a setter, and that the setter is not init-only
|
||||
if (symbol is not { GetMethod: { } getMethod, SetMethod: { IsInitOnly: false } setMethod })
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
// Track the property accessibility if explicitly set
|
||||
if (node.Modifiers.Count > 0)
|
||||
{
|
||||
declaredAccessibility = symbol.DeclaredAccessibility;
|
||||
}
|
||||
|
||||
// Track the accessors accessibility, if explicitly set
|
||||
foreach (AccessorDeclarationSyntax accessor in node.AccessorList?.Accessors ?? [])
|
||||
{
|
||||
if (accessor.Modifiers.Count == 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
switch (accessor.Kind())
|
||||
{
|
||||
case SyntaxKind.GetAccessorDeclaration:
|
||||
getterAccessibility = getMethod.DeclaredAccessibility;
|
||||
break;
|
||||
case SyntaxKind.SetAccessorDeclaration:
|
||||
setterAccessibility = setMethod.DeclaredAccessibility;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the invalidation type to use for the generated effect property.
|
||||
/// </summary>
|
||||
/// <param name="attributeData">The <see cref="AttributeData"/> instance for the processed attribute.</param>
|
||||
/// <returns>The resulting <see cref="CanvasEffectInvalidationType"/> to use for the generated property.</returns>
|
||||
public static CanvasEffectInvalidationType GetCanvasEffectInvalidationType(AttributeData attributeData)
|
||||
{
|
||||
if (attributeData.ConstructorArguments is [{ Kind: TypedConstantKind.Enum, Value: byte enumValue }])
|
||||
{
|
||||
return (CanvasEffectInvalidationType)enumValue;
|
||||
}
|
||||
|
||||
// No constructor parameter, or an invalid one. In this case we either just use the default
|
||||
// invalidation mode, or let the analyzer emit a diagnostic to let the user know.
|
||||
return CanvasEffectInvalidationType.Update;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes all implementations of partial effect property declarations.
|
||||
/// </summary>
|
||||
/// <param name="properties">The input set of declared effect properties.</param>
|
||||
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
|
||||
public static void WritePropertyDeclarations(EquatableArray<CanvasEffectPropertyInfo> properties, IndentedTextWriter writer)
|
||||
{
|
||||
// Helper to get the nullable type name for the initial property value
|
||||
static string GetOldValueTypeNameAsNullable(CanvasEffectPropertyInfo propertyInfo)
|
||||
{
|
||||
// Prepare the nullable type for the previous property value. This is needed because if the type is a reference
|
||||
// type, the previous value might be null even if the property type is not nullable, as the first invocation would
|
||||
// happen when the property is first set to some value that is not null (but the backing field would still be so).
|
||||
// As a cheap way to check whether we need to add nullable, we can simply check whether the type name with nullability
|
||||
// annotations ends with a '?'. If it doesn't and the type is a reference type, we add it. Otherwise, we keep it.
|
||||
return propertyInfo.IsReferenceTypeOrUnconstraindTypeParameter switch
|
||||
{
|
||||
true when !propertyInfo.TypeNameWithNullabilityAnnotations.EndsWith("?")
|
||||
=> $"{propertyInfo.TypeNameWithNullabilityAnnotations}?",
|
||||
_ => propertyInfo.TypeNameWithNullabilityAnnotations
|
||||
};
|
||||
}
|
||||
|
||||
// Helper to get the accessibility with a trailing space
|
||||
static string GetExpressionWithTrailingSpace(Accessibility accessibility)
|
||||
{
|
||||
return accessibility.GetExpression() switch
|
||||
{
|
||||
{ Length: > 0 } expression => expression + " ",
|
||||
_ => ""
|
||||
};
|
||||
}
|
||||
|
||||
// First, generate all partial property implementations at the top of the partial type declaration
|
||||
foreach (CanvasEffectPropertyInfo propertyInfo in properties)
|
||||
{
|
||||
string oldValueTypeNameAsNullable = GetOldValueTypeNameAsNullable(propertyInfo);
|
||||
|
||||
writer.WriteLine("/// <inheritdoc/>");
|
||||
writer.WriteGeneratedAttributes(GeneratorName);
|
||||
writer.Write(GetExpressionWithTrailingSpace(propertyInfo.DeclaredAccessibility));
|
||||
writer.WriteIf(propertyInfo.IsRequired, "required ");
|
||||
writer.WriteLine($"partial {propertyInfo.TypeNameWithNullabilityAnnotations} {propertyInfo.PropertyName}");
|
||||
writer.WriteLine($$"""
|
||||
{
|
||||
{{GetExpressionWithTrailingSpace(propertyInfo.GetterAccessibility)}}get => field;
|
||||
{{GetExpressionWithTrailingSpace(propertyInfo.SetterAccessibility)}}set
|
||||
{
|
||||
if (global::System.Collections.Generic.EqualityComparer<{{oldValueTypeNameAsNullable}}>.Default.Equals(field, value))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
{{oldValueTypeNameAsNullable}} oldValue = field;
|
||||
|
||||
On{{propertyInfo.PropertyName}}Changing(value);
|
||||
On{{propertyInfo.PropertyName}}Changing(oldValue, value);
|
||||
|
||||
field = value;
|
||||
|
||||
On{{propertyInfo.PropertyName}}Changed(value);
|
||||
On{{propertyInfo.PropertyName}}Changed(oldValue, value);
|
||||
|
||||
InvalidateEffectGraph(global::{{WellKnownTypeNames.CanvasEffectInvalidationType}}.{{propertyInfo.InvalidationType}});
|
||||
}
|
||||
}
|
||||
""", isMultiline: true);
|
||||
writer.WriteLine();
|
||||
}
|
||||
|
||||
// Next, emit all partial method declarations at the bottom of the file
|
||||
foreach (CanvasEffectPropertyInfo propertyInfo in properties)
|
||||
{
|
||||
// On<PROPERTY_NAME>Changing, only with new value
|
||||
writer.WriteLine(skipIfPresent: true);
|
||||
writer.WriteLine($"""
|
||||
/// <summary>Executes the logic for when <see cref="{propertyInfo.PropertyName}"/> is changing.</summary>
|
||||
/// <param name="value">The new property value being set.</param>
|
||||
/// <remarks>This method is invoked right before the value of <see cref="{propertyInfo.PropertyName}"/> is changed.</remarks>
|
||||
""", isMultiline: true);
|
||||
writer.WriteGeneratedAttributes(GeneratorName, includeNonUserCodeAttributes: false);
|
||||
writer.WriteLine($"partial void On{propertyInfo.PropertyName}Changing({propertyInfo.TypeNameWithNullabilityAnnotations} newValue);");
|
||||
|
||||
string oldValueTypeNameAsNullable = GetOldValueTypeNameAsNullable(propertyInfo);
|
||||
|
||||
// On<PROPERTY_NAME>Changing, with both values
|
||||
writer.WriteLine();
|
||||
writer.WriteLine($"""
|
||||
/// <summary>Executes the logic for when <see cref="{propertyInfo.PropertyName}"/> is changing.</summary>
|
||||
/// <param name="oldValue">The previous property value that is being replaced.</param>
|
||||
/// <param name="newValue">The new property value being set.</param>
|
||||
/// <remarks>This method is invoked right before the value of <see cref="{propertyInfo.PropertyName}"/> is changed.</remarks>
|
||||
""", isMultiline: true);
|
||||
writer.WriteGeneratedAttributes(GeneratorName, includeNonUserCodeAttributes: false);
|
||||
writer.WriteLine($"partial void On{propertyInfo.PropertyName}Changing({oldValueTypeNameAsNullable} oldValue, {propertyInfo.TypeNameWithNullabilityAnnotations} newValue);");
|
||||
|
||||
// On<PROPERTY_NAME>Changed, only with new value
|
||||
writer.WriteLine();
|
||||
writer.WriteLine($"""
|
||||
/// <summary>Executes the logic for when <see cref="{propertyInfo.PropertyName}"/> has just changed.</summary>
|
||||
/// <param name="value">The new property value that has been set.</param>
|
||||
/// <remarks>This method is invoked right after the value of <see cref="{propertyInfo.PropertyName}"/> is changed.</remarks>
|
||||
""", isMultiline: true);
|
||||
writer.WriteGeneratedAttributes(GeneratorName, includeNonUserCodeAttributes: false);
|
||||
writer.WriteLine($"partial void On{propertyInfo.PropertyName}Changed({propertyInfo.TypeNameWithNullabilityAnnotations} newValue);");
|
||||
|
||||
// On<PROPERTY_NAME>Changed, with both values
|
||||
writer.WriteLine();
|
||||
writer.WriteLine($"""
|
||||
/// <summary>Executes the logic for when <see cref="{propertyInfo.PropertyName}"/> has just changed.</summary>
|
||||
/// <param name="oldValue">The previous property value that has been replaced.</param>
|
||||
/// <param name="newValue">The new property value that has been set.</param>
|
||||
/// <remarks>This method is invoked right after the value of <see cref="{propertyInfo.PropertyName}"/> is changed.</remarks>
|
||||
""", isMultiline: true);
|
||||
writer.WriteGeneratedAttributes(GeneratorName, includeNonUserCodeAttributes: false);
|
||||
writer.WriteLine($"partial void On{propertyInfo.PropertyName}Changed({oldValueTypeNameAsNullable} oldValue, {propertyInfo.TypeNameWithNullabilityAnnotations} newValue);");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,145 +0,0 @@
|
||||
#if WINDOWS_UWP
|
||||
using ComputeSharp.D2D1.Uwp.SourceGenerators.Constants;
|
||||
using ComputeSharp.D2D1.Uwp.SourceGenerators.Models;
|
||||
#else
|
||||
using ComputeSharp.D2D1.WinUI.SourceGenerators.Constants;
|
||||
using ComputeSharp.D2D1.WinUI.SourceGenerators.Models;
|
||||
#endif
|
||||
using ComputeSharp.SourceGeneration.Constants;
|
||||
using ComputeSharp.SourceGeneration.Extensions;
|
||||
using ComputeSharp.SourceGeneration.Helpers;
|
||||
using ComputeSharp.SourceGeneration.Models;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.CSharp.Syntax;
|
||||
|
||||
#if WINDOWS_UWP
|
||||
namespace ComputeSharp.D2D1.Uwp.SourceGenerators;
|
||||
#else
|
||||
namespace ComputeSharp.D2D1.WinUI.SourceGenerators;
|
||||
#endif
|
||||
|
||||
/// <summary>
|
||||
/// A source generator creating implementations of effect properties.
|
||||
/// </summary>
|
||||
[Generator(LanguageNames.CSharp)]
|
||||
public sealed partial class CanvasEffectPropertyGenerator : IIncrementalGenerator
|
||||
{
|
||||
/// <summary>
|
||||
/// The name of generator to include in the generated code.
|
||||
/// </summary>
|
||||
internal const string GeneratorName =
|
||||
#if WINDOWS_UWP
|
||||
"ComputeSharp.D2D1.Uwp.CanvasEffectPropertyGenerator";
|
||||
#else
|
||||
"ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator";
|
||||
#endif
|
||||
|
||||
/// <inheritdoc/>
|
||||
public void Initialize(IncrementalGeneratorInitializationContext context)
|
||||
{
|
||||
IncrementalValuesProvider<CanvasEffectPropertyInfo> propertyInfo =
|
||||
context.SyntaxProvider
|
||||
.ForAttributeWithMetadataName(
|
||||
WellKnownTypeNames.GeneratedCanvasEffectPropertyAttribute,
|
||||
Execute.IsCandidatePropertyDeclaration,
|
||||
static (context, token) =>
|
||||
{
|
||||
// This generator requires C# preview to be used (due to the use of the 'field' keyword)
|
||||
if (!context.SemanticModel.Compilation.IsLanguageVersionPreview())
|
||||
{
|
||||
return default;
|
||||
}
|
||||
|
||||
// Ensure we do have a property with a valid containing type
|
||||
if (context.TargetSymbol is not IPropertySymbol { ContainingType: INamedTypeSymbol typeSymbol } propertySymbol)
|
||||
{
|
||||
return default;
|
||||
}
|
||||
|
||||
// Ensure that the property declaration is a partial definition with no implementation
|
||||
if (propertySymbol is not { IsPartialDefinition: true, PartialImplementationPart: null })
|
||||
{
|
||||
return default;
|
||||
}
|
||||
|
||||
// Also ignore all properties that have an invalid declaration
|
||||
if (propertySymbol.ReturnsByRef || propertySymbol.ReturnsByRefReadonly || propertySymbol.Type.IsRefLikeType)
|
||||
{
|
||||
return default;
|
||||
}
|
||||
|
||||
// Ensure that the containing type derives from CanvasEffect
|
||||
if (!typeSymbol.InheritsFromFullyQualifiedMetadataName(WellKnownTypeNames.CanvasEffect))
|
||||
{
|
||||
return default;
|
||||
}
|
||||
|
||||
token.ThrowIfCancellationRequested();
|
||||
|
||||
// Get the accessibility values, if the property is valid
|
||||
if (!Execute.TryGetAccessibilityModifiers(
|
||||
node: (PropertyDeclarationSyntax)context.TargetNode,
|
||||
symbol: propertySymbol,
|
||||
out Accessibility declaredAccessibility,
|
||||
out Accessibility getterAccessibility,
|
||||
out Accessibility setterAccessibility))
|
||||
{
|
||||
return default;
|
||||
}
|
||||
|
||||
token.ThrowIfCancellationRequested();
|
||||
|
||||
string typeNameWithNullabilityAnnotations = propertySymbol.Type.GetFullyQualifiedNameWithNullabilityAnnotations();
|
||||
|
||||
token.ThrowIfCancellationRequested();
|
||||
|
||||
CanvasEffectInvalidationType invalidationType = Execute.GetCanvasEffectInvalidationType(context.Attributes[0]);
|
||||
|
||||
token.ThrowIfCancellationRequested();
|
||||
|
||||
// We're using IsValueType here and not IsReferenceType to also cover unconstrained type parameter cases.
|
||||
// This will cover both reference types as well T when the constraints are not struct or unmanaged.
|
||||
// If this is true, it means the field storage can potentially be in a null state (even if not annotated).
|
||||
bool isReferenceTypeOrUnconstraindTypeParameter = !propertySymbol.Type.IsValueType;
|
||||
bool isRequired = propertySymbol.IsRequired;
|
||||
|
||||
// Finally, get the hierarchy too
|
||||
HierarchyInfo hierarchyInfo = HierarchyInfo.From(typeSymbol);
|
||||
|
||||
token.ThrowIfCancellationRequested();
|
||||
|
||||
return new CanvasEffectPropertyInfo(
|
||||
Hierarchy: hierarchyInfo,
|
||||
PropertyName: propertySymbol.Name,
|
||||
DeclaredAccessibility: declaredAccessibility,
|
||||
GetterAccessibility: getterAccessibility,
|
||||
SetterAccessibility: setterAccessibility,
|
||||
TypeNameWithNullabilityAnnotations: typeNameWithNullabilityAnnotations,
|
||||
IsReferenceTypeOrUnconstraindTypeParameter: isReferenceTypeOrUnconstraindTypeParameter,
|
||||
IsRequired: isRequired,
|
||||
InvalidationType: invalidationType);
|
||||
})
|
||||
.WithTrackingName(WellKnownTrackingNames.Execute)
|
||||
.Where(static item => item is not null)!;
|
||||
|
||||
// Split and group by containing type
|
||||
IncrementalValuesProvider<(HierarchyInfo Hierarchy, EquatableArray<CanvasEffectPropertyInfo> Properties)> groupedPropertyInfo =
|
||||
propertyInfo
|
||||
.GroupBy(keySelector: static item => item.Hierarchy, elementSelector: static item => item)
|
||||
.WithTrackingName(WellKnownTrackingNames.Output);
|
||||
|
||||
// Generate the source files, if any
|
||||
context.RegisterSourceOutput(groupedPropertyInfo, static (context, item) =>
|
||||
{
|
||||
using IndentedTextWriter writer = new();
|
||||
|
||||
item.Hierarchy.WriteSyntax(
|
||||
state: item.Properties,
|
||||
writer: writer,
|
||||
baseTypes: [],
|
||||
memberCallbacks: [Execute.WritePropertyDeclarations]);
|
||||
|
||||
context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.g.cs", writer.ToString());
|
||||
});
|
||||
}
|
||||
}
|
||||
-24
@@ -1,24 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<PropertyGroup>
|
||||
<MSBuildAllProjects Condition="'$(MSBuildVersion)' == '' Or '$(MSBuildVersion)' < '16.0'">$(MSBuildAllProjects);$(MSBuildThisFileFullPath)</MSBuildAllProjects>
|
||||
<HasSharedItems>true</HasSharedItems>
|
||||
<SharedGUID>d20e610f-eb37-46e7-b028-04784d7400d5</SharedGUID>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Label="Configuration">
|
||||
<Import_RootNamespace>ComputeSharp.D2D1.UI.SourceGenerators</Import_RootNamespace>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<Compile Include="$(MSBuildThisFileDirectory)CanvasEffectPropertyGenerator.cs" />
|
||||
<Compile Include="$(MSBuildThisFileDirectory)CanvasEffectPropertyGenerator.Execute.cs" />
|
||||
<Compile Include="$(MSBuildThisFileDirectory)Constants\WellKnownTypeNames.cs" />
|
||||
<Compile Include="$(MSBuildThisFileDirectory)Diagnostics\Analyzers\InvalidGeneratedCanvasEffectPropertyAccessorsAnalyzer.cs" />
|
||||
<Compile Include="$(MSBuildThisFileDirectory)Diagnostics\Analyzers\InvalidGeneratedCanvasEffectPropertyContainingTypeAnalyzer.cs" />
|
||||
<Compile Include="$(MSBuildThisFileDirectory)Diagnostics\Analyzers\InvalidGeneratedCanvasEffectPropertyDeclarationAnalyzer.cs" />
|
||||
<Compile Include="$(MSBuildThisFileDirectory)Diagnostics\Analyzers\RequireCSharpLanguageVersionPreviewAnalyzer.cs" />
|
||||
<Compile Include="$(MSBuildThisFileDirectory)Diagnostics\Analyzers\UseGeneratedCanvasEffectPropertyOnSemiAutoPropertyAnalyzer.cs" />
|
||||
<Compile Include="$(MSBuildThisFileDirectory)Diagnostics\DiagnosticDescriptors.cs" />
|
||||
<Compile Include="$(MSBuildThisFileDirectory)Models\CanvasEffectPropertyInfo.cs" />
|
||||
<Compile Include="$(MSBuildThisFileDirectory)..\ComputeSharp.D2D1.UI\CanvasEffectInvalidationType.cs" Link="ComputeSharp.D2D1.UI\CanvasEffectInvalidationType.cs" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -1,13 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<PropertyGroup Label="Globals">
|
||||
<ProjectGuid>d20e610f-eb37-46e7-b028-04784d7400d5</ProjectGuid>
|
||||
<MinimumVisualStudioVersion>14.0</MinimumVisualStudioVersion>
|
||||
</PropertyGroup>
|
||||
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
|
||||
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.Common.Default.props" />
|
||||
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.Common.props" />
|
||||
<PropertyGroup />
|
||||
<Import Project="ComputeSharp.D2D1.UI.SourceGenerators.projitems" Label="Shared" />
|
||||
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.CSharp.targets" />
|
||||
</Project>
|
||||
@@ -1,41 +0,0 @@
|
||||
#if WINDOWS_UWP
|
||||
namespace ComputeSharp.D2D1.Uwp.SourceGenerators.Constants;
|
||||
#else
|
||||
namespace ComputeSharp.D2D1.WinUI.SourceGenerators.Constants;
|
||||
#endif
|
||||
|
||||
/// <summary>
|
||||
/// The well known names for types used by source generators and analyzers.
|
||||
/// </summary>
|
||||
internal static class WellKnownTypeNames
|
||||
{
|
||||
/// <summary>
|
||||
/// The fully qualified type name for the <c>[GeneratedCanvasEffectProperty]</c> type.
|
||||
/// </summary>
|
||||
public const string GeneratedCanvasEffectPropertyAttribute =
|
||||
#if WINDOWS_UWP
|
||||
"ComputeSharp.D2D1.Uwp.GeneratedCanvasEffectPropertyAttribute";
|
||||
#else
|
||||
"ComputeSharp.D2D1.WinUI.GeneratedCanvasEffectPropertyAttribute";
|
||||
#endif
|
||||
|
||||
/// <summary>
|
||||
/// The fully qualified type name for the <c>CanvasEffect</c> type.
|
||||
/// </summary>
|
||||
public const string CanvasEffect =
|
||||
#if WINDOWS_UWP
|
||||
"ComputeSharp.D2D1.Uwp.CanvasEffect";
|
||||
#else
|
||||
"ComputeSharp.D2D1.WinUI.CanvasEffect";
|
||||
#endif
|
||||
|
||||
/// <summary>
|
||||
/// The fully qualified type name for the <c>CanvasEffect</c> type.
|
||||
/// </summary>
|
||||
public const string CanvasEffectInvalidationType =
|
||||
#if WINDOWS_UWP
|
||||
"ComputeSharp.D2D1.Uwp.CanvasEffectInvalidationType";
|
||||
#else
|
||||
"ComputeSharp.D2D1.WinUI.CanvasEffectInvalidationType";
|
||||
#endif
|
||||
}
|
||||
-70
@@ -1,70 +0,0 @@
|
||||
using System.Collections.Immutable;
|
||||
#if WINDOWS_UWP
|
||||
using ComputeSharp.D2D1.Uwp.SourceGenerators.Constants;
|
||||
#else
|
||||
using ComputeSharp.D2D1.WinUI.SourceGenerators.Constants;
|
||||
#endif
|
||||
using ComputeSharp.SourceGeneration.Extensions;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.Diagnostics;
|
||||
#if WINDOWS_UWP
|
||||
using static ComputeSharp.D2D1.Uwp.SourceGenerators.DiagnosticDescriptors;
|
||||
#else
|
||||
using static ComputeSharp.D2D1.WinUI.SourceGenerators.DiagnosticDescriptors;
|
||||
#endif
|
||||
|
||||
#if WINDOWS_UWP
|
||||
namespace ComputeSharp.D2D1.Uwp.SourceGenerators;
|
||||
#else
|
||||
namespace ComputeSharp.D2D1.WinUI.SourceGenerators;
|
||||
#endif
|
||||
|
||||
/// <summary>
|
||||
/// A diagnostic analyzer that generates errors when a property using [GeneratedCanvasEffectProperty] has invalid accessors.
|
||||
/// </summary>
|
||||
[DiagnosticAnalyzer(LanguageNames.CSharp)]
|
||||
public sealed class InvalidGeneratedCanvasEffectPropertyAccessorsAnalyzer : DiagnosticAnalyzer
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = [InvalidGeneratedCanvasEffectPropertyAccessors];
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override void Initialize(AnalysisContext context)
|
||||
{
|
||||
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics);
|
||||
context.EnableConcurrentExecution();
|
||||
|
||||
context.RegisterCompilationStartAction(static context =>
|
||||
{
|
||||
// Get the [GeneratedCanvasEffectProperty] symbols
|
||||
if (context.Compilation.GetTypeByMetadataName(WellKnownTypeNames.GeneratedCanvasEffectPropertyAttribute) is not { } generatedCanvasEffectPropertyAttributeSymbol)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
context.RegisterSymbolAction(context =>
|
||||
{
|
||||
// Check that the property doesn't have 'get' and 'set' accessors
|
||||
if (context.Symbol is IPropertySymbol { GetMethod: { }, SetMethod.IsInitOnly: false })
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Skip implementation parts to avoid duplicate errors
|
||||
if (context.Symbol is IPropertySymbol { PartialDefinitionPart: not null })
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// If the property is using [GeneratedCanvasEffectProperty], emit the diagnostic
|
||||
if (context.Symbol.TryGetAttributeWithType(generatedCanvasEffectPropertyAttributeSymbol, out AttributeData? generatedCanvasEffectPropertyAttribute))
|
||||
{
|
||||
context.ReportDiagnostic(Diagnostic.Create(
|
||||
InvalidGeneratedCanvasEffectPropertyAccessors,
|
||||
generatedCanvasEffectPropertyAttribute.GetLocation(),
|
||||
context.Symbol));
|
||||
}
|
||||
}, SymbolKind.Property);
|
||||
});
|
||||
}
|
||||
}
|
||||
-71
@@ -1,71 +0,0 @@
|
||||
using System.Collections.Immutable;
|
||||
#if WINDOWS_UWP
|
||||
using ComputeSharp.D2D1.Uwp.SourceGenerators.Constants;
|
||||
#else
|
||||
using ComputeSharp.D2D1.WinUI.SourceGenerators.Constants;
|
||||
#endif
|
||||
using ComputeSharp.SourceGeneration.Extensions;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.Diagnostics;
|
||||
#if WINDOWS_UWP
|
||||
using static ComputeSharp.D2D1.Uwp.SourceGenerators.DiagnosticDescriptors;
|
||||
#else
|
||||
using static ComputeSharp.D2D1.WinUI.SourceGenerators.DiagnosticDescriptors;
|
||||
#endif
|
||||
|
||||
#if WINDOWS_UWP
|
||||
namespace ComputeSharp.D2D1.Uwp.SourceGenerators;
|
||||
#else
|
||||
namespace ComputeSharp.D2D1.WinUI.SourceGenerators;
|
||||
#endif
|
||||
|
||||
/// <summary>
|
||||
/// A diagnostic analyzer that generates errors when a property using [GeneratedCanvasEffectProperty] is in an invalid type.
|
||||
/// </summary>
|
||||
[DiagnosticAnalyzer(LanguageNames.CSharp)]
|
||||
public sealed class InvalidGeneratedCanvasEffectPropertyContainingTypeAnalyzer : DiagnosticAnalyzer
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = [InvalidGeneratedCanvasEffectPropertyContainingType];
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override void Initialize(AnalysisContext context)
|
||||
{
|
||||
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics);
|
||||
context.EnableConcurrentExecution();
|
||||
|
||||
context.RegisterCompilationStartAction(static context =>
|
||||
{
|
||||
// Get the [GeneratedCanvasEffectProperty] and CanvasEffect symbols
|
||||
if (context.Compilation.GetTypeByMetadataName(WellKnownTypeNames.GeneratedCanvasEffectPropertyAttribute) is not { } generatedCanvasEffectPropertyAttributeSymbol ||
|
||||
context.Compilation.GetTypeByMetadataName(WellKnownTypeNames.CanvasEffect) is not { } canvasEffectSymbol)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
context.RegisterSymbolAction(context =>
|
||||
{
|
||||
// Validate that we have a valid containing type (also skip implementation parts)
|
||||
if (context.Symbol is not IPropertySymbol { ContainingType: { } containingTypeSymbol, PartialDefinitionPart: null })
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// If the property is not using [GeneratedCanvasEffectProperty], there's nothing to do
|
||||
if (!context.Symbol.TryGetAttributeWithType(generatedCanvasEffectPropertyAttributeSymbol, out AttributeData? generatedCanvasEffectPropertyAttribute))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Issue a diagnostic if the type doesn't derive from CanvasEffect
|
||||
if (!containingTypeSymbol.InheritsFromType(canvasEffectSymbol))
|
||||
{
|
||||
context.ReportDiagnostic(Diagnostic.Create(
|
||||
InvalidGeneratedCanvasEffectPropertyContainingType,
|
||||
generatedCanvasEffectPropertyAttribute.GetLocation(),
|
||||
context.Symbol));
|
||||
}
|
||||
}, SymbolKind.Property);
|
||||
});
|
||||
}
|
||||
}
|
||||
-115
@@ -1,115 +0,0 @@
|
||||
using System.Collections.Immutable;
|
||||
#if WINDOWS_UWP
|
||||
using ComputeSharp.D2D1.Uwp.SourceGenerators.Constants;
|
||||
#else
|
||||
using ComputeSharp.D2D1.WinUI.SourceGenerators.Constants;
|
||||
#endif
|
||||
using ComputeSharp.SourceGeneration.Extensions;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.Diagnostics;
|
||||
#if WINDOWS_UWP
|
||||
using static ComputeSharp.D2D1.Uwp.SourceGenerators.DiagnosticDescriptors;
|
||||
#else
|
||||
using static ComputeSharp.D2D1.WinUI.SourceGenerators.DiagnosticDescriptors;
|
||||
#endif
|
||||
|
||||
#if WINDOWS_UWP
|
||||
namespace ComputeSharp.D2D1.Uwp.SourceGenerators;
|
||||
#else
|
||||
namespace ComputeSharp.D2D1.WinUI.SourceGenerators;
|
||||
#endif
|
||||
|
||||
/// <summary>
|
||||
/// A diagnostic analyzer that generates errors when a property using [GeneratedCanvasEffectProperty] has invalid accessors.
|
||||
/// </summary>
|
||||
[DiagnosticAnalyzer(LanguageNames.CSharp)]
|
||||
public sealed class InvalidGeneratedCanvasEffectPropertyDeclarationAnalyzer : DiagnosticAnalyzer
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } =
|
||||
[
|
||||
InvalidGeneratedCanvasEffectPropertyDeclarationIsStatic,
|
||||
InvalidGeneratedCanvasEffectPropertyDeclarationIsNotIncompletePartialDefinition,
|
||||
InvalidGeneratedCanvasEffectPropertyDeclarationReturnsByRef,
|
||||
InvalidGeneratedCanvasEffectPropertyDeclarationReturnsRefLikeType
|
||||
];
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override void Initialize(AnalysisContext context)
|
||||
{
|
||||
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics);
|
||||
context.EnableConcurrentExecution();
|
||||
|
||||
context.RegisterCompilationStartAction(static context =>
|
||||
{
|
||||
// Get the [GeneratedCanvasEffectProperty] and [GeneratedCode] symbols
|
||||
if (context.Compilation.GetTypeByMetadataName(WellKnownTypeNames.GeneratedCanvasEffectPropertyAttribute) is not { } generatedCanvasEffectPropertyAttributeSymbol ||
|
||||
context.Compilation.GetTypeByMetadataName("System.CodeDom.Compiler.GeneratedCodeAttribute") is not { } generatedCodeAttributeSymbol)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
context.RegisterSymbolAction(context =>
|
||||
{
|
||||
// Ensure that we have some target property to analyze (also skip implementation parts)
|
||||
if (context.Symbol is not IPropertySymbol { PartialDefinitionPart: null } propertySymbol)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// If the property is not using [GeneratedCanvasEffectProperty], there's nothing to do
|
||||
if (!context.Symbol.TryGetAttributeWithType(generatedCanvasEffectPropertyAttributeSymbol, out AttributeData? generatedCanvasEffectPropertyAttribute))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Emit an error if the property is static
|
||||
if (propertySymbol.IsStatic)
|
||||
{
|
||||
context.ReportDiagnostic(Diagnostic.Create(
|
||||
InvalidGeneratedCanvasEffectPropertyDeclarationIsStatic,
|
||||
generatedCanvasEffectPropertyAttribute.GetLocation(),
|
||||
context.Symbol));
|
||||
}
|
||||
|
||||
// Emit an error if the property is not a partial definition with no implementation...
|
||||
if (propertySymbol is not { IsPartialDefinition: true, PartialImplementationPart: null })
|
||||
{
|
||||
// ...But only if it wasn't actually generated by the [GeneratedCanvasEffectProperty] generator.
|
||||
bool isImplementationAllowed =
|
||||
propertySymbol is { IsPartialDefinition: true, PartialImplementationPart: IPropertySymbol implementationPartSymbol } &&
|
||||
implementationPartSymbol.TryGetAttributeWithType(generatedCodeAttributeSymbol, out AttributeData? generatedCodeAttributeData) &&
|
||||
generatedCodeAttributeData.TryGetConstructorArgument(0, out string? toolName) &&
|
||||
toolName == CanvasEffectPropertyGenerator.GeneratorName;
|
||||
|
||||
// Emit the diagnostic only for cases that were not valid generator outputs
|
||||
if (!isImplementationAllowed)
|
||||
{
|
||||
context.ReportDiagnostic(Diagnostic.Create(
|
||||
InvalidGeneratedCanvasEffectPropertyDeclarationIsNotIncompletePartialDefinition,
|
||||
generatedCanvasEffectPropertyAttribute.GetLocation(),
|
||||
context.Symbol));
|
||||
}
|
||||
}
|
||||
|
||||
// Emit an error if the property returns a value by ref
|
||||
if (propertySymbol.ReturnsByRef || propertySymbol.ReturnsByRefReadonly)
|
||||
{
|
||||
context.ReportDiagnostic(Diagnostic.Create(
|
||||
InvalidGeneratedCanvasEffectPropertyDeclarationReturnsByRef,
|
||||
generatedCanvasEffectPropertyAttribute.GetLocation(),
|
||||
context.Symbol));
|
||||
}
|
||||
|
||||
// Emit an error if the property type is a ref struct
|
||||
if (propertySymbol.Type.IsRefLikeType)
|
||||
{
|
||||
context.ReportDiagnostic(Diagnostic.Create(
|
||||
InvalidGeneratedCanvasEffectPropertyDeclarationReturnsRefLikeType,
|
||||
generatedCanvasEffectPropertyAttribute.GetLocation(),
|
||||
context.Symbol));
|
||||
}
|
||||
}, SymbolKind.Property);
|
||||
});
|
||||
}
|
||||
}
|
||||
-70
@@ -1,70 +0,0 @@
|
||||
using System.Collections.Immutable;
|
||||
#if WINDOWS_UWP
|
||||
using ComputeSharp.D2D1.Uwp.SourceGenerators.Constants;
|
||||
#else
|
||||
using ComputeSharp.D2D1.WinUI.SourceGenerators.Constants;
|
||||
#endif
|
||||
using ComputeSharp.SourceGeneration.Extensions;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.Diagnostics;
|
||||
#if WINDOWS_UWP
|
||||
using static ComputeSharp.D2D1.Uwp.SourceGenerators.DiagnosticDescriptors;
|
||||
#else
|
||||
using static ComputeSharp.D2D1.WinUI.SourceGenerators.DiagnosticDescriptors;
|
||||
#endif
|
||||
|
||||
#if WINDOWS_UWP
|
||||
namespace ComputeSharp.D2D1.Uwp.SourceGenerators;
|
||||
#else
|
||||
namespace ComputeSharp.D2D1.WinUI.SourceGenerators;
|
||||
#endif
|
||||
|
||||
/// <summary>
|
||||
/// A diagnostic analyzer that generates errors when a property using [GeneratedCanvasEffectProperty] is in a project with the C# language version not set to preview.
|
||||
/// </summary>
|
||||
[DiagnosticAnalyzer(LanguageNames.CSharp)]
|
||||
public sealed class RequireCSharpLanguageVersionPreviewAnalyzer : DiagnosticAnalyzer
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = [CSharpLanguageVersionIsNotPreview];
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override void Initialize(AnalysisContext context)
|
||||
{
|
||||
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics);
|
||||
context.EnableConcurrentExecution();
|
||||
|
||||
context.RegisterCompilationStartAction(static context =>
|
||||
{
|
||||
// If the language version is set to preview, we'll never emit diagnostics
|
||||
if (context.Compilation.IsLanguageVersionPreview())
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Get the [GeneratedCanvasEffectProperty] symbols
|
||||
if (context.Compilation.GetTypeByMetadataName(WellKnownTypeNames.GeneratedCanvasEffectPropertyAttribute) is not { } generatedCanvasEffectPropertyAttributeSymbol)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
context.RegisterSymbolAction(context =>
|
||||
{
|
||||
// We only want to target partial property definitions (also include non-partial ones for diagnostics)
|
||||
if (context.Symbol is not IPropertySymbol { PartialDefinitionPart: null })
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// If the property is using [GeneratedCanvasEffectProperty], emit the diagnostic
|
||||
if (context.Symbol.TryGetAttributeWithType(generatedCanvasEffectPropertyAttributeSymbol, out AttributeData? generatedCanvasEffectPropertyAttribute))
|
||||
{
|
||||
context.ReportDiagnostic(Diagnostic.Create(
|
||||
CSharpLanguageVersionIsNotPreview,
|
||||
generatedCanvasEffectPropertyAttribute.GetLocation(),
|
||||
context.Symbol));
|
||||
}
|
||||
}, SymbolKind.Property);
|
||||
});
|
||||
}
|
||||
}
|
||||
-356
@@ -1,356 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Immutable;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#if WINDOWS_UWP
|
||||
using ComputeSharp.D2D1.Uwp.SourceGenerators.Constants;
|
||||
#else
|
||||
using ComputeSharp.D2D1.WinUI.SourceGenerators.Constants;
|
||||
#endif
|
||||
using ComputeSharp.SourceGeneration.Extensions;
|
||||
using ComputeSharp.SourceGeneration.Helpers;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.CSharp;
|
||||
using Microsoft.CodeAnalysis.CSharp.Syntax;
|
||||
using Microsoft.CodeAnalysis.Diagnostics;
|
||||
using Microsoft.CodeAnalysis.Operations;
|
||||
#if WINDOWS_UWP
|
||||
using static ComputeSharp.D2D1.Uwp.SourceGenerators.DiagnosticDescriptors;
|
||||
#else
|
||||
using static ComputeSharp.D2D1.WinUI.SourceGenerators.DiagnosticDescriptors;
|
||||
#endif
|
||||
|
||||
#if WINDOWS_UWP
|
||||
namespace ComputeSharp.D2D1.Uwp.SourceGenerators;
|
||||
#else
|
||||
namespace ComputeSharp.D2D1.WinUI.SourceGenerators;
|
||||
#endif
|
||||
|
||||
/// <summary>
|
||||
/// A diagnostic analyzer that generates a suggestion whenever <c>[GeneratedCanvasEffectProperty]</c> is used on a semi-auto property when a partial property could be used instead.
|
||||
/// </summary>
|
||||
[DiagnosticAnalyzer(LanguageNames.CSharp)]
|
||||
public sealed class UseGeneratedCanvasEffectPropertyOnSemiAutoPropertyAnalyzer : DiagnosticAnalyzer
|
||||
{
|
||||
/// <summary>
|
||||
/// The number of pooled flags per stack (ie. how many properties we expect on average per type).
|
||||
/// </summary>
|
||||
private const int NumberOfPooledFlagsPerStack = 20;
|
||||
|
||||
/// <summary>
|
||||
/// Shared pool for <see cref="Dictionary{TKey, TValue}"/> instances.
|
||||
/// </summary>
|
||||
[SuppressMessage("MicrosoftCodeAnalysisPerformance", "RS1008", Justification = "This is a pool of (empty) dictionaries, it is not actually storing compilation data.")]
|
||||
private static readonly ObjectPool<Dictionary<IPropertySymbol, byte[]>> PropertyMapPool = new(static () => new Dictionary<IPropertySymbol, byte[]>(SymbolEqualityComparer.Default));
|
||||
|
||||
/// <summary>
|
||||
/// Shared pool for <see cref="Stack{T}"/>-s of flags, one per type being processed.
|
||||
/// </summary>
|
||||
private static readonly ObjectPool<Stack<byte[]>> PropertyFlagsStackPool = new(CreatePropertyFlagsStack);
|
||||
|
||||
/// <summary>
|
||||
/// The property name for the serialized invalidation type.
|
||||
/// </summary>
|
||||
public const string InvalidationTypePropertyName = "InvalidationType";
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = [UseGeneratedCanvasEffectPropertyOnSemiAutoProperty];
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override void Initialize(AnalysisContext context)
|
||||
{
|
||||
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
|
||||
context.EnableConcurrentExecution();
|
||||
|
||||
context.RegisterCompilationStartAction(static context =>
|
||||
{
|
||||
// Using [GeneratedCanvasEffectProperty] on partial properties is only supported when using C# preview.
|
||||
// As such, if that is not the case, return immediately, as no diagnostic should be produced.
|
||||
if (!context.Compilation.IsLanguageVersionPreview())
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Get the [GeneratedCanvasEffectProperty] and CanvasEffect symbols
|
||||
if (context.Compilation.GetTypeByMetadataName(WellKnownTypeNames.GeneratedCanvasEffectPropertyAttribute) is not { } generatedCanvasEffectPropertyAttributeSymbol ||
|
||||
context.Compilation.GetTypeByMetadataName(WellKnownTypeNames.CanvasEffect) is not { } canvasEffectSymbol)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Get the symbol for the SetPropertyAndInvalidateEffectGraph<T> method as well
|
||||
if (!TryGetSetPropertyMethodSymbol(canvasEffectSymbol, out IMethodSymbol? setPropertySymbol))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
context.RegisterSymbolStartAction(context =>
|
||||
{
|
||||
// We only care about types that could derive from ObservableObject
|
||||
if (context.Symbol is not INamedTypeSymbol { IsStatic: false, IsReferenceType: true, BaseType.SpecialType: not SpecialType.System_Object } typeSymbol)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// If the type does not derive from ObservableObject, ignore it
|
||||
if (!typeSymbol.InheritsFromType(canvasEffectSymbol))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
Dictionary<IPropertySymbol, byte[]> propertyMap = PropertyMapPool.Allocate();
|
||||
Stack<byte[]> propertyFlagsStack = PropertyFlagsStackPool.Allocate();
|
||||
|
||||
// Crawl all members to discover properties that might be of interest
|
||||
foreach (ISymbol memberSymbol in typeSymbol.GetMembers())
|
||||
{
|
||||
// We're only looking for properties that might be valid candidates for conversion
|
||||
if (memberSymbol is not IPropertySymbol
|
||||
{
|
||||
IsStatic: false,
|
||||
IsPartialDefinition: false,
|
||||
PartialDefinitionPart: null,
|
||||
PartialImplementationPart: null,
|
||||
ReturnsByRef: false,
|
||||
ReturnsByRefReadonly: false,
|
||||
Type.IsRefLikeType: false,
|
||||
GetMethod: not null,
|
||||
SetMethod.IsInitOnly: false
|
||||
} propertySymbol)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
// We can safely ignore properties that already have [GeneratedCanvasEffectProperty].
|
||||
// This is because in that case, the other analyzer will already emit an error.
|
||||
if (propertySymbol.HasAttributeWithType(generatedCanvasEffectPropertyAttributeSymbol))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
// Take an array from the stack or create a new one otherwise
|
||||
byte[] flags = propertyFlagsStack.Count > 0
|
||||
? propertyFlagsStack.Pop()
|
||||
: new byte[2];
|
||||
|
||||
// Track the property for later
|
||||
propertyMap.Add(propertySymbol, flags);
|
||||
}
|
||||
|
||||
// We want to process both accessors, where we specifically need both the syntax
|
||||
// and their semantic model to verify what they're doing. We can use a code callback.
|
||||
context.RegisterOperationBlockAction(context =>
|
||||
{
|
||||
// Make sure the current symbol is a property accessor
|
||||
if (context.OwningSymbol is not IMethodSymbol { MethodKind: MethodKind.PropertyGet or MethodKind.PropertySet, AssociatedSymbol: IPropertySymbol propertySymbol })
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// If so, check that we are actually processing one of the properties we care about
|
||||
if (!propertyMap.TryGetValue(propertySymbol, out byte[]? validFlags))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Handle the 'get' logic
|
||||
if (SymbolEqualityComparer.Default.Equals(propertySymbol.GetMethod, context.OwningSymbol))
|
||||
{
|
||||
// We expect a top-level block operation, that immediately returns an expression
|
||||
if (context.OperationBlocks is not [IBlockOperation { Operations: [IReturnOperation returnOperation] }])
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Next, we expect the return to produce a field reference
|
||||
if (returnOperation is not { ReturnedValue: IFieldReferenceOperation fieldReferenceOperation })
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// The field has to be implicitly declared and not constant (and not static)
|
||||
if (fieldReferenceOperation.Field is not { IsImplicitlyDeclared: true, IsStatic: false } fieldSymbol)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Validate tha the field is indeed 'field' (it will be associated with the property)
|
||||
if (!SymbolEqualityComparer.Default.Equals(fieldSymbol.AssociatedSymbol, propertySymbol))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// The 'get' accessor is valid
|
||||
validFlags[0] = 1;
|
||||
}
|
||||
else if (SymbolEqualityComparer.Default.Equals(propertySymbol.SetMethod, context.OwningSymbol))
|
||||
{
|
||||
// We expect a top-level block operation, that immediately performs an invocation
|
||||
if (context.OperationBlocks is not [IBlockOperation { Operations: [IExpressionStatementOperation { Operation: IInvocationOperation invocationOperation }] }])
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Brief filtering of the target method, also get the original definition
|
||||
if (invocationOperation.TargetMethod is not { Name: "SetPropertyAndInvalidateEffectGraph", IsGenericMethod: true, IsStatic: false } methodSymbol)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// First, check that we're calling 'CanvasEffect.SetPropertyAndInvalidateEffectGraph'
|
||||
if (!SymbolEqualityComparer.Default.Equals(methodSymbol.ConstructedFrom, setPropertySymbol))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// We matched the method, now let's validate the arguments
|
||||
if (invocationOperation.Arguments is not [{ } locationArgument, { } valueArgument, { } invalidationTypeArgument])
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// The field has to be implicitly declared and not constant (and not static)
|
||||
if (locationArgument.Value is not IFieldReferenceOperation { Field: { IsImplicitlyDeclared: true, IsStatic: false } fieldSymbol })
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Validate tha the field is indeed 'field' (it will be associated with the property)
|
||||
if (!SymbolEqualityComparer.Default.Equals(fieldSymbol.AssociatedSymbol, propertySymbol))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// The value is just the 'value' keyword
|
||||
if (valueArgument.Value is not IParameterReferenceOperation { Syntax: IdentifierNameSyntax { Identifier.Text: "value" } })
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// The invalidation mode can either be the default value...
|
||||
if (invalidationTypeArgument is { IsImplicit: true, ArgumentKind: ArgumentKind.DefaultValue })
|
||||
{
|
||||
validFlags[1] = 1;
|
||||
}
|
||||
else if (invalidationTypeArgument is { Value.ConstantValue: { HasValue: true, Value: byte mode } } && mode is 0 or 1)
|
||||
{
|
||||
// ...Or is has to be set explicitly to one of the two supported values
|
||||
validFlags[1] = (byte)(mode + 1);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// We also need to track getters which have no body, and we need syntax for that
|
||||
context.RegisterSyntaxNodeAction(context =>
|
||||
{
|
||||
// Let's just make sure we do have a property symbol
|
||||
if (context.ContainingSymbol is not IPropertySymbol { GetMethod: not null } propertySymbol)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Lookup the property to get its flags
|
||||
if (!propertyMap.TryGetValue(propertySymbol, out byte[]? validFlags))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// We expect two accessors, skip if otherwise (the setter will be validated by the other callback)
|
||||
if (context.Node is not PropertyDeclarationSyntax { AccessorList.Accessors: [{ } firstAccessor, { } secondAccessor] })
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Check that either of them is a semicolon token 'get;' accessor (it can be in either position)
|
||||
if ((firstAccessor.IsKind(SyntaxKind.GetAccessorDeclaration) &&
|
||||
firstAccessor.SemicolonToken.IsKind(SyntaxKind.SemicolonToken) &&
|
||||
firstAccessor.ExpressionBody is null) ||
|
||||
(secondAccessor.IsKind(SyntaxKind.GetAccessorDeclaration) &&
|
||||
secondAccessor.SemicolonToken.IsKind(SyntaxKind.SemicolonToken) &&
|
||||
secondAccessor.ExpressionBody is null))
|
||||
{
|
||||
validFlags[0] = 1;
|
||||
}
|
||||
}, SyntaxKind.PropertyDeclaration);
|
||||
|
||||
// Finally, we can consume this information when we finish processing the symbol
|
||||
context.RegisterSymbolEndAction(context =>
|
||||
{
|
||||
// Emit a diagnostic for each property that was a valid match
|
||||
foreach (KeyValuePair<IPropertySymbol, byte[]> pair in propertyMap)
|
||||
{
|
||||
if (pair.Value is [1, 1 or 2])
|
||||
{
|
||||
// Shift back the index to match the actual enum values, to simplify the code fixer. Here we're adding 1 to
|
||||
// signal "the setter is valid", but we want to hide this implementation detail to downstream consumers.
|
||||
int invalidationType = pair.Value[1] - 1;
|
||||
|
||||
context.ReportDiagnostic(Diagnostic.Create(
|
||||
UseGeneratedCanvasEffectPropertyOnSemiAutoProperty,
|
||||
pair.Key.Locations.FirstOrDefault(),
|
||||
ImmutableDictionary.Create<string, string?>().Add(InvalidationTypePropertyName, invalidationType.ToString()),
|
||||
pair.Key));
|
||||
}
|
||||
}
|
||||
|
||||
// Before clearing the dictionary, move back all values to the stack
|
||||
foreach (byte[] propertyFlags in propertyMap.Values)
|
||||
{
|
||||
// Make sure the array is cleared before returning it
|
||||
propertyFlags.AsSpan().Clear();
|
||||
|
||||
propertyFlagsStack.Push(propertyFlags);
|
||||
}
|
||||
|
||||
// We are now done processing the symbol, we can return the dictionary.
|
||||
// Note that we must clear it before doing so to avoid leaks and issues.
|
||||
propertyMap.Clear();
|
||||
|
||||
PropertyMapPool.Free(propertyMap);
|
||||
|
||||
// Also do the same for the stack, except we don't need to clean it (since it roots no compilation objects)
|
||||
PropertyFlagsStackPool.Free(propertyFlagsStack);
|
||||
});
|
||||
}, SymbolKind.NamedType);
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Tries to get the symbol for the target <c>SetPropertyAndInvalidateEffectGraph</c> method this analyzer looks for.
|
||||
/// </summary>
|
||||
/// <param name="canvasEffectSymbol">The symbol for <c>CanvasEffect</c>.</param>
|
||||
/// <param name="setPropertySymbol">The resulting method symbol, if found (this should always be the case).</param>
|
||||
/// <returns>Whether <paramref name="setPropertySymbol"/> could be resolved correctly.</returns>
|
||||
private static bool TryGetSetPropertyMethodSymbol(INamedTypeSymbol canvasEffectSymbol, [NotNullWhen(true)] out IMethodSymbol? setPropertySymbol)
|
||||
{
|
||||
foreach (ISymbol symbol in canvasEffectSymbol.GetMembers("SetPropertyAndInvalidateEffectGraph"))
|
||||
{
|
||||
// There's only one method with this name, so we can just return it directly
|
||||
setPropertySymbol = (IMethodSymbol)symbol;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
setPropertySymbol = null;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Produces a new <see cref="Stack{T}"/> instance to pool.
|
||||
/// </summary>
|
||||
/// <returns>The resulting <see cref="Stack{T}"/> instance to use.</returns>
|
||||
private static Stack<byte[]> CreatePropertyFlagsStack()
|
||||
{
|
||||
static IEnumerable<byte[]> EnumerateFlags()
|
||||
{
|
||||
for (int i = 0; i < NumberOfPooledFlagsPerStack; i++)
|
||||
{
|
||||
yield return new byte[2];
|
||||
}
|
||||
}
|
||||
|
||||
return new(EnumerateFlags());
|
||||
}
|
||||
}
|
||||
@@ -1,166 +0,0 @@
|
||||
using Microsoft.CodeAnalysis;
|
||||
|
||||
#if WINDOWS_UWP
|
||||
namespace ComputeSharp.D2D1.Uwp.SourceGenerators;
|
||||
#else
|
||||
namespace ComputeSharp.D2D1.WinUI.SourceGenerators;
|
||||
#endif
|
||||
|
||||
/// <summary>
|
||||
/// A container for all <see cref="DiagnosticDescriptor"/> instances for errors reported by analyzers in this project.
|
||||
/// </summary>
|
||||
internal static class DiagnosticDescriptors
|
||||
{
|
||||
/// <summary>
|
||||
/// The prefix of all diagnostics for available analyzers.
|
||||
/// </summary>
|
||||
private const string DiagnosticIdPrefix =
|
||||
#if WINDOWS_UWP
|
||||
"CMPSD2DUWP";
|
||||
#else
|
||||
"CMPSD2DWINUI";
|
||||
#endif
|
||||
|
||||
/// <summary>
|
||||
/// The category of all diagnostics for available analyzers.
|
||||
/// </summary>
|
||||
private const string DiagnosticCategory =
|
||||
#if WINDOWS_UWP
|
||||
"ComputeSharp.D2D1.Uwp.Effects";
|
||||
#else
|
||||
"ComputeSharp.D2D1.WinUI.Effects";
|
||||
#endif
|
||||
|
||||
/// <summary>
|
||||
/// The diagnostic id for <see cref="UseGeneratedCanvasEffectPropertyOnSemiAutoProperty"/>.
|
||||
/// </summary>
|
||||
public const string UseGeneratedCanvasEffectPropertyOnSemiAutoPropertyId = $"{DiagnosticIdPrefix}0008";
|
||||
|
||||
/// <summary>
|
||||
/// Gets a <see cref="DiagnosticDescriptor"/> for an invalid CanvasEffect property.
|
||||
/// <para>
|
||||
/// Format: <c>"The property "{0}" is not in a type that derives from CanvasEffect ([GeneratedCanvasEffectProperty] must be used in effect types that extend CanvasEffect)"</c>.
|
||||
/// </para>
|
||||
/// </summary>
|
||||
public static readonly DiagnosticDescriptor InvalidGeneratedCanvasEffectPropertyContainingType = new(
|
||||
id: $"{DiagnosticIdPrefix}0001",
|
||||
title: "Invalid generated CanvasEffect property containing type",
|
||||
messageFormat: """The property "{0}" is not in a type that derives from CanvasEffect ([GeneratedCanvasEffectProperty] must be used in effect types that extend CanvasEffect)""",
|
||||
category: DiagnosticCategory,
|
||||
defaultSeverity: DiagnosticSeverity.Error,
|
||||
isEnabledByDefault: true,
|
||||
description: "A property using [GeneratedCanvasEffectProperty] is in a type that does not derive from CanvasEffect ([GeneratedCanvasEffectProperty] must be used in effect types that extend CanvasEffect).",
|
||||
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
|
||||
|
||||
/// <summary>
|
||||
/// Gets a <see cref="DiagnosticDescriptor"/> for a CanvasEffect property with invalid accessors.
|
||||
/// <para>
|
||||
/// Format: <c>"The property "{0}" does not have a getter and a setter ([GeneratedCanvasEffectProperty] must be used on properties with get and set accessors)"</c>.
|
||||
/// </para>
|
||||
/// </summary>
|
||||
public static readonly DiagnosticDescriptor InvalidGeneratedCanvasEffectPropertyAccessors = new(
|
||||
id: $"{DiagnosticIdPrefix}0002",
|
||||
title: "Invalid generated CanvasEffect property accessors",
|
||||
messageFormat: """The property "{0}" does not have a getter and a setter ([GeneratedCanvasEffectProperty] must be used on properties with get and set accessors)""",
|
||||
category: DiagnosticCategory,
|
||||
defaultSeverity: DiagnosticSeverity.Error,
|
||||
isEnabledByDefault: true,
|
||||
description: "A property using [GeneratedCanvasEffectProperty] does not have a getter and a setter ([GeneratedCanvasEffectProperty] must be used on properties with get and set accessors).",
|
||||
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
|
||||
|
||||
/// <summary>
|
||||
/// Gets a <see cref="DiagnosticDescriptor"/> for a static CanvasEffect property.
|
||||
/// <para>
|
||||
/// Format: <c>"The property "{0}" is static ([GeneratedCanvasEffectProperty] must be used on instance properties)"</c>.
|
||||
/// </para>
|
||||
/// </summary>
|
||||
public static readonly DiagnosticDescriptor InvalidGeneratedCanvasEffectPropertyDeclarationIsStatic = new(
|
||||
id: $"{DiagnosticIdPrefix}0003",
|
||||
title: "Invalid generated CanvasEffect property declaration (static member)",
|
||||
messageFormat: """The property "{0}" is static ([GeneratedCanvasEffectProperty] must be used on instance properties)""",
|
||||
category: DiagnosticCategory,
|
||||
defaultSeverity: DiagnosticSeverity.Error,
|
||||
isEnabledByDefault: true,
|
||||
description: "A property using [GeneratedCanvasEffectProperty] cannot be static ([GeneratedCanvasEffectProperty] must be used on instance properties).",
|
||||
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
|
||||
|
||||
/// <summary>
|
||||
/// Gets a <see cref="DiagnosticDescriptor"/> for a CanvasEffect property that is not an incomplete partial property definition.
|
||||
/// <para>
|
||||
/// Format: <c>"The property "{0}" is not an incomplete partial definition ([GeneratedCanvasEffectProperty] must be used on partial property definitions with no implementation part)"</c>.
|
||||
/// </para>
|
||||
/// </summary>
|
||||
public static readonly DiagnosticDescriptor InvalidGeneratedCanvasEffectPropertyDeclarationIsNotIncompletePartialDefinition = new(
|
||||
id: $"{DiagnosticIdPrefix}0004",
|
||||
title: "Invalid generated CanvasEffect property declaration (not incomplete partial definition)",
|
||||
messageFormat: """The property "{0}" is not an incomplete partial definition ([GeneratedCanvasEffectProperty] must be used on partial property definitions with no implementation part)""",
|
||||
category: DiagnosticCategory,
|
||||
defaultSeverity: DiagnosticSeverity.Error,
|
||||
isEnabledByDefault: true,
|
||||
description: "A property using [GeneratedCanvasEffectProperty] is either not partial, or a partial implementation part ([GeneratedCanvasEffectProperty] must be used on partial property definitions with no implementation part).",
|
||||
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
|
||||
|
||||
/// <summary>
|
||||
/// Gets a <see cref="DiagnosticDescriptor"/> for a CanvasEffect property that returns a ref value.
|
||||
/// <para>
|
||||
/// Format: <c>"The property "{0}" returns a value by reference ([GeneratedCanvasEffectProperty] must be used on properties returning a type by value)"</c>.
|
||||
/// </para>
|
||||
/// </summary>
|
||||
public static readonly DiagnosticDescriptor InvalidGeneratedCanvasEffectPropertyDeclarationReturnsByRef = new(
|
||||
id: $"{DiagnosticIdPrefix}0005",
|
||||
title: "Invalid generated CanvasEffect property declaration (returns byref)",
|
||||
messageFormat: """The property "{0}" returns a value by reference ([GeneratedCanvasEffectProperty] must be used on properties returning a type by value)""",
|
||||
category: DiagnosticCategory,
|
||||
defaultSeverity: DiagnosticSeverity.Error,
|
||||
isEnabledByDefault: true,
|
||||
description: "A property using [GeneratedCanvasEffectProperty] returns a value by reference ([GeneratedCanvasEffectProperty] must be used on properties returning a type by value).",
|
||||
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
|
||||
|
||||
/// <summary>
|
||||
/// Gets a <see cref="DiagnosticDescriptor"/> for a CanvasEffect property that returns a byref-like value.
|
||||
/// <para>
|
||||
/// Format: <c>"The property "{0}" returns a ref struct value ([GeneratedCanvasEffectProperty] must be used on properties with a type that is not a ref struct)"</c>.
|
||||
/// </para>
|
||||
/// </summary>
|
||||
public static readonly DiagnosticDescriptor InvalidGeneratedCanvasEffectPropertyDeclarationReturnsRefLikeType = new(
|
||||
id: $"{DiagnosticIdPrefix}0006",
|
||||
title: "Invalid generated CanvasEffect property declaration (returns ref struct type)",
|
||||
messageFormat: """The property "{0}" returns a ref struct value ([GeneratedCanvasEffectProperty] must be used on properties with a type that is not a ref struct)""",
|
||||
category: DiagnosticCategory,
|
||||
defaultSeverity: DiagnosticSeverity.Error,
|
||||
isEnabledByDefault: true,
|
||||
description: "A property using [GeneratedCanvasEffectProperty] has a ref struct type ([GeneratedCanvasEffectProperty] must be used on properties with a type that is not a ref struct).",
|
||||
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
|
||||
|
||||
/// <summary>
|
||||
/// Gets a <see cref="DiagnosticDescriptor"/> for when C# is not set to 'preview'.
|
||||
/// <para>
|
||||
/// Format: <c>"Using [GeneratedCanvasEffectProperty] requires the C# language version to be set to 'preview', as support for the 'field' keyword is needed by the source generators to emit valid code (add <LangVersion>preview</LangVersion> to your .csproj/.props file)"</c>.
|
||||
/// </para>
|
||||
/// </summary>
|
||||
public static readonly DiagnosticDescriptor CSharpLanguageVersionIsNotPreview = new(
|
||||
id: $"{DiagnosticIdPrefix}0007",
|
||||
title: "C# language version is not 'preview'",
|
||||
messageFormat: """Using [GeneratedCanvasEffectProperty] requires the C# language version to be set to 'preview', as support for the 'field' keyword is needed by the source generators to emit valid code (add <LangVersion>preview</LangVersion> to your .csproj/.props file)""",
|
||||
category: DiagnosticCategory,
|
||||
defaultSeverity: DiagnosticSeverity.Error,
|
||||
isEnabledByDefault: true,
|
||||
description: "The C# language version must be set to 'preview' when using [GeneratedComputeShaderDescriptor] for the source generators to emit valid code (the <LangVersion>preview</LangVersion> option must be set in the .csproj/.props file).",
|
||||
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
|
||||
|
||||
/// <summary>
|
||||
/// Gets a <see cref="DiagnosticDescriptor"/> for when a semi-auto property can be converted to use <c>[GeneratedCanvasEffectProperty]</c> instead.
|
||||
/// <para>
|
||||
/// Format: <c>"The semi-auto property "{0}" can be converted to a partial property using [GeneratedCanvasEffectProperty], which is recommended (doing so makes the code less verbose and results in more optimized code)"</c>.
|
||||
/// </para>
|
||||
/// </summary>
|
||||
public static readonly DiagnosticDescriptor UseGeneratedCanvasEffectPropertyOnSemiAutoProperty = new(
|
||||
id: UseGeneratedCanvasEffectPropertyOnSemiAutoPropertyId,
|
||||
title: "Prefer using [GeneratedCanvasEffectProperty] over semi-auto properties",
|
||||
messageFormat: """The semi-auto property "{0}" can be converted to a partial property using [GeneratedCanvasEffectProperty], which is recommended (doing so makes the code less verbose and results in more optimized code)""",
|
||||
category: DiagnosticCategory,
|
||||
defaultSeverity: DiagnosticSeverity.Info,
|
||||
isEnabledByDefault: true,
|
||||
description: "Semi-auto properties should be converted to partial properties using [GeneratedCanvasEffectProperty] when possible, which is recommended (doing so makes the code less verbose and results in more optimized code).",
|
||||
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
using ComputeSharp.SourceGeneration.Models;
|
||||
using Microsoft.CodeAnalysis;
|
||||
|
||||
#if WINDOWS_UWP
|
||||
namespace ComputeSharp.D2D1.Uwp.SourceGenerators.Models;
|
||||
#else
|
||||
namespace ComputeSharp.D2D1.WinUI.SourceGenerators.Models;
|
||||
#endif
|
||||
|
||||
/// <summary>
|
||||
/// A model representing a generated canvas effect property.
|
||||
/// </summary>
|
||||
/// <param name="Hierarchy">The hierarchy info for the shader type.</param>
|
||||
/// <param name="PropertyName">The generated property name.</param>
|
||||
/// <param name="DeclaredAccessibility">The accessibility of the property, if available.</param>
|
||||
/// <param name="GetterAccessibility">The accessibility of the <see langword="get"/> accessor, if available.</param>
|
||||
/// <param name="SetterAccessibility">The accessibility of the <see langword="set"/> accessor, if available.</param>
|
||||
/// <param name="TypeNameWithNullabilityAnnotations">The type name for the generated property, including nullability annotations.</param>
|
||||
/// <param name="IsReferenceTypeOrUnconstraindTypeParameter">Indicates whether the property is of a reference type or an unconstrained type parameter.</param>
|
||||
/// <param name="IsRequired">Whether or not the generated property should be marked as required.</param>
|
||||
/// <param name="InvalidationType">The invalidation type to request.</param>
|
||||
internal sealed record CanvasEffectPropertyInfo(
|
||||
HierarchyInfo Hierarchy,
|
||||
string PropertyName,
|
||||
Accessibility DeclaredAccessibility,
|
||||
Accessibility GetterAccessibility,
|
||||
Accessibility SetterAccessibility,
|
||||
string TypeNameWithNullabilityAnnotations,
|
||||
bool IsReferenceTypeOrUnconstraindTypeParameter,
|
||||
bool IsRequired,
|
||||
CanvasEffectInvalidationType InvalidationType);
|
||||
@@ -1,43 +0,0 @@
|
||||
using System;
|
||||
using System.Runtime.CompilerServices;
|
||||
using ComputeSharp.Win32;
|
||||
|
||||
#pragma warning disable CS0649, IDE1006
|
||||
|
||||
namespace ABI.Microsoft.Graphics.Canvas;
|
||||
|
||||
/// <summary>
|
||||
/// The native WinRT interface for <see cref="global::Microsoft.Graphics.Canvas.CanvasDevice"/> objects.
|
||||
/// </summary>
|
||||
[NativeTypeName("class ICanvasDevice : IInspectable")]
|
||||
[NativeInheritance("IInspectable")]
|
||||
internal unsafe struct ICanvasDevice
|
||||
{
|
||||
public void** lpVtbl;
|
||||
|
||||
/// <inheritdoc cref="IUnknown.QueryInterface"/>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
[VtblIndex(0)]
|
||||
public HRESULT QueryInterface([NativeTypeName("const IID &")] Guid* riid, void** ppvObject)
|
||||
{
|
||||
return ((delegate* unmanaged[MemberFunction]<ICanvasDevice*, Guid*, void**, int>)this.lpVtbl[0])((ICanvasDevice*)Unsafe.AsPointer(ref this), riid, ppvObject);
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="IUnknown.AddRef"/>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
[VtblIndex(1)]
|
||||
[return: NativeTypeName("ULONG")]
|
||||
public uint AddRef()
|
||||
{
|
||||
return ((delegate* unmanaged[MemberFunction]<ICanvasDevice*, uint>)this.lpVtbl[1])((ICanvasDevice*)Unsafe.AsPointer(ref this));
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="IUnknown.Release"/>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
[VtblIndex(2)]
|
||||
[return: NativeTypeName("ULONG")]
|
||||
public uint Release()
|
||||
{
|
||||
return ((delegate* unmanaged[MemberFunction]<ICanvasDevice*, uint>)this.lpVtbl[2])((ICanvasDevice*)Unsafe.AsPointer(ref this));
|
||||
}
|
||||
}
|
||||
@@ -1,69 +0,0 @@
|
||||
using System;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
using ComputeSharp.Win32;
|
||||
|
||||
#pragma warning disable CS0649, IDE0055, IDE1006
|
||||
|
||||
namespace ABI.Microsoft.Graphics.Canvas.Effects;
|
||||
|
||||
/// <summary>
|
||||
/// The native WinRT interface for <see cref="global::Microsoft.Graphics.Canvas.Effects.ICanvasEffect"/> objects.
|
||||
/// </summary>
|
||||
[NativeTypeName("class ICanvasEffect : IInspectable")]
|
||||
[NativeInheritance("IInspectable")]
|
||||
internal unsafe struct ICanvasEffect : IComObject
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
static Guid* IComObject.IID
|
||||
{
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
get
|
||||
{
|
||||
ReadOnlySpan<byte> data =
|
||||
[
|
||||
0x8C, 0x6F, 0xF9, 0x0E,
|
||||
0x5E, 0x9B,
|
||||
0xF0, 0x4B,
|
||||
0x99,
|
||||
0xA3,
|
||||
0xAA,
|
||||
0xD8,
|
||||
0xCE,
|
||||
0x53,
|
||||
0xDB,
|
||||
0x55
|
||||
];
|
||||
|
||||
return (Guid*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(data));
|
||||
}
|
||||
}
|
||||
|
||||
public void** lpVtbl;
|
||||
|
||||
/// <inheritdoc cref="IUnknown.QueryInterface"/>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
[VtblIndex(0)]
|
||||
public HRESULT QueryInterface([NativeTypeName("const IID &")] Guid* riid, void** ppvObject)
|
||||
{
|
||||
return ((delegate* unmanaged[MemberFunction]<ICanvasEffect*, Guid*, void**, int>)this.lpVtbl[0])((ICanvasEffect*)Unsafe.AsPointer(ref this), riid, ppvObject);
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="IUnknown.AddRef"/>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
[VtblIndex(1)]
|
||||
[return: NativeTypeName("ULONG")]
|
||||
public uint AddRef()
|
||||
{
|
||||
return ((delegate* unmanaged[MemberFunction]<ICanvasEffect*, uint>)this.lpVtbl[1])((ICanvasEffect*)Unsafe.AsPointer(ref this));
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="IUnknown.Release"/>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
[VtblIndex(2)]
|
||||
[return: NativeTypeName("ULONG")]
|
||||
public uint Release()
|
||||
{
|
||||
return ((delegate* unmanaged[MemberFunction]<ICanvasEffect*, uint>)this.lpVtbl[2])((ICanvasEffect*)Unsafe.AsPointer(ref this));
|
||||
}
|
||||
}
|
||||
@@ -1,178 +0,0 @@
|
||||
using System;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
using ComputeSharp.Win32;
|
||||
using WinRT;
|
||||
using WinRT.Interop;
|
||||
using IInspectable = ComputeSharp.Win32.IInspectable;
|
||||
|
||||
#pragma warning disable CS0649, IDE0055, IDE1006
|
||||
|
||||
namespace ABI.Microsoft.Graphics.Canvas
|
||||
{
|
||||
/// <summary>
|
||||
/// The interop Win2D interface for factories of external effects.
|
||||
/// </summary>
|
||||
[NativeTypeName("class ICanvasEffectFactoryNative : IUnknown")]
|
||||
[NativeInheritance("IUnknown")]
|
||||
internal unsafe struct ICanvasEffectFactoryNative : IComObject
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
public static Guid* IID
|
||||
{
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
get
|
||||
{
|
||||
ReadOnlySpan<byte> data =
|
||||
[
|
||||
0x1F, 0x1A, 0xBA, 0x29,
|
||||
0xFE, 0x1C,
|
||||
0xC3, 0x44,
|
||||
0x98, 0x4D,
|
||||
0x42,
|
||||
0x6D,
|
||||
0x61,
|
||||
0xB5,
|
||||
0x14,
|
||||
0x27
|
||||
];
|
||||
|
||||
return (Guid*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(data));
|
||||
}
|
||||
}
|
||||
|
||||
public void** lpVtbl;
|
||||
|
||||
/// <inheritdoc cref="IUnknown.QueryInterface"/>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
[VtblIndex(0)]
|
||||
public HRESULT QueryInterface([NativeTypeName("const IID &")] Guid* riid, void** ppvObject)
|
||||
{
|
||||
return ((delegate* unmanaged[MemberFunction]<ICanvasEffectFactoryNative*, Guid*, void**, int>)this.lpVtbl[0])((ICanvasEffectFactoryNative*)Unsafe.AsPointer(ref this), riid, ppvObject);
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="IUnknown.AddRef"/>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
[VtblIndex(1)]
|
||||
[return: NativeTypeName("ULONG")]
|
||||
public uint AddRef()
|
||||
{
|
||||
return ((delegate* unmanaged[MemberFunction]<ICanvasEffectFactoryNative*, uint>)this.lpVtbl[1])((ICanvasEffectFactoryNative*)Unsafe.AsPointer(ref this));
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="IUnknown.Release"/>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
[VtblIndex(2)]
|
||||
[return: NativeTypeName("ULONG")]
|
||||
public uint Release()
|
||||
{
|
||||
return ((delegate* unmanaged[MemberFunction]<ICanvasEffectFactoryNative*, uint>)this.lpVtbl[2])((ICanvasEffectFactoryNative*)Unsafe.AsPointer(ref this));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new inspectable wrapper for an input D2D effect previosly registered through <see cref="ICanvasFactoryNative.RegisterEffectFactory"/>.
|
||||
/// </summary>
|
||||
/// <param name="device">The input canvas device.</param>
|
||||
/// <param name="resource">The input native effect to create a wrapper for.</param>
|
||||
/// <param name="dpi">The realization DPIs for <paramref name="resource"/>.</param>
|
||||
/// <param name="wrapper">The resulting wrapper for <paramref name="resource"/>.</param>
|
||||
/// <returns>The <see cref="HRESULT"/> for the operation.</returns>
|
||||
/// <remarks>
|
||||
/// All parameters are directly forwarded from the ones the caller passed to <see cref="ICanvasFactoryNative.GetOrCreate"/>. The returned
|
||||
/// wrapper should implement <see cref="global::Microsoft.Graphics.Canvas.ICanvasImage"/> to be returned correctly from Win2D after this call.
|
||||
/// </remarks>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
[VtblIndex(3)]
|
||||
public HRESULT CreateWrapper(ICanvasDevice* device, ID2D1Effect* resource, float dpi, IInspectable** wrapper)
|
||||
{
|
||||
return ((delegate* unmanaged[MemberFunction]<ICanvasEffectFactoryNative*, ICanvasDevice*, ID2D1Effect*, float, IInspectable**, int>)this.lpVtbl[3])(
|
||||
(ICanvasEffectFactoryNative*)Unsafe.AsPointer(ref this),
|
||||
device,
|
||||
resource,
|
||||
dpi,
|
||||
wrapper);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The ABI methods for <see cref="ICanvasEffectFactoryNative"/>.
|
||||
/// </summary>
|
||||
internal static unsafe class ICanvasEffectFactoryNativeMethods
|
||||
{
|
||||
/// <inheritdoc cref="ICanvasEffectFactoryNative.IID"/>
|
||||
public static Guid IID => *ICanvasEffectFactoryNative.IID;
|
||||
|
||||
/// <inheritdoc cref="global::Microsoft.Graphics.Canvas.ICanvasEffectFactoryNative.Vftbl.AbiToProjectionVftablePtr"/>
|
||||
public static IntPtr AbiToProjectionVftablePtr => global::Microsoft.Graphics.Canvas.ICanvasEffectFactoryNative.Vftbl.AbiToProjectionVftablePtr;
|
||||
}
|
||||
}
|
||||
|
||||
namespace Microsoft.Graphics.Canvas
|
||||
{
|
||||
using ABI.Microsoft.Graphics.Canvas;
|
||||
|
||||
/// <summary>
|
||||
/// The managed implementation of <see cref="ABI.Microsoft.Graphics.Canvas.ICanvasEffectFactoryNative"/>.
|
||||
/// </summary>
|
||||
[Guid("29BA1A1F-1CFE-44C3-984D-426D61B51427")]
|
||||
[WindowsRuntimeType]
|
||||
[WindowsRuntimeHelperType(typeof(ICanvasEffectFactoryNative))]
|
||||
internal unsafe interface ICanvasEffectFactoryNative
|
||||
{
|
||||
/// <inheritdoc cref="ABI.Microsoft.Graphics.Canvas.ICanvasEffectFactoryNative.CreateWrapper"/>
|
||||
[return: NativeTypeName("HRESULT")]
|
||||
int CreateWrapper(ICanvasDevice* device, ID2D1Effect* resource, float dpi, IInspectable** wrapper);
|
||||
|
||||
/// <summary>
|
||||
/// The vtable type for <see cref="ICanvasEffectFactoryNative"/>.
|
||||
/// </summary>
|
||||
public struct Vftbl
|
||||
{
|
||||
/// <summary>
|
||||
/// Allows CsWinRT to retrieve a pointer to the projection vtable (the name is hardcoded by convention).
|
||||
/// </summary>
|
||||
public static readonly IntPtr AbiToProjectionVftablePtr = InitVtbl();
|
||||
|
||||
/// <summary>
|
||||
/// Builds the custom method table pointer for <see cref="ICanvasEffectFactoryNative"/>.
|
||||
/// </summary>
|
||||
/// <returns>The method table pointer for <see cref="ICanvasEffectFactoryNative"/>.</returns>
|
||||
private static IntPtr InitVtbl()
|
||||
{
|
||||
Vftbl* lpVtbl = (Vftbl*)ComWrappersSupport.AllocateVtableMemory(typeof(Vftbl), sizeof(Vftbl));
|
||||
|
||||
lpVtbl->IUnknownVftbl = IUnknownVftbl.AbiToProjectionVftbl;
|
||||
lpVtbl->CreateWrapper = &CreateWrapperFromAbi;
|
||||
|
||||
return (IntPtr)lpVtbl;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The IUnknown vtable.
|
||||
/// </summary>
|
||||
private IUnknownVftbl IUnknownVftbl;
|
||||
|
||||
/// <summary>
|
||||
/// Function pointer for <see cref="CreateWrapperFromAbi"/>.
|
||||
/// </summary>
|
||||
private delegate* unmanaged[MemberFunction]<IntPtr, ICanvasDevice*, ID2D1Effect*, float, IInspectable**, int> CreateWrapper;
|
||||
|
||||
/// <inheritdoc cref="ICanvasEffectFactoryNative.CreateWrapper"/>
|
||||
[UnmanagedCallersOnly(CallConvs = [typeof(CallConvMemberFunction)])]
|
||||
[return: NativeTypeName("HRESULT")]
|
||||
private static int CreateWrapperFromAbi(IntPtr thisPtr, ICanvasDevice* device, ID2D1Effect* resource, float dpi, IInspectable** wrapper)
|
||||
{
|
||||
try
|
||||
{
|
||||
return ComWrappersSupport.FindObject<ICanvasEffectFactoryNative>(thisPtr).CreateWrapper(device, resource, dpi, wrapper);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
ExceptionHelpers.SetErrorInfo(e);
|
||||
|
||||
return ExceptionHelpers.GetHRForException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,168 +0,0 @@
|
||||
using System;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
using ComputeSharp.Win32;
|
||||
|
||||
#pragma warning disable CS0649, IDE0055, IDE1006
|
||||
|
||||
namespace ABI.Microsoft.Graphics.Canvas;
|
||||
|
||||
/// <summary>
|
||||
/// The activation factory for <see cref="global::Microsoft.Graphics.Canvas.CanvasDevice"/>.
|
||||
/// </summary>
|
||||
[NativeTypeName("class ICanvasFactoryNative : public IInspectable")]
|
||||
[NativeInheritance("IInspectable")]
|
||||
internal unsafe struct ICanvasFactoryNative : IComObject
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
public static Guid* IID
|
||||
{
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
get
|
||||
{
|
||||
ReadOnlySpan<byte> data =
|
||||
[
|
||||
0x0D, 0x44, 0x5C, 0x69,
|
||||
0xB3, 0x04,
|
||||
0xDD, 0x4E,
|
||||
0xBF, 0xD9,
|
||||
0x63,
|
||||
0xE5,
|
||||
0x1E,
|
||||
0x9F,
|
||||
0x72,
|
||||
0x02
|
||||
];
|
||||
|
||||
return (Guid*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(data));
|
||||
}
|
||||
}
|
||||
|
||||
public void** lpVtbl;
|
||||
|
||||
/// <inheritdoc cref="IUnknown.QueryInterface"/>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
[VtblIndex(0)]
|
||||
public HRESULT QueryInterface([NativeTypeName("const IID &")] Guid* riid, void** ppvObject)
|
||||
{
|
||||
return ((delegate* unmanaged[MemberFunction]<ICanvasFactoryNative*, Guid*, void**, int>)this.lpVtbl[0])((ICanvasFactoryNative*)Unsafe.AsPointer(ref this), riid, ppvObject);
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="IUnknown.AddRef"/>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
[VtblIndex(1)]
|
||||
[return: NativeTypeName("ULONG")]
|
||||
public uint AddRef()
|
||||
{
|
||||
return ((delegate* unmanaged[MemberFunction]<ICanvasFactoryNative*, uint>)this.lpVtbl[1])((ICanvasFactoryNative*)Unsafe.AsPointer(ref this));
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="IUnknown.Release"/>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
[VtblIndex(2)]
|
||||
[return: NativeTypeName("ULONG")]
|
||||
public uint Release()
|
||||
{
|
||||
return ((delegate* unmanaged[MemberFunction]<ICanvasFactoryNative*, uint>)this.lpVtbl[2])((ICanvasFactoryNative*)Unsafe.AsPointer(ref this));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets or creates an <c>IInspectable</c> Win2D wrapper for a given native D2D resource.
|
||||
/// </summary>
|
||||
/// <param name="device">The input canvas device (as a marshalled <see cref="global::Microsoft.Graphics.Canvas.CanvasDevice"/>).</param>
|
||||
/// <param name="resource">The input native resource to create a wrapper for.</param>
|
||||
/// <param name="dpi">The realization DPIs for <paramref name="resource"/>.</param>
|
||||
/// <param name="wrapper">The resulting wrapper for <paramref name="resource"/>.</param>
|
||||
/// <returns>The <see cref="HRESULT"/> for the operation.</returns>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
[VtblIndex(6)]
|
||||
public HRESULT GetOrCreate(ICanvasDevice* device, IUnknown* resource, float dpi, IInspectable** wrapper)
|
||||
{
|
||||
return ((delegate* unmanaged[MemberFunction]<ICanvasFactoryNative*, ICanvasDevice*, IUnknown*, float, IInspectable**, int>)this.lpVtbl[6])(
|
||||
(ICanvasFactoryNative*)Unsafe.AsPointer(ref this),
|
||||
device,
|
||||
resource,
|
||||
dpi,
|
||||
wrapper);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registers an <c>IInspectable</c> wrapper for a given native D2D resource.
|
||||
/// </summary>
|
||||
/// <param name="resource">The input native resource to register a wrapper for.</param>
|
||||
/// <param name="wrapper">The wrapper to register for <paramref name="resource"/>.</param>
|
||||
/// <returns>
|
||||
/// The <see cref="HRESULT"/> for the operation. In case of success, it will be <see cref="S.S_OK"/> if the wrapper
|
||||
/// was not previously registered, or <see cref="S.S_FALSE"/> if <paramref name="resource"/> was already registered.
|
||||
/// </returns>
|
||||
/// <remarks>
|
||||
/// The method validates at runtime that <paramref name="resource"/> is an <see cref="ID2D1Image"/>
|
||||
/// and that <paramref name="wrapper"/> is an <see cref="global::Microsoft.Graphics.Canvas.ICanvasImage"/>. Additionally,
|
||||
/// <paramref name="wrapper"/> has to implement <c>IWeakReferenceSource</c> for this method to be successful.
|
||||
/// </remarks>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
[VtblIndex(7)]
|
||||
public HRESULT RegisterWrapper(IUnknown* resource, IInspectable* wrapper)
|
||||
{
|
||||
return ((delegate* unmanaged[MemberFunction]<ICanvasFactoryNative*, IUnknown*, IInspectable*, int>)this.lpVtbl[7])(
|
||||
(ICanvasFactoryNative*)Unsafe.AsPointer(ref this),
|
||||
resource,
|
||||
wrapper);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Unregisters a native D2D resource previously registered with <see cref="RegisterWrapper"/>.
|
||||
/// </summary>
|
||||
/// <param name="resource">The input native resource to unregister.</param>
|
||||
/// <returns>
|
||||
/// The <see cref="HRESULT"/> for the operation. In case of success, it will be <see cref="S.S_OK"/> if the
|
||||
/// resource was previously registered and could be correctly unregistered, <see cref="S.S_FALSE"/> otherwise.
|
||||
/// </returns>
|
||||
/// <remarks>
|
||||
/// The method validates at runtime that <paramref name="resource"/> is an <see cref="ID2D1Image"/>.
|
||||
/// </remarks>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
[VtblIndex(8)]
|
||||
public HRESULT UnregisterWrapper(IUnknown* resource)
|
||||
{
|
||||
return ((delegate* unmanaged[MemberFunction]<ICanvasFactoryNative*, IUnknown*, int>)this.lpVtbl[8])(
|
||||
(ICanvasFactoryNative*)Unsafe.AsPointer(ref this),
|
||||
resource);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registers a factory of wrappers for custom effects.
|
||||
/// </summary>
|
||||
/// <param name="effectId">The id of the effects to register a factory for.</param>
|
||||
/// <param name="factory">The input factory to create wrappers of native effects.</param>
|
||||
/// <returns>
|
||||
/// The <see cref="HRESULT"/> for the operation. In case of success, it will be <see cref="S.S_OK"/> if the factory
|
||||
/// was not previously registered, or <see cref="S.S_FALSE"/> if <paramref name="effectId"/> was already registered.
|
||||
/// </returns>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
[VtblIndex(9)]
|
||||
public HRESULT RegisterEffectFactory([NativeTypeName("const IID &")] Guid* effectId, ICanvasEffectFactoryNative* factory)
|
||||
{
|
||||
return ((delegate* unmanaged[MemberFunction]<ICanvasFactoryNative*, Guid*, ICanvasEffectFactoryNative*, int>)this.lpVtbl[9])(
|
||||
(ICanvasFactoryNative*)Unsafe.AsPointer(ref this),
|
||||
effectId,
|
||||
factory);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Unregisters an effect factory that was previosuly registered with <see cref="RegisterEffectFactory"/>.
|
||||
/// </summary>
|
||||
/// <param name="effectId">The id of the effects to unregister the factory for.</param>
|
||||
/// <returns>
|
||||
/// The <see cref="HRESULT"/> for the operation. In case of success, it will be <see cref="S.S_OK"/> if the
|
||||
/// factory was previously registered and could be correctly unregistered, <see cref="S.S_FALSE"/> otherwise.
|
||||
/// </returns>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
[VtblIndex(10)]
|
||||
public HRESULT UnregisterEffectFactory([NativeTypeName("const IID &")] Guid* effectId)
|
||||
{
|
||||
return ((delegate* unmanaged[MemberFunction]<ICanvasFactoryNative*, Guid*, int>)this.lpVtbl[10])(
|
||||
(ICanvasFactoryNative*)Unsafe.AsPointer(ref this),
|
||||
effectId);
|
||||
}
|
||||
}
|
||||
@@ -1,233 +0,0 @@
|
||||
using System;
|
||||
using System.ComponentModel;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
using ComputeSharp.Win32;
|
||||
using WinRT;
|
||||
using WinRT.Interop;
|
||||
|
||||
#pragma warning disable CS0649, IDE0055, IDE1006
|
||||
|
||||
namespace ABI.Microsoft.Graphics.Canvas
|
||||
{
|
||||
/// <summary>
|
||||
/// An interop Win2D interface for all images and effects that can be drawn.
|
||||
/// </summary>
|
||||
[NativeTypeName("class ICanvasImageInterop : IUnknown")]
|
||||
[NativeInheritance("IUnknown")]
|
||||
internal unsafe struct ICanvasImageInterop : IComObject
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
public static Guid* IID
|
||||
{
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
get
|
||||
{
|
||||
ReadOnlySpan<byte> data =
|
||||
[
|
||||
0xF7, 0xD1, 0x42, 0xE0,
|
||||
0xAD, 0xF9,
|
||||
0x79, 0x44,
|
||||
0xA7, 0x13,
|
||||
0x67,
|
||||
0x62,
|
||||
0x7E,
|
||||
0xA3,
|
||||
0x18,
|
||||
0x63
|
||||
];
|
||||
|
||||
return (Guid*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(data));
|
||||
}
|
||||
}
|
||||
|
||||
public void** lpVtbl;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the device that the effect is currently realized on, if any.
|
||||
/// </summary>
|
||||
/// <param name="device">The resulting device, if available (as a marshalled <see cref="global::Microsoft.Graphics.Canvas.CanvasDevice"/>).</param>
|
||||
/// <param name="type">The <see cref="WIN2D_GET_DEVICE_ASSOCIATION_TYPE"/> value describing the returned instance.</param>
|
||||
/// <returns>The <see cref="HRESULT"/> for the operation.</returns>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
[VtblIndex(3)]
|
||||
public HRESULT GetDevice(ICanvasDevice** device, WIN2D_GET_DEVICE_ASSOCIATION_TYPE* type)
|
||||
{
|
||||
return ((delegate* unmanaged[MemberFunction]<ICanvasImageInterop*, ICanvasDevice**, WIN2D_GET_DEVICE_ASSOCIATION_TYPE*, int>)this.lpVtbl[3])((ICanvasImageInterop*)Unsafe.AsPointer(ref this), device, type);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets an <see cref="ID2D1Image"/> from an <see cref="ICanvasImageInterop"/> instance.
|
||||
/// </summary>
|
||||
/// <param name="device">The input canvas device (as a marshalled <see cref="global::Microsoft.Graphics.Canvas.CanvasDevice"/>).</param>
|
||||
/// <param name="deviceContext">
|
||||
/// The device context in use. This value is is optional (but recommended), except when the
|
||||
/// <see cref="WIN2D_GET_D2D_IMAGE_FLAGS.WIN2D_GET_D2D_IMAGE_FLAGS_READ_DPI_FROM_DEVICE_CONTEXT"/> flag is specified. This is because
|
||||
/// not all callers of <see cref="GetD2DImage"/> have easy access to a context. It is always
|
||||
/// possible to get a resource creation context from the device, but the context is only
|
||||
/// actually necessary if a new effect realization needs to be created, so it is more efficient
|
||||
/// to have the implementation do this lookup only if/when it turns out to be needed.
|
||||
/// </param>
|
||||
/// <param name="flags">The flags to use to get the image.</param>
|
||||
/// <param name="targetDpi">
|
||||
/// The DPI of the target device context. This is used to determine when a <c>D2D1DpiCompensation</c>
|
||||
/// effect needs to be inserted. Behavior of this parameter can be overridden by the flag values
|
||||
/// <see cref="WIN2D_GET_D2D_IMAGE_FLAGS.WIN2D_GET_D2D_IMAGE_FLAGS_READ_DPI_FROM_DEVICE_CONTEXT"/>,
|
||||
/// <see cref="WIN2D_GET_D2D_IMAGE_FLAGS.WIN2D_GET_D2D_IMAGE_FLAGS_ALWAYS_INSERT_DPI_COMPENSATION"/>
|
||||
/// or <see cref="WIN2D_GET_D2D_IMAGE_FLAGS.WIN2D_GET_D2D_IMAGE_FLAGS_NEVER_INSERT_DPI_COMPENSATION"/>
|
||||
/// </param>
|
||||
/// <param name="realizeDpi">
|
||||
/// The DPI of a source bitmap, or zero if the image does not have a fixed DPI. A <c>D2D1DpiCompensation</c> effect
|
||||
/// will be inserted if <paramref name="targetDpi"/> and <paramref name="realizeDpi"/> are different (flags permitting).
|
||||
/// </param>
|
||||
/// <param name="ppImage">The resulting <see cref="ID2D1Image"/> for the effect.</param>
|
||||
/// <returns>The <see cref="HRESULT"/> for the operation.</returns>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
[VtblIndex(4)]
|
||||
public HRESULT GetD2DImage(
|
||||
ICanvasDevice* device,
|
||||
ID2D1DeviceContext* deviceContext,
|
||||
WIN2D_GET_D2D_IMAGE_FLAGS flags,
|
||||
float targetDpi,
|
||||
float* realizeDpi,
|
||||
ID2D1Image** ppImage)
|
||||
{
|
||||
return ((delegate* unmanaged[MemberFunction]<ICanvasImageInterop*, ICanvasDevice*, ID2D1DeviceContext*, WIN2D_GET_D2D_IMAGE_FLAGS, float, float*, ID2D1Image**, int>)this.lpVtbl[4])(
|
||||
(ICanvasImageInterop*)Unsafe.AsPointer(ref this),
|
||||
device,
|
||||
deviceContext,
|
||||
flags,
|
||||
targetDpi,
|
||||
realizeDpi,
|
||||
ppImage);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The ABI methods for <see cref="ICanvasImageInterop"/>.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// This type has public accessibility to allow the AOT generator in CsWinRT to reference
|
||||
/// the <see cref="IID"/> and <see cref="AbiToProjectionVftablePtr"/> properties to make
|
||||
/// marshalling of CCW types AOT-safe. It is not meant to be used directly by developers.
|
||||
/// </remarks>
|
||||
[EditorBrowsable(EditorBrowsableState.Never)]
|
||||
public static unsafe class ICanvasImageInteropMethods
|
||||
{
|
||||
/// <inheritdoc cref="ICanvasImageInterop.IID"/>
|
||||
public static Guid IID => *ICanvasImageInterop.IID;
|
||||
|
||||
/// <inheritdoc cref="global::Microsoft.Graphics.Canvas.ICanvasImageInterop.Vftbl.AbiToProjectionVftablePtr"/>
|
||||
public static IntPtr AbiToProjectionVftablePtr => global::Microsoft.Graphics.Canvas.ICanvasImageInterop.Vftbl.AbiToProjectionVftablePtr;
|
||||
}
|
||||
}
|
||||
|
||||
namespace Microsoft.Graphics.Canvas
|
||||
{
|
||||
using ABI.Microsoft.Graphics.Canvas;
|
||||
|
||||
/// <summary>
|
||||
/// The managed implementation of <see cref="ABI.Microsoft.Graphics.Canvas.ICanvasImageInterop"/>.
|
||||
/// </summary>
|
||||
[Guid("E042D1F7-F9AD-4479-A713-67627EA31863")]
|
||||
[WindowsRuntimeType]
|
||||
[WindowsRuntimeHelperType(typeof(ICanvasImageInterop))]
|
||||
internal unsafe interface ICanvasImageInterop
|
||||
{
|
||||
/// <inheritdoc cref="ABI.Microsoft.Graphics.Canvas.ICanvasImageInterop.GetDevice"/>
|
||||
[return: NativeTypeName("HRESULT")]
|
||||
int GetDevice(ICanvasDevice** device, WIN2D_GET_DEVICE_ASSOCIATION_TYPE* type);
|
||||
|
||||
/// <inheritdoc cref="ABI.Microsoft.Graphics.Canvas.ICanvasImageInterop.GetD2DImage"/>
|
||||
[return: NativeTypeName("HRESULT")]
|
||||
int GetD2DImage(
|
||||
ICanvasDevice* device,
|
||||
ID2D1DeviceContext* deviceContext,
|
||||
WIN2D_GET_D2D_IMAGE_FLAGS flags,
|
||||
float targetDpi,
|
||||
float* realizeDpi,
|
||||
ID2D1Image** ppImage);
|
||||
|
||||
/// <summary>
|
||||
/// The vtable type for <see cref="ICanvasImageInterop"/>.
|
||||
/// </summary>
|
||||
public struct Vftbl
|
||||
{
|
||||
/// <summary>
|
||||
/// Allows CsWinRT to retrieve a pointer to the projection vtable (the name is hardcoded by convention).
|
||||
/// </summary>
|
||||
public static readonly IntPtr AbiToProjectionVftablePtr = InitVtbl();
|
||||
|
||||
/// <summary>
|
||||
/// Builds the custom method table pointer for <see cref="ICanvasImageInterop"/>.
|
||||
/// </summary>
|
||||
/// <returns>The method table pointer for <see cref="ICanvasImageInterop"/>.</returns>
|
||||
private static IntPtr InitVtbl()
|
||||
{
|
||||
Vftbl* lpVtbl = (Vftbl*)ComWrappersSupport.AllocateVtableMemory(typeof(Vftbl), sizeof(Vftbl));
|
||||
|
||||
lpVtbl->IUnknownVftbl = IUnknownVftbl.AbiToProjectionVftbl;
|
||||
lpVtbl->GetDevice = &GetDeviceFromAbi;
|
||||
lpVtbl->GetD2DImage = &GetD2DImageFromAbi;
|
||||
|
||||
return (IntPtr)lpVtbl;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The IUnknown vtable.
|
||||
/// </summary>
|
||||
private IUnknownVftbl IUnknownVftbl;
|
||||
|
||||
/// <summary>
|
||||
/// Function pointer for <see cref="GetDeviceFromAbi"/>.
|
||||
/// </summary>
|
||||
private delegate* unmanaged[MemberFunction]<IntPtr, ICanvasDevice**, WIN2D_GET_DEVICE_ASSOCIATION_TYPE*, int> GetDevice;
|
||||
|
||||
/// <summary>
|
||||
/// Function pointer for <see cref="GetD2DImageFromAbi"/>.
|
||||
/// </summary>
|
||||
private delegate* unmanaged[MemberFunction]<IntPtr, ICanvasDevice*, ID2D1DeviceContext*, WIN2D_GET_D2D_IMAGE_FLAGS, float, float*, ID2D1Image**, int> GetD2DImage;
|
||||
|
||||
/// <inheritdoc cref="ICanvasImageInterop.GetDevice"/>
|
||||
[UnmanagedCallersOnly(CallConvs = [typeof(CallConvMemberFunction)])]
|
||||
[return: NativeTypeName("HRESULT")]
|
||||
private static int GetDeviceFromAbi(IntPtr thisPtr, ICanvasDevice** device, WIN2D_GET_DEVICE_ASSOCIATION_TYPE* type)
|
||||
{
|
||||
try
|
||||
{
|
||||
return ComWrappersSupport.FindObject<ICanvasImageInterop>(thisPtr).GetDevice(device, type);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
ExceptionHelpers.SetErrorInfo(e);
|
||||
|
||||
return ExceptionHelpers.GetHRForException(e);
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="ICanvasImageInterop.GetDevice"/>
|
||||
[UnmanagedCallersOnly(CallConvs = [typeof(CallConvMemberFunction)])]
|
||||
[return: NativeTypeName("HRESULT")]
|
||||
private static int GetD2DImageFromAbi(
|
||||
IntPtr thisPtr,
|
||||
ICanvasDevice* device,
|
||||
ID2D1DeviceContext* deviceContext,
|
||||
WIN2D_GET_D2D_IMAGE_FLAGS flags,
|
||||
float targetDpi,
|
||||
float* realizeDpi,
|
||||
ID2D1Image** ppImage)
|
||||
{
|
||||
try
|
||||
{
|
||||
return ComWrappersSupport.FindObject<ICanvasImageInterop>(thisPtr).GetD2DImage(device, deviceContext, flags, targetDpi, realizeDpi, ppImage);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
ExceptionHelpers.SetErrorInfo(e);
|
||||
|
||||
return ExceptionHelpers.GetHRForException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,69 +0,0 @@
|
||||
using System;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
using ComputeSharp.Win32;
|
||||
|
||||
#pragma warning disable CS0649, IDE0055, IDE1006
|
||||
|
||||
namespace ABI.Microsoft.Graphics.Canvas;
|
||||
|
||||
/// <summary>
|
||||
/// The native WinRT interface for <see cref="global::Microsoft.Graphics.Canvas.ICanvasResourceCreator"/> objects.
|
||||
/// </summary>
|
||||
[NativeTypeName("class ICanvasResourceCreator : IInspectable")]
|
||||
[NativeInheritance("IInspectable")]
|
||||
internal unsafe struct ICanvasResourceCreator : IComObject
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
static Guid* IComObject.IID
|
||||
{
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
get
|
||||
{
|
||||
ReadOnlySpan<byte> data =
|
||||
[
|
||||
0xA8, 0x8A, 0x6D, 0x8F,
|
||||
0x2F, 0x49,
|
||||
0xC6, 0x4B,
|
||||
0xB3,
|
||||
0xD0,
|
||||
0xE7,
|
||||
0xF5,
|
||||
0xEA,
|
||||
0xE8,
|
||||
0x4B,
|
||||
0x11
|
||||
];
|
||||
|
||||
return (Guid*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(data));
|
||||
}
|
||||
}
|
||||
|
||||
public void** lpVtbl;
|
||||
|
||||
/// <inheritdoc cref="IUnknown.QueryInterface"/>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
[VtblIndex(0)]
|
||||
public HRESULT QueryInterface([NativeTypeName("const IID &")] Guid* riid, void** ppvObject)
|
||||
{
|
||||
return ((delegate* unmanaged[MemberFunction]<ICanvasResourceCreator*, Guid*, void**, int>)this.lpVtbl[0])((ICanvasResourceCreator*)Unsafe.AsPointer(ref this), riid, ppvObject);
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="IUnknown.AddRef"/>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
[VtblIndex(1)]
|
||||
[return: NativeTypeName("ULONG")]
|
||||
public uint AddRef()
|
||||
{
|
||||
return ((delegate* unmanaged[MemberFunction]<ICanvasResourceCreator*, uint>)this.lpVtbl[1])((ICanvasResourceCreator*)Unsafe.AsPointer(ref this));
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="IUnknown.Release"/>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
[VtblIndex(2)]
|
||||
[return: NativeTypeName("ULONG")]
|
||||
public uint Release()
|
||||
{
|
||||
return ((delegate* unmanaged[MemberFunction]<ICanvasResourceCreator*, uint>)this.lpVtbl[2])((ICanvasResourceCreator*)Unsafe.AsPointer(ref this));
|
||||
}
|
||||
}
|
||||
@@ -1,69 +0,0 @@
|
||||
using System;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
using ComputeSharp.Win32;
|
||||
|
||||
#pragma warning disable CS0649, IDE0055, IDE1006
|
||||
|
||||
namespace ABI.Microsoft.Graphics.Canvas;
|
||||
|
||||
/// <summary>
|
||||
/// The native WinRT interface for <see cref="global::Microsoft.Graphics.Canvas.ICanvasResourceCreatorWithDpi"/> objects.
|
||||
/// </summary>
|
||||
[NativeTypeName("class ICanvasResourceCreatorWithDpi : IInspectable")]
|
||||
[NativeInheritance("IInspectable")]
|
||||
internal unsafe struct ICanvasResourceCreatorWithDpi : IComObject
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
static Guid* IComObject.IID
|
||||
{
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
get
|
||||
{
|
||||
ReadOnlySpan<byte> data =
|
||||
[
|
||||
0x12, 0xB5, 0x75, 0x1A,
|
||||
0xFA, 0xE9,
|
||||
0xE6, 0x49,
|
||||
0xA8,
|
||||
0x76,
|
||||
0x38,
|
||||
0xCA,
|
||||
0xE1,
|
||||
0x94,
|
||||
0x01,
|
||||
0x3E
|
||||
];
|
||||
|
||||
return (Guid*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(data));
|
||||
}
|
||||
}
|
||||
|
||||
public void** lpVtbl;
|
||||
|
||||
/// <inheritdoc cref="IUnknown.QueryInterface"/>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
[VtblIndex(0)]
|
||||
public HRESULT QueryInterface([NativeTypeName("const IID &")] Guid* riid, void** ppvObject)
|
||||
{
|
||||
return ((delegate* unmanaged[MemberFunction]<ICanvasResourceCreatorWithDpi*, Guid*, void**, int>)this.lpVtbl[0])((ICanvasResourceCreatorWithDpi*)Unsafe.AsPointer(ref this), riid, ppvObject);
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="IUnknown.AddRef"/>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
[VtblIndex(1)]
|
||||
[return: NativeTypeName("ULONG")]
|
||||
public uint AddRef()
|
||||
{
|
||||
return ((delegate* unmanaged[MemberFunction]<ICanvasResourceCreatorWithDpi*, uint>)this.lpVtbl[1])((ICanvasResourceCreatorWithDpi*)Unsafe.AsPointer(ref this));
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="IUnknown.Release"/>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
[VtblIndex(2)]
|
||||
[return: NativeTypeName("ULONG")]
|
||||
public uint Release()
|
||||
{
|
||||
return ((delegate* unmanaged[MemberFunction]<ICanvasResourceCreatorWithDpi*, uint>)this.lpVtbl[2])((ICanvasResourceCreatorWithDpi*)Unsafe.AsPointer(ref this));
|
||||
}
|
||||
}
|
||||
@@ -1,79 +0,0 @@
|
||||
using System;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
using ComputeSharp.Win32;
|
||||
|
||||
#pragma warning disable CS0649, IDE0055, IDE1006
|
||||
|
||||
namespace ABI.Microsoft.Graphics.Canvas;
|
||||
|
||||
/// <summary>
|
||||
/// An interop wrapper type for Win2D objects (see <see href="https://microsoft.github.io/Win2D/WinUI3/html/Interop.htm"/>).
|
||||
/// </summary>
|
||||
[NativeTypeName("class ICanvasResourceWrapperNative : IUnknown")]
|
||||
[NativeInheritance("IUnknown")]
|
||||
internal unsafe struct ICanvasResourceWrapperNative : IComObject
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
static Guid* IComObject.IID
|
||||
{
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
get
|
||||
{
|
||||
ReadOnlySpan<byte> data =
|
||||
[
|
||||
0x8D, 0x68, 0x10, 0x5F,
|
||||
0x55, 0xEA,
|
||||
0x55, 0x4D,
|
||||
0xA3,
|
||||
0xB0,
|
||||
0x4D,
|
||||
0xDB,
|
||||
0x55,
|
||||
0xC0,
|
||||
0xC2,
|
||||
0x0A
|
||||
];
|
||||
|
||||
return (Guid*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(data));
|
||||
}
|
||||
}
|
||||
|
||||
public void** lpVtbl;
|
||||
|
||||
/// <inheritdoc cref="IUnknown.QueryInterface"/>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
[VtblIndex(0)]
|
||||
public HRESULT QueryInterface([NativeTypeName("const IID &")] Guid* riid, void** ppvObject)
|
||||
{
|
||||
return ((delegate* unmanaged[MemberFunction]<ICanvasResourceWrapperNative*, Guid*, void**, int>)this.lpVtbl[0])((ICanvasResourceWrapperNative*)Unsafe.AsPointer(ref this), riid, ppvObject);
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="IUnknown.AddRef"/>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
[VtblIndex(1)]
|
||||
[return: NativeTypeName("ULONG")]
|
||||
public uint AddRef()
|
||||
{
|
||||
return ((delegate* unmanaged[MemberFunction]<ICanvasResourceWrapperNative*, uint>)this.lpVtbl[1])((ICanvasResourceWrapperNative*)Unsafe.AsPointer(ref this));
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="IUnknown.Release"/>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
[VtblIndex(2)]
|
||||
[return: NativeTypeName("ULONG")]
|
||||
public uint Release()
|
||||
{
|
||||
return ((delegate* unmanaged[MemberFunction]<ICanvasResourceWrapperNative*, uint>)this.lpVtbl[2])((ICanvasResourceWrapperNative*)Unsafe.AsPointer(ref this));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Interface provided by various Win2D objects that is able to retrieve the wrapped resource.
|
||||
/// </summary>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
[VtblIndex(3)]
|
||||
public HRESULT GetNativeResource(ICanvasDevice* device, float dpi, [NativeTypeName("REFIID")] Guid* iid, void** resource)
|
||||
{
|
||||
return ((delegate* unmanaged[MemberFunction]<ICanvasResourceWrapperNative*, ICanvasDevice*, float, Guid*, void**, int>)this.lpVtbl[3])((ICanvasResourceWrapperNative*)Unsafe.AsPointer(ref this), device, dpi, iid, resource);
|
||||
}
|
||||
}
|
||||
@@ -1,56 +0,0 @@
|
||||
using System;
|
||||
using System.Runtime.CompilerServices;
|
||||
using ComputeSharp.Win32;
|
||||
|
||||
#pragma warning disable CS0649, IDE1006
|
||||
|
||||
namespace ABI.Microsoft.Graphics.Canvas;
|
||||
|
||||
/// <summary>
|
||||
/// An interface for a COM object that provides access to a pooled <see cref="ID2D1DeviceContext"/> object.
|
||||
/// </summary>
|
||||
[NativeTypeName("class ID2D1DeviceContextLease : IUnknown")]
|
||||
[NativeInheritance("IUnknown")]
|
||||
internal unsafe struct ID2D1DeviceContextLease
|
||||
{
|
||||
public void** lpVtbl;
|
||||
|
||||
/// <inheritdoc cref="IUnknown.QueryInterface"/>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
[VtblIndex(0)]
|
||||
public HRESULT QueryInterface([NativeTypeName("const IID &")] Guid* riid, void** ppvObject)
|
||||
{
|
||||
return ((delegate* unmanaged[MemberFunction]<ID2D1DeviceContextLease*, Guid*, void**, int>)this.lpVtbl[0])((ID2D1DeviceContextLease*)Unsafe.AsPointer(ref this), riid, ppvObject);
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="IUnknown.AddRef"/>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
[VtblIndex(1)]
|
||||
[return: NativeTypeName("ULONG")]
|
||||
public uint AddRef()
|
||||
{
|
||||
return ((delegate* unmanaged[MemberFunction]<ID2D1DeviceContextLease*, uint>)this.lpVtbl[1])((ID2D1DeviceContextLease*)Unsafe.AsPointer(ref this));
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="IUnknown.Release"/>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
[VtblIndex(2)]
|
||||
[return: NativeTypeName("ULONG")]
|
||||
public uint Release()
|
||||
{
|
||||
return ((delegate* unmanaged[MemberFunction]<ID2D1DeviceContextLease*, uint>)this.lpVtbl[2])((ID2D1DeviceContextLease*)Unsafe.AsPointer(ref this));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Provides access to the <see cref="ID2D1DeviceContext"/> object wrapped by the current instance.
|
||||
/// </summary>
|
||||
/// <param name="deviceContext">The resulting <see cref="ID2D1DeviceContext"/> object wrapped by the current instance.</param>
|
||||
/// <returns>The <see cref="HRESULT"/> for the operation.</returns>
|
||||
/// <remarks>The returned <see cref="ID2D1DeviceContext"/> cannot be used once the owning lease has been released.</remarks>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
[VtblIndex(3)]
|
||||
public HRESULT GetD2DDeviceContext(ID2D1DeviceContext** deviceContext)
|
||||
{
|
||||
return ((delegate* unmanaged[MemberFunction]<ID2D1DeviceContextLease*, ID2D1DeviceContext**, int>)this.lpVtbl[3])((ID2D1DeviceContextLease*)Unsafe.AsPointer(ref this), deviceContext);
|
||||
}
|
||||
}
|
||||
@@ -1,81 +0,0 @@
|
||||
using System;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
using ComputeSharp.Win32;
|
||||
|
||||
#pragma warning disable CS0649, IDE0055, IDE1006
|
||||
|
||||
namespace ABI.Microsoft.Graphics.Canvas;
|
||||
|
||||
/// <summary>
|
||||
/// An interface for an object that provides access to pooled <see cref="ID2D1DeviceContext"/> objects.
|
||||
/// </summary>
|
||||
[NativeTypeName("class ID2D1DeviceContextPool : IUnknown")]
|
||||
[NativeInheritance("IUnknown")]
|
||||
internal unsafe struct ID2D1DeviceContextPool : IComObject
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
static Guid* IComObject.IID
|
||||
{
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
get
|
||||
{
|
||||
ReadOnlySpan<byte> data =
|
||||
[
|
||||
0xA1, 0x82, 0x4A, 0x45,
|
||||
0x24, 0xF0,
|
||||
0xDB, 0x40,
|
||||
0xBD,
|
||||
0x5B,
|
||||
0x8F,
|
||||
0x52,
|
||||
0x7F,
|
||||
0xD5,
|
||||
0x8A,
|
||||
0xD0
|
||||
];
|
||||
|
||||
return (Guid*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(data));
|
||||
}
|
||||
}
|
||||
|
||||
public void** lpVtbl;
|
||||
|
||||
/// <inheritdoc cref="IUnknown.QueryInterface"/>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
[VtblIndex(0)]
|
||||
public HRESULT QueryInterface([NativeTypeName("const IID &")] Guid* riid, void** ppvObject)
|
||||
{
|
||||
return ((delegate* unmanaged[MemberFunction]<ID2D1DeviceContextPool*, Guid*, void**, int>)this.lpVtbl[0])((ID2D1DeviceContextPool*)Unsafe.AsPointer(ref this), riid, ppvObject);
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="IUnknown.AddRef"/>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
[VtblIndex(1)]
|
||||
[return: NativeTypeName("ULONG")]
|
||||
public uint AddRef()
|
||||
{
|
||||
return ((delegate* unmanaged[MemberFunction]<ID2D1DeviceContextPool*, uint>)this.lpVtbl[1])((ID2D1DeviceContextPool*)Unsafe.AsPointer(ref this));
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="IUnknown.Release"/>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
[VtblIndex(2)]
|
||||
[return: NativeTypeName("ULONG")]
|
||||
public uint Release()
|
||||
{
|
||||
return ((delegate* unmanaged[MemberFunction]<ID2D1DeviceContextPool*, uint>)this.lpVtbl[2])((ID2D1DeviceContextPool*)Unsafe.AsPointer(ref this));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Retrieves a new <see cref="ID2D1DeviceContextLease"/> object from the current instance.
|
||||
/// </summary>
|
||||
/// <param name="lease">The resulting <see cref="ID2D1DeviceContextLease"/> object to use.</param>
|
||||
/// <returns>The <see cref="HRESULT"/> for the operation.</returns>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
[VtblIndex(3)]
|
||||
public HRESULT GetDeviceContextLease(ID2D1DeviceContextLease** lease)
|
||||
{
|
||||
return ((delegate* unmanaged[MemberFunction]<ID2D1DeviceContextPool*, ID2D1DeviceContextLease**, int>)this.lpVtbl[3])((ID2D1DeviceContextPool*)Unsafe.AsPointer(ref this), lease);
|
||||
}
|
||||
}
|
||||
@@ -1,47 +0,0 @@
|
||||
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
|
||||
|
||||
// Ported from winrt/inspectable.h in the Windows SDK for Windows 10.0.22621.0
|
||||
// Original source is Copyright © Microsoft. All rights reserved.
|
||||
|
||||
using System;
|
||||
using System.Runtime.CompilerServices;
|
||||
|
||||
#pragma warning disable CS0649, IDE1006
|
||||
|
||||
namespace ComputeSharp.Win32;
|
||||
|
||||
/// <summary>
|
||||
/// The native WinRT interface for <see href="https://learn.microsoft.com/windows/win32/api/inspectable/nn-inspectable-iinspectable"><c>IInspectable</c></see> objects.
|
||||
/// </summary>
|
||||
[NativeTypeName("struct IInspectable : IUnknown")]
|
||||
[NativeInheritance("IUnknown")]
|
||||
internal unsafe struct IInspectable
|
||||
{
|
||||
public void** lpVtbl;
|
||||
|
||||
/// <inheritdoc cref="IUnknown.QueryInterface" />
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
[VtblIndex(0)]
|
||||
public HRESULT QueryInterface([NativeTypeName("const IID &")] Guid* riid, void** ppvObject)
|
||||
{
|
||||
return ((delegate* unmanaged[MemberFunction]<IInspectable*, Guid*, void**, int>)this.lpVtbl[0])((IInspectable*)Unsafe.AsPointer(ref this), riid, ppvObject);
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="IUnknown.AddRef" />
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
[VtblIndex(1)]
|
||||
[return: NativeTypeName("ULONG")]
|
||||
public uint AddRef()
|
||||
{
|
||||
return ((delegate* unmanaged[MemberFunction]<IInspectable*, uint>)this.lpVtbl[1])((IInspectable*)Unsafe.AsPointer(ref this));
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="IUnknown.Release" />
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
[VtblIndex(2)]
|
||||
[return: NativeTypeName("ULONG")]
|
||||
public uint Release()
|
||||
{
|
||||
return ((delegate* unmanaged[MemberFunction]<IInspectable*, uint>)this.lpVtbl[2])((IInspectable*)Unsafe.AsPointer(ref this));
|
||||
}
|
||||
}
|
||||
588ファイル中100ファイルを読み込みました。 変更されたファイルが多すぎるため、それ以降のファイルは表示していません。
さらに表示
新しいイシューから参照
ユーザーをブロックする