Port base APIs for D2D1 generator

このコミットが含まれているのは:
Sergio Pedri committed 2022-04-24 21:03:46 +02:00
1 親 2b0c7131ee
コミット 2212b8716d
39ファイル変更
+4354 -97

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

@@ -68,6 +68,11 @@
<Compile Include="..\ComputeSharp.D2D1Interop\Attributes\D2DInputCountAttribute.cs" Link="ComputeSharp.D2D1Interop\Attributes\D2DInputCountAttribute.cs" />
<Compile Include="..\ComputeSharp.D2D1Interop\Attributes\D2DInputSimpleAttribute.cs" Link="ComputeSharp.D2D1Interop\Attributes\D2DInputSimpleAttribute.cs" />
<Compile Include="..\ComputeSharp.D2D1Interop\Attributes\D2DRequiresScenePositionAttribute.cs" Link="ComputeSharp.D2D1Interop\Attributes\D2DRequiresScenePositionAttribute.cs" />
<Compile Include="..\ComputeSharp.D2D1Interop\Interfaces\ID2D1PixelShader.cs" Link="ComputeSharp.D2D1Interop\Interfaces\ID2D1PixelShader.cs" />
<Compile Include="..\ComputeSharp.D2D1Interop\Interfaces\__Internals\ID2D1BytecodeLoader.cs" Link="ComputeSharp.D2D1Interop\Interfaces\__Internals\ID2D1BytecodeLoader.cs" />
<Compile Include="..\ComputeSharp.D2D1Interop\Interfaces\__Internals\ID2D1DispatchDataLoader.cs" Link="ComputeSharp.D2D1Interop\Interfaces\__Internals\ID2D1DispatchDataLoader.cs" />
<Compile Include="..\ComputeSharp.D2D1Interop\Interfaces\__Internals\ID2D1Shader.cs" Link="ComputeSharp.D2D1Interop\Interfaces\__Internals\ID2D1Shader.cs" />
<Compile Include="..\ComputeSharp.D2D1Interop\Intrinsics\D2D1.cs" Link="ComputeSharp.D2D1Interop\Intrinsics\D2D1.cs" />
</ItemGroup>
<ItemGroup>
+684
ファイルの表示
@@ -0,0 +1,684 @@
using Microsoft.CodeAnalysis;
namespace ComputeSharp.D2D1Interop.SourceGenerators.Diagnostics;
#pragma warning disable IDE0090 // Use 'new(...)'
#pragma warning disable RS2000 // TODO
/// <summary>
/// A container for all <see cref="DiagnosticDescriptor"/> instances for errors reported by analyzers in this project.
/// </summary>
internal static class DiagnosticDescriptors
{
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for an invalid shader field.
/// <para>
/// Format: <c>"The compute shader of type {0} contains a field \"{1}\" of an invalid type {2}"</c>.
/// </para>
/// </summary>
public static readonly DiagnosticDescriptor InvalidShaderField = new DiagnosticDescriptor(
id: "CMPS0001",
title: "Invalid shader field",
messageFormat: "The compute shader of type {0} contains a field \"{1}\" of an invalid type {2}",
category: "ComputeSharp.D2D1Interop.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "A type representing a compute shader contains a field of a type that is not supported in HLSL.",
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for an invalid group shared field type.
/// <para>
/// Format: <c>"The compute shader of type {0} contains a group shared field \"{1}\" of an invalid type {2}"</c>.
/// </para>
/// </summary>
public static readonly DiagnosticDescriptor InvalidGroupSharedFieldType = new DiagnosticDescriptor(
id: "CMPS0002",
title: "Invalid group shared field type",
messageFormat: "The compute shader of type {0} contains a group shared field \"{1}\" of an invalid type {2} (it must be an array)",
category: "ComputeSharp.D2D1Interop.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "A group shared field must be of an array type.",
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for an invalid group shared field element type.
/// <para>
/// Format: <c>"The compute shader of type {0} contains a group shared field \"{1}\" of an invalid element type {2}"</c>.
/// </para>
/// </summary>
public static readonly DiagnosticDescriptor InvalidGroupSharedFieldElementType = new DiagnosticDescriptor(
id: "CMPS0003",
title: "Invalid group shared field element type",
messageFormat: "The compute shader of type {0} contains a group shared field \"{1}\" of an invalid type {2} (it must be a primitive or unmanaged type)",
category: "ComputeSharp.D2D1Interop.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "A group shared field element must be of a primitive or unmanaged type.",
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for an invalid group shared field declaration.
/// <para>
/// Format: <c>"The compute shader of type {0} contains a group shared field \"{1}\" that is not static"</c>.
/// </para>
/// </summary>
public static readonly DiagnosticDescriptor InvalidGroupSharedFieldDeclaration = new DiagnosticDescriptor(
id: "CMPS0004",
title: "Invalid group shared field declaration",
messageFormat: "The compute shader of type {0} contains a group shared field \"{1}\" that is not static",
category: "ComputeSharp.D2D1Interop.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "A group shared field must be static.",
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for a shader with no resources.
/// <para>
/// Format: <c>"The compute shader of type {0} contains no resources to work on"</c>.
/// </para>
/// </summary>
public static readonly DiagnosticDescriptor MissingShaderResources = new DiagnosticDescriptor(
id: "CMPS0005",
title: "Missing shader resources",
messageFormat: "The compute shader of type {0} contains no resources to work on",
category: "ComputeSharp.D2D1Interop.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "A compute shader must contain at least one resource.",
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for an invalid <see cref="ThreadIds"/> usage.
/// </summary>
public static readonly DiagnosticDescriptor InvalidThreadIdsUsage = new DiagnosticDescriptor(
id: "CMPS0006",
title: "Invalid ThreadIds usage",
messageFormat: "The ThreadIds type can only be used within the main body of a compute shader",
category: "ComputeSharp.D2D1Interop.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "The ThreadIds type can only be used within the main body of a compute shader.",
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for an invalid <see cref="GroupIds"/> usage.
/// </summary>
public static readonly DiagnosticDescriptor InvalidGroupIdsUsage = new DiagnosticDescriptor(
id: "CMPS0007",
title: "Invalid GroupIds usage",
messageFormat: "The GroupIds type can only be used within the main body of a compute shader",
category: "ComputeSharp.D2D1Interop.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "The GroupIds type can only be used within the main body of a compute shader.",
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for an invalid <see cref="GroupSize"/> usage.
/// </summary>
public static readonly DiagnosticDescriptor InvalidGroupSizeUsage = new DiagnosticDescriptor(
id: "CMPS0008",
title: "Invalid GroupSize usage",
messageFormat: "The GroupSize type can only be used within the main body of a compute shader",
category: "ComputeSharp.D2D1Interop.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "The GroupSize type can only be used within the main body of a compute shader.",
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for an invalid <see cref="GridIds"/> usage.
/// </summary>
public static readonly DiagnosticDescriptor InvalidGridIdsUsage = new DiagnosticDescriptor(
id: "CMPS0009",
title: "Invalid GridIds usage",
messageFormat: "The GridIds type can only be used within the main body of a compute shader",
category: "ComputeSharp.D2D1Interop.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "The GridIds type can only be used within the main body of a compute shader.",
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for an invalid object creation expression.
/// <para>
/// Format: <c>"The type {0} cannot be created in a compute shader"</c>.
/// </para>
/// </summary>
public static readonly DiagnosticDescriptor InvalidObjectCreationExpression = new DiagnosticDescriptor(
id: "CMPS0010",
title: "Invalid object creation expression",
messageFormat: "The type {0} cannot be created in a compute shader (only unmanaged types are supported)",
category: "ComputeSharp.D2D1Interop.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "Only unmanaged value type objects can be created in a compute shader.",
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for an anonymous object creation expression.
/// </summary>
public static readonly DiagnosticDescriptor AnonymousObjectCreationExpression = new DiagnosticDescriptor(
id: "CMPS0011",
title: "Anonymous object creation expression",
messageFormat: "An anonymous object cannot be created in a compute shader",
category: "ComputeSharp.D2D1Interop.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "An anonymous object cannot be created in a compute shader.",
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for an async modifier on a method or function.
/// </summary>
public static readonly DiagnosticDescriptor AsyncModifierOnMethodOrFunction = new DiagnosticDescriptor(
id: "CMPS0012",
title: "Async modifier on method or function",
messageFormat: "The async modifier cannot be used in methods or functions used in a compute shader",
category: "ComputeSharp.D2D1Interop.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "The async modifier cannot be used in methods or functions used in a compute shader.",
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for an await expression.
/// </summary>
public static readonly DiagnosticDescriptor AwaitExpression = new DiagnosticDescriptor(
id: "CMPS0013",
title: "Await expression",
messageFormat: "The await expression cannot be used in a compute shader",
category: "ComputeSharp.D2D1Interop.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "The await expression cannot be used in a compute shader.",
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for a checked expression.
/// </summary>
public static readonly DiagnosticDescriptor CheckedExpression = new DiagnosticDescriptor(
id: "CMPS0014",
title: "Checked expression",
messageFormat: "A checked expression cannot be used in a compute shader",
category: "ComputeSharp.D2D1Interop.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "A checked expression cannot be used in a compute shader.",
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for a checked statement.
/// </summary>
public static readonly DiagnosticDescriptor CheckedStatement = new DiagnosticDescriptor(
id: "CMPS0015",
title: "Checked statement",
messageFormat: "A checked statement cannot be used in a compute shader",
category: "ComputeSharp.D2D1Interop.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "A checked statement cannot be used in a compute shader.",
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for a fixed statement.
/// </summary>
public static readonly DiagnosticDescriptor FixedStatement = new DiagnosticDescriptor(
id: "CMPS0016",
title: "Fixed statement",
messageFormat: "A fixed statement cannot be used in a compute shader",
category: "ComputeSharp.D2D1Interop.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "A fixed statement cannot be used in a compute shader.",
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for a foreach statement.
/// </summary>
public static readonly DiagnosticDescriptor ForEachStatement = new DiagnosticDescriptor(
id: "CMPS0017",
title: "Foreach statement",
messageFormat: "A foreach statement cannot be used in a compute shader",
category: "ComputeSharp.D2D1Interop.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "A foreach statement cannot be used in a compute shader.",
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for a lock statement.
/// </summary>
public static readonly DiagnosticDescriptor LockStatement = new DiagnosticDescriptor(
id: "CMPS0018",
title: "Foreach statement",
messageFormat: "A lock statement cannot be used in a compute shader",
category: "ComputeSharp.D2D1Interop.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "A lock statement cannot be used in a compute shader.",
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for a query statement.
/// </summary>
public static readonly DiagnosticDescriptor QueryExpression = new DiagnosticDescriptor(
id: "CMPS0019",
title: "Foreach statement",
messageFormat: "A LINQ query expression cannot be used in a compute shader",
category: "ComputeSharp.D2D1Interop.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "A LINQ query expression cannot be used in a compute shader.",
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for a range expression.
/// </summary>
public static readonly DiagnosticDescriptor RangeExpression = new DiagnosticDescriptor(
id: "CMPS0020",
title: "Range expression",
messageFormat: "A range expression cannot be used in a compute shader",
category: "ComputeSharp.D2D1Interop.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "A range expression cannot be used in a compute shader.",
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for a recursive pattern.
/// </summary>
public static readonly DiagnosticDescriptor RecursivePattern = new DiagnosticDescriptor(
id: "CMPS0021",
title: "Recursive pattern",
messageFormat: "A recursive pattern cannot be used in a compute shader",
category: "ComputeSharp.D2D1Interop.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "A recursive pattern cannot be used in a compute shader.",
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for a ref type.
/// </summary>
public static readonly DiagnosticDescriptor RefType = new DiagnosticDescriptor(
id: "CMPS0022",
title: "Ref type",
messageFormat: "A compute shader cannot have a ref type declaration",
category: "ComputeSharp.D2D1Interop.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "A compute shader cannot have a ref type declaration.",
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for a relational pattern.
/// </summary>
public static readonly DiagnosticDescriptor RelationalPattern = new DiagnosticDescriptor(
id: "CMPS0023",
title: "Relational pattern",
messageFormat: "A relational pattern cannot be used in a compute shader",
category: "ComputeSharp.D2D1Interop.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "A relational pattern cannot be used in a compute shader.",
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for a sizeof expression.
/// </summary>
public static readonly DiagnosticDescriptor SizeOfExpression = new DiagnosticDescriptor(
id: "CMPS0024",
title: "Sizeof expression",
messageFormat: "A sizeof expression cannot be used in a compute shader",
category: "ComputeSharp.D2D1Interop.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "A sizeof expression cannot be used in a compute shader.",
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for a stackalloc expression.
/// </summary>
public static readonly DiagnosticDescriptor StackAllocArrayCreationExpression = new DiagnosticDescriptor(
id: "CMPS0025",
title: "Stackalloc expression",
messageFormat: "A stackalloc expression cannot be used in a compute shader",
category: "ComputeSharp.D2D1Interop.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "A stackalloc expression cannot be used in a compute shader.",
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for a throw expression or statement.
/// </summary>
public static readonly DiagnosticDescriptor ThrowExpressionOrStatement = new DiagnosticDescriptor(
id: "CMPS0026",
title: "Throw expression or statement",
messageFormat: "Throw expressions and statements cannot be used in a compute shader",
category: "ComputeSharp.D2D1Interop.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "Throw expressions and statements cannot be used in a compute shader.",
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for a try statement.
/// </summary>
public static readonly DiagnosticDescriptor TryStatement = new DiagnosticDescriptor(
id: "CMPS0027",
title: "Try statement",
messageFormat: "A try statement cannot be used in a compute shader",
category: "ComputeSharp.D2D1Interop.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "A try statement cannot be used in a compute shader.",
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for a tuple type.
/// </summary>
public static readonly DiagnosticDescriptor TupleType = new DiagnosticDescriptor(
id: "CMPS0028",
title: "Tuple type",
messageFormat: "A compute shader cannot have a tuple type declaration",
category: "ComputeSharp.D2D1Interop.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "A compute shader cannot have a tuple type declaration.",
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for a using statement or declaration.
/// </summary>
public static readonly DiagnosticDescriptor UsingStatementOrDeclaration = new DiagnosticDescriptor(
id: "CMPS0029",
title: "Using statement or declaration",
messageFormat: "Using statements and declarations cannot be used in a compute shader",
category: "ComputeSharp.D2D1Interop.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "Using statements and declarations cannot be used in a compute shader.",
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for a yield statement.
/// </summary>
public static readonly DiagnosticDescriptor YieldStatement = new DiagnosticDescriptor(
id: "CMPS0030",
title: "Yield statement",
messageFormat: "A yield statement cannot be used in a compute shader",
category: "ComputeSharp.D2D1Interop.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "A yield statement cannot be used in a compute shader.",
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for an invalid object declaration.
/// <para>
/// Format: <c>"A variable of type {0} cannot be declared in a compute shader"</c>.
/// </para>
/// </summary>
public static readonly DiagnosticDescriptor InvalidObjectDeclaration = new DiagnosticDescriptor(
id: "CMPS0031",
title: "Invalid object declaration",
messageFormat: "A variable of type {0} cannot be declared in a compute shader (only unmanaged types are supported)",
category: "ComputeSharp.D2D1Interop.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "Only unmanaged value type objects can be declared in a compute shader.",
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for a pointer type.
/// </summary>
public static readonly DiagnosticDescriptor PointerType = new DiagnosticDescriptor(
id: "CMPS0032",
title: "Pointer type",
messageFormat: "A compute shader cannot have a pointer type declaration",
category: "ComputeSharp.D2D1Interop.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "A compute shader cannot have a pointer type declaration.",
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for a function pointer type.
/// </summary>
public static readonly DiagnosticDescriptor FunctionPointer = new DiagnosticDescriptor(
id: "CMPS0033",
title: "Function pointer type",
messageFormat: "A compute shader cannot have a function pointer type declaration",
category: "ComputeSharp.D2D1Interop.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "A compute shader cannot have a function pointer type declaration.",
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for an unsafe statement.
/// </summary>
public static readonly DiagnosticDescriptor UnsafeStatement = new DiagnosticDescriptor(
id: "CMPS0034",
title: "Unsafe statement",
messageFormat: "A compute shader cannot have an unsafe statement",
category: "ComputeSharp.D2D1Interop.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "A compute shader cannot have an unsafe statement.",
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for an unsafe modifier on a method or function.
/// </summary>
public static readonly DiagnosticDescriptor UnsafeModifierOnMethodOrFunction = new DiagnosticDescriptor(
id: "CMPS0035",
title: "Unsafe modifier on method or function",
messageFormat: "The unsafe modifier cannot be used in methods or functions used in a compute shader",
category: "ComputeSharp.D2D1Interop.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "The unsafe modifier cannot be used in methods or functions used in a compute shader.",
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for a string literal.
/// </summary>
public static readonly DiagnosticDescriptor StringLiteralExpression = new DiagnosticDescriptor(
id: "CMPS0036",
title: "String literal expression",
messageFormat: "String literal expressions cannot be used in a compute shader",
category: "ComputeSharp.D2D1Interop.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "String literal expressions cannot be used in a compute shader.",
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for an incorrect matrix swizzling property argument.
/// </summary>
public static readonly DiagnosticDescriptor NonConstantMatrixSwizzledIndex = new DiagnosticDescriptor(
id: "CMPS0037",
title: "Non constant matrix swizzled property argument",
messageFormat: "The arguments in a swizzled indexer for a matrix type must be compile-time constants",
category: "ComputeSharp.D2D1Interop.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "The arguments in a swizzled indexer for a matrix type must be compile-time constants.",
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for an invalid shader static field type.
/// <para>
/// Format: <c>"The compute shader of type {0} contains a static field \"{1}\" of an invalid type {2} (only primitive, vector and matrix types are supported)"</c>.
/// </para>
/// </summary>
public static readonly DiagnosticDescriptor InvalidShaderStaticFieldType = new DiagnosticDescriptor(
id: "CMPS0038",
title: "Invalid shader static field type",
messageFormat: "The compute shader of type {0} contains a static field \"{1}\" of an invalid type {2} (only primitive, vector and matrix types are supported)",
category: "ComputeSharp.D2D1Interop.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "A type representing a compute shader contains a static field of a type that is not supported.",
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for an invalid <see cref="DispatchSize"/> usage.
/// </summary>
public static readonly DiagnosticDescriptor InvalidDispatchSizeUsage = new DiagnosticDescriptor(
id: "CMPS0039",
title: "Invalid DispatchSize usage",
messageFormat: "The DispatchSize type can only be used within the main body of a compute shader",
category: "ComputeSharp.D2D1Interop.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "The DispatchSize type can only be used within the main body of a compute shader.",
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for a property declaration.
/// </summary>
public static readonly DiagnosticDescriptor PropertyDeclaration = new DiagnosticDescriptor(
id: "CMPS0040",
title: "Property declaration",
messageFormat: "Property declarations cannot be used in a compute shader",
category: "ComputeSharp.D2D1Interop.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "Property declarations cannot be used in a compute shader.",
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for a shader with a root signature that is too large.
/// <para>
/// Format: <c>"The compute shader of type {0} has exceeded the maximum allowed size for captured values and resources"</c>.
/// </para>
/// </summary>
public static readonly DiagnosticDescriptor ShaderDispatchDataSizeExceeded = new DiagnosticDescriptor(
id: "CMPS0041",
title: "Shader dispatch data size exceeded",
messageFormat: "The compute shader of type {0} has exceeded the maximum allowed size for captured values and resources",
category: "ComputeSharp.D2D1Interop.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "The compute shader of type {0} has exceeded the maximum allowed size for captured values and resources.",
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for a type implementing multiple shader interfaces.
/// <para>
/// Format: <c>"The shader of type {0} cannot implement more than one shader interface"</c>.
/// </para>
/// </summary>
public static readonly DiagnosticDescriptor MultipleShaderTypesImplemented = new DiagnosticDescriptor(
id: "CMPS0042",
title: "Multiple shader implementations for type declaration",
messageFormat: "The shader of type {0} cannot implement more than one shader interface",
category: "ComputeSharp.D2D1Interop.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "A shader type cannot implement more than one shader interface.",
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for a dynamic shader annotated as an embedded bytecode.
/// <para>
/// Format: <c>"The shader of type {0} cannot be precompiled, as it is dynamic (it captures delegate fields)"</c>.
/// </para>
/// </summary>
public static readonly DiagnosticDescriptor EmbeddedBytecodeWithDynamicShader = new DiagnosticDescriptor(
id: "CMPS0043",
title: "Embedded bytecode for dynamic shader",
messageFormat: "The shader of type {0} cannot be precompiled, as it is dynamic (it captures delegate fields)",
category: "ComputeSharp.D2D1Interop.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "A shader type cannot be precompiled if it captures one or more delegate values.",
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for an embedded bytecode shader with invalid thread ids values.
/// <para>
/// Format: <c>"The shader of type {0} is annotated with invalid thread ids values ({1}, {2}, {3})"</c>.
/// </para>
/// </summary>
public static readonly DiagnosticDescriptor InvalidEmbeddedBytecodeThreadIds = new DiagnosticDescriptor(
id: "CMPS0044",
title: "Invalid thread ids for shader with embedded bytecode",
messageFormat: "The shader of type {0} is annotated with invalid thread ids values ({1}, {2}, {3})",
category: "ComputeSharp.D2D1Interop.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "The thread ids values for a shader marked as embedded bytecode have to be in the valid range.",
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for an embedded bytecode shader failed due to a Win32 exception.
/// <para>
/// Format: <c>"The shader of type {0} failed to compile due to a Win32 exception (HRESULT: {1:X8}, Message: "{2}")"</c>.
/// </para>
/// </summary>
public static readonly DiagnosticDescriptor EmbeddedBytecodeFailedWithWin32Exception = new DiagnosticDescriptor(
id: "CMPS0045",
title: "Embedded bytecode compilation failed due to Win32 exception",
messageFormat: "The shader of type {0} failed to compile due to a Win32 exception (HRESULT: {1:X8}, Message: \"{2}\")",
category: "ComputeSharp.D2D1Interop.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "The embedded bytecode for a shader failed to be compiled due to a Win32 exception.",
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for an embedded bytecode shader failed due to an HLSL compilation exception.
/// <para>
/// Format: <c>"The shader of type {{0}} failed to compile due to an HLSL compiler error (Message: "{1}")"</c>.
/// </para>
/// </summary>
public static readonly DiagnosticDescriptor EmbeddedBytecodeFailedWithDxcCompilationException = new DiagnosticDescriptor(
id: "CMPS0046",
title: "Embedded bytecode compilation failed due to an HLSL compiler error",
messageFormat: "The shader of type {0} failed to compile due to an HLSL compiler error (Message: \"{1}\")",
category: "ComputeSharp.D2D1Interop.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "The embedded bytecode for a shader failed to be compiled due to an HLSL compiler error.",
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for a shader without the embedded bytecode attribute, when dynamic shaders are not supported.
/// <para>
/// Format: <c>"The shader of type {0} needs to be annotated as having embedded bytecode (using the [EmbeddedBytecode] attribute), as dynamic shader compilation is not supported"</c>.
/// </para>
/// </summary>
public static readonly DiagnosticDescriptor MissingEmbeddedBytecodeAttributeWhenDynamicShaderCompilationIsNotSupported = new DiagnosticDescriptor(
id: "CMPS0047",
title: "Embedded bytecode compilation failed due to an HLSL compiler error",
messageFormat: "The shader of type {0} needs to be annotated as having embedded bytecode (using the [EmbeddedBytecode] attribute), as dynamic shader compilation is not supported",
category: "ComputeSharp.D2D1Interop.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "When dynamic shader compilation is not supported (ie. when ComputeSharp.Dynamic is not referenced), all shaders need to be annotated as having embedded bytecode (using the [EmbeddedBytecode] attribute).",
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for an embedded bytecode shader with an invalid dispatch axis value.
/// <para>
/// Format: <c>"The shader of type {0} is annotated with an invalid dispatch axis value"</c>.
/// </para>
/// </summary>
public static readonly DiagnosticDescriptor InvalidEmbeddedBytecodeDispatchAxis = new DiagnosticDescriptor(
id: "CMPS0048",
title: "Invalid dispatch axis for shader with embedded bytecode",
messageFormat: "The shader of type {0} is annotated with with an invalid dispatch axis value",
category: "ComputeSharp.D2D1Interop.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "The dispatch axis value for a shader marked as embedded bytecode have to be valid (flags are not supported).",
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
}
+91
ファイルの表示
@@ -0,0 +1,91 @@
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis;
namespace ComputeSharp.D2D1Interop.SourceGenerators.Diagnostics;
/// <summary>
/// Extension methods for <see cref="GeneratorExecutionContext"/>, specifically for reporting diagnostics.
/// </summary>
internal static class DiagnosticsExtensions
{
/// <summary>
/// Adds a new diagnostics to the current compilation.
/// </summary>
/// <param name="context">The <see cref="GeneratorExecutionContext"/> instance currently in use.</param>
/// <param name="descriptor">The input <see cref="DiagnosticDescriptor"/> for the diagnostics to create.</param>
/// <param name="symbol">The source <see cref="ISymbol"/> to attach the diagnostics to.</param>
/// <param name="args">The optional arguments for the formatted message to include.</param>
public static void ReportDiagnostic(
this GeneratorExecutionContext context,
DiagnosticDescriptor descriptor,
ISymbol symbol,
params object[] args)
{
context.ReportDiagnostic(Diagnostic.Create(descriptor, symbol.Locations.FirstOrDefault(), args));
}
/// <summary>
/// Adds a new diagnostics to the current compilation.
/// </summary>
/// <param name="context">The <see cref="GeneratorExecutionContext"/> instance currently in use.</param>
/// <param name="descriptor">The input <see cref="DiagnosticDescriptor"/> for the diagnostics to create.</param>
/// <param name="node">The source <see cref="SyntaxNode"/> to attach the diagnostics to.</param>
/// <param name="args">The optional arguments for the formatted message to include.</param>
public static void ReportDiagnostic(
this GeneratorExecutionContext context,
DiagnosticDescriptor descriptor,
SyntaxNode node,
params object[] args)
{
context.ReportDiagnostic(Diagnostic.Create(descriptor, node.GetLocation(), args));
}
/// <summary>
/// Adds a new diagnostics to the target builder.
/// </summary>
/// <param name="diagnostics">The collection of produced <see cref="Diagnostic"/> instances.</param>
/// <param name="descriptor">The input <see cref="DiagnosticDescriptor"/> for the diagnostics to create.</param>
/// <param name="symbol">The source <see cref="ISymbol"/> to attach the diagnostics to.</param>
/// <param name="args">The optional arguments for the formatted message to include.</param>
public static void Add(
this ImmutableArray<Diagnostic>.Builder diagnostics,
DiagnosticDescriptor descriptor,
ISymbol symbol,
params object[] args)
{
diagnostics.Add(Diagnostic.Create(descriptor, symbol.Locations.FirstOrDefault(), args));
}
/// <summary>
/// Adds a new diagnostics to the target builder.
/// </summary>
/// <param name="diagnostics">The collection of produced <see cref="Diagnostic"/> instances.</param>
/// <param name="descriptor">The input <see cref="DiagnosticDescriptor"/> for the diagnostics to create.</param>
/// <param name="node">The source <see cref="SyntaxNode"/> to attach the diagnostics to.</param>
/// <param name="args">The optional arguments for the formatted message to include.</param>
public static void Add(
this ImmutableArray<Diagnostic>.Builder diagnostics,
DiagnosticDescriptor descriptor,
SyntaxNode node,
params object[] args)
{
diagnostics.Add(Diagnostic.Create(descriptor, node.GetLocation(), args));
}
/// <summary>
/// Registers an output node into an <see cref="IncrementalGeneratorInitializationContext"/> to output diagnostics.
/// </summary>
/// <param name="context">The input <see cref="IncrementalGeneratorInitializationContext"/> instance.</param>
/// <param name="diagnostics">The input <see cref="IncrementalValuesProvider{TValues}"/> sequence of diagnostics.</param>
public static void ReportDiagnostics(this IncrementalGeneratorInitializationContext context, IncrementalValuesProvider<ImmutableArray<Diagnostic>> diagnostics)
{
context.RegisterSourceOutput(diagnostics, static (context, diagnostics) =>
{
foreach (Diagnostic diagnostic in diagnostics)
{
context.ReportDiagnostic(diagnostic);
}
});
}
}
+40
ファイルの表示
@@ -0,0 +1,40 @@
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
namespace ComputeSharp.D2D1Interop.SourceGenerators.Extensions;
/// <summary>
/// Extension methods for <see cref="HashCode"/>.
/// </summary>
internal static class HashCodeExtensions
{
/// <summary>
/// Adds all items from a given <see cref="ImmutableArray{T}"/> instance to an hashcode.
/// </summary>
/// <typeparam name="T">The type of items to hash.</typeparam>
/// <param name="hashCode">The target <see cref="HashCode"/> instance.</param>
/// <param name="items">The input items to hash.</param>
public static void AddRange<T>(this ref HashCode hashCode, ImmutableArray<T> items)
{
foreach (T item in items)
{
hashCode.Add(item);
}
}
/// <summary>
/// Adds all items from a given <see cref="ImmutableArray{T}"/> instance to an hashcode.
/// </summary>
/// <typeparam name="T">The type of items to hash.</typeparam>
/// <param name="hashCode">The target <see cref="HashCode"/> instance.</param>
/// <param name="comparer">A comparer to get hashcodes for <typeparamref name="T"/> items.</param>
/// <param name="items">The input items to hash.</param>
public static void AddRange<T>(this ref HashCode hashCode, ImmutableArray<T> items, IEqualityComparer<T> comparer)
{
foreach (T item in items)
{
hashCode.Add(item, comparer);
}
}
}
@@ -0,0 +1,59 @@
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
namespace ComputeSharp.D2D1Interop.SourceGenerators.Extensions;
/// <summary>
/// Extension methods for <see cref="IEqualityComparer{T}"/>.
/// </summary>
internal static class IEqualityComparerExtensions
{
/// <summary>
/// Gets an <see cref="IEqualityComparer{T}"/> for an <see cref="ImmutableArray{T}"/> sequence.
/// </summary>
/// <typeparam name="T">The type of items to compare.</typeparam>
/// <param name="comparer">The compare for individual <typeparamref name="T"/> items.</param>
public static IEqualityComparer<ImmutableArray<T>> ForImmutableArray<T>(this IEqualityComparer<T> comparer)
{
return new Comparer<T>(comparer);
}
/// <summary>
/// An <see cref="IEqualityComparer{T}"/> implementation for an <see cref="ImmutableArray{T}"/> value.
/// </summary>
public sealed class Comparer<T> : IEqualityComparer<ImmutableArray<T>>
{
/// <summary>
/// The <typeparamref name="T"/> comparer.
/// </summary>
private readonly IEqualityComparer<T> comparer;
/// <summary>
/// Creates a new <see cref="Comparer{T}"/> instance with the specified parameters.
/// </summary>
/// <param name="comparer">The <typeparamref name="T"/> comparer.</param>
public Comparer(IEqualityComparer<T> comparer)
{
this.comparer = comparer;
}
/// <inheritdoc/>
public bool Equals(ImmutableArray<T> x, ImmutableArray<T> y)
{
return
x == y ||
x.SequenceEqual(y, this.comparer);
}
/// <inheritdoc/>
public int GetHashCode(ImmutableArray<T> obj)
{
HashCode hashCode = default;
hashCode.AddRange(obj, this.comparer);
return hashCode.ToHashCode();
}
}
}
+134
ファイルの表示
@@ -0,0 +1,134 @@
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ComputeSharp.D2D1Interop.SourceGenerators.Mappings;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
namespace ComputeSharp.D2D1Interop.SourceGenerators.Extensions;
/// <summary>
/// Extension methods for <see cref="ISymbol"/> types.
/// </summary>
internal static class ISymbolExtensions
{
/// <summary>
/// A custom <see cref="SymbolDisplayFormat"/> instance with fully qualified style, without global::.
/// </summary>
public static readonly SymbolDisplayFormat FullyQualifiedWithoutGlobalFormat = new(
globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted,
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters);
/// <summary>
/// A custom <see cref="SymbolDisplayFormat"/> instance with fully qualified style, without global:: and parameters.
/// </summary>
private static readonly SymbolDisplayFormat FullyQualifiedWithoutGlobalAndParametersFormat =
FullyQualifiedWithoutGlobalFormat
.WithMemberOptions(SymbolDisplayMemberOptions.IncludeContainingType)
.WithParameterOptions(SymbolDisplayParameterOptions.None);
/// <summary>
/// Gets the full metadata name for a given <see cref="ITypeSymbol"/> instance.
/// </summary>
/// <param name="symbol">The input <see cref="ITypeSymbol"/> instance.</param>
/// <returns>The full metadata name for <paramref name="symbol"/>.</returns>
public static string GetFullMetadataName(this ITypeSymbol symbol)
{
static StringBuilder BuildFrom(ISymbol? symbol, StringBuilder builder)
{
return symbol switch
{
INamespaceSymbol ns when ns.IsGlobalNamespace => builder,
INamespaceSymbol ns when ns.ContainingNamespace is { IsGlobalNamespace: false }
=> BuildFrom(ns.ContainingNamespace, builder.Insert(0, $".{ns.MetadataName}")),
ITypeSymbol ts when ts.ContainingType is ISymbol containingType
=> BuildFrom(containingType, builder.Insert(0, $"+{ts.MetadataName}")),
ITypeSymbol ts when ts.ContainingNamespace is ISymbol containingNamespace and not INamespaceSymbol { IsGlobalNamespace: true }
=> BuildFrom(containingNamespace, builder.Insert(0, $".{ts.MetadataName}")),
ISymbol => BuildFrom(symbol.ContainingSymbol, builder.Insert(0, symbol.MetadataName)),
_ => builder
};
}
return BuildFrom(symbol, new StringBuilder(256)).ToString();
}
/// <summary>
/// Gets the full metadata name for a given <see cref="IMethodSymbol"/> instance.
/// </summary>
/// <param name="symbol">The input <see cref="IMethodSymbol"/> instance.</param>
/// <param name="includeParameters">Whether or not to also include parameter types.</param>
/// <returns>The full metadata name for <paramref name="symbol"/>.</returns>
public static string GetFullMetadataName(this IMethodSymbol symbol, bool includeParameters = false)
{
if (includeParameters)
{
var parameters = string.Join(", ", symbol.Parameters.Select(static p => ((INamedTypeSymbol)p.Type).GetFullMetadataName()));
return $"{symbol.ToDisplayString(FullyQualifiedWithoutGlobalAndParametersFormat)}({parameters})";
}
return symbol.ToDisplayString(FullyQualifiedWithoutGlobalAndParametersFormat);
}
/// <summary>
/// Gets the full metadata name for a given <see cref="IPropertySymbol"/> instance.
/// </summary>
/// <param name="symbol">The input <see cref="IPropertySymbol"/> instance.</param>
/// <returns>The full metadata name for <paramref name="symbol"/>.</returns>
public static string GetFullMetadataName(this IPropertySymbol symbol)
{
string declaringTypeName = symbol.ContainingType.GetFullMetadataName();
if (symbol.IsIndexer)
{
var parameters = string.Join(", ", symbol.Parameters.Select(static p => ((INamedTypeSymbol)p.Type).GetFullMetadataName()));
return $"{declaringTypeName}.this[{parameters}]";
}
return $"{declaringTypeName}.{symbol.Name}";
}
/// <summary>
/// Gets the full metadata name for a given <see cref="IFieldSymbol"/> instance.
/// </summary>
/// <param name="symbol">The input <see cref="IFieldSymbol"/> instance.</param>
/// <returns>The full metadata name for <paramref name="symbol"/>.</returns>
public static string GetFullMetadataName(this IFieldSymbol symbol)
{
return $"{symbol.ContainingType.GetFullMetadataName()}.{symbol.Name}";
}
/// <summary>
/// Gets a valid filename for a target symbol and generator type.
/// </summary>
/// <param name="symbol">The symbol being processed.</param>
/// <returns>A filename in the form "&lt;SYMBOL_FULLNAME&gt;"</returns>
public static string GetGeneratedFileName(this INamedTypeSymbol symbol)
{
return symbol.GetFullMetadataName().Replace('`', '-').Replace('+', '.');
}
/// <summary>
/// Tracks an <see cref="ITypeSymbol"/> instance and returns an HLSL compatible <see cref="TypeSyntax"/> object.
/// </summary>
/// <param name="typeSymbol">The input <see cref="ITypeSymbol"/> instance to process.</param>
/// <param name="discoveredTypes">The collection of currently discovered types.</param>
/// <returns>A <see cref="SyntaxNode"/> instance that represents a type compatible with HLSL.</returns>
public static TypeSyntax TrackType(this ITypeSymbol typeSymbol, ICollection<INamedTypeSymbol> discoveredTypes)
{
string typeName = typeSymbol.ToDisplayString(FullyQualifiedWithoutGlobalFormat);
discoveredTypes.Add((INamedTypeSymbol)typeSymbol);
if (HlslKnownTypes.TryGetMappedName(typeName, out string? mappedName))
{
return ParseTypeName(mappedName!);
}
return ParseTypeName(typeName.ToHlslIdentifierName());
}
}
@@ -0,0 +1,50 @@
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
namespace ComputeSharp.D2D1Interop.SourceGenerators.Extensions;
/// <summary>
/// Extension methods for <see cref="ImmutableArray{T}"/>.
/// </summary>
internal static class ImmutableArrayExtensions
{
/// <summary>
/// Compares two sequences for equality.
/// </summary>
/// <typeparam name="T">The items to compare.</typeparam>
/// <param name="left">The left sequence of items.</param>
/// <param name="right">The right sequence of items.</param>
/// <returns>Whether or not <paramref name="left"/> equals <paramref name="right"/>.</returns>
public static bool SequenceEqual<T>(this ImmutableArray<T> left, ImmutableArray<T> right)
where T : IEquatable<T>
{
return left.AsSpan().SequenceEqual(right.AsSpan());
}
/// <summary>
/// Compares two sequences for equality.
/// </summary>
/// <typeparam name="T">The items to compare.</typeparam>
/// <param name="left">The left sequence of items.</param>
/// <param name="right">The right sequence of items.</param>
/// <param name="comparer">The <see cref="IEqualityComparer{T}"/> instance used to compare <typeparamref name="T"/> items.</param>
/// <returns>Whether or not <paramref name="left"/> equals <paramref name="right"/>.</returns>
public static bool SequenceEqual<T>(this ImmutableArray<T> left, ImmutableArray<T> right, IEqualityComparer<T> comparer)
{
if (left.Length != right.Length)
{
return false;
}
for (int i = 0; i < left.Length; i++)
{
if (!comparer.Equals(left[i], right[i]))
{
return false;
}
}
return true;
}
}
@@ -0,0 +1,143 @@
using System;
using System.Collections.Generic;
using Microsoft.CodeAnalysis;
namespace ComputeSharp.D2D1Interop.SourceGenerators.Extensions;
/// <summary>
/// Extension methods for <see cref="IncrementalValuesProvider{TValues}"/>.
/// </summary>
internal static class IncrementalValuesProviderExtensions
{
/// <summary>
/// Creates a new <see cref="IncrementalValuesProvider{TValues}"/> instance with a gven pair of comparers.
/// </summary>
/// <typeparam name="TLeft">The type of left items in each tuple.</typeparam>
/// <typeparam name="TRight">The type of right items in each tuple.</typeparam>
/// <param name="source">The input <see cref="IncrementalValuesProvider{TValues}"/> instance.</param>
/// <param name="comparerLeft">An <see cref="IEqualityComparer{T}"/> instance for <typeparamref name="TLeft"/> items.</param>
/// <param name="comparerRight">An <see cref="IEqualityComparer{T}"/> instance for <typeparamref name="TRight"/> items.</param>
/// <returns>An <see cref="IncrementalValuesProvider{TValues}"/> with the specified comparers applied to each item.</returns>
public static IncrementalValuesProvider<(TLeft Left, TRight Right)> WithComparers<TLeft, TRight>(
this IncrementalValuesProvider<(TLeft Left, TRight Right)> source,
IEqualityComparer<TLeft> comparerLeft,
IEqualityComparer<TRight> comparerRight)
{
return source.WithComparer(new Comparer<TLeft, TRight>(comparerLeft, comparerRight));
}
/// <summary>
/// Creates a new <see cref="IncrementalValuesProvider{TValues}"/> instance with a gven pair of comparers.
/// </summary>
/// <typeparam name="T1">The type of first items in each tuple.</typeparam>
/// <typeparam name="T2">The type of second items in each tuple.</typeparam>
/// <typeparam name="T3">The type of third items in each tuple.</typeparam>
/// <param name="source">The input <see cref="IncrementalValuesProvider{TValues}"/> instance.</param>
/// <param name="comparer1">An <see cref="IEqualityComparer{T}"/> instance for <typeparamref name="T1"/> items.</param>
/// <param name="comparer2">An <see cref="IEqualityComparer{T}"/> instance for <typeparamref name="T2"/> items.</param>
/// <param name="comparer3">An <see cref="IEqualityComparer{T}"/> instance for <typeparamref name="T3"/> items.</param>
/// <returns>An <see cref="IncrementalValuesProvider{TValues}"/> with the specified comparers applied to each item.</returns>
public static IncrementalValuesProvider<(T1, T2, T3)> WithComparers<T1, T2, T3>(
this IncrementalValuesProvider<(T1, T2, T3)> source,
IEqualityComparer<T1> comparer1,
IEqualityComparer<T2> comparer2,
IEqualityComparer<T3> comparer3)
{
return source.WithComparer(new Comparer<T1, T2, T3>(comparer1, comparer2, comparer3));
}
/// <summary>
/// An <see cref="IEqualityComparer{T}"/> implementation for a value tuple.
/// </summary>
public sealed class Comparer<TLeft, TRight> : IEqualityComparer<(TLeft Left, TRight Right)>
{
/// <summary>
/// The <typeparamref name="TLeft"/> comparer.
/// </summary>
private readonly IEqualityComparer<TLeft> comparerLeft;
/// <summary>
/// The <typeparamref name="TRight"/> comparer.
/// </summary>
private readonly IEqualityComparer<TRight> comparerRight;
/// <summary>
/// Creates a new <see cref="Comparer{TLeft, TRight}"/> instance with the specified parameters.
/// </summary>
/// <param name="comparerLeft">The <typeparamref name="TLeft"/> comparer.</param>
/// <param name="comparerRight">The <typeparamref name="TRight"/> comparer.</param>
public Comparer(IEqualityComparer<TLeft> comparerLeft, IEqualityComparer<TRight> comparerRight)
{
this.comparerLeft = comparerLeft;
this.comparerRight = comparerRight;
}
/// <inheritdoc/>
public bool Equals((TLeft Left, TRight Right) x, (TLeft Left, TRight Right) y)
{
return
this.comparerLeft.Equals(x.Left, y.Left) &&
this.comparerRight.Equals(x.Right, y.Right);
}
/// <inheritdoc/>
public int GetHashCode((TLeft Left, TRight Right) obj)
{
return HashCode.Combine(
this.comparerLeft.GetHashCode(obj.Left),
this.comparerRight.GetHashCode(obj.Right));
}
}
/// <summary>
/// An <see cref="IEqualityComparer{T}"/> implementation for a value tuple.
/// </summary>
public sealed class Comparer<T1, T2, T3> : IEqualityComparer<(T1, T2, T3)>
{
/// <summary>
/// The <typeparamref name="T1"/> comparer.
/// </summary>
private readonly IEqualityComparer<T1> comparer1;
/// <summary>
/// The <typeparamref name="T2"/> comparer.
/// </summary>
private readonly IEqualityComparer<T2> comparer2;
/// <summary>
/// The <typeparamref name="T3"/> comparer.
/// </summary>
private readonly IEqualityComparer<T3> comparer3;
/// <summary>
/// Creates a new <see cref="Comparer{T1, T2, T3}"/> instance with the specified parameters.
/// </summary>
/// <param name="comparer1">The <typeparamref name="T1"/> comparer.</param>
/// <param name="comparer2">The <typeparamref name="T2"/> comparer.</param>
/// <param name="comparer3">The <typeparamref name="T3"/> comparer.</param>
public Comparer(IEqualityComparer<T1> comparer1, IEqualityComparer<T2> comparer2, IEqualityComparer<T3> comparer3)
{
this.comparer1 = comparer1;
this.comparer2 = comparer2;
this.comparer3 = comparer3;
}
/// <inheritdoc/>
public bool Equals((T1, T2, T3) x, (T1, T2, T3) y)
{
return
this.comparer1.Equals(x.Item1, y.Item1) &&
this.comparer2.Equals(x.Item2, y.Item2) &&
this.comparer3.Equals(x.Item3, y.Item3);
}
/// <inheritdoc/>
public int GetHashCode((T1, T2, T3) obj)
{
return HashCode.Combine(
this.comparer1.GetHashCode(obj.Item1),
this.comparer2.GetHashCode(obj.Item2),
this.comparer3.GetHashCode(obj.Item3));
}
}
}
+18
ファイルの表示
@@ -0,0 +1,18 @@
namespace ComputeSharp.D2D1Interop.SourceGenerators.Extensions;
/// <summary>
/// Extension methods for <see cref="string"/> types.
/// </summary>
internal static class StringExtensions
{
/// <summary>
/// Converts a given <see cref="string"/> instance to a valid HLSL identifier name.
/// </summary>
/// <param name="text">The input <see cref="string"/> instance to convert.</param>
/// <returns>An valid HLSL identifier name from <paramref name="text"/>.</returns>
public static string ToHlslIdentifierName(this string text)
{
return text.Replace('.', '_').Replace('+', '_');
}
}
+198
ファイルの表示
@@ -0,0 +1,198 @@
using System.Collections.Generic;
using System.Linq;
using ComputeSharp.D2D1Interop.SourceGenerators.Mappings;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
namespace ComputeSharp.D2D1Interop.SourceGenerators.Extensions;
/// <summary>
/// A <see langword="class"/> with some extension methods for C# syntax nodes.
/// </summary>
internal static class SyntaxNodeExtensions
{
/// <summary>
/// Checks a <see cref="SyntaxNode"/> value and replaces the value type to be HLSL compatible, if needed.
/// </summary>
/// <typeparam name="TRoot">The type of the input <see cref="TypeSyntax"/> instance.</typeparam>
/// <param name="node">The input <see cref="SyntaxNode"/> to check and modify if needed.</param>
/// <param name="sourceType">The source <see cref="SyntaxNode"/> to use to get type into from <paramref name="semanticModel"/>.</param>
/// <param name="semanticModel">The <see cref="SemanticModel"/> instance with info on the input tree.</param>
/// <param name="discoveredTypes">The collection of currently discovered types.</param>
/// <returns>A <see cref="SyntaxNode"/> instance that represents a type compatible with HLSL.</returns>
public static TRoot ReplaceAndTrackType<TRoot>(this TRoot node, SyntaxNode sourceType, SemanticModel semanticModel, ICollection<INamedTypeSymbol> discoveredTypes)
where TRoot : TypeSyntax
{
return node.ReplaceAndTrackType(node, sourceType, semanticModel, discoveredTypes);
}
/// <summary>
/// Checks a <see cref="SyntaxNode"/> value and replaces the value type to be HLSL compatible, if needed.
/// </summary>
/// <typeparam name="TRoot">The type of the input <see cref="SyntaxNode"/> instance.</typeparam>
/// <param name="node">The input <see cref="SyntaxNode"/> to check and modify if needed.</param>
/// <param name="targetType">The target <see cref="TypeSyntax"/> node to replace.</param>
/// <param name="sourceType">The source <see cref="SyntaxNode"/> to use to get type into from <paramref name="semanticModel"/>.</param>
/// <param name="semanticModel">The <see cref="SemanticModel"/> instance with info on the input tree.</param>
/// <param name="discoveredTypes">The collection of currently discovered types.</param>
/// <returns>A <see cref="SyntaxNode"/> instance that represents a type compatible with HLSL.</returns>
public static TRoot ReplaceAndTrackType<TRoot>(this TRoot node, TypeSyntax targetType, SyntaxNode sourceType, SemanticModel semanticModel, ICollection<INamedTypeSymbol> discoveredTypes)
where TRoot : SyntaxNode
{
// Skip immediately for function pointers
if (sourceType is FunctionPointerTypeSyntax)
{
return node.ReplaceNode(targetType, ParseTypeName("void*"));
}
// Handle the various possible type kinds
ITypeSymbol typeSymbol = sourceType switch
{
RefTypeSyntax refType => semanticModel.GetTypeInfo(refType.Type).Type!,
PointerTypeSyntax pointerType => semanticModel.GetTypeInfo(pointerType.ElementType).Type!,
_ => semanticModel.GetTypeInfo(sourceType).Type!
};
// Do nothing if the type is just void
if (typeSymbol.SpecialType == SpecialType.System_Void)
{
return node;
}
string typeName = typeSymbol.ToDisplayString(ISymbolExtensions.FullyQualifiedWithoutGlobalFormat);
discoveredTypes.Add((INamedTypeSymbol)typeSymbol);
if (HlslKnownTypes.TryGetMappedName(typeName, out string? mappedName))
{
TypeSyntax newType = ParseTypeName(mappedName!);
return node.ReplaceNode(targetType, newType);
}
return node.ReplaceNode(targetType, ParseTypeName(typeName.ToHlslIdentifierName()));
}
/// <summary>
/// Tracks the associated type for a <see cref="SyntaxNode"/> value and returns the HLSL compatible <see cref="TypeSyntax"/>.
/// </summary>
/// <param name="node">The input <see cref="SyntaxNode"/> to check.</param>
/// <param name="semanticModel">The <see cref="SemanticModel"/> instance with info on the input tree.</param>
/// <param name="discoveredTypes">The collection of currently discovered types.</param>
/// <returns>A <see cref="SyntaxNode"/> instance that represents a type compatible with HLSL.</returns>
public static TypeSyntax TrackType(this SyntaxNode node, SemanticModel semanticModel, ICollection<INamedTypeSymbol> discoveredTypes)
{
ITypeSymbol typeSymbol = semanticModel.GetTypeInfo(node).Type!;
string typeName = typeSymbol.ToDisplayString(ISymbolExtensions.FullyQualifiedWithoutGlobalFormat);
discoveredTypes.Add((INamedTypeSymbol)typeSymbol);
if (HlslKnownTypes.TryGetMappedName(typeName, out string? mappedName))
{
return ParseTypeName(mappedName!);
}
return ParseTypeName(typeName.ToHlslIdentifierName());
}
/// <summary>
/// Returns a <see cref="MethodDeclarationSyntax"/> with a block body.
/// </summary>
/// <param name="node">The input <see cref="MethodDeclarationSyntax"/> node.</param>
/// <returns>A node like the one in input, but always with a block body.</returns>
public static MethodDeclarationSyntax WithBlockBody(this MethodDeclarationSyntax node)
{
if (node.ExpressionBody is ArrowExpressionClauseSyntax arrow)
{
StatementSyntax statement = node.ReturnType switch
{
PredefinedTypeSyntax pts when pts.Keyword.IsKind(SyntaxKind.VoidKeyword) => ExpressionStatement(arrow.Expression),
_ => ReturnStatement(arrow.Expression)
};
return node
.WithBody(Block(statement))
.WithExpressionBody(null)
.WithSemicolonToken(MissingToken(SyntaxKind.SemicolonToken));
}
return node;
}
/// <summary>
/// Returns a <see cref="MethodDeclarationSyntax"/> as a method definition.
/// </summary>
/// <param name="node">The input <see cref="MethodDeclarationSyntax"/> node.</param>
/// <returns>A node like the one in input, but just as a definition.</returns>
public static MethodDeclarationSyntax AsDefinition(this MethodDeclarationSyntax node)
{
if (node.ExpressionBody is ArrowExpressionClauseSyntax)
{
return node.WithExpressionBody(null).WithSemicolonToken(Token(SyntaxKind.SemicolonToken));
}
return node.WithBody(null).WithSemicolonToken(Token(SyntaxKind.SemicolonToken));
}
/// <summary>
/// Returns a <see cref="LocalFunctionStatementSyntax"/> with a block body.
/// </summary>
/// <param name="node">The input <see cref="LocalFunctionStatementSyntax"/> node.</param>
/// <returns>A node like the one in input, but always with a block body.</returns>
/// <remarks>
/// This method is the same as <see cref="WithBlockBody(MethodDeclarationSyntax)"/>, but it is necessary to
/// duplicate the code because the two types don't have a common base type or interface that can be leveraged.
/// </remarks>
public static LocalFunctionStatementSyntax WithBlockBody(this LocalFunctionStatementSyntax node)
{
if (node.ExpressionBody is ArrowExpressionClauseSyntax arrow)
{
StatementSyntax statement = node.ReturnType switch
{
PredefinedTypeSyntax pts when pts.Keyword.IsKind(SyntaxKind.VoidKeyword) => ExpressionStatement(arrow.Expression),
_ => ReturnStatement(arrow.Expression)
};
return node
.WithBody(Block(statement))
.WithExpressionBody(null)
.WithSemicolonToken(MissingToken(SyntaxKind.SemicolonToken));
}
return node;
}
/// <summary>
/// Returns a <see cref="LocalFunctionStatementSyntax"/> as a method definition.
/// </summary>
/// <param name="node">The input <see cref="LocalFunctionStatementSyntax"/> node.</param>
/// <returns>A node like the one in input, but just as a definition.</returns>
public static LocalFunctionStatementSyntax AsDefinition(this LocalFunctionStatementSyntax node)
{
if (node.ExpressionBody is ArrowExpressionClauseSyntax)
{
return node.WithExpressionBody(null).WithSemicolonToken(Token(SyntaxKind.SemicolonToken));
}
return node.WithBody(null).WithSemicolonToken(Token(SyntaxKind.SemicolonToken));
}
/// <summary>
/// Returns a <see cref="MethodDeclarationSyntax"/> instance with no accessibility modifiers.
/// </summary>
/// <param name="node">The input <see cref="MethodDeclarationSyntax"/> node.</param>
/// <returns>A node just like <paramref name="node"/> but with no accessibility modifiers.</returns>
public static MethodDeclarationSyntax WithoutAccessibilityModifiers(this MethodDeclarationSyntax node)
{
return node.WithModifiers(TokenList(node.Modifiers.Where(static modifier => modifier.Kind() switch
{
SyntaxKind.PublicKeyword => false,
SyntaxKind.PrivateKeyword => false,
SyntaxKind.ProtectedKeyword => false,
SyntaxKind.InternalKeyword => false,
_ => true
}).ToArray()));
}
}
+47
ファイルの表示
@@ -0,0 +1,47 @@
using System.Collections.Generic;
using Microsoft.CodeAnalysis;
namespace ComputeSharp.D2D1Interop.SourceGenerators.Helpers;
/// <summary>
/// A type providing <see cref="SemanticModel"/> instances for nodes.
/// </summary>
internal sealed class SemanticModelProvider
{
/// <summary>
/// The source <see cref="Compilation"/> instance.
/// </summary>
private readonly Compilation compilation;
/// <summary>
/// The map of loaded <see cref="SemanticModel"/> instances.
/// </summary>
private readonly Dictionary<SyntaxTree, SemanticModel> semanticModelsMap;
/// <summary>
/// Creates a new <see cref="SemanticModelProvider"/> instance with the specified parameters.
/// </summary>
/// <param name="compilation">The source <see cref="Compilation"/> instance.</param>
public SemanticModelProvider(Compilation compilation)
{
this.compilation = compilation;
this.semanticModelsMap = new Dictionary<SyntaxTree, SemanticModel>();
}
/// <summary>
/// Gets a <see cref="SemanticModel"/> instance with info on a given <see cref="SyntaxNode"/>.
/// </summary>
/// <param name="syntaxNode">The input <see cref="SyntaxNode"/> to get info for.</param>
/// <returns>A <see cref="SemanticModel"/> instance containing info on <paramref name="syntaxNode"/>.</returns>
public SemanticModel For(SyntaxNode syntaxNode)
{
if (!this.semanticModelsMap.TryGetValue(syntaxNode.SyntaxTree, out SemanticModel semanticModel))
{
semanticModel = this.compilation.GetSemanticModel(syntaxNode.SyntaxTree);
this.semanticModelsMap.Add(syntaxNode.SyntaxTree, semanticModel);
}
return semanticModel;
}
}
+133
ファイルの表示
@@ -0,0 +1,133 @@
using System.Collections.Generic;
using ComputeSharp.D2D1Interop.__Internals;
using ComputeSharp.D2D1Interop.SourceGenerators.Models;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
#pragma warning disable CS0618
namespace ComputeSharp.D2D1Interop.SourceGenerators;
/// <inheritdoc/>
public sealed partial class ID2D1ShaderGenerator
{
/// <summary>
/// Gets the shader type for a given shader, if any.
/// </summary>
/// <param name="typeSymbol">The input <see cref="INamedTypeSymbol"/> instance to check.</param>
/// <param name="d2D1ShaderSymbol">The <see cref="INamedTypeSymbol"/> instance for <see cref="ID2D1Shader"/>.</param>
/// <returns>Whether or not <paramref name="typeSymbol"/> implements <paramref name="d2D1ShaderSymbol"/>.</returns>
private static bool IsD2D1ShaderType(INamedTypeSymbol typeSymbol, INamedTypeSymbol d2D1ShaderSymbol)
{
foreach (INamedTypeSymbol interfaceSymbol in typeSymbol.Interfaces)
{
if (interfaceSymbol.Name == nameof(ID2D1Shader) &&
SymbolEqualityComparer.Default.Equals(interfaceSymbol, d2D1ShaderSymbol))
{
return true;
}
}
return false;
}
/// <summary>
/// Creates a <see cref="CompilationUnitSyntax"/> instance wrapping the given method.
/// </summary>
/// <param name="hierarchyInfo">The <see cref="HierarchyInfo"/> instance for the current type.</param>
/// <param name="methodDeclaration">The <see cref="MethodDeclarationSyntax"/> item to insert.</param>
/// <param name="canUseSkipLocalsInit">Whether <c>[SkipLocalsInit]</c> can be used.</param>
/// <returns>A <see cref="CompilationUnitSyntax"/> object wrapping <paramref name="methodDeclaration"/>.</returns>
private static CompilationUnitSyntax GetCompilationUnitFromMethod(
HierarchyInfo hierarchyInfo,
MethodDeclarationSyntax methodDeclaration,
bool canUseSkipLocalsInit)
{
// Method attributes
List<AttributeListSyntax> attributes = new()
{
AttributeList(SingletonSeparatedList(
Attribute(IdentifierName("global::System.CodeDom.Compiler.GeneratedCode")).AddArgumentListArguments(
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(ID2D1ShaderGenerator).FullName))),
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(ID2D1ShaderGenerator).Assembly.GetName().Version.ToString())))))),
AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Diagnostics.DebuggerNonUserCode")))),
AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage")))),
AttributeList(SingletonSeparatedList(
Attribute(IdentifierName("global::System.ComponentModel.EditorBrowsable")).AddArgumentListArguments(
AttributeArgument(ParseExpression("global::System.ComponentModel.EditorBrowsableState.Never"))))),
AttributeList(SingletonSeparatedList(
Attribute(IdentifierName("global::System.Obsolete")).AddArgumentListArguments(
AttributeArgument(LiteralExpression(
SyntaxKind.StringLiteralExpression,
Literal("This method is not intended to be used directly by user code"))))))
};
// Add [SkipLocalsInit] if the target project allows it
if (canUseSkipLocalsInit)
{
attributes.Add(AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Runtime.CompilerServices.SkipLocalsInit")))));
}
// Create the partial shader type declaration with the given method implementation.
// This code produces a struct declaration as follows:
//
// partial struct <SHADER_TYPE>
// {
// <METHOD>
// }
StructDeclarationSyntax structDeclarationSyntax =
StructDeclaration(hierarchyInfo.Names[0])
.AddModifiers(Token(SyntaxKind.PartialKeyword))
.AddMembers(methodDeclaration.AddAttributeLists(attributes.ToArray()));
TypeDeclarationSyntax typeDeclarationSyntax = structDeclarationSyntax;
// Add all parent types in ascending order, if any
foreach (string parentType in hierarchyInfo.Names.AsSpan().Slice(1))
{
typeDeclarationSyntax =
ClassDeclaration(parentType)
.AddModifiers(Token(SyntaxKind.PartialKeyword))
.AddMembers(typeDeclarationSyntax);
}
if (hierarchyInfo.Namespace is "")
{
// If there is no namespace, attach the pragma directly to the declared type,
// and skip the namespace declaration. This is the same additional path also
// used when generating custom constructors. This will produce code as follows:
//
// #pragma warning disable
//
// <TYPE_HIERARCHY>
return
CompilationUnit().AddMembers(
typeDeclarationSyntax
.WithModifiers(TokenList(Token(
TriviaList(Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))),
SyntaxKind.PartialKeyword,
TriviaList()))))
.NormalizeWhitespace(eol: "\n");
}
// Create the compilation unit with disabled warnings, target namespace and generated type.
// This will produce code as follows:
//
// #pragma warning disable
//
// namespace <NAMESPACE>;
//
// <TYPE_HIERARCHY>
return
CompilationUnit().AddMembers(
FileScopedNamespaceDeclaration(IdentifierName(hierarchyInfo.Namespace))
.AddMembers(typeDeclarationSyntax)
.WithNamespaceKeyword(Token(TriviaList(
Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))),
SyntaxKind.NamespaceKeyword,
TriviaList())))
.NormalizeWhitespace(eol: "\n");
}
}
+16
ファイルの表示
@@ -0,0 +1,16 @@
using Microsoft.CodeAnalysis;
namespace ComputeSharp.D2D1Interop.SourceGenerators;
/// <summary>
/// A source generator creating data loaders for the <see cref="ID2D1PixelShader"/> type.
/// </summary>
[Generator]
public sealed partial class IShaderGenerator : IIncrementalGenerator
{
/// <inheritdoc/>
public void Initialize(IncrementalGeneratorInitializationContext context)
{
}
}
+71
ファイルの表示
@@ -0,0 +1,71 @@
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using ComputeSharp.Core.Intrinsics.Attributes;
namespace ComputeSharp.D2D1Interop.SourceGenerators.Mappings;
/// <summary>
/// A <see langword="class"/> that contains and maps known HLSL identifier names valid HLSL names.
/// </summary>
internal static class HlslKnownKeywords
{
/// <summary>
/// The mapping of known HLSL keywords.
/// </summary>
private static readonly IReadOnlyCollection<string> KnownKeywords = BuildKnownKeywordsMap();
/// <summary>
/// Builds the mapping of all known HLSL keywords.
/// </summary>
private static IReadOnlyCollection<string> BuildKnownKeywordsMap()
{
// HLSL keywords
HashSet<string> knownKeywords = new(new[]
{
"asm", "asm_fragment", "cbuffer", "centroid", "column_major",
"compile", "discard", "dword", "export", "fxgroup", "groupshared",
"half", "inline", "inout", "line", "lineadj", "linear", "matrix",
"nointerpolation", "noperspective", "NULL", "packoffset", "pass",
"pixelfragment", "point", "precise", "register", "row_major", "sample",
"sampler", "shared", "snorm", "stateblock", "stateblock_state", "tbuffer",
"technique", "typedef", "triangle", "triangleadj", "uniform", "unorm",
"unsigned", "vector", "vertexfragment", "zero"
});
// HLSL intrinsics method names
foreach (var method in typeof(Hlsl).GetMethods(BindingFlags.Public | BindingFlags.Static))
{
string name = method.GetCustomAttribute<HlslIntrinsicNameAttribute>()?.Name ?? method.Name;
knownKeywords.Add(name);
}
// D2D1 intrinsics method names
foreach (var method in typeof(D2D1).GetMethods(BindingFlags.Public | BindingFlags.Static))
{
string name = method.GetCustomAttribute<HlslIntrinsicNameAttribute>()?.Name ?? method.Name;
knownKeywords.Add(name);
}
return knownKeywords;
}
/// <summary>
/// Tries to get the mapped HLSL-compatible identifier name for the input identifier name.
/// </summary>
/// <param name="name">The input identifier name.</param>
/// <param name="mapped">The mapped identifier name, if a replacement is needed.</param>
/// <returns>The HLSL-compatible identifier name that can be used in an HLSL shader.</returns>
public static bool TryGetMappedName(string name, out string? mapped)
{
mapped = KnownKeywords.Contains(name) switch
{
true => $"__reserved__{name}",
false => null
};
return mapped is not null;
}
}
+233
ファイルの表示
@@ -0,0 +1,233 @@
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Numerics;
using System.Reflection;
using System.Text.RegularExpressions;
namespace ComputeSharp.D2D1Interop.SourceGenerators.Mappings;
/// <summary>
/// A <see langword="class"/> that contains and maps known HLSL member names to common .NET members.
/// </summary>
internal static class HlslKnownMembers
{
/// <summary>
/// The mapping of supported known members to HLSL names.
/// </summary>
private static readonly IReadOnlyDictionary<string, string> KnownMembers = BuildKnownMembersMap();
/// <summary>
/// Builds the mapping of supported known members to HLSL names.
/// </summary>
private static IReadOnlyDictionary<string, string> BuildKnownMembersMap()
{
Dictionary<string, string> knownMembers = new()
{
[$"{typeof(Vector2).FullName}.{nameof(Vector2.X)}"] = "x",
[$"{typeof(Vector2).FullName}.{nameof(Vector2.Y)}"] = "y",
[$"{typeof(Vector2).FullName}.{nameof(Vector2.Zero)}"] = "(float2)0",
[$"{typeof(Vector2).FullName}.{nameof(Vector2.One)}"] = "float2(1.0f, 1.0f)",
[$"{typeof(Vector2).FullName}.{nameof(Vector2.UnitX)}"] = "float2(1.0f, 0.0f)",
[$"{typeof(Vector2).FullName}.{nameof(Vector2.UnitY)}"] = "float2(0.0f, 1.0f)",
[$"{typeof(Vector3).FullName}.{nameof(Vector3.X)}"] = "x",
[$"{typeof(Vector3).FullName}.{nameof(Vector3.Y)}"] = "y",
[$"{typeof(Vector3).FullName}.{nameof(Vector3.Z)}"] = "z",
[$"{typeof(Vector3).FullName}.{nameof(Vector3.Zero)}"] = "(float3)0",
[$"{typeof(Vector3).FullName}.{nameof(Vector3.One)}"] = "float3(1.0f, 1.0f, 1.0f)",
[$"{typeof(Vector3).FullName}.{nameof(Vector3.UnitX)}"] = "float3(1.0f, 0.0f, 0.0f)",
[$"{typeof(Vector3).FullName}.{nameof(Vector3.UnitY)}"] = "float3(0.0f, 1.0f, 0.0f)",
[$"{typeof(Vector3).FullName}.{nameof(Vector3.UnitZ)}"] = "float3(0.0f, 0.0f, 1.0f)",
[$"{typeof(Vector4).FullName}.{nameof(Vector4.X)}"] = "x",
[$"{typeof(Vector4).FullName}.{nameof(Vector4.Y)}"] = "y",
[$"{typeof(Vector4).FullName}.{nameof(Vector4.Z)}"] = "z",
[$"{typeof(Vector4).FullName}.{nameof(Vector4.W)}"] = "w",
[$"{typeof(Vector4).FullName}.{nameof(Vector4.Zero)}"] = "(float4)0",
[$"{typeof(Vector4).FullName}.{nameof(Vector4.One)}"] = "float4(1.0f, 1.0f, 1.0f, 1.0f)",
[$"{typeof(Bool2).FullName}.{nameof(Bool2.False)}"] = "(bool2)0",
[$"{typeof(Bool2).FullName}.{nameof(Bool2.True)}"] = "bool2(true, true)",
[$"{typeof(Bool2).FullName}.{nameof(Bool2.TrueX)}"] = "bool2(true, false)",
[$"{typeof(Bool2).FullName}.{nameof(Bool2.TrueY)}"] = "bool2(false, true)",
[$"{typeof(Bool3).FullName}.{nameof(Bool3.False)}"] = "(bool3)0",
[$"{typeof(Bool3).FullName}.{nameof(Bool3.True)}"] = "bool3(true, true, true)",
[$"{typeof(Bool3).FullName}.{nameof(Bool3.TrueX)}"] = "bool3(true, false, false)",
[$"{typeof(Bool3).FullName}.{nameof(Bool3.TrueY)}"] = "bool3(false, true, false)",
[$"{typeof(Bool3).FullName}.{nameof(Bool3.TrueZ)}"] = "bool3(false, false, true)",
[$"{typeof(Bool4).FullName}.{nameof(Bool4.False)}"] = "(bool4)0",
[$"{typeof(Bool4).FullName}.{nameof(Bool4.True)}"] = "bool4(true, true, true, true)",
[$"{typeof(Bool4).FullName}.{nameof(Bool4.TrueX)}"] = "bool4(true, false, false, false)",
[$"{typeof(Bool4).FullName}.{nameof(Bool4.TrueY)}"] = "bool4(false, true, false, false)",
[$"{typeof(Bool4).FullName}.{nameof(Bool4.TrueZ)}"] = "bool4(false, false, true, false)",
[$"{typeof(Bool4).FullName}.{nameof(Bool4.TrueW)}"] = "bool4(false, false, false, true)",
[$"{typeof(Int2).FullName}.{nameof(Int2.Zero)}"] = "(int2)0",
[$"{typeof(Int2).FullName}.{nameof(Int2.One)}"] = "int2(1, 1)",
[$"{typeof(Int2).FullName}.{nameof(Int2.UnitX)}"] = "int2(1, 0)",
[$"{typeof(Int2).FullName}.{nameof(Int2.UnitY)}"] = "int2(0, 1)",
[$"{typeof(Int3).FullName}.{nameof(Int3.Zero)}"] = "(int3)0",
[$"{typeof(Int3).FullName}.{nameof(Int3.One)}"] = "int3(1, 1, 1)",
[$"{typeof(Int3).FullName}.{nameof(Int3.UnitX)}"] = "int3(1, 0, 0)",
[$"{typeof(Int3).FullName}.{nameof(Int3.UnitY)}"] = "int3(0, 1, 0)",
[$"{typeof(Int3).FullName}.{nameof(Int3.UnitZ)}"] = "int3(0, 0, 1)",
[$"{typeof(Int4).FullName}.{nameof(Int4.Zero)}"] = "(int4)0",
[$"{typeof(Int4).FullName}.{nameof(Int4.One)}"] = "int4(1, 1, 1, 1)",
[$"{typeof(Int4).FullName}.{nameof(Int4.UnitX)}"] = "int4(1, 0, 0, 0)",
[$"{typeof(Int4).FullName}.{nameof(Int4.UnitY)}"] = "int4(0, 1, 0, 0)",
[$"{typeof(Int4).FullName}.{nameof(Int4.UnitZ)}"] = "int4(0, 0, 1, 0)",
[$"{typeof(Int4).FullName}.{nameof(Int4.UnitW)}"] = "int4(0, 0, 0, 1)",
[$"{typeof(UInt2).FullName}.{nameof(UInt2.Zero)}"] = "(uint2)0",
[$"{typeof(UInt2).FullName}.{nameof(UInt2.One)}"] = "uint2(1u, 1u)",
[$"{typeof(UInt2).FullName}.{nameof(UInt2.UnitX)}"] = "uint2(1u, 0u)",
[$"{typeof(UInt2).FullName}.{nameof(UInt2.UnitY)}"] = "uint2(0u, 1u)",
[$"{typeof(UInt3).FullName}.{nameof(UInt3.Zero)}"] = "(uint3)0",
[$"{typeof(UInt3).FullName}.{nameof(UInt3.One)}"] = "uint3(1u, 1u, 1u)",
[$"{typeof(UInt3).FullName}.{nameof(UInt3.UnitX)}"] = "uint3(1u, 0u, 0u)",
[$"{typeof(UInt3).FullName}.{nameof(UInt3.UnitY)}"] = "uint3(0u, 1u, 0u)",
[$"{typeof(UInt3).FullName}.{nameof(UInt3.UnitZ)}"] = "uint3(0u, 0u, 1u)",
[$"{typeof(UInt4).FullName}.{nameof(UInt4.Zero)}"] = "(uint4)0",
[$"{typeof(UInt4).FullName}.{nameof(UInt4.One)}"] = "uint4(1u, 1u, 1u, 1u)",
[$"{typeof(UInt4).FullName}.{nameof(UInt4.UnitX)}"] = "uint4(1u, 0u, 0u, 0u)",
[$"{typeof(UInt4).FullName}.{nameof(UInt4.UnitY)}"] = "uint4(0u, 1u, 0u, 0u)",
[$"{typeof(UInt4).FullName}.{nameof(UInt4.UnitZ)}"] = "uint4(0u, 0u, 1u, 0u)",
[$"{typeof(UInt4).FullName}.{nameof(UInt4.UnitW)}"] = "uint4(0u, 0u, 0u, 1u)",
[$"{typeof(Float2).FullName}.{nameof(Float2.Zero)}"] = "(float2)0",
[$"{typeof(Float2).FullName}.{nameof(Float2.One)}"] = "float2(1.0f, 1.0f)",
[$"{typeof(Float2).FullName}.{nameof(Float2.UnitX)}"] = "float2(1.0f, 0.0f)",
[$"{typeof(Float2).FullName}.{nameof(Float2.UnitY)}"] = "float2(0.0f, 1.0f)",
[$"{typeof(Float3).FullName}.{nameof(Float3.Zero)}"] = "(float3)0",
[$"{typeof(Float3).FullName}.{nameof(Float3.One)}"] = "float3(1.0f, 1.0f, 1.0f)",
[$"{typeof(Float3).FullName}.{nameof(Float3.UnitX)}"] = "float3(1.0f, 0.0f, 0.0f)",
[$"{typeof(Float3).FullName}.{nameof(Float3.UnitY)}"] = "float3(0.0f, 1.0f, 0.0f)",
[$"{typeof(Float3).FullName}.{nameof(Float3.UnitZ)}"] = "float3(0.0f, 0.0f, 1.0f)",
[$"{typeof(Float4).FullName}.{nameof(Float4.Zero)}"] = "(float4)0",
[$"{typeof(Float4).FullName}.{nameof(Float4.One)}"] = "float4(1.0f, 1.0f, 1.0f, 1.0f)",
[$"{typeof(Float4).FullName}.{nameof(Float4.UnitX)}"] = "float4(1.0f, 0.0f, 0.0f, 0.0f)",
[$"{typeof(Float4).FullName}.{nameof(Float4.UnitY)}"] = "float4(0.0f, 1.0f, 0.0f, 0.0f)",
[$"{typeof(Float4).FullName}.{nameof(Float4.UnitZ)}"] = "float4(0.0f, 0.0f, 1.0f, 0.0f)",
[$"{typeof(Float4).FullName}.{nameof(Float4.UnitW)}"] = "float4(0.0f, 0.0f, 0.0f, 1.0f)",
[$"{typeof(Double2).FullName}.{nameof(Double2.Zero)}"] = "(double2)0",
[$"{typeof(Double2).FullName}.{nameof(Double2.One)}"] = "double2(1.0, 1.0)",
[$"{typeof(Double2).FullName}.{nameof(Double2.UnitX)}"] = "double2(1.0, 0.0)",
[$"{typeof(Double2).FullName}.{nameof(Double2.UnitY)}"] = "double2(0.0, 1.0)",
[$"{typeof(Double3).FullName}.{nameof(Double3.Zero)}"] = "(double3)0",
[$"{typeof(Double3).FullName}.{nameof(Double3.One)}"] = "double3(1.0, 1.0, 1.0)",
[$"{typeof(Double3).FullName}.{nameof(Double3.UnitX)}"] = "double3(1.0, 0.0, 0.0)",
[$"{typeof(Double3).FullName}.{nameof(Double3.UnitY)}"] = "double3(0.0, 1.0, 0.0)",
[$"{typeof(Double3).FullName}.{nameof(Double3.UnitZ)}"] = "double3(0.0, 0.0, 1.0)",
[$"{typeof(Double4).FullName}.{nameof(Double4.Zero)}"] = "(double4)0",
[$"{typeof(Double4).FullName}.{nameof(Double4.One)}"] = "double4(1.0, 1.0, 1.0, 1.0)",
[$"{typeof(Double4).FullName}.{nameof(Double4.UnitX)}"] = "double4(1.0, 0.0, 0.0, 0.0)",
[$"{typeof(Double4).FullName}.{nameof(Double4.UnitY)}"] = "double4(0.0, 1.0, 0.0, 0.0)",
[$"{typeof(Double4).FullName}.{nameof(Double4.UnitZ)}"] = "double4(0.0, 0.0, 1.0, 0.0)",
[$"{typeof(Double4).FullName}.{nameof(Double4.UnitW)}"] = "double4(0.0, 0.0, 0.0, 1.0)"
};
// Programmatically load mappings for the instance members of the HLSL vector types
foreach (var item in
from type in HlslKnownTypes.KnownVectorTypes
from property in type.GetProperties(BindingFlags.Instance | BindingFlags.Public)
select (Type: type, Property: property))
{
knownMembers.Add($"{item.Type.FullName}{Type.Delimiter}{item.Property.Name}", $"{item.Property.Name.ToLower()}");
}
// Load mappings for the matrix properties as well
foreach (var item in
from type in HlslKnownTypes.KnownMatrixTypes
from property in type.GetProperties(BindingFlags.Instance | BindingFlags.Public)
where Regex.IsMatch(property.Name, "^M[1-4]{2}$")
select (Type: type, Property: property))
{
char row = (char)(item.Property.Name[1] - 1);
char column = (char)(item.Property.Name[2] - 1);
knownMembers.Add($"{item.Type.FullName}{Type.Delimiter}{item.Property.Name}", $"_m{row}{column}");
}
return knownMembers;
}
/// <summary>
/// The mapping of supported known members to HLSL names.
/// </summary>
private static readonly IReadOnlyCollection<string> KnownMatrixIndexers = BuildKnownMatrixIndexers();
/// <summary>
/// Builds the mapping of swizzled matrix indexer properties.
/// </summary>
private static IReadOnlyCollection<string> BuildKnownMatrixIndexers()
{
return (
from type in Assembly.GetExecutingAssembly().ExportedTypes
where Regex.IsMatch(type.FullName, @"ComputeSharp\.(Bool|Double|Float|Int|UInt)[1-4]x[1-4]")
from property in type.GetProperties()
let indices = property.GetIndexParameters()
where indices.Length > 0 &&
indices.All(static index => index.ParameterType == typeof(MatrixIndex))
let metadataName = $"{type.FullName}.this[{string.Join(", ", indices.Select(index => index.ParameterType))}]"
select metadataName).ToImmutableHashSet();
}
/// <summary>
/// The mapping of supported known members to HLSL names.
/// </summary>
private static readonly IReadOnlyCollection<string> KnownMatrixIndices = BuildKnownMatrixIndices();
/// <summary>
/// Builds the mapping of swizzled matrix indices.
/// </summary>
private static IReadOnlyCollection<string> BuildKnownMatrixIndices()
{
return (
from name in Enum.GetNames(typeof(MatrixIndex))
select $"{typeof(MatrixIndex).FullName}.{name}").ToImmutableHashSet();
}
/// <summary>
/// Checks whether or not a given property fullname matches a matrix swizzled indexer.
/// </summary>
/// <param name="name">The input fully qualified member name.</param>
/// <returns>Whether or not <paramref name="name"/> is a matrix swizzled indexer.</returns>
public static bool IsKnownMatrixIndexer(string name)
{
return KnownMatrixIndexers.Contains(name);
}
/// <summary>
/// Checks whether or not a given property fullname matches a matrix swizzled index.
/// </summary>
/// <param name="name">The input fully qualified member name.</param>
/// <returns>Whether or not <paramref name="name"/> is a matrix swizzled index.</returns>
public static bool IsKnownMatrixIndex(string name)
{
return KnownMatrixIndices.Contains(name);
}
/// <summary>
/// Tries to get the mapped HLSL-compatible member name for the input member name.
/// </summary>
/// <param name="name">The input fully qualified member name.</param>
/// <param name="mapped">The mapped name, if one is found.</param>
/// <returns>The HLSL-compatible member name that can be used in an HLSL shader.</returns>
public static bool TryGetMappedName(string name, out string? mapped)
{
return KnownMembers.TryGetValue(name, out mapped);
}
}
+165
ファイルの表示
@@ -0,0 +1,165 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using System.Reflection;
using ComputeSharp.Core.Intrinsics.Attributes;
namespace ComputeSharp.D2D1Interop.SourceGenerators.Mappings;
/// <summary>
/// A <see langword="class"/> that contains and maps known HLSL method names to common .NET methods.
/// </summary>
internal static class HlslKnownMethods
{
/// <summary>
/// The mapping of supported known methods to HLSL names.
/// </summary>
private static readonly IReadOnlyDictionary<string, string> KnownMethods = BuildKnownMethodsMap();
/// <summary>
/// Builds the mapping of supported known methods to HLSL names.
/// </summary>
private static IReadOnlyDictionary<string, string> BuildKnownMethodsMap()
{
Dictionary<string, string> knownMethods = new()
{
[$"{typeof(Math).FullName}.{nameof(Math.Abs)}"] = "abs",
[$"{typeof(Math).FullName}.{nameof(Math.Max)}"] = "max",
[$"{typeof(Math).FullName}.{nameof(Math.Min)}"] = "min",
[$"{typeof(Math).FullName}.{nameof(Math.Pow)}"] = "pow",
[$"{typeof(Math).FullName}.{nameof(Math.Sin)}"] = "sin",
[$"{typeof(Math).FullName}.{nameof(Math.Sinh)}"] = "sinh",
[$"{typeof(Math).FullName}.{nameof(Math.Asin)}"] = "asin",
[$"{typeof(Math).FullName}.{nameof(Math.Cos)}"] = "cos",
[$"{typeof(Math).FullName}.{nameof(Math.Cosh)}"] = "cosh",
[$"{typeof(Math).FullName}.{nameof(Math.Acos)}"] = "acos",
[$"{typeof(Math).FullName}.{nameof(Math.Tan)}"] = "tan",
[$"{typeof(Math).FullName}.{nameof(Math.Tanh)}"] = "tanh",
[$"{typeof(Math).FullName}.{nameof(Math.Atan)}"] = "atan",
[$"{typeof(Math).FullName}.{nameof(Math.Atan2)}"] = "atan2",
[$"{typeof(Math).FullName}.{nameof(Math.Ceiling)}"] = "ceil",
[$"{typeof(Math).FullName}.{nameof(Math.Floor)}"] = "floor",
[$"{typeof(Math).FullName}.Clamp"] = "clamp",
[$"{typeof(Math).FullName}.{nameof(Math.Exp)}"] = "exp",
[$"{typeof(Math).FullName}.{nameof(Math.Log)}"] = "log",
[$"{typeof(Math).FullName}.{nameof(Math.Log10)}"] = "log10",
[$"{typeof(Math).FullName}.{nameof(Math.Max)}"] = "max",
[$"{typeof(Math).FullName}.{nameof(Math.Min)}"] = "min",
[$"{typeof(Math).FullName}.{nameof(Math.Round)}"] = "round",
[$"{typeof(Math).FullName}.{nameof(Math.Sqrt)}"] = "sqrt",
[$"{typeof(Math).FullName}.{nameof(Math.Sign)}"] = "sign",
[$"{typeof(Math).FullName}.{nameof(Math.Truncate)}"] = "trunc",
["System.MathF.Abs"] = "abs",
["System.MathF.Max"] = "max",
["System.MathF.Min"] = "min",
["System.MathF.Pow"] = "pow",
["System.MathF.Sin"] = "sin",
["System.MathF.Sinh"] = "sinh",
["System.MathF.Asin"] = "asin",
["System.MathF.Cos"] = "cos",
["System.MathF.Cosh"] = "cosh",
["System.MathF.Acos"] = "acos",
["System.MathF.Tan"] = "tan",
["System.MathF.Tanh"] = "tanh",
["System.MathF.Atan"] = "atan",
["System.MathF.Atan2"] = "atan2",
["System.MathF.Ceiling"] = "ceil",
["System.MathF.Floor"] = "floor",
["System.MathF.Clamp"] = "clamp",
["System.MathF.Exp"] = "exp",
["System.MathF.Log"] = "log",
["System.MathF.Log10"] = "log10",
["System.MathF.Max"] = "max",
["System.MathF.Min"] = "min",
["System.MathF.Round"] = "round",
["System.MathF.Sqrt"] = "sqrt",
["System.MathF.Sign"] = "sign",
["System.MathF.Truncate"] = "trunc",
[$"{typeof(float).FullName}.IsFinite"] = "isfinite",
[$"{typeof(float).FullName}.{nameof(float.IsInfinity)}"] = "isinf",
[$"{typeof(float).FullName}.{nameof(float.IsNaN)}"] = "isnan",
[$"{typeof(double).FullName}.IsFinite"] = "isfinite",
[$"{typeof(double).FullName}.{nameof(double.IsInfinity)}"] = "isinf",
[$"{typeof(double).FullName}.{nameof(double.IsNaN)}"] = "isnan",
[$"{typeof(Vector2).FullName}.{nameof(Vector2.Abs)}"] = "abs",
[$"{typeof(Vector2).FullName}.{nameof(Vector2.Clamp)}"] = "clamp",
[$"{typeof(Vector2).FullName}.{nameof(Vector2.Distance)}"] = "distance",
[$"{typeof(Vector2).FullName}.{nameof(Vector2.Dot)}"] = "dot",
[$"{typeof(Vector2).FullName}.{nameof(Vector2.Lerp)}"] = "lerp",
[$"{typeof(Vector2).FullName}.{nameof(Vector2.Max)}"] = "max",
[$"{typeof(Vector2).FullName}.{nameof(Vector2.Min)}"] = "min",
[$"{typeof(Vector2).FullName}.{nameof(Vector2.Reflect)}"] = "reflect",
[$"{typeof(Vector2).FullName}.{nameof(Vector2.Transform)}"] = "mul",
[$"{typeof(Vector2).FullName}.{nameof(Vector2.TransformNormal)}"] = "mul",
[$"{typeof(Vector2).FullName}.{nameof(Vector2.Normalize)}"] = "normalize",
[$"{typeof(Vector3).FullName}.{nameof(Vector3.Abs)}"] = "abs",
[$"{typeof(Vector3).FullName}.{nameof(Vector3.Clamp)}"] = "clamp",
[$"{typeof(Vector3).FullName}.{nameof(Vector3.Cross)}"] = "cross",
[$"{typeof(Vector3).FullName}.{nameof(Vector3.Distance)}"] = "distance",
[$"{typeof(Vector3).FullName}.{nameof(Vector3.Dot)}"] = "dot",
[$"{typeof(Vector3).FullName}.{nameof(Vector3.Lerp)}"] = "lerp",
[$"{typeof(Vector3).FullName}.{nameof(Vector3.Max)}"] = "max",
[$"{typeof(Vector3).FullName}.{nameof(Vector3.Min)}"] = "min",
[$"{typeof(Vector3).FullName}.{nameof(Vector3.Reflect)}"] = "reflect",
[$"{typeof(Vector3).FullName}.{nameof(Vector3.Transform)}"] = "mul",
[$"{typeof(Vector3).FullName}.{nameof(Vector3.TransformNormal)}"] = "mul",
[$"{typeof(Vector3).FullName}.{nameof(Vector3.Normalize)}"] = "normalize",
[$"{typeof(Vector4).FullName}.{nameof(Vector4.Abs)}"] = "abs",
[$"{typeof(Vector4).FullName}.{nameof(Vector4.Clamp)}"] = "clamp",
[$"{typeof(Vector4).FullName}.{nameof(Vector4.Distance)}"] = "distance",
[$"{typeof(Vector4).FullName}.{nameof(Vector4.Dot)}"] = "dot",
[$"{typeof(Vector4).FullName}.{nameof(Vector4.Lerp)}"] = "lerp",
[$"{typeof(Vector4).FullName}.{nameof(Vector4.Max)}"] = "max",
[$"{typeof(Vector4).FullName}.{nameof(Vector4.Min)}"] = "min",
[$"{typeof(Vector4).FullName}.{nameof(Vector4.Transform)}"] = "mul",
[$"{typeof(Vector4).FullName}.{nameof(Vector4.Normalize)}"] = "normalize"
};
// Programmatically load mappings from the Hlsl class as well
foreach (var method in
from method in typeof(Hlsl).GetMethods(BindingFlags.Public | BindingFlags.Static)
group method by method.Name
into groups
select groups.First())
{
// Check whether the current method should be translated with the original name
// or with the lowercase version. This is needed because all C# methods are exposed
// with the upper camel case format, while HLSL intrinsics use multiple different formats.
string hlslName = method.GetCustomAttribute<HlslIntrinsicNameAttribute>()?.Name ?? method.Name;
knownMethods.Add($"{typeof(Hlsl).FullName}{Type.Delimiter}{method.Name}", hlslName);
}
// Programmatically load mappings from the D2D1 class as well
foreach (var method in
from method in typeof(D2D1).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(D2D1).FullName}{Type.Delimiter}{method.Name}", hlslName);
}
return knownMethods;
}
/// <summary>
/// Tries to get the mapped HLSL-compatible method name for the input method name.
/// </summary>
/// <param name="name">The input fully qualified method name.</param>
/// <param name="mapped">The mapped name, if one is found.</param>
/// <returns>The HLSL-compatible member name that can be used in an HLSL shader.</returns>
public static bool TryGetMappedName(string name, out string? mapped)
{
return KnownMethods.TryGetValue(name, out mapped);
}
}
+58
ファイルの表示
@@ -0,0 +1,58 @@
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using System.Reflection;
using System.Text.RegularExpressions;
namespace ComputeSharp.D2D1Interop.SourceGenerators.Mappings;
/// <summary>
/// A <see langword="class"/> that contains and maps known HLSL types to their alignment sizes.
/// </summary>
internal static class HlslKnownSizes
{
/// <summary>
/// The mapping of supported known sizes to HLSL type names.
/// </summary>
private static readonly IReadOnlyDictionary<string, (int, int)> KnownSizes = BuildKnownSizesMap();
/// <summary>
/// Builds the mapping of known type sizes and alignments.
/// </summary>
private static IReadOnlyDictionary<string, (int, int)> BuildKnownSizesMap()
{
Dictionary<string, (int, int)> knownSizes = new()
{
[typeof(bool).FullName] = (4, 4),
[typeof(int).FullName] = (4, 4),
[typeof(uint).FullName] = (4, 4),
[typeof(float).FullName] = (4, 4),
[typeof(double).FullName] = (8, 8),
[typeof(Vector2).FullName] = (8, 4),
[typeof(Vector3).FullName] = (12, 4),
[typeof(Vector4).FullName] = (16, 4)
};
foreach (
var type in
from type in Assembly.GetExecutingAssembly().ExportedTypes
where Regex.IsMatch(type.FullName, @"^ComputeSharp\.(Bool|Double|Float|Int|UInt)")
select type)
{
knownSizes.Add(type.FullName, (type.StructLayoutAttribute.Size, type.StructLayoutAttribute.Pack));
}
return knownSizes;
}
/// <summary>
/// Gets the size and alignment info for a specified primitive type.
/// </summary>
/// <param name="typeName">The type name to get info for.</param>
/// <returns>The size and and alignment for the input type.</returns>
public static (int Size, int Pack) GetTypeInfo(string typeName)
{
return KnownSizes[typeName];
}
}
+289
ファイルの表示
@@ -0,0 +1,289 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using System.Text.RegularExpressions;
using ComputeSharp.D2D1Interop.SourceGenerators.Extensions;
using Microsoft.CodeAnalysis;
#pragma warning disable RS1024
namespace ComputeSharp.D2D1Interop.SourceGenerators.Mappings;
/// <summary>
/// A <see langword="class"/> that contains and maps known HLSL type names to common .NET types.
/// </summary>
internal static class HlslKnownTypes
{
/// <summary>
/// Gets the set of HLSL vector types.
/// </summary>
public static IReadOnlyCollection<Type> KnownVectorTypes { get; } = new[]
{
typeof(Bool2), typeof(Bool3), typeof(Bool4),
typeof(Int2), typeof(Int3), typeof(Int4),
typeof(UInt2), typeof(UInt3), typeof(UInt4),
typeof(Float2), typeof(Float3), typeof(Float4),
typeof(Double2), typeof(Double3), typeof(Double4)
};
/// <summary>
/// Gets the set of HLSL matrix types.
/// </summary>
public static IReadOnlyCollection<Type> KnownMatrixTypes { get; } = new[]
{
typeof(Bool1x1), typeof(Bool1x2), typeof(Bool1x3), typeof(Bool1x4),
typeof(Bool2x1), typeof(Bool2x2), typeof(Bool2x3), typeof(Bool2x4),
typeof(Bool3x1), typeof(Bool3x2), typeof(Bool3x3), typeof(Bool3x4),
typeof(Bool4x1), typeof(Bool4x2), typeof(Bool4x3), typeof(Bool4x4),
typeof(Int1x1), typeof(Int1x2), typeof(Int1x3), typeof(Int1x4),
typeof(Int2x1), typeof(Int2x2), typeof(Int2x3), typeof(Int2x4),
typeof(Int3x1), typeof(Int3x2), typeof(Int3x3), typeof(Int3x4),
typeof(Int4x1), typeof(Int4x2), typeof(Int4x3), typeof(Int4x4),
typeof(UInt1x1), typeof(UInt1x2), typeof(UInt1x3), typeof(UInt1x4),
typeof(UInt2x1), typeof(UInt2x2), typeof(UInt2x3), typeof(UInt2x4),
typeof(UInt3x1), typeof(UInt3x2), typeof(UInt3x3), typeof(UInt3x4),
typeof(UInt4x1), typeof(UInt4x2), typeof(UInt4x3), typeof(UInt4x4),
typeof(Float1x1), typeof(Float1x2), typeof(Float1x3), typeof(Float1x4),
typeof(Float2x1), typeof(Float2x2), typeof(Float2x3), typeof(Float2x4),
typeof(Float3x1), typeof(Float3x2), typeof(Float3x3), typeof(Float3x4),
typeof(Float4x1), typeof(Float4x2), typeof(Float4x3), typeof(Float4x4),
typeof(Double1x1), typeof(Double1x2), typeof(Double1x3), typeof(Double1x4),
typeof(Double2x1), typeof(Double2x2), typeof(Double2x3), typeof(Double2x4),
typeof(Double3x1), typeof(Double3x2), typeof(Double3x3), typeof(Double3x4),
typeof(Double4x1), typeof(Double4x2), typeof(Double4x3), typeof(Double4x4)
};
/// <summary>
/// The mapping of supported known types to HLSL types.
/// </summary>
private static readonly IReadOnlyDictionary<string, string> KnownHlslTypes = BuildKnownHlslTypes();
/// <summary>
/// Builds the mapping of known primitive types.
/// </summary>
private static IReadOnlyDictionary<string, string> BuildKnownHlslTypes()
{
Dictionary<string, string> knownTypes = new()
{
[typeof(bool).FullName] = "bool",
[typeof(int).FullName] = "int",
[typeof(uint).FullName] = "uint",
[typeof(float).FullName] = "float",
[typeof(Vector2).FullName] = "float2",
[typeof(Vector3).FullName] = "float3",
[typeof(Vector4).FullName] = "float4",
[typeof(double).FullName] = "double"
};
// Add all the vector types
foreach (var type in KnownVectorTypes)
{
knownTypes.Add(type.FullName, type.Name.ToLower());
}
// Add all the matrix types
foreach (var type in KnownMatrixTypes)
{
knownTypes.Add(type.FullName, type.Name.ToLower());
}
return knownTypes;
}
/// <summary>
/// Checks whether or not a given type name matches a known HLSL primitive type (scalar, vector or matrix).
/// </summary>
/// <param name="typeName">The input type name to check.</param>
/// <returns>Whether or not <paramref name="typeName"/> represents a scalar, vector or matrix type.</returns>
public static bool IsKnownHlslType(string typeName)
{
return KnownHlslTypes.ContainsKey(typeName);
}
/// <summary>
/// Checks whether or not a given type name matches a vector type.
/// </summary>
/// <param name="typeName">The input type name to check.</param>
/// <returns>Whether or not <paramref name="typeName"/> represents a vector type.</returns>
public static bool IsVectorType(string typeName)
{
return KnownVectorTypes.Any(type => type.FullName == typeName);
}
/// <summary>
/// Checks whether or not a given type name matches a matrix type.
/// </summary>
/// <param name="typeName">The input type name to check.</param>
/// <returns>Whether or not <paramref name="typeName"/> represents a matrix type.</returns>
public static bool IsMatrixType(string typeName)
{
return KnownMatrixTypes.Any(type => type.FullName == typeName);
}
/// <summary>
/// Checks whether or not a given type name is a non linear matrix type.
/// That is, a matrix type with more than a single row (which affects the constant buffer alignment).
/// </summary>
/// <param name="typeName">The input type name to check.</param>
/// <param name="elementName">The element name of the matrix type.</param>
/// <param name="rows">The number of rows in the matrix type.</param>
/// <param name="columns">The number of columns in the matrix type.</param>
/// <returns>Whether or not <paramref name="typeName"/> represents a non linear matrix type.</returns>
public static bool IsNonLinearMatrixType(string typeName, out string? elementName, out int rows, out int columns)
{
if (KnownMatrixTypes.Any(type => type.FullName == typeName))
{
var match = Regex.Match(typeName, @"^ComputeSharp\.(Bool|Int|UInt|Float|Double)([2-4])x([1-4])$");
if (match.Success)
{
elementName = match.Groups[1].Value;
rows = int.Parse(match.Groups[2].Value);
columns = int.Parse(match.Groups[3].Value);
return true;
}
}
elementName = null;
rows = columns = 0;
return false;
}
/// <summary>
/// Gets the mapped HLSL-compatible type name for the input type symbol.
/// </summary>
/// <param name="typeSymbol">The input type to map.</param>
/// <returns>The HLSL-compatible type name that can be used in an HLSL shader.</returns>
public static string GetMappedName(INamedTypeSymbol typeSymbol)
{
string typeName = typeSymbol.GetFullMetadataName();
// The captured field is of an HLSL primitive type
if (KnownHlslTypes.TryGetValue(typeName, out string? mappedType))
{
return mappedType;
}
// The captured field is of a custom struct type
return typeName.ToHlslIdentifierName();
}
/// <summary>
/// Gets the mapped HLSL-compatible type name for the input element type symbol.
/// </summary>
/// <param name="typeSymbol">The input type to map.</param>
/// <returns>The HLSL-compatible type name that can be used in an HLSL shader.</returns>
public static string GetMappedElementName(IArrayTypeSymbol typeSymbol)
{
string elementTypeName = ((INamedTypeSymbol)typeSymbol.ElementType).GetFullMetadataName();
if (KnownHlslTypes.TryGetValue(elementTypeName, out string? mapped))
{
return mapped;
}
return elementTypeName.ToHlslIdentifierName();
}
/// <summary>
/// Gets the mapped HLSL-compatible type name for the input type name.
/// </summary>
/// <param name="originalName">The input type name to map.</param>
/// <param name="mappedName">The resulting mapped type name, if found.</param>
/// <returns>The HLSL-compatible type name that can be used in an HLSL shader.</returns>
public static bool TryGetMappedName(string originalName, out string? mappedName)
{
return KnownHlslTypes.TryGetValue(originalName, out mappedName);
}
/// <summary>
/// Gets the sequence of unique custom types from a collection of discovered types.
/// </summary>
/// <param name="discoveredTypes">The input collection of discovered types.</param>
/// <returns>The list of unique custom types.</returns>
public static IEnumerable<INamedTypeSymbol> GetCustomTypes(IEnumerable<INamedTypeSymbol> discoveredTypes)
{
// Local function to recursively gather nested types
static void ExploreTypes(INamedTypeSymbol type, HashSet<INamedTypeSymbol> customTypes)
{
if (KnownHlslTypes.ContainsKey(type.GetFullMetadataName())) return;
if (!customTypes.Add(type)) return;
foreach (var field in type.GetMembers().OfType<IFieldSymbol>())
{
if (field.IsStatic) continue;
ExploreTypes((INamedTypeSymbol)field.Type, customTypes);
}
}
HashSet<INamedTypeSymbol> customTypes = new(SymbolEqualityComparer.Default);
// Explore all input types and their nested types
foreach (INamedTypeSymbol type in discoveredTypes)
{
ExploreTypes(type, customTypes);
}
return OrderByDependency(customTypes);
}
/// <summary>
/// Orders the input sequence of types so that they can be declared in HLSL successfully.
/// </summary>
/// <param name="types">The input collection of types to declare.</param>
/// <returns>The same list as input, but in a valid HLSL declaration order.</returns>
private static IEnumerable<INamedTypeSymbol> OrderByDependency(IEnumerable<INamedTypeSymbol> types)
{
Queue<(INamedTypeSymbol Type, HashSet<INamedTypeSymbol> Fields)> queue = new();
// Build a mapping of type dependencies for all the captured types. A type depends on another
// when the latter is a field in the first type. HLSL requires custom types to be declared in
// order of usage, so we need to ensure that types are declared in an order that guarantees
// that no type will be referenced before being defined. To do so, we can create a mapping of
// types and their dependencies, and iteratively remove items from the map when they have no
// dependencies left. When one type is processed and removed, it is also removed from the list
// of dependencies of all other remaining types in the map, until there is none left.
foreach (var type in types)
{
HashSet<INamedTypeSymbol> dependencies = new(SymbolEqualityComparer.Default);
// Only add other custom types as dependencies, and ignore HLSL types
foreach (var field in type.GetMembers().OfType<IFieldSymbol>())
{
if (field.IsStatic) continue;
INamedTypeSymbol fieldType = (INamedTypeSymbol)field.Type;
if (!KnownHlslTypes.ContainsKey(fieldType.GetFullMetadataName()))
{
_ = dependencies.Add(fieldType);
}
}
queue.Enqueue((type, dependencies));
}
while (queue.Count > 0)
{
var entry = queue.Dequeue();
// No dependencies left, we can declare this type
if (entry.Fields.Count == 0)
{
// Remove the current type from dependencies of others
foreach (var pair in queue)
{
_ = pair.Fields.Remove(entry.Type);
}
yield return entry.Type;
}
else queue.Enqueue(entry);
}
}
}
+64
ファイルの表示
@@ -0,0 +1,64 @@
using System;
using System.Collections.Generic;
using System.Linq;
using ComputeSharp.D2D1Interop.SourceGenerators.Extensions;
using Microsoft.CodeAnalysis;
namespace ComputeSharp.D2D1Interop.SourceGenerators.Models;
/// <summary>
/// A model for a serializeable diagnostic provider.
/// </summary>
/// <param name="Descriptor">The wrapped <see cref="DiagnosticDescriptor"/> instance.</param>
/// <param name="Args">The diagnostic args.</param>
internal sealed record DiagnosticInfo(DiagnosticDescriptor Descriptor, params object[] Args)
{
/// <summary>
/// An <see cref="IEqualityComparer{T}"/> implementation for <see cref="DiagnosticInfo"/>.
/// </summary>
public sealed class Comparer : IEqualityComparer<DiagnosticInfo>
{
/// <summary>
/// The singleton <see cref="Comparer"/> instance.
/// </summary>
public static Comparer Default { get; } = new();
/// <inheritdoc/>
public bool Equals(DiagnosticInfo? x, DiagnosticInfo? y)
{
if (x is null && y is null)
{
return true;
}
if (x is null || y is null)
{
return false;
}
if (ReferenceEquals(x, y))
{
return true;
}
return
x.Descriptor.Equals(y.Descriptor) &&
x.Args.SequenceEqual(y.Args);
}
/// <inheritdoc/>
public int GetHashCode(DiagnosticInfo obj)
{
HashCode hashCode = default;
hashCode.Add(obj.Descriptor);
foreach (object arg in obj.Args)
{
hashCode.Add(arg);
}
return hashCode.ToHashCode();
}
}
}
+73
ファイルの表示
@@ -0,0 +1,73 @@
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using ComputeSharp.D2D1Interop.SourceGenerators.Extensions;
namespace ComputeSharp.D2D1Interop.SourceGenerators.Models;
/// <summary>
/// A model representing gathered info on a shader dispatch data.
/// </summary>
/// <param name="Hierarchy">The hierarchy data for the shader.</param>
/// <param name="Type">The shader interface type.</param>
/// <param name="FieldInfos">The description on shader instance fields.</param>
/// <param name="ResourceCount">The total number of captured resources.</param>
/// <param name="Root32BitConstantCount">The size of the shader root signature, in 32 bit constants.</param>
internal sealed record DispatchDataInfo(
HierarchyInfo Hierarchy,
Type Type,
ImmutableArray<FieldInfo> FieldInfos,
int ResourceCount,
int Root32BitConstantCount)
{
/// <summary>
/// An <see cref="IEqualityComparer{T}"/> implementation for <see cref="DispatchDataInfo"/>.
/// </summary>
public sealed class Comparer : IEqualityComparer<DispatchDataInfo>
{
/// <summary>
/// The singleton <see cref="Comparer"/> instance.
/// </summary>
public static Comparer Default { get; } = new();
/// <inheritdoc/>
public bool Equals(DispatchDataInfo? x, DispatchDataInfo? y)
{
if (x is null && y is null)
{
return true;
}
if (x is null || y is null)
{
return false;
}
if (ReferenceEquals(x, y))
{
return true;
}
return
HierarchyInfo.Comparer.Default.Equals(x.Hierarchy, y.Hierarchy) &&
x.Type == y.Type &&
x.FieldInfos.SequenceEqual(y.FieldInfos, FieldInfo.Comparer.Default) &&
x.ResourceCount == y.ResourceCount &&
x.Root32BitConstantCount == y.Root32BitConstantCount;
}
/// <inheritdoc/>
public int GetHashCode(DispatchDataInfo obj)
{
HashCode hashCode = default;
hashCode.Add(HierarchyInfo.Comparer.Default.GetHashCode(obj.Hierarchy));
hashCode.Add(obj.Type);
hashCode.AddRange(obj.FieldInfos, FieldInfo.Comparer.Default);
hashCode.Add(obj.ResourceCount);
hashCode.Add(obj.Root32BitConstantCount);
return hashCode.ToHashCode();
}
}
}
+55
ファイルの表示
@@ -0,0 +1,55 @@
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using ComputeSharp.D2D1Interop.SourceGenerators.Extensions;
namespace ComputeSharp.D2D1Interop.SourceGenerators.Models;
/// <summary>
/// A model representing gathered info on a shader dispatch id.
/// </summary>
/// <param name="Delegates">The list of delegate field names for the shader.</param>
internal sealed record DispatchIdInfo(ImmutableArray<string> Delegates)
{
/// <summary>
/// An <see cref="IEqualityComparer{T}"/> implementation for <see cref="DispatchIdInfo"/>.
/// </summary>
public sealed class Comparer : IEqualityComparer<DispatchIdInfo>
{
/// <summary>
/// The singleton <see cref="Comparer"/> instance.
/// </summary>
public static Comparer Default { get; } = new();
/// <inheritdoc/>
public bool Equals(DispatchIdInfo? x, DispatchIdInfo? y)
{
if (x is null && y is null)
{
return true;
}
if (x is null || y is null)
{
return false;
}
if (ReferenceEquals(x, y))
{
return true;
}
return x.Delegates.SequenceEqual(y.Delegates);
}
/// <inheritdoc/>
public int GetHashCode(DispatchIdInfo obj)
{
HashCode hashCode = default;
hashCode.AddRange(obj.Delegates);
return hashCode.ToHashCode();
}
}
}
+65
ファイルの表示
@@ -0,0 +1,65 @@
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using ComputeSharp.D2D1Interop.SourceGenerators.Extensions;
namespace ComputeSharp.D2D1Interop.SourceGenerators.Models;
/// <summary>
/// A model containing info on shader dispatch metadata.
/// </summary>
/// <param name="Root32BitConstantCount">The size of the shader root signature, in 32 bit constants.</param>
/// <param name="IsSamplerUsed">Whether or not the static sampler is used.</param>
/// <param name="ResourceDescriptors">The sequence of resource descriptors for the shader.</param>
internal sealed record DispatchMetadataInfo(
int Root32BitConstantCount,
bool IsSamplerUsed,
ImmutableArray<ResourceDescriptor> ResourceDescriptors)
{
/// <summary>
/// An <see cref="IEqualityComparer{T}"/> implementation for <see cref="DispatchMetadataInfo"/>.
/// </summary>
public sealed class Comparer : IEqualityComparer<DispatchMetadataInfo>
{
/// <summary>
/// The singleton <see cref="Comparer"/> instance.
/// </summary>
public static Comparer Default { get; } = new();
/// <inheritdoc/>
public bool Equals(DispatchMetadataInfo? x, DispatchMetadataInfo? y)
{
if (x is null && y is null)
{
return true;
}
if (x is null || y is null)
{
return false;
}
if (ReferenceEquals(x, y))
{
return true;
}
return
x.Root32BitConstantCount == y.Root32BitConstantCount &&
x.IsSamplerUsed == y.IsSamplerUsed &&
x.ResourceDescriptors.SequenceEqual(y.ResourceDescriptors, ResourceDescriptor.Comparer.Default);
}
/// <inheritdoc/>
public int GetHashCode(DispatchMetadataInfo obj)
{
HashCode hashCode = default;
hashCode.Add(obj.Root32BitConstantCount);
hashCode.Add(obj.IsSamplerUsed);
hashCode.AddRange(obj.ResourceDescriptors, ResourceDescriptor.Comparer.Default);
return hashCode.ToHashCode();
}
}
}
+65
ファイルの表示
@@ -0,0 +1,65 @@
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using ComputeSharp.D2D1Interop.SourceGenerators.Extensions;
namespace ComputeSharp.D2D1Interop.SourceGenerators.Models;
/// <summary>
/// A model representing a compiled shader bytecode, or none.
/// </summary>
/// <param name="X">The thread ids value for the X axis.</param>
/// <param name="Y">The thread ids value for the Y axis.</param>
/// <param name="Z">The thread ids value for the Z axis.</param>
/// <param name="Bytecode">The compiled shader bytecode, if available.</param>
internal sealed record EmbeddedBytecodeInfo(int X, int Y, int Z, ImmutableArray<byte> Bytecode)
{
/// <summary>
/// An <see cref="IEqualityComparer{T}"/> implementation for <see cref="EmbeddedBytecodeInfo"/>.
/// </summary>
public sealed class Comparer : IEqualityComparer<EmbeddedBytecodeInfo>
{
/// <summary>
/// The singleton <see cref="Comparer"/> instance.
/// </summary>
public static Comparer Default { get; } = new();
/// <inheritdoc/>
public bool Equals(EmbeddedBytecodeInfo? x, EmbeddedBytecodeInfo? y)
{
if (x is null && y is null)
{
return true;
}
if (x is null || y is null)
{
return false;
}
if (ReferenceEquals(x, y))
{
return true;
}
return
x.X == y.X &&
x.Y == y.Y &&
x.Z == y.Z &&
x.Bytecode.SequenceEqual(y.Bytecode);
}
/// <inheritdoc/>
public int GetHashCode(EmbeddedBytecodeInfo obj)
{
HashCode hashCode = default;
hashCode.Add(obj.X);
hashCode.Add(obj.Y);
hashCode.Add(obj.Z);
hashCode.AddBytes(obj.Bytecode.AsSpan());
return hashCode.ToHashCode();
}
}
}
+137
ファイルの表示
@@ -0,0 +1,137 @@
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using ComputeSharp.D2D1Interop.SourceGenerators.Extensions;
namespace ComputeSharp.D2D1Interop.SourceGenerators.Models;
/// <summary>
/// A base type for a model describing a given captured field in a shader.
/// </summary>
internal abstract record FieldInfo
{
/// <summary>
/// A captured resource (either a buffer or a texture).
/// </summary>
/// <param name="FieldName">The name of the resource field.</param>
/// <param name="TypeName">The full metadata name for the resource type.</param>
/// <param name="Offset">The offset for the resource within the root signature.</param>
public sealed record Resource(string FieldName, string TypeName, int Offset) : FieldInfo;
/// <summary>
/// A captured primitive value (either a scalar, a vector, or a linear matrix).
/// </summary>
/// <param name="FieldPath">The path of the field with respect to the shader instance.</param>
/// <param name="TypeName">The full metadata name for the primitive type.</param>
/// <param name="Offset">The byte offset of the value within the root signature.</param>
public sealed record Primitive(ImmutableArray<string> FieldPath, string TypeName, int Offset) : FieldInfo;
/// <summary>
/// A captured non linear matrix value.
/// </summary>
/// <param name="FieldPath">The path of the field with respect to the shader instance.</param>
/// <param name="TypeName">The full metadata name for the matrix type.</param>
/// <param name="ElementName">The name of each element in the matrix type.</param>
/// <param name="Rows">The number of rows in the matrix.</param>
/// <param name="Columns">The number of columns in the matrix.</param>
/// <param name="Offsets">The sequence of byte offsets for each row within the root signature.</param>
public sealed record NonLinearMatrix(
ImmutableArray<string> FieldPath,
string TypeName,
string ElementName,
int Rows,
int Columns,
ImmutableArray<int> Offsets) : FieldInfo;
/// <summary>
/// An <see cref="IEqualityComparer{T}"/> implementation for <see cref="FieldInfo"/>.
/// </summary>
public sealed class Comparer : IEqualityComparer<FieldInfo>
{
/// <summary>
/// The singleton <see cref="Comparer"/> instance.
/// </summary>
public static Comparer Default { get; } = new();
/// <inheritdoc/>
public bool Equals(FieldInfo? x, FieldInfo? y)
{
if (x is null && y is null)
{
return true;
}
if (x is null || y is null)
{
return false;
}
if (ReferenceEquals(x, y))
{
return true;
}
if (x is Resource resourceX && y is Resource resourceY)
{
return
resourceX.FieldName == resourceY.FieldName &&
resourceX.TypeName == resourceY.TypeName &&
resourceX.Offset == resourceY.Offset;
}
else if (x is Primitive primitiveX && y is Primitive primitiveY)
{
return
primitiveX.FieldPath.SequenceEqual(primitiveY.FieldPath) &&
primitiveX.TypeName == primitiveY.TypeName &&
primitiveX.Offset == primitiveY.Offset;
}
else if (x is NonLinearMatrix matrixX && y is NonLinearMatrix matrixY)
{
return
matrixX.FieldPath.SequenceEqual(matrixY.FieldPath) &&
matrixX.TypeName == matrixY.TypeName &&
matrixX.ElementName == matrixY.ElementName &&
matrixX.Rows == matrixY.Rows &&
matrixY.Columns == matrixY.Columns &&
matrixX.Offsets.SequenceEqual(matrixY.Offsets);
}
return false;
}
/// <inheritdoc/>
public int GetHashCode(FieldInfo obj)
{
switch (obj)
{
case Resource resource:
return HashCode.Combine(resource.FieldName, resource.TypeName, resource.Offset);
case Primitive primitive:
{
HashCode hashCode = default;
hashCode.AddRange(primitive.FieldPath);
hashCode.Add(primitive.TypeName);
hashCode.Add(primitive.Offset);
return hashCode.ToHashCode();
}
case NonLinearMatrix matrix:
{
HashCode hashCode = default;
hashCode.AddRange(matrix.FieldPath);
hashCode.Add(matrix.TypeName);
hashCode.Add(matrix.ElementName);
hashCode.Add(matrix.Rows);
hashCode.Add(matrix.Columns);
hashCode.AddRange(matrix.Offsets);
return hashCode.ToHashCode();
}
default:
return 0;
}
}
}
}
+90
ファイルの表示
@@ -0,0 +1,90 @@
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using ComputeSharp.D2D1Interop.SourceGenerators.Extensions;
using Microsoft.CodeAnalysis;
using static Microsoft.CodeAnalysis.SymbolDisplayTypeQualificationStyle;
namespace ComputeSharp.D2D1Interop.SourceGenerators.Models;
/// <summary>
/// A model describing the hierarchy info for a specific type.
/// </summary>
/// <param name="FilenameHint">The filename hint for the current type.</param>
/// <param name="MetadataName">The metadata name for the current type.</param>
/// <param name="Namespace">Gets the namespace for the current type.</param>
/// <param name="Names">Gets the sequence of type definitions containing the current type.</param>
internal sealed record HierarchyInfo(string FilenameHint, string MetadataName, string Namespace, ImmutableArray<string> Names)
{
/// <summary>
/// Creates a new <see cref="HierarchyInfo"/> instance from a given <see cref="INamedTypeSymbol"/>.
/// </summary>
/// <param name="typeSymbol">The input <see cref="INamedTypeSymbol"/> instance to gather info for.</param>
/// <returns>A <see cref="HierarchyInfo"/> instance describing <paramref name="typeSymbol"/>.</returns>
public static HierarchyInfo From(INamedTypeSymbol typeSymbol)
{
ImmutableArray<string>.Builder names = ImmutableArray.CreateBuilder<string>();
for (INamedTypeSymbol? parent = typeSymbol;
parent is not null;
parent = parent.ContainingType)
{
names.Add(parent.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat));
}
return new(
typeSymbol.GetGeneratedFileName(),
typeSymbol.MetadataName,
typeSymbol.ContainingNamespace.ToDisplayString(new(typeQualificationStyle: NameAndContainingTypesAndNamespaces)),
names.ToImmutable());
}
/// <summary>
/// An <see cref="IEqualityComparer{T}"/> implementation for <see cref="HierarchyInfo"/>.
/// </summary>
public sealed class Comparer : IEqualityComparer<HierarchyInfo>
{
/// <summary>
/// The singleton <see cref="Comparer"/> instance.
/// </summary>
public static Comparer Default { get; } = new();
/// <inheritdoc/>
public bool Equals(HierarchyInfo? x, HierarchyInfo? y)
{
if (x is null && y is null)
{
return true;
}
if (x is null || y is null)
{
return false;
}
if (ReferenceEquals(x, y))
{
return true;
}
return
x.FilenameHint == y.FilenameHint &&
x.MetadataName == y.MetadataName &&
x.Namespace == y.Namespace &&
x.Names.SequenceEqual(y.Names);
}
/// <inheritdoc/>
public int GetHashCode(HierarchyInfo obj)
{
HashCode hashCode = default;
hashCode.Add(obj.FilenameHint);
hashCode.Add(obj.MetadataName);
hashCode.Add(obj.Namespace);
hashCode.AddRange(obj.Names);
return hashCode.ToHashCode();
}
}
}
+73
ファイルの表示
@@ -0,0 +1,73 @@
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using ComputeSharp.D2D1Interop.SourceGenerators.Extensions;
namespace ComputeSharp.D2D1Interop.SourceGenerators.Models;
/// <summary>
/// A model for extracted info on a processed HLSL method.
/// </summary>
/// <param name="MetadataName">The metadata name for the method.</param>
/// <param name="EntryPoint">The meethod entry point.</param>
/// <param name="DefinedTypes">The discovered declared types.</param>
/// <param name="DefinedConstants">The discovered defined constants.</param>
/// <param name="DependentMethods">The dependent captured methods.</param>
internal sealed record HlslMethodSourceInfo(
string MetadataName,
string EntryPoint,
ImmutableArray<(string Name, string Definition)> DefinedTypes,
ImmutableArray<(string Name, string Value)> DefinedConstants,
ImmutableArray<(string Signature, string Definition)> DependentMethods)
{
/// <summary>
/// An <see cref="IEqualityComparer{T}"/> implementation for <see cref="HlslMethodSourceInfo"/>.
/// </summary>
public sealed class Comparer : IEqualityComparer<HlslMethodSourceInfo>
{
/// <summary>
/// The singleton <see cref="Comparer"/> instance.
/// </summary>
public static Comparer Default { get; } = new();
/// <inheritdoc/>
public bool Equals(HlslMethodSourceInfo? x, HlslMethodSourceInfo? y)
{
if (x is null && y is null)
{
return true;
}
if (x is null || y is null)
{
return false;
}
if (ReferenceEquals(x, y))
{
return true;
}
return
x.MetadataName == y.MetadataName &&
x.EntryPoint == y.EntryPoint &&
x.DefinedTypes.SequenceEqual(y.DefinedTypes) &&
x.DefinedConstants.SequenceEqual(y.DefinedConstants) &&
x.DependentMethods.SequenceEqual(y.DependentMethods);
}
/// <inheritdoc/>
public int GetHashCode(HlslMethodSourceInfo obj)
{
HashCode hashCode = default;
hashCode.Add(obj.MetadataName);
hashCode.Add(obj.EntryPoint);
hashCode.AddRange(obj.DefinedTypes);
hashCode.AddRange(obj.DefinedConstants);
hashCode.AddRange(obj.DependentMethods);
return hashCode.ToHashCode();
}
}
}
+109
ファイルの表示
@@ -0,0 +1,109 @@
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using ComputeSharp.D2D1Interop.SourceGenerators.Extensions;
namespace ComputeSharp.D2D1Interop.SourceGenerators.Models;
/// <summary>
/// A model for extracted info on a processed HLSL shader.
/// </summary>
/// <param name="HeaderAndThreadsX">The shader generated header and <c>threadsX</c> count declaration.</param>
/// <param name="ThreadsY">The <c>threadsY</c> count declaration.</param>
/// <param name="ThreadsZ">The <c>threadsZ</c> count declaration.</param>
/// <param name="Defines">The define statements, if any.</param>
/// <param name="StaticFieldsAndDeclaredTypes">The static fields and declared types, if any.</param>
/// <param name="CapturedFieldsAndResourcesAndForwardDeclarations">The captured fields, and method forward declarations.</param>
/// <param name="CapturedMethods">The captured method implementations.</param>
/// <param name="EntryPoint">The shader entry point.</param>
/// <param name="ImplicitTextureType">The type of the implicit texture type, if any.</param>
/// <param name="IsSamplerUsed">Whether or not the static sampler is used.</param>
/// <param name="DefinedTypes">The names of declared types.</param>
/// <param name="DefinedConstants">The names of defined constants.</param>
/// <param name="MethodSignatures">The signatures for captured methods.</param>
/// <param name="Delegates">The list of delegate fields.</param>
internal sealed record HlslShaderSourceInfo(
string HeaderAndThreadsX,
string ThreadsY,
string ThreadsZ,
string Defines,
string StaticFieldsAndDeclaredTypes,
string CapturedFieldsAndResourcesAndForwardDeclarations,
string CapturedMethods,
string EntryPoint,
string? ImplicitTextureType,
bool IsSamplerUsed,
ImmutableArray<string> DefinedTypes,
ImmutableArray<string> DefinedConstants,
ImmutableArray<string> MethodSignatures,
ImmutableArray<string> Delegates)
{
/// <summary>
/// An <see cref="IEqualityComparer{T}"/> implementation for <see cref="HlslShaderSourceInfo"/>.
/// </summary>
public sealed class Comparer : IEqualityComparer<HlslShaderSourceInfo>
{
/// <summary>
/// The singleton <see cref="Comparer"/> instance.
/// </summary>
public static Comparer Default { get; } = new();
/// <inheritdoc/>
public bool Equals(HlslShaderSourceInfo? x, HlslShaderSourceInfo? y)
{
if (x is null && y is null)
{
return true;
}
if (x is null || y is null)
{
return false;
}
if (ReferenceEquals(x, y))
{
return true;
}
return
x.HeaderAndThreadsX == y.HeaderAndThreadsX &&
x.ThreadsY == y.ThreadsY &&
x.ThreadsZ == y.ThreadsZ &&
x.Defines == y.Defines &&
x.StaticFieldsAndDeclaredTypes == y.StaticFieldsAndDeclaredTypes &&
x.CapturedFieldsAndResourcesAndForwardDeclarations == y.CapturedFieldsAndResourcesAndForwardDeclarations &&
x.CapturedMethods == y.CapturedMethods &&
x.EntryPoint == y.EntryPoint &&
x.ImplicitTextureType == y.ImplicitTextureType &&
x.IsSamplerUsed == y.IsSamplerUsed &&
x.DefinedTypes.SequenceEqual(y.DefinedTypes) &&
x.DefinedConstants.SequenceEqual(y.DefinedTypes) &&
x.MethodSignatures.SequenceEqual(y.MethodSignatures) &&
x.Delegates.SequenceEqual(y.Delegates);
}
/// <inheritdoc/>
public int GetHashCode(HlslShaderSourceInfo obj)
{
HashCode hashCode = default;
hashCode.Add(obj.HeaderAndThreadsX);
hashCode.Add(obj.ThreadsY);
hashCode.Add(obj.ThreadsZ);
hashCode.Add(obj.Defines);
hashCode.Add(obj.StaticFieldsAndDeclaredTypes);
hashCode.Add(obj.CapturedFieldsAndResourcesAndForwardDeclarations);
hashCode.Add(obj.CapturedMethods);
hashCode.Add(obj.EntryPoint);
hashCode.Add(obj.ImplicitTextureType);
hashCode.Add(obj.IsSamplerUsed);
hashCode.AddRange(obj.DefinedTypes);
hashCode.AddRange(obj.DefinedConstants);
hashCode.AddRange(obj.MethodSignatures);
hashCode.AddRange(obj.Delegates);
return hashCode.ToHashCode();
}
}
}
+8
ファイルの表示
@@ -0,0 +1,8 @@
namespace ComputeSharp.D2D1Interop.SourceGenerators.Models;
/// <summary>
/// A model describing info on a constructor parameter.
/// </summary>
/// <param name="Type">The fully qualified type name.</param>
/// <param name="Name">The parameter name.</param>
internal sealed record ParameterInfo(string Type, string Name);
+54
ファイルの表示
@@ -0,0 +1,54 @@
using System;
using System.Collections.Generic;
namespace ComputeSharp.D2D1Interop.SourceGenerators.Models;
/// <summary>
/// A resource descriptor for a captured resource in a shader.
/// </summary>
/// <param name="TypeId">The type id for the resource.</param>
/// <param name="RegisterOffset">The offset of the resource in its containing register.</param>
/// <param name="Offset">The offset of the resource descriptor in the shader root signature.</param>
internal sealed record ResourceDescriptor(int TypeId, int RegisterOffset, int Offset)
{
/// <summary>
/// An <see cref="IEqualityComparer{T}"/> implementation for <see cref="ResourceDescriptor"/>.
/// </summary>
public sealed class Comparer : IEqualityComparer<ResourceDescriptor>
{
/// <summary>
/// The singleton <see cref="Comparer"/> instance.
/// </summary>
public static Comparer Default { get; } = new();
/// <inheritdoc/>
public bool Equals(ResourceDescriptor? x, ResourceDescriptor? y)
{
if (x is null && y is null)
{
return true;
}
if (x is null || y is null)
{
return false;
}
if (ReferenceEquals(x, y))
{
return true;
}
return
x.TypeId == y.TypeId &&
x.RegisterOffset == y.RegisterOffset &&
x.Offset == y.Offset;
}
/// <inheritdoc/>
public int GetHashCode(ResourceDescriptor obj)
{
return HashCode.Combine(obj.TypeId, obj.RegisterOffset, obj.Offset);
}
}
}
+12
ファイルの表示
@@ -0,0 +1,12 @@
using System.Collections.Immutable;
using Microsoft.CodeAnalysis;
namespace ComputeSharp.D2D1Interop.SourceGenerators.Models;
/// <summary>
/// A model representing a value and an associated set of diagnostic errors.
/// </summary>
/// <typeparam name="TValue">The type of the wrapped value.</typeparam>
/// <param name="Value">The wrapped value for the current result.</param>
/// <param name="Errors">The associated diagnostic errors, if any.</param>
internal sealed record Result<TValue>(TValue Value, ImmutableArray<Diagnostic> Errors);
+56
ファイルの表示
@@ -0,0 +1,56 @@
using System;
using System.Collections.Generic;
namespace ComputeSharp.D2D1Interop.SourceGenerators.Models;
/// <summary>
/// A model representing gathered info on a embedded thread ids.
/// </summary>
/// <param name="IsDefault">Whether the values are diascarded.</param>
/// <param name="X">The thread ids value for the X axis.</param>
/// <param name="Y">The thread ids value for the Y axis.</param>
/// <param name="Z">The thread ids value for the Z axis.</param>
internal sealed record ThreadIdsInfo(bool IsDefault, int X, int Y, int Z)
{
/// <summary>
/// An <see cref="IEqualityComparer{T}"/> implementation for <see cref="ThreadIdsInfo"/>.
/// </summary>
public sealed class Comparer : IEqualityComparer<ThreadIdsInfo>
{
/// <summary>
/// The singleton <see cref="Comparer"/> instance.
/// </summary>
public static Comparer Default { get; } = new();
/// <inheritdoc/>
public bool Equals(ThreadIdsInfo? x, ThreadIdsInfo? y)
{
if (x is null && y is null)
{
return true;
}
if (x is null || y is null)
{
return false;
}
if (ReferenceEquals(x, y))
{
return true;
}
return
x.IsDefault == y.IsDefault &&
x.X == y.X &&
x.Y == y.Y &&
x.Z == y.Y;
}
/// <inheritdoc/>
public int GetHashCode(ThreadIdsInfo obj)
{
return HashCode.Combine(obj.IsDefault, obj.X, obj.Y, obj.Z);
}
}
}
@@ -0,0 +1,205 @@
using ComputeSharp.D2D1Interop.SourceGenerators.Diagnostics;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using static ComputeSharp.D2D1Interop.SourceGenerators.Diagnostics.DiagnosticDescriptors;
namespace ComputeSharp.D2D1Interop.SourceGenerators.SyntaxRewriters;
/// <inheritdoc cref="HlslSourceRewriter"/>
internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter
{
/// <inheritdoc/>
public override SyntaxNode? VisitAnonymousObjectCreationExpression(AnonymousObjectCreationExpressionSyntax node)
{
var updatedNode = (AnonymousObjectCreationExpressionSyntax)base.VisitAnonymousObjectCreationExpression(node)!;
Diagnostics.Add(AnonymousObjectCreationExpression, node);
return updatedNode;
}
/// <inheritdoc/>
public override SyntaxNode? VisitAwaitExpression(AwaitExpressionSyntax node)
{
Diagnostics.Add(AwaitExpression, node);
return base.VisitAwaitExpression(node);
}
/// <inheritdoc/>
public override SyntaxNode? VisitCheckedExpression(CheckedExpressionSyntax node)
{
Diagnostics.Add(CheckedExpression, node);
return base.VisitCheckedExpression(node);
}
/// <inheritdoc/>
public override SyntaxNode? VisitCheckedStatement(CheckedStatementSyntax node)
{
Diagnostics.Add(CheckedStatement, node);
return base.VisitCheckedStatement(node);
}
/// <inheritdoc/>
public override SyntaxNode? VisitFixedStatement(FixedStatementSyntax node)
{
Diagnostics.Add(FixedStatement, node);
return base.VisitFixedStatement(node);
}
/// <inheritdoc/>
public override SyntaxNode? VisitForEachStatement(ForEachStatementSyntax node)
{
Diagnostics.Add(ForEachStatement, node);
return base.VisitForEachStatement(node);
}
/// <inheritdoc/>
public override SyntaxNode? VisitForEachVariableStatement(ForEachVariableStatementSyntax node)
{
Diagnostics.Add(ForEachStatement, node);
return base.VisitForEachVariableStatement(node);
}
/// <inheritdoc/>
public override SyntaxNode? VisitLockStatement(LockStatementSyntax node)
{
Diagnostics.Add(LockStatement, node);
return base.VisitLockStatement(node);
}
/// <inheritdoc/>
public override SyntaxNode? VisitQueryExpression(QueryExpressionSyntax node)
{
Diagnostics.Add(QueryExpression, node);
return base.VisitQueryExpression(node);
}
/// <inheritdoc/>
public override SyntaxNode? VisitRangeExpression(RangeExpressionSyntax node)
{
Diagnostics.Add(RangeExpression, node);
return base.VisitRangeExpression(node);
}
/// <inheritdoc/>
public override SyntaxNode? VisitRecursivePattern(RecursivePatternSyntax node)
{
Diagnostics.Add(RecursivePattern, node);
return base.VisitRecursivePattern(node);
}
/// <inheritdoc/>
public override SyntaxNode? VisitRefType(RefTypeSyntax node)
{
Diagnostics.Add(RefType, node);
return base.VisitRefType(node);
}
/// <inheritdoc/>
public override SyntaxNode? VisitRelationalPattern(RelationalPatternSyntax node)
{
Diagnostics.Add(RelationalPattern, node);
return base.VisitRelationalPattern(node);
}
/// <inheritdoc/>
public override SyntaxNode? VisitSizeOfExpression(SizeOfExpressionSyntax node)
{
Diagnostics.Add(SizeOfExpression, node);
return base.VisitSizeOfExpression(node);
}
/// <inheritdoc/>
public override SyntaxNode? VisitStackAllocArrayCreationExpression(StackAllocArrayCreationExpressionSyntax node)
{
Diagnostics.Add(StackAllocArrayCreationExpression, node);
return base.VisitStackAllocArrayCreationExpression(node);
}
/// <inheritdoc/>
public override SyntaxNode? VisitThrowExpression(ThrowExpressionSyntax node)
{
Diagnostics.Add(ThrowExpressionOrStatement, node);
return base.VisitThrowExpression(node);
}
/// <inheritdoc/>
public override SyntaxNode? VisitThrowStatement(ThrowStatementSyntax node)
{
Diagnostics.Add(ThrowExpressionOrStatement, node);
return base.VisitThrowStatement(node);
}
/// <inheritdoc/>
public override SyntaxNode? VisitTryStatement(TryStatementSyntax node)
{
Diagnostics.Add(TryStatement, node);
return base.VisitTryStatement(node);
}
/// <inheritdoc/>
public override SyntaxNode? VisitTupleType(TupleTypeSyntax node)
{
Diagnostics.Add(TupleType, node);
return base.VisitTupleType(node);
}
/// <inheritdoc/>
public override SyntaxNode? VisitUsingStatement(UsingStatementSyntax node)
{
Diagnostics.Add(UsingStatementOrDeclaration, node);
return base.VisitUsingStatement(node);
}
/// <inheritdoc/>
public override SyntaxNode? VisitYieldStatement(YieldStatementSyntax node)
{
Diagnostics.Add(YieldStatement, node);
return base.VisitYieldStatement(node);
}
/// <inheritdoc/>
public override SyntaxNode? VisitFunctionPointerType(FunctionPointerTypeSyntax node)
{
Diagnostics.Add(FunctionPointer, node);
return base.VisitFunctionPointerType(node);
}
/// <inheritdoc/>
public override SyntaxNode? VisitPointerType(PointerTypeSyntax node)
{
Diagnostics.Add(PointerType, node);
return base.VisitPointerType(node);
}
/// <inheritdoc/>
public override SyntaxNode? VisitUnsafeStatement(UnsafeStatementSyntax node)
{
Diagnostics.Add(UnsafeStatement, node);
return base.VisitUnsafeStatement(node);
}
}
+302
ファイルの表示
@@ -0,0 +1,302 @@
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Globalization;
using System.Linq;
using ComputeSharp.D2D1Interop.SourceGenerators.Diagnostics;
using ComputeSharp.D2D1Interop.SourceGenerators.Extensions;
using ComputeSharp.D2D1Interop.SourceGenerators.Helpers;
using ComputeSharp.D2D1Interop.SourceGenerators.Mappings;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Operations;
using static ComputeSharp.D2D1Interop.SourceGenerators.Diagnostics.DiagnosticDescriptors;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
namespace ComputeSharp.D2D1Interop.SourceGenerators.SyntaxRewriters;
/// <summary>
/// A base <see cref="CSharpSyntaxRewriter"/> type that processes C# source to convert to HLSL compliant code.
/// This class contains only the shared logic for all derived HLSL source rewriters.
/// </summary>
internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter
{
/// <summary>
/// The <see cref="SemanticModelProvider"/> instance with semantic info on the target syntax tree.
/// </summary>
protected readonly SemanticModelProvider SemanticModel;
/// <summary>
/// The collection of discovered custom types.
/// </summary>
protected readonly ICollection<INamedTypeSymbol> DiscoveredTypes;
/// <summary>
/// The collection of discovered constant definitions.
/// </summary>
protected readonly IDictionary<IFieldSymbol, string> ConstantDefinitions;
/// <summary>
/// The collection of produced <see cref="Diagnostic"/> instances.
/// </summary>
protected readonly ImmutableArray<Diagnostic>.Builder Diagnostics;
/// <summary>
/// Creates a new <see cref="HlslSourceRewriter"/> instance with the specified parameters.
/// </summary>
/// <param name="semanticModel">The <see cref="Microsoft.CodeAnalysis.SemanticModel"/> instance for the target syntax tree.</param>
/// <param name="discoveredTypes">The set of discovered custom types.</param>
/// <param name="constantDefinitions">The collection of discovered constant definitions.</param>
/// <param name="diagnostics">The collection of produced <see cref="Diagnostic"/> instances.</param>
protected HlslSourceRewriter(
SemanticModelProvider semanticModel,
ICollection<INamedTypeSymbol> discoveredTypes,
IDictionary<IFieldSymbol, string> constantDefinitions,
ImmutableArray<Diagnostic>.Builder diagnostics)
{
SemanticModel = semanticModel;
DiscoveredTypes = discoveredTypes;
ConstantDefinitions = constantDefinitions;
Diagnostics = diagnostics;
}
/// <inheritdoc/>
public override SyntaxNode VisitCastExpression(CastExpressionSyntax node)
{
var updatedNode = (CastExpressionSyntax)base.VisitCastExpression(node)!;
return updatedNode.ReplaceAndTrackType(updatedNode.Type, node.Type, SemanticModel.For(node), DiscoveredTypes);
}
/// <inheritdoc/>
public override SyntaxNode? VisitVariableDeclaration(VariableDeclarationSyntax node)
{
var updatedNode = (VariableDeclarationSyntax)base.VisitVariableDeclaration(node)!;
if (SemanticModel.For(node).GetTypeInfo(node.Type).Type is ITypeSymbol { IsUnmanagedType: false } type)
{
Diagnostics.Add(InvalidObjectDeclaration, node, type);
}
// If var is used, replace it with the explicit type
if (updatedNode.Type is IdentifierNameSyntax { IsVar: true })
{
updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.Type, node.Type, SemanticModel.For(node), DiscoveredTypes);
}
return updatedNode;
}
/// <inheritdoc/>
public override SyntaxNode VisitObjectCreationExpression(ObjectCreationExpressionSyntax node)
{
var updatedNode = (ObjectCreationExpressionSyntax)base.VisitObjectCreationExpression(node)!;
if (SemanticModel.For(node).GetTypeInfo(node).Type is ITypeSymbol { IsUnmanagedType: false } type)
{
Diagnostics.Add(InvalidObjectCreationExpression, node, type);
}
updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.Type, node, SemanticModel.For(node), DiscoveredTypes);
// New objects use the default HLSL cast syntax, eg. (float4)0
if (updatedNode.ArgumentList!.Arguments.Count == 0)
{
return CastExpression(updatedNode.Type, LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0)));
}
// Add explicit casts for matrix constructors to help the overload resolution
if (SemanticModel.For(node).GetTypeInfo(node).Type is ITypeSymbol matrixType &&
HlslKnownTypes.IsMatrixType(matrixType.GetFullMetadataName()))
{
for (int i = 0; i < node.ArgumentList!.Arguments.Count; i++)
{
IArgumentOperation argumentOperation = (IArgumentOperation)SemanticModel.For(node).GetOperation(node.ArgumentList.Arguments[i])!;
INamedTypeSymbol elementType = (INamedTypeSymbol)argumentOperation.Parameter!.Type;
updatedNode = updatedNode.ReplaceNode(
updatedNode.ArgumentList!.Arguments[i].Expression,
CastExpression(IdentifierName(HlslKnownTypes.GetMappedName(elementType)), updatedNode.ArgumentList.Arguments[i].Expression));
}
}
return InvocationExpression(updatedNode.Type, updatedNode.ArgumentList!);
}
/// <inheritdoc/>
public override SyntaxNode VisitImplicitObjectCreationExpression(ImplicitObjectCreationExpressionSyntax node)
{
var updatedNode = (ImplicitObjectCreationExpressionSyntax)base.VisitImplicitObjectCreationExpression(node)!;
if (SemanticModel.For(node).GetTypeInfo(node).Type is ITypeSymbol { IsUnmanagedType: false } type)
{
Diagnostics.Add(InvalidObjectCreationExpression, node, type);
}
TypeSyntax explicitType = IdentifierName("").ReplaceAndTrackType(node, SemanticModel.For(node), DiscoveredTypes);
// Mutate the syntax like with explicit object creation expressions
if (updatedNode.ArgumentList!.Arguments.Count == 0)
{
return CastExpression(explicitType, LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0)));
}
// Add explicit casts like with the explicit object creation expressions above
if (SemanticModel.For(node).GetTypeInfo(node).Type is ITypeSymbol matrixType &&
HlslKnownTypes.IsMatrixType(matrixType.GetFullMetadataName()))
{
for (int i = 0; i < node.ArgumentList.Arguments.Count; i++)
{
IArgumentOperation argumentOperation = (IArgumentOperation)SemanticModel.For(node).GetOperation(node.ArgumentList.Arguments[i])!;
INamedTypeSymbol elementType = (INamedTypeSymbol)argumentOperation.Parameter!.Type;
updatedNode = updatedNode.ReplaceNode(
updatedNode.ArgumentList.Arguments[i].Expression,
CastExpression(IdentifierName(HlslKnownTypes.GetMappedName(elementType)), updatedNode.ArgumentList.Arguments[i].Expression));
}
}
return InvocationExpression(explicitType, updatedNode.ArgumentList);
}
/// <inheritdoc/>
public override SyntaxNode VisitDefaultExpression(DefaultExpressionSyntax node)
{
var updatedNode = (DefaultExpressionSyntax)base.VisitDefaultExpression(node)!;
updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.Type, node.Type, SemanticModel.For(node), DiscoveredTypes);
// A default expression becomes (T)0 in HLSL
return CastExpression(updatedNode.Type, LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0)));
}
/// <inheritdoc/>
public override SyntaxNode? VisitLiteralExpression(LiteralExpressionSyntax node)
{
var updatedNode = (LiteralExpressionSyntax)base.VisitLiteralExpression(node)!;
if (updatedNode.IsKind(SyntaxKind.DefaultLiteralExpression))
{
TypeSyntax type = node.TrackType(SemanticModel.For(node), DiscoveredTypes);
// Same HLSL-style expression in the form (T)0
return CastExpression(type, LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0)));
}
else if (updatedNode.IsKind(SyntaxKind.NumericLiteralExpression) &&
SemanticModel.For(node).GetOperation(node) is ILiteralOperation operation &&
operation.Type is INamedTypeSymbol type)
{
// If the expression is a literal floating point value, we need to ensure the proper suffixes are
// used in the HLSL representation. Floating point values accept either f or F, but they don't work
// when the literal doesn't contain a decimal point. Since 32 bit floating point values are the default
// in HLSL, we can remove the suffix entirely. As for 64 bit values, we simply use the 'L' suffix.
if (type.GetFullMetadataName().Equals(typeof(float).FullName))
{
string literal = updatedNode.Token.ValueText;
// If the numeric literal is neither a decimal nor an exponential, add the ".0" suffix
if (literal.IndexOfAny(new[] { '.', 'E' }) == -1)
{
literal += ".0";
}
return updatedNode.WithToken(Literal(literal, 0f));
}
else if (type.GetFullMetadataName().Equals(typeof(double).FullName))
{
return updatedNode.WithToken(Literal(updatedNode.Token.ValueText + "L", 0d));
}
}
else if (updatedNode.IsKind(SyntaxKind.StringLiteralExpression))
{
Diagnostics.Add(StringLiteralExpression, node);
}
return updatedNode;
}
/// <inheritdoc/>
public override SyntaxNode? VisitElementAccessExpression(ElementAccessExpressionSyntax node)
{
var updatedNode = (ElementAccessExpressionSyntax)base.VisitElementAccessExpression(node)!;
if (SemanticModel.For(node).GetOperation(node) is IPropertyReferenceOperation operation)
{
string propertyName = operation.Property.GetFullMetadataName();
// If the current property is a swizzled matrix indexer, ensure all the arguments are constants, and rewrite
// the property access to the corresponding HLSL syntax. For instance, m[M11, M12] will become m._m00_m01.
if (HlslKnownMembers.IsKnownMatrixIndexer(propertyName))
{
bool isValid = true;
// Validate the arguments
foreach (ArgumentSyntax argument in node.ArgumentList.Arguments)
{
if (SemanticModel.For(node).GetOperation(argument.Expression) is not IFieldReferenceOperation fieldReference ||
!HlslKnownMembers.IsKnownMatrixIndex(fieldReference.Field.GetFullMetadataName()))
{
Diagnostics.Add(NonConstantMatrixSwizzledIndex, argument);
isValid = false;
}
}
if (isValid)
{
// Rewrite the indexer as a property access
string hlslPropertyName = string.Join("",
from argument in node.ArgumentList.Arguments
let fieldReference = (IFieldReferenceOperation)SemanticModel.For(node).GetOperation(argument.Expression)!
let fieldName = fieldReference.Field.Name
let row = (char)(fieldName[1] - 1)
let column = (char)(fieldName[2] - 1)
select $"_m{row}{column}");
return MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
updatedNode.Expression,
IdentifierName(hlslPropertyName));
}
}
}
return updatedNode;
}
/// <inheritdoc/>
public override SyntaxNode? VisitIdentifierName(IdentifierNameSyntax node)
{
var updatedNode = (IdentifierNameSyntax)base.VisitIdentifierName(node)!;
if (SemanticModel.For(node).GetOperation(node) is IFieldReferenceOperation operation &&
operation.Field.IsConst &&
operation.Type!.TypeKind != TypeKind.Enum)
{
ConstantDefinitions[operation.Field] = ((IFormattable)operation.Field.ConstantValue!).ToString(null, CultureInfo.InvariantCulture);
var ownerTypeName = ((INamedTypeSymbol)operation.Field.ContainingSymbol).ToDisplayString().ToHlslIdentifierName();
var constantName = $"__{ownerTypeName}__{operation.Field.Name}";
return IdentifierName(constantName);
}
return updatedNode;
}
/// <inheritdoc/>
public override SyntaxToken VisitToken(SyntaxToken token)
{
SyntaxToken updatedToken = base.VisitToken(token);
// Replace all identifier tokens when needed, to avoid colliding with HLSL keywords
if (updatedToken.IsKind(SyntaxKind.IdentifierToken) &&
HlslKnownKeywords.TryGetMappedName(updatedToken.Text, out string? mapped))
{
return ParseToken(mapped!);
}
return updatedToken.WithoutTrivia();
}
}
+332
ファイルの表示
@@ -0,0 +1,332 @@
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Globalization;
using System.Linq;
using ComputeSharp.D2D1Interop.SourceGenerators.Diagnostics;
using ComputeSharp.D2D1Interop.SourceGenerators.Extensions;
using ComputeSharp.D2D1Interop.SourceGenerators.Helpers;
using ComputeSharp.D2D1Interop.SourceGenerators.Mappings;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Operations;
using static ComputeSharp.D2D1Interop.SourceGenerators.Diagnostics.DiagnosticDescriptors;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
namespace ComputeSharp.D2D1Interop.SourceGenerators.SyntaxRewriters;
/// <summary>
/// A custom <see cref="CSharpSyntaxRewriter"/> type that processes C# methods to convert to HLSL compliant code.
/// </summary>
internal sealed class ShaderSourceRewriter : HlslSourceRewriter
{
/// <summary>
/// The type symbol for the shader type.
/// </summary>
private readonly INamedTypeSymbol? shaderType;
/// <summary>
/// The collection of discovered static methods.
/// </summary>
private readonly IDictionary<IMethodSymbol, MethodDeclarationSyntax> staticMethods;
/// <summary>
/// The collection of processed local functions in the current tree.
/// </summary>
private readonly Dictionary<string, LocalFunctionStatementSyntax> localFunctions;
/// <summary>
/// The list of implicit variables to declare at the start of the body.
/// </summary>
private readonly List<VariableDeclarationSyntax> implicitVariables;
/// <summary>
/// The current <see cref="MethodDeclarationSyntax"/> tree being visited.
/// </summary>
private MethodDeclarationSyntax? currentMethod;
/// <summary>
/// Creates a new <see cref="ShaderSourceRewriter"/> instance with the specified parameters.
/// </summary>
/// <param name="shaderType">The type symbol for the shader type.</param>
/// <param name="semanticModel">The <see cref="SemanticModelProvider"/> instance for the target syntax tree.</param>
/// <param name="discoveredTypes">The set of discovered custom types.</param>
/// <param name="staticMethods">The set of discovered and processed static methods.</param>
/// <param name="constantDefinitions">The collection of discovered constant definitions.</param>
/// <param name="diagnostics">The collection of produced <see cref="Diagnostic"/> instances.</param>
public ShaderSourceRewriter(
INamedTypeSymbol shaderType,
SemanticModelProvider semanticModel,
ICollection<INamedTypeSymbol> discoveredTypes,
IDictionary<IMethodSymbol, MethodDeclarationSyntax> staticMethods,
IDictionary<IFieldSymbol, string> constantDefinitions,
ImmutableArray<Diagnostic>.Builder diagnostics)
: base(semanticModel, discoveredTypes, constantDefinitions, diagnostics)
{
this.shaderType = shaderType;
this.staticMethods = staticMethods;
this.localFunctions = new();
this.implicitVariables = new();
}
/// <summary>
/// Creates a new <see cref="ShaderSourceRewriter"/> instance with the specified parameters.
/// </summary>
/// <param name="semanticModel">The <see cref="SemanticModelProvider"/> instance for the target syntax tree.</param>
/// <param name="discoveredTypes">The set of discovered custom types.</param>
/// <param name="staticMethods">The set of discovered and processed static methods.</param>
/// <param name="constantDefinitions">The collection of discovered constant definitions.</param>
/// <param name="diagnostics">The collection of produced <see cref="Diagnostic"/> instances.</param>
public ShaderSourceRewriter(
SemanticModelProvider semanticModel,
ICollection<INamedTypeSymbol> discoveredTypes,
IDictionary<IMethodSymbol, MethodDeclarationSyntax> staticMethods,
IDictionary<IFieldSymbol, string> constantDefinitions,
ImmutableArray<Diagnostic>.Builder diagnostics)
: base(semanticModel, discoveredTypes, constantDefinitions, diagnostics)
{
this.staticMethods = staticMethods;
this.implicitVariables = new();
this.localFunctions = new();
}
/// <summary>
/// Gets the collection of processed local functions in the current tree.
/// </summary>
public IReadOnlyDictionary<string, LocalFunctionStatementSyntax> LocalFunctions => this.localFunctions;
/// <inheritdoc cref="CSharpSyntaxRewriter.Visit(SyntaxNode?)"/>
public MethodDeclarationSyntax? Visit(MethodDeclarationSyntax? node)
{
this.currentMethod = node;
var updatedNode = (MethodDeclarationSyntax?)base.Visit(node)!;
updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.ReturnType, node!.ReturnType, SemanticModel.For(node), DiscoveredTypes);
if (node!.Modifiers.Any(m => m.IsKind(SyntaxKind.AsyncKeyword)))
{
Diagnostics.Add(AsyncModifierOnMethodOrFunction, node);
}
if (node!.Modifiers.Any(m => m.IsKind(SyntaxKind.UnsafeKeyword)))
{
Diagnostics.Add(UnsafeModifierOnMethodOrFunction, node);
}
if (updatedNode is not null)
{
var implicitBlock = Block(this.implicitVariables.Select(static v => LocalDeclarationStatement(v)).ToArray());
// Add the tracked implicit declarations (at the start of the body)
updatedNode = updatedNode.WithBody(implicitBlock).AddBodyStatements(updatedNode.Body!.Statements.ToArray());
}
return updatedNode;
}
/// <inheritdoc/>
public override SyntaxNode VisitParameter(ParameterSyntax node)
{
var updatedNode = (ParameterSyntax)base.VisitParameter(node)!;
// Convert the C# parameter modifiers to the HLSL equivalent
SyntaxToken modifier =
node.Modifiers
.Where(static m => m.Kind() is SyntaxKind.OutKeyword or SyntaxKind.RefKeyword or SyntaxKind.InKeyword)
.Select(static m => m.Kind() switch
{
SyntaxKind.OutKeyword => m,
SyntaxKind.InKeyword => m,
SyntaxKind.RefKeyword => ParseToken("inout"),
_ => Token(SyntaxKind.None)
}).FirstOrDefault();
return updatedNode
.WithAttributeLists(default)
.ReplaceAndTrackType(updatedNode.Type!, node.Type!, SemanticModel.For(node), DiscoveredTypes)
.WithModifiers(TokenList(modifier));
}
/// <inheritdoc/>
public override SyntaxNode VisitLocalDeclarationStatement(LocalDeclarationStatementSyntax node)
{
var updatedNode = ((LocalDeclarationStatementSyntax)base.VisitLocalDeclarationStatement(node)!);
if (SemanticModel.For(node).GetOperation(node) is IOperation { Kind: OperationKind.UsingDeclaration })
{
Diagnostics.Add(UsingStatementOrDeclaration, node);
}
return updatedNode.ReplaceAndTrackType(updatedNode.Declaration.Type, node.Declaration.Type, SemanticModel.For(node), DiscoveredTypes);
}
/// <inheritdoc/>
public override SyntaxNode? VisitDeclarationExpression(DeclarationExpressionSyntax node)
{
var updatedNode = (DeclarationExpressionSyntax)base.VisitDeclarationExpression(node)!;
updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.Type, node.Type, SemanticModel.For(node), DiscoveredTypes);
// Add the variable to the list of implicit declarations
this.implicitVariables.Add(VariableDeclaration(updatedNode.Type).AddVariables(VariableDeclarator(updatedNode.Designation.ToString())));
return IdentifierName(updatedNode.Designation.ToString());
}
/// <inheritdoc/>
public override SyntaxNode? VisitMethodDeclaration(MethodDeclarationSyntax node)
{
return
((MethodDeclarationSyntax)base.VisitMethodDeclaration(node)!)
.WithBlockBody()
.WithoutAccessibilityModifiers()
.WithAttributeLists(List<AttributeListSyntax>());
}
/// <inheritdoc/>
public override SyntaxNode? VisitLocalFunctionStatement(LocalFunctionStatementSyntax node)
{
var updatedNode =
((LocalFunctionStatementSyntax)base.VisitLocalFunctionStatement(node)!)
.WithBlockBody()
.WithAttributeLists(List<AttributeListSyntax>())
.WithIdentifier(Identifier($"__{this.currentMethod!.Identifier.Text}__{node.Identifier.Text}"));
updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.ReturnType, node!.ReturnType, SemanticModel.For(node), DiscoveredTypes);
if (node.Modifiers.Any(m => m.IsKind(SyntaxKind.AsyncKeyword)))
{
Diagnostics.Add(AsyncModifierOnMethodOrFunction, node);
}
if (node.Modifiers.Any(m => m.IsKind(SyntaxKind.UnsafeKeyword)))
{
Diagnostics.Add(UnsafeModifierOnMethodOrFunction, node);
}
// HLSL doesn't support local functions, so we first process them as usual and then remove
// them from the current syntax tree completely. These will be added to the shader source
// as external static method with a special name to avoid conflicts with other methods.
// The name will simply be in the format: "__<MethodName>__<FunctionName>".
this.localFunctions.Add(updatedNode.Identifier.Text, updatedNode);
return null;
}
/// <inheritdoc/>
public override SyntaxNode VisitMemberAccessExpression(MemberAccessExpressionSyntax node)
{
var updatedNode = (MemberAccessExpressionSyntax)base.VisitMemberAccessExpression(node)!;
if (node.IsKind(SyntaxKind.SimpleMemberAccessExpression) &&
SemanticModel.For(node).GetOperation(node) is IMemberReferenceOperation operation)
{
// If the member access is a constant, track it and replace the tree with the processed constant name
if (operation is IFieldReferenceOperation fieldOperation &&
fieldOperation.Field.IsConst &&
fieldOperation.Type!.TypeKind != TypeKind.Enum)
{
ConstantDefinitions[fieldOperation.Field] = ((IFormattable)fieldOperation.Field.ConstantValue!).ToString(null, CultureInfo.InvariantCulture);
var ownerTypeName = ((INamedTypeSymbol)fieldOperation.Field.ContainingSymbol).ToDisplayString().ToHlslIdentifierName();
var constantName = $"__{ownerTypeName}__{fieldOperation.Field.Name}";
return IdentifierName(constantName);
}
// If the current member access is a field or property access, check the lookup table
// to see if the member should be rewritten for HLSL compliance, and rewrite if needed.
if (HlslKnownMembers.TryGetMappedName(operation.Member.ToDisplayString(), out string? mapping))
{
// Static and instance members are handled differently, with static members being
// converted into a literal expression, and instance getting an updated identifier.
// For instance, consider these three cases:
// - Vector3.One (static) => float3(1.0f, 1.0f, 1.0f)
// - ThreadIds.X (custom) => ThreadIds.x
// - uint3.X (instance) => [arg].x
return operation.Member.IsStatic switch
{
true => ParseExpression(mapping!),
false => updatedNode.WithName(IdentifierName(mapping!))
};
}
}
return updatedNode;
}
/// <inheritdoc/>
public override SyntaxNode? VisitInvocationExpression(InvocationExpressionSyntax node)
{
var updatedNode = (InvocationExpressionSyntax)base.VisitInvocationExpression(node)!;
if (SemanticModel.For(node).GetOperation(node) is IInvocationOperation operation &&
operation.TargetMethod is IMethodSymbol method &&
method.IsStatic)
{
// If the invocation consists of invoking a static method that has a direct
// mapping to HLSL, rewrite the expression in the current invocation node.
// For instance: Math.Abs(expr) => abs(expr).
if (HlslKnownMethods.TryGetMappedName(method.GetFullMetadataName(), out string? mapping))
{
return updatedNode.WithExpression(ParseExpression(mapping!));
}
// Update the name if the target is a local function. The exact schema for the
// updated name is detailed in the override handling the local function statement.
if (method.MethodKind == MethodKind.LocalFunction)
{
var functionIdentifier = $"__{this.currentMethod!.Identifier.Text}__{method.Name}";
return updatedNode.WithExpression(ParseExpression(functionIdentifier));
}
// If the method is an external static method, import and rewrite it as well.
// This assumes that the target method is actually part of the same compilation.
// We need to check the declaring type to avoid rewriting static methods in the shader
// type as well, as they will be processed by the generator in a different path.
if (!SymbolEqualityComparer.Default.Equals(this.shaderType, method.ContainingType))
{
var methodIdentifier = method.GetFullMetadataName().ToHlslIdentifierName();
if (!this.staticMethods.ContainsKey(method))
{
ShaderSourceRewriter shaderSourceRewriter = new(SemanticModel, DiscoveredTypes, this.staticMethods, ConstantDefinitions, Diagnostics);
MethodDeclarationSyntax methodNode = (MethodDeclarationSyntax)method.DeclaringSyntaxReferences[0].GetSyntax();
MethodDeclarationSyntax processedMethod = shaderSourceRewriter.Visit(methodNode)!.NormalizeWhitespace(eol: "\n").WithoutTrivia();
this.staticMethods.Add(method, processedMethod.WithIdentifier(Identifier(methodIdentifier)));
}
return updatedNode.WithExpression(ParseExpression(methodIdentifier));
}
}
return updatedNode;
}
/// <inheritdoc/>
public override SyntaxNode? VisitArgument(ArgumentSyntax node)
{
var updatedNode = (ArgumentSyntax)base.VisitArgument(node)!;
// Strip the ref keywords from arguments
updatedNode = updatedNode.WithRefKindKeyword(Token(SyntaxKind.None));
// Track and rewrite the discarded declaration
if (SemanticModel.For(node).GetOperation(node.Expression) is IDiscardOperation operation)
{
TypeSyntax typeSyntax = operation.Type!.TrackType(DiscoveredTypes);
string identifier = $"__implicit{this.implicitVariables.Count}";
// Add the variable to the list of implicit declarations
this.implicitVariables.Add(VariableDeclaration(typeSyntax).AddVariables(VariableDeclarator(identifier)));
return updatedNode.WithExpression(IdentifierName(identifier));
}
return updatedNode;
}
}
+111
ファイルの表示
@@ -0,0 +1,111 @@
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Globalization;
using ComputeSharp.D2D1Interop.SourceGenerators.Extensions;
using ComputeSharp.D2D1Interop.SourceGenerators.Helpers;
using ComputeSharp.D2D1Interop.SourceGenerators.Mappings;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Operations;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
namespace ComputeSharp.D2D1Interop.SourceGenerators.SyntaxRewriters;
/// <summary>
/// A custom <see cref="CSharpSyntaxRewriter"/> type that processes C# static field to convert to HLSL static fields (possibly constant).
/// </summary>
internal sealed class StaticFieldRewriter : HlslSourceRewriter
{
/// <summary>
/// Creates a new <see cref="StaticFieldRewriter"/> instance with the specified parameters.
/// </summary>
/// <param name="semanticModel">The <see cref="SemanticModelProvider"/> instance for the target syntax tree.</param>
/// <param name="discoveredTypes">The set of discovered custom types.</param>
/// <param name="constantDefinitions">The collection of discovered constant definitions.</param>
/// <param name="diagnostics">The collection of produced <see cref="Diagnostic"/> instances.</param>
public StaticFieldRewriter(
SemanticModelProvider semanticModel,
ICollection<INamedTypeSymbol> discoveredTypes,
IDictionary<IFieldSymbol, string> constantDefinitions,
ImmutableArray<Diagnostic>.Builder diagnostics)
: base(semanticModel, discoveredTypes, constantDefinitions, diagnostics)
{
}
/// <inheritdoc cref="CSharpSyntaxRewriter.Visit(SyntaxNode?)"/>
public ExpressionSyntax? Visit(VariableDeclaratorSyntax? node)
{
if (node?.Initializer is EqualsValueClauseSyntax fieldInitializer)
{
return ((EqualsValueClauseSyntax)Visit(fieldInitializer))!.Value;
}
return null;
}
/// <inheritdoc/>
public override SyntaxNode VisitMemberAccessExpression(MemberAccessExpressionSyntax node)
{
var updatedNode = (MemberAccessExpressionSyntax)base.VisitMemberAccessExpression(node)!;
if (node.IsKind(SyntaxKind.SimpleMemberAccessExpression) &&
SemanticModel.For(node).GetOperation(node) is IMemberReferenceOperation operation)
{
// Track and replace constants
if (operation is IFieldReferenceOperation fieldOperation &&
fieldOperation.Field.IsConst &&
fieldOperation.Type!.TypeKind != TypeKind.Enum)
{
ConstantDefinitions[fieldOperation.Field] = ((IFormattable)fieldOperation.Field.ConstantValue!).ToString(null, CultureInfo.InvariantCulture);
var ownerTypeName = ((INamedTypeSymbol)fieldOperation.Field.ContainingSymbol).ToDisplayString().ToHlslIdentifierName();
var constantName = $"__{ownerTypeName}__{fieldOperation.Field.Name}";
return IdentifierName(constantName);
}
if (HlslKnownMembers.TryGetMappedName(operation.Member.ToDisplayString(), out string? mapping))
{
// Rewrite static and instance mapped members
return operation.Member.IsStatic switch
{
true => ParseExpression(mapping!),
false => updatedNode.WithName(IdentifierName(mapping!))
};
}
}
return updatedNode;
}
/// <inheritdoc/>
public override SyntaxNode? VisitInvocationExpression(InvocationExpressionSyntax node)
{
var updatedNode = (InvocationExpressionSyntax)base.VisitInvocationExpression(node)!;
if (SemanticModel.For(node).GetOperation(node) is IInvocationOperation operation &&
operation.TargetMethod is IMethodSymbol method &&
method.IsStatic)
{
// Rewrite HLSL intrinsic methods
if (HlslKnownMethods.TryGetMappedName(method.GetFullMetadataName(), out string? mapping))
{
return updatedNode.WithExpression(ParseExpression(mapping!));
}
}
return updatedNode;
}
/// <inheritdoc/>
public override SyntaxNode? VisitArgument(ArgumentSyntax node)
{
var updatedNode = (ArgumentSyntax)base.VisitArgument(node)!;
updatedNode = updatedNode.WithRefKindKeyword(Token(SyntaxKind.None));
return updatedNode;
}
}
@@ -0,0 +1,12 @@
using System.ComponentModel;
namespace System.Runtime.CompilerServices;
/// <summary>
/// Reserved to be used by the compiler for tracking metadata.
/// This class should not be used by developers in source code.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
internal static class IsExternalInit
{
}
+48 -48
ファイルの表示
@@ -7,51 +7,51 @@
Rule ID | Category | Severity | Notes
--------|----------|----------|-------
CMPS0001 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0002 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0003 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0004 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0005 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0006 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0007 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0008 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0009 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0010 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0011 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0012 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0013 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0014 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0015 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0016 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0017 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0018 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0019 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0020 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0021 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0022 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0023 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0024 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0025 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0026 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0027 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0028 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0029 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0030 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0031 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0032 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0033 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0034 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0035 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0036 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0037 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0038 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0039 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0040 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0041 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0042 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0043 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0044 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0045 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0046 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0047 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0048 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0001 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0002 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0003 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0004 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0005 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0006 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0007 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0008 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0009 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0010 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0011 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0012 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0013 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0014 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0015 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0016 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0017 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0018 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0019 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0020 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0021 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0022 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0023 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0024 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0025 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0026 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0027 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0028 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0029 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0030 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0031 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0032 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0033 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0034 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0035 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0036 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0037 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0038 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0039 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0040 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0041 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0042 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0043 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0044 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0045 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0046 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0047 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0048 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
+48 -48
ファイルの表示
@@ -19,7 +19,7 @@ internal static class DiagnosticDescriptors
id: "CMPS0001",
title: "Invalid shader field",
messageFormat: "The compute shader of type {0} contains a field \"{1}\" of an invalid type {2}",
category: typeof(IComputeShader).FullName,
category: "ComputeSharp.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "A type representing a compute shader contains a field of a type that is not supported in HLSL.",
@@ -35,7 +35,7 @@ internal static class DiagnosticDescriptors
id: "CMPS0002",
title: "Invalid group shared field type",
messageFormat: "The compute shader of type {0} contains a group shared field \"{1}\" of an invalid type {2} (it must be an array)",
category: typeof(IComputeShader).FullName,
category: "ComputeSharp.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "A group shared field must be of an array type.",
@@ -51,7 +51,7 @@ internal static class DiagnosticDescriptors
id: "CMPS0003",
title: "Invalid group shared field element type",
messageFormat: "The compute shader of type {0} contains a group shared field \"{1}\" of an invalid type {2} (it must be a primitive or unmanaged type)",
category: typeof(IComputeShader).FullName,
category: "ComputeSharp.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "A group shared field element must be of a primitive or unmanaged type.",
@@ -67,7 +67,7 @@ internal static class DiagnosticDescriptors
id: "CMPS0004",
title: "Invalid group shared field declaration",
messageFormat: "The compute shader of type {0} contains a group shared field \"{1}\" that is not static",
category: typeof(IComputeShader).FullName,
category: "ComputeSharp.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "A group shared field must be static.",
@@ -83,7 +83,7 @@ internal static class DiagnosticDescriptors
id: "CMPS0005",
title: "Missing shader resources",
messageFormat: "The compute shader of type {0} contains no resources to work on",
category: typeof(IComputeShader).FullName,
category: "ComputeSharp.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "A compute shader must contain at least one resource.",
@@ -96,7 +96,7 @@ internal static class DiagnosticDescriptors
id: "CMPS0006",
title: "Invalid ThreadIds usage",
messageFormat: "The ThreadIds type can only be used within the main body of a compute shader",
category: typeof(IComputeShader).FullName,
category: "ComputeSharp.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "The ThreadIds type can only be used within the main body of a compute shader.",
@@ -109,7 +109,7 @@ internal static class DiagnosticDescriptors
id: "CMPS0007",
title: "Invalid GroupIds usage",
messageFormat: "The GroupIds type can only be used within the main body of a compute shader",
category: typeof(IComputeShader).FullName,
category: "ComputeSharp.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "The GroupIds type can only be used within the main body of a compute shader.",
@@ -122,7 +122,7 @@ internal static class DiagnosticDescriptors
id: "CMPS0008",
title: "Invalid GroupSize usage",
messageFormat: "The GroupSize type can only be used within the main body of a compute shader",
category: typeof(IComputeShader).FullName,
category: "ComputeSharp.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "The GroupSize type can only be used within the main body of a compute shader.",
@@ -135,7 +135,7 @@ internal static class DiagnosticDescriptors
id: "CMPS0009",
title: "Invalid GridIds usage",
messageFormat: "The GridIds type can only be used within the main body of a compute shader",
category: typeof(IComputeShader).FullName,
category: "ComputeSharp.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "The GridIds type can only be used within the main body of a compute shader.",
@@ -151,7 +151,7 @@ internal static class DiagnosticDescriptors
id: "CMPS0010",
title: "Invalid object creation expression",
messageFormat: "The type {0} cannot be created in a compute shader (only unmanaged types are supported)",
category: typeof(IComputeShader).FullName,
category: "ComputeSharp.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "Only unmanaged value type objects can be created in a compute shader.",
@@ -164,7 +164,7 @@ internal static class DiagnosticDescriptors
id: "CMPS0011",
title: "Anonymous object creation expression",
messageFormat: "An anonymous object cannot be created in a compute shader",
category: typeof(IComputeShader).FullName,
category: "ComputeSharp.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "An anonymous object cannot be created in a compute shader.",
@@ -177,7 +177,7 @@ internal static class DiagnosticDescriptors
id: "CMPS0012",
title: "Async modifier on method or function",
messageFormat: "The async modifier cannot be used in methods or functions used in a compute shader",
category: typeof(IComputeShader).FullName,
category: "ComputeSharp.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "The async modifier cannot be used in methods or functions used in a compute shader.",
@@ -190,7 +190,7 @@ internal static class DiagnosticDescriptors
id: "CMPS0013",
title: "Await expression",
messageFormat: "The await expression cannot be used in a compute shader",
category: typeof(IComputeShader).FullName,
category: "ComputeSharp.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "The await expression cannot be used in a compute shader.",
@@ -203,7 +203,7 @@ internal static class DiagnosticDescriptors
id: "CMPS0014",
title: "Checked expression",
messageFormat: "A checked expression cannot be used in a compute shader",
category: typeof(IComputeShader).FullName,
category: "ComputeSharp.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "A checked expression cannot be used in a compute shader.",
@@ -216,7 +216,7 @@ internal static class DiagnosticDescriptors
id: "CMPS0015",
title: "Checked statement",
messageFormat: "A checked statement cannot be used in a compute shader",
category: typeof(IComputeShader).FullName,
category: "ComputeSharp.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "A checked statement cannot be used in a compute shader.",
@@ -229,7 +229,7 @@ internal static class DiagnosticDescriptors
id: "CMPS0016",
title: "Fixed statement",
messageFormat: "A fixed statement cannot be used in a compute shader",
category: typeof(IComputeShader).FullName,
category: "ComputeSharp.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "A fixed statement cannot be used in a compute shader.",
@@ -242,7 +242,7 @@ internal static class DiagnosticDescriptors
id: "CMPS0017",
title: "Foreach statement",
messageFormat: "A foreach statement cannot be used in a compute shader",
category: typeof(IComputeShader).FullName,
category: "ComputeSharp.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "A foreach statement cannot be used in a compute shader.",
@@ -255,7 +255,7 @@ internal static class DiagnosticDescriptors
id: "CMPS0018",
title: "Foreach statement",
messageFormat: "A lock statement cannot be used in a compute shader",
category: typeof(IComputeShader).FullName,
category: "ComputeSharp.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "A lock statement cannot be used in a compute shader.",
@@ -268,7 +268,7 @@ internal static class DiagnosticDescriptors
id: "CMPS0019",
title: "Foreach statement",
messageFormat: "A LINQ query expression cannot be used in a compute shader",
category: typeof(IComputeShader).FullName,
category: "ComputeSharp.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "A LINQ query expression cannot be used in a compute shader.",
@@ -281,7 +281,7 @@ internal static class DiagnosticDescriptors
id: "CMPS0020",
title: "Range expression",
messageFormat: "A range expression cannot be used in a compute shader",
category: typeof(IComputeShader).FullName,
category: "ComputeSharp.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "A range expression cannot be used in a compute shader.",
@@ -294,7 +294,7 @@ internal static class DiagnosticDescriptors
id: "CMPS0021",
title: "Recursive pattern",
messageFormat: "A recursive pattern cannot be used in a compute shader",
category: typeof(IComputeShader).FullName,
category: "ComputeSharp.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "A recursive pattern cannot be used in a compute shader.",
@@ -307,7 +307,7 @@ internal static class DiagnosticDescriptors
id: "CMPS0022",
title: "Ref type",
messageFormat: "A compute shader cannot have a ref type declaration",
category: typeof(IComputeShader).FullName,
category: "ComputeSharp.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "A compute shader cannot have a ref type declaration.",
@@ -320,7 +320,7 @@ internal static class DiagnosticDescriptors
id: "CMPS0023",
title: "Relational pattern",
messageFormat: "A relational pattern cannot be used in a compute shader",
category: typeof(IComputeShader).FullName,
category: "ComputeSharp.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "A relational pattern cannot be used in a compute shader.",
@@ -333,7 +333,7 @@ internal static class DiagnosticDescriptors
id: "CMPS0024",
title: "Sizeof expression",
messageFormat: "A sizeof expression cannot be used in a compute shader",
category: typeof(IComputeShader).FullName,
category: "ComputeSharp.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "A sizeof expression cannot be used in a compute shader.",
@@ -346,7 +346,7 @@ internal static class DiagnosticDescriptors
id: "CMPS0025",
title: "Stackalloc expression",
messageFormat: "A stackalloc expression cannot be used in a compute shader",
category: typeof(IComputeShader).FullName,
category: "ComputeSharp.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "A stackalloc expression cannot be used in a compute shader.",
@@ -359,7 +359,7 @@ internal static class DiagnosticDescriptors
id: "CMPS0026",
title: "Throw expression or statement",
messageFormat: "Throw expressions and statements cannot be used in a compute shader",
category: typeof(IComputeShader).FullName,
category: "ComputeSharp.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "Throw expressions and statements cannot be used in a compute shader.",
@@ -372,7 +372,7 @@ internal static class DiagnosticDescriptors
id: "CMPS0027",
title: "Try statement",
messageFormat: "A try statement cannot be used in a compute shader",
category: typeof(IComputeShader).FullName,
category: "ComputeSharp.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "A try statement cannot be used in a compute shader.",
@@ -385,7 +385,7 @@ internal static class DiagnosticDescriptors
id: "CMPS0028",
title: "Tuple type",
messageFormat: "A compute shader cannot have a tuple type declaration",
category: typeof(IComputeShader).FullName,
category: "ComputeSharp.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "A compute shader cannot have a tuple type declaration.",
@@ -398,7 +398,7 @@ internal static class DiagnosticDescriptors
id: "CMPS0029",
title: "Using statement or declaration",
messageFormat: "Using statements and declarations cannot be used in a compute shader",
category: typeof(IComputeShader).FullName,
category: "ComputeSharp.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "Using statements and declarations cannot be used in a compute shader.",
@@ -411,7 +411,7 @@ internal static class DiagnosticDescriptors
id: "CMPS0030",
title: "Yield statement",
messageFormat: "A yield statement cannot be used in a compute shader",
category: typeof(IComputeShader).FullName,
category: "ComputeSharp.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "A yield statement cannot be used in a compute shader.",
@@ -427,7 +427,7 @@ internal static class DiagnosticDescriptors
id: "CMPS0031",
title: "Invalid object declaration",
messageFormat: "A variable of type {0} cannot be declared in a compute shader (only unmanaged types are supported)",
category: typeof(IComputeShader).FullName,
category: "ComputeSharp.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "Only unmanaged value type objects can be declared in a compute shader.",
@@ -440,7 +440,7 @@ internal static class DiagnosticDescriptors
id: "CMPS0032",
title: "Pointer type",
messageFormat: "A compute shader cannot have a pointer type declaration",
category: typeof(IComputeShader).FullName,
category: "ComputeSharp.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "A compute shader cannot have a pointer type declaration.",
@@ -453,7 +453,7 @@ internal static class DiagnosticDescriptors
id: "CMPS0033",
title: "Function pointer type",
messageFormat: "A compute shader cannot have a function pointer type declaration",
category: typeof(IComputeShader).FullName,
category: "ComputeSharp.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "A compute shader cannot have a function pointer type declaration.",
@@ -466,7 +466,7 @@ internal static class DiagnosticDescriptors
id: "CMPS0034",
title: "Unsafe statement",
messageFormat: "A compute shader cannot have an unsafe statement",
category: typeof(IComputeShader).FullName,
category: "ComputeSharp.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "A compute shader cannot have an unsafe statement.",
@@ -479,7 +479,7 @@ internal static class DiagnosticDescriptors
id: "CMPS0035",
title: "Unsafe modifier on method or function",
messageFormat: "The unsafe modifier cannot be used in methods or functions used in a compute shader",
category: typeof(IComputeShader).FullName,
category: "ComputeSharp.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "The unsafe modifier cannot be used in methods or functions used in a compute shader.",
@@ -492,7 +492,7 @@ internal static class DiagnosticDescriptors
id: "CMPS0036",
title: "String literal expression",
messageFormat: "String literal expressions cannot be used in a compute shader",
category: typeof(IComputeShader).FullName,
category: "ComputeSharp.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "String literal expressions cannot be used in a compute shader.",
@@ -505,7 +505,7 @@ internal static class DiagnosticDescriptors
id: "CMPS0037",
title: "Non constant matrix swizzled property argument",
messageFormat: "The arguments in a swizzled indexer for a matrix type must be compile-time constants",
category: typeof(ShaderMethodSourceGenerator).FullName,
category: "ComputeSharp.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "The arguments in a swizzled indexer for a matrix type must be compile-time constants.",
@@ -521,7 +521,7 @@ internal static class DiagnosticDescriptors
id: "CMPS0038",
title: "Invalid shader static field type",
messageFormat: "The compute shader of type {0} contains a static field \"{1}\" of an invalid type {2} (only primitive, vector and matrix types are supported)",
category: typeof(IComputeShader).FullName,
category: "ComputeSharp.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "A type representing a compute shader contains a static field of a type that is not supported.",
@@ -534,7 +534,7 @@ internal static class DiagnosticDescriptors
id: "CMPS0039",
title: "Invalid DispatchSize usage",
messageFormat: "The DispatchSize type can only be used within the main body of a compute shader",
category: typeof(IComputeShader).FullName,
category: "ComputeSharp.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "The DispatchSize type can only be used within the main body of a compute shader.",
@@ -547,7 +547,7 @@ internal static class DiagnosticDescriptors
id: "CMPS0040",
title: "Property declaration",
messageFormat: "Property declarations cannot be used in a compute shader",
category: typeof(IComputeShader).FullName,
category: "ComputeSharp.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "Property declarations cannot be used in a compute shader.",
@@ -563,7 +563,7 @@ internal static class DiagnosticDescriptors
id: "CMPS0041",
title: "Shader dispatch data size exceeded",
messageFormat: "The compute shader of type {0} has exceeded the maximum allowed size for captured values and resources",
category: typeof(IComputeShader).FullName,
category: "ComputeSharp.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "The compute shader of type {0} has exceeded the maximum allowed size for captured values and resources.",
@@ -579,7 +579,7 @@ internal static class DiagnosticDescriptors
id: "CMPS0042",
title: "Multiple shader implementations for type declaration",
messageFormat: "The shader of type {0} cannot implement more than one shader interface",
category: typeof(IShaderGenerator).FullName,
category: "ComputeSharp.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "A shader type cannot implement more than one shader interface.",
@@ -595,7 +595,7 @@ internal static class DiagnosticDescriptors
id: "CMPS0043",
title: "Embedded bytecode for dynamic shader",
messageFormat: "The shader of type {0} cannot be precompiled, as it is dynamic (it captures delegate fields)",
category: typeof(IShaderGenerator).FullName,
category: "ComputeSharp.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "A shader type cannot be precompiled if it captures one or more delegate values.",
@@ -611,7 +611,7 @@ internal static class DiagnosticDescriptors
id: "CMPS0044",
title: "Invalid thread ids for shader with embedded bytecode",
messageFormat: "The shader of type {0} is annotated with invalid thread ids values ({1}, {2}, {3})",
category: typeof(IShaderGenerator).FullName,
category: "ComputeSharp.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "The thread ids values for a shader marked as embedded bytecode have to be in the valid range.",
@@ -627,7 +627,7 @@ internal static class DiagnosticDescriptors
id: "CMPS0045",
title: "Embedded bytecode compilation failed due to Win32 exception",
messageFormat: "The shader of type {0} failed to compile due to a Win32 exception (HRESULT: {1:X8}, Message: \"{2}\")",
category: typeof(IShaderGenerator).FullName,
category: "ComputeSharp.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "The embedded bytecode for a shader failed to be compiled due to a Win32 exception.",
@@ -643,7 +643,7 @@ internal static class DiagnosticDescriptors
id: "CMPS0046",
title: "Embedded bytecode compilation failed due to an HLSL compiler error",
messageFormat: "The shader of type {0} failed to compile due to an HLSL compiler error (Message: \"{1}\")",
category: typeof(IShaderGenerator).FullName,
category: "ComputeSharp.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "The embedded bytecode for a shader failed to be compiled due to an HLSL compiler error.",
@@ -659,7 +659,7 @@ internal static class DiagnosticDescriptors
id: "CMPS0047",
title: "Embedded bytecode compilation failed due to an HLSL compiler error",
messageFormat: "The shader of type {0} needs to be annotated as having embedded bytecode (using the [EmbeddedBytecode] attribute), as dynamic shader compilation is not supported",
category: typeof(IShaderGenerator).FullName,
category: "ComputeSharp.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "When dynamic shader compilation is not supported (ie. when ComputeSharp.Dynamic is not referenced), all shaders need to be annotated as having embedded bytecode (using the [EmbeddedBytecode] attribute).",
@@ -675,7 +675,7 @@ internal static class DiagnosticDescriptors
id: "CMPS0048",
title: "Invalid dispatch axis for shader with embedded bytecode",
messageFormat: "The shader of type {0} is annotated with with an invalid dispatch axis value",
category: typeof(IShaderGenerator).FullName,
category: "ComputeSharp.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "The dispatch axis value for a shader marked as embedded bytecode have to be valid (flags are not supported).",
+1 -1
ファイルの表示
@@ -14,7 +14,7 @@ internal static class HlslKnownSizes
/// <summary>
/// The mapping of supported known sizes to HLSL type names.
/// </summary>
private static IReadOnlyDictionary<string, (int, int)> KnownSizes = BuildKnownSizesMap();
private static readonly IReadOnlyDictionary<string, (int, int)> KnownSizes = BuildKnownSizesMap();
/// <summary>
/// Builds the mapping of known type sizes and alignments.