From 2212b8716de1adb53a6189d5e133eae466667892 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 5 Apr 2022 00:13:20 +0200 Subject: [PATCH] Port base APIs for D2D1 generator --- ...eSharp.D2D1Interop.SourceGenerators.csproj | 5 + .../Diagnostics/DiagnosticDescriptors.cs | 684 ++++++++++++++++++ .../Diagnostics/DiagnosticsExtensions.cs | 91 +++ .../Extensions/HashCodeExtensions.cs | 40 + .../Extensions/IEqualityComparerExtensions.cs | 59 ++ .../Extensions/ISymbolExtensions.cs | 134 ++++ .../Extensions/ImmutableArrayExtensions.cs | 50 ++ .../IncrementalValuesProviderExtensions.cs | 143 ++++ .../Extensions/StringExtensions.cs | 18 + .../Extensions/SyntaxNodeExtensions.cs | 198 +++++ .../Helpers/SemanticModelProvider.cs | 47 ++ .../IShaderGenerator.Helpers.cs | 133 ++++ .../IShaderGenerator.cs | 16 + .../Mappings/HlslKnownKeywords.cs | 71 ++ .../Mappings/HlslKnownMembers.cs | 233 ++++++ .../Mappings/HlslKnownMethods.cs | 165 +++++ .../Mappings/HlslKnownSizes.cs | 58 ++ .../Mappings/HlslKnownTypes.cs | 289 ++++++++ .../Models/DiagnosticInfo.cs | 64 ++ .../Models/DispatchDataInfo.cs | 73 ++ .../Models/DispatchIdInfo.cs | 55 ++ .../Models/DispatchMetadataInfo.cs | 65 ++ .../Models/EmbeddedBytecodeInfo.cs | 65 ++ .../Models/FieldInfo.cs | 137 ++++ .../Models/HierarchyInfo.cs | 90 +++ .../Models/HlslMethodSourceInfo.cs | 73 ++ .../Models/HlslShaderSourceInfo.cs | 109 +++ .../Models/ParameterInfo.cs | 8 + .../Models/ResourceDescriptor.cs | 54 ++ .../Models/Result{T}.cs | 12 + .../Models/ThreadIdsInfo.cs | 56 ++ .../HlslSourceRewriter.Diagnostics.cs | 205 ++++++ .../SyntaxRewriters/HlslSourceRewriter.cs | 302 ++++++++ .../SyntaxRewriters/ShaderSourceRewriter.cs | 332 +++++++++ .../SyntaxRewriters/StaticFieldRewriter.cs | 111 +++ .../IsExternalInit.cs | 12 + .../AnalyzerReleases.Shipped.md | 96 +-- .../Diagnostics/DiagnosticDescriptors.cs | 96 +-- .../Mappings/HlslKnownSizes.cs | 2 +- 39 files changed, 4354 insertions(+), 97 deletions(-) create mode 100644 src/ComputeSharp.D2D1Interop.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs create mode 100644 src/ComputeSharp.D2D1Interop.SourceGenerators/Diagnostics/DiagnosticsExtensions.cs create mode 100644 src/ComputeSharp.D2D1Interop.SourceGenerators/Extensions/HashCodeExtensions.cs create mode 100644 src/ComputeSharp.D2D1Interop.SourceGenerators/Extensions/IEqualityComparerExtensions.cs create mode 100644 src/ComputeSharp.D2D1Interop.SourceGenerators/Extensions/ISymbolExtensions.cs create mode 100644 src/ComputeSharp.D2D1Interop.SourceGenerators/Extensions/ImmutableArrayExtensions.cs create mode 100644 src/ComputeSharp.D2D1Interop.SourceGenerators/Extensions/IncrementalValuesProviderExtensions.cs create mode 100644 src/ComputeSharp.D2D1Interop.SourceGenerators/Extensions/StringExtensions.cs create mode 100644 src/ComputeSharp.D2D1Interop.SourceGenerators/Extensions/SyntaxNodeExtensions.cs create mode 100644 src/ComputeSharp.D2D1Interop.SourceGenerators/Helpers/SemanticModelProvider.cs create mode 100644 src/ComputeSharp.D2D1Interop.SourceGenerators/IShaderGenerator.Helpers.cs create mode 100644 src/ComputeSharp.D2D1Interop.SourceGenerators/IShaderGenerator.cs create mode 100644 src/ComputeSharp.D2D1Interop.SourceGenerators/Mappings/HlslKnownKeywords.cs create mode 100644 src/ComputeSharp.D2D1Interop.SourceGenerators/Mappings/HlslKnownMembers.cs create mode 100644 src/ComputeSharp.D2D1Interop.SourceGenerators/Mappings/HlslKnownMethods.cs create mode 100644 src/ComputeSharp.D2D1Interop.SourceGenerators/Mappings/HlslKnownSizes.cs create mode 100644 src/ComputeSharp.D2D1Interop.SourceGenerators/Mappings/HlslKnownTypes.cs create mode 100644 src/ComputeSharp.D2D1Interop.SourceGenerators/Models/DiagnosticInfo.cs create mode 100644 src/ComputeSharp.D2D1Interop.SourceGenerators/Models/DispatchDataInfo.cs create mode 100644 src/ComputeSharp.D2D1Interop.SourceGenerators/Models/DispatchIdInfo.cs create mode 100644 src/ComputeSharp.D2D1Interop.SourceGenerators/Models/DispatchMetadataInfo.cs create mode 100644 src/ComputeSharp.D2D1Interop.SourceGenerators/Models/EmbeddedBytecodeInfo.cs create mode 100644 src/ComputeSharp.D2D1Interop.SourceGenerators/Models/FieldInfo.cs create mode 100644 src/ComputeSharp.D2D1Interop.SourceGenerators/Models/HierarchyInfo.cs create mode 100644 src/ComputeSharp.D2D1Interop.SourceGenerators/Models/HlslMethodSourceInfo.cs create mode 100644 src/ComputeSharp.D2D1Interop.SourceGenerators/Models/HlslShaderSourceInfo.cs create mode 100644 src/ComputeSharp.D2D1Interop.SourceGenerators/Models/ParameterInfo.cs create mode 100644 src/ComputeSharp.D2D1Interop.SourceGenerators/Models/ResourceDescriptor.cs create mode 100644 src/ComputeSharp.D2D1Interop.SourceGenerators/Models/Result{T}.cs create mode 100644 src/ComputeSharp.D2D1Interop.SourceGenerators/Models/ThreadIdsInfo.cs create mode 100644 src/ComputeSharp.D2D1Interop.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.Diagnostics.cs create mode 100644 src/ComputeSharp.D2D1Interop.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.cs create mode 100644 src/ComputeSharp.D2D1Interop.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs create mode 100644 src/ComputeSharp.D2D1Interop.SourceGenerators/SyntaxRewriters/StaticFieldRewriter.cs create mode 100644 src/ComputeSharp.D2D1Interop.SourceGenerators/System.Runtime.CompilerServices/IsExternalInit.cs diff --git a/src/ComputeSharp.D2D1Interop.SourceGenerators/ComputeSharp.D2D1Interop.SourceGenerators.csproj b/src/ComputeSharp.D2D1Interop.SourceGenerators/ComputeSharp.D2D1Interop.SourceGenerators.csproj index 111af272..241f979a 100644 --- a/src/ComputeSharp.D2D1Interop.SourceGenerators/ComputeSharp.D2D1Interop.SourceGenerators.csproj +++ b/src/ComputeSharp.D2D1Interop.SourceGenerators/ComputeSharp.D2D1Interop.SourceGenerators.csproj @@ -68,6 +68,11 @@ + + + + + diff --git a/src/ComputeSharp.D2D1Interop.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs b/src/ComputeSharp.D2D1Interop.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs new file mode 100644 index 00000000..c696e2cf --- /dev/null +++ b/src/ComputeSharp.D2D1Interop.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs @@ -0,0 +1,684 @@ +using Microsoft.CodeAnalysis; + +namespace ComputeSharp.D2D1Interop.SourceGenerators.Diagnostics; + +#pragma warning disable IDE0090 // Use 'new(...)' +#pragma warning disable RS2000 // TODO + +/// +/// A container for all instances for errors reported by analyzers in this project. +/// +internal static class DiagnosticDescriptors +{ + /// + /// Gets a for an invalid shader field. + /// + /// Format: "The compute shader of type {0} contains a field \"{1}\" of an invalid type {2}". + /// + /// + 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"); + + /// + /// Gets a for an invalid group shared field type. + /// + /// Format: "The compute shader of type {0} contains a group shared field \"{1}\" of an invalid type {2}". + /// + /// + 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"); + + /// + /// Gets a for an invalid group shared field element type. + /// + /// Format: "The compute shader of type {0} contains a group shared field \"{1}\" of an invalid element type {2}". + /// + /// + 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"); + + /// + /// Gets a for an invalid group shared field declaration. + /// + /// Format: "The compute shader of type {0} contains a group shared field \"{1}\" that is not static". + /// + /// + 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"); + + /// + /// Gets a for a shader with no resources. + /// + /// Format: "The compute shader of type {0} contains no resources to work on". + /// + /// + 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"); + + /// + /// Gets a for an invalid usage. + /// + 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"); + + /// + /// Gets a for an invalid usage. + /// + 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"); + + /// + /// Gets a for an invalid usage. + /// + 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"); + + /// + /// Gets a for an invalid usage. + /// + 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"); + + /// + /// Gets a for an invalid object creation expression. + /// + /// Format: "The type {0} cannot be created in a compute shader". + /// + /// + 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"); + + /// + /// Gets a for an anonymous object creation expression. + /// + 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"); + + /// + /// Gets a for an async modifier on a method or function. + /// + 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"); + + /// + /// Gets a for an await expression. + /// + 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"); + + /// + /// Gets a for a checked expression. + /// + 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"); + + /// + /// Gets a for a checked statement. + /// + 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"); + + /// + /// Gets a for a fixed statement. + /// + 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"); + + /// + /// Gets a for a foreach statement. + /// + 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"); + + /// + /// Gets a for a lock statement. + /// + 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"); + + /// + /// Gets a for a query statement. + /// + 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"); + + /// + /// Gets a for a range expression. + /// + 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"); + + /// + /// Gets a for a recursive pattern. + /// + 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"); + + /// + /// Gets a for a ref type. + /// + 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"); + + /// + /// Gets a for a relational pattern. + /// + 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"); + + /// + /// Gets a for a sizeof expression. + /// + 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"); + + /// + /// Gets a for a stackalloc expression. + /// + 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"); + + /// + /// Gets a for a throw expression or statement. + /// + 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"); + + /// + /// Gets a for a try statement. + /// + 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"); + + /// + /// Gets a for a tuple type. + /// + 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"); + + /// + /// Gets a for a using statement or declaration. + /// + 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"); + + /// + /// Gets a for a yield statement. + /// + 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"); + + /// + /// Gets a for an invalid object declaration. + /// + /// Format: "A variable of type {0} cannot be declared in a compute shader". + /// + /// + 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"); + + /// + /// Gets a for a pointer type. + /// + 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"); + + /// + /// Gets a for a function pointer type. + /// + 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"); + + /// + /// Gets a for an unsafe statement. + /// + 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"); + + /// + /// Gets a for an unsafe modifier on a method or function. + /// + 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"); + + /// + /// Gets a for a string literal. + /// + 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"); + + /// + /// Gets a for an incorrect matrix swizzling property argument. + /// + 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"); + + /// + /// Gets a for an invalid shader static field type. + /// + /// Format: "The compute shader of type {0} contains a static field \"{1}\" of an invalid type {2} (only primitive, vector and matrix types are supported)". + /// + /// + 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"); + + /// + /// Gets a for an invalid usage. + /// + 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"); + + /// + /// Gets a for a property declaration. + /// + 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"); + + /// + /// Gets a for a shader with a root signature that is too large. + /// + /// Format: "The compute shader of type {0} has exceeded the maximum allowed size for captured values and resources". + /// + /// + 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"); + + /// + /// Gets a for a type implementing multiple shader interfaces. + /// + /// Format: "The shader of type {0} cannot implement more than one shader interface". + /// + /// + 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"); + + /// + /// Gets a for a dynamic shader annotated as an embedded bytecode. + /// + /// Format: "The shader of type {0} cannot be precompiled, as it is dynamic (it captures delegate fields)". + /// + /// + 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"); + + /// + /// Gets a for an embedded bytecode shader with invalid thread ids values. + /// + /// Format: "The shader of type {0} is annotated with invalid thread ids values ({1}, {2}, {3})". + /// + /// + 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"); + + /// + /// Gets a for an embedded bytecode shader failed due to a Win32 exception. + /// + /// Format: "The shader of type {0} failed to compile due to a Win32 exception (HRESULT: {1:X8}, Message: "{2}")". + /// + /// + 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"); + + /// + /// Gets a for an embedded bytecode shader failed due to an HLSL compilation exception. + /// + /// Format: "The shader of type {{0}} failed to compile due to an HLSL compiler error (Message: "{1}")". + /// + /// + 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"); + + /// + /// Gets a for a shader without the embedded bytecode attribute, when dynamic shaders are not supported. + /// + /// Format: "The shader of type {0} needs to be annotated as having embedded bytecode (using the [EmbeddedBytecode] attribute), as dynamic shader compilation is not supported". + /// + /// + 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"); + + /// + /// Gets a for an embedded bytecode shader with an invalid dispatch axis value. + /// + /// Format: "The shader of type {0} is annotated with an invalid dispatch axis value". + /// + /// + 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"); +} diff --git a/src/ComputeSharp.D2D1Interop.SourceGenerators/Diagnostics/DiagnosticsExtensions.cs b/src/ComputeSharp.D2D1Interop.SourceGenerators/Diagnostics/DiagnosticsExtensions.cs new file mode 100644 index 00000000..ce4a709c --- /dev/null +++ b/src/ComputeSharp.D2D1Interop.SourceGenerators/Diagnostics/DiagnosticsExtensions.cs @@ -0,0 +1,91 @@ +using System.Collections.Immutable; +using System.Linq; +using Microsoft.CodeAnalysis; + +namespace ComputeSharp.D2D1Interop.SourceGenerators.Diagnostics; + +/// +/// Extension methods for , specifically for reporting diagnostics. +/// +internal static class DiagnosticsExtensions +{ + /// + /// Adds a new diagnostics to the current compilation. + /// + /// The instance currently in use. + /// The input for the diagnostics to create. + /// The source to attach the diagnostics to. + /// The optional arguments for the formatted message to include. + public static void ReportDiagnostic( + this GeneratorExecutionContext context, + DiagnosticDescriptor descriptor, + ISymbol symbol, + params object[] args) + { + context.ReportDiagnostic(Diagnostic.Create(descriptor, symbol.Locations.FirstOrDefault(), args)); + } + + /// + /// Adds a new diagnostics to the current compilation. + /// + /// The instance currently in use. + /// The input for the diagnostics to create. + /// The source to attach the diagnostics to. + /// The optional arguments for the formatted message to include. + public static void ReportDiagnostic( + this GeneratorExecutionContext context, + DiagnosticDescriptor descriptor, + SyntaxNode node, + params object[] args) + { + context.ReportDiagnostic(Diagnostic.Create(descriptor, node.GetLocation(), args)); + } + + /// + /// Adds a new diagnostics to the target builder. + /// + /// The collection of produced instances. + /// The input for the diagnostics to create. + /// The source to attach the diagnostics to. + /// The optional arguments for the formatted message to include. + public static void Add( + this ImmutableArray.Builder diagnostics, + DiagnosticDescriptor descriptor, + ISymbol symbol, + params object[] args) + { + diagnostics.Add(Diagnostic.Create(descriptor, symbol.Locations.FirstOrDefault(), args)); + } + + /// + /// Adds a new diagnostics to the target builder. + /// + /// The collection of produced instances. + /// The input for the diagnostics to create. + /// The source to attach the diagnostics to. + /// The optional arguments for the formatted message to include. + public static void Add( + this ImmutableArray.Builder diagnostics, + DiagnosticDescriptor descriptor, + SyntaxNode node, + params object[] args) + { + diagnostics.Add(Diagnostic.Create(descriptor, node.GetLocation(), args)); + } + + /// + /// Registers an output node into an to output diagnostics. + /// + /// The input instance. + /// The input sequence of diagnostics. + public static void ReportDiagnostics(this IncrementalGeneratorInitializationContext context, IncrementalValuesProvider> diagnostics) + { + context.RegisterSourceOutput(diagnostics, static (context, diagnostics) => + { + foreach (Diagnostic diagnostic in diagnostics) + { + context.ReportDiagnostic(diagnostic); + } + }); + } +} diff --git a/src/ComputeSharp.D2D1Interop.SourceGenerators/Extensions/HashCodeExtensions.cs b/src/ComputeSharp.D2D1Interop.SourceGenerators/Extensions/HashCodeExtensions.cs new file mode 100644 index 00000000..56bf33c9 --- /dev/null +++ b/src/ComputeSharp.D2D1Interop.SourceGenerators/Extensions/HashCodeExtensions.cs @@ -0,0 +1,40 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; + +namespace ComputeSharp.D2D1Interop.SourceGenerators.Extensions; + +/// +/// Extension methods for . +/// +internal static class HashCodeExtensions +{ + /// + /// Adds all items from a given instance to an hashcode. + /// + /// The type of items to hash. + /// The target instance. + /// The input items to hash. + public static void AddRange(this ref HashCode hashCode, ImmutableArray items) + { + foreach (T item in items) + { + hashCode.Add(item); + } + } + + /// + /// Adds all items from a given instance to an hashcode. + /// + /// The type of items to hash. + /// The target instance. + /// A comparer to get hashcodes for items. + /// The input items to hash. + public static void AddRange(this ref HashCode hashCode, ImmutableArray items, IEqualityComparer comparer) + { + foreach (T item in items) + { + hashCode.Add(item, comparer); + } + } +} diff --git a/src/ComputeSharp.D2D1Interop.SourceGenerators/Extensions/IEqualityComparerExtensions.cs b/src/ComputeSharp.D2D1Interop.SourceGenerators/Extensions/IEqualityComparerExtensions.cs new file mode 100644 index 00000000..70c4e95b --- /dev/null +++ b/src/ComputeSharp.D2D1Interop.SourceGenerators/Extensions/IEqualityComparerExtensions.cs @@ -0,0 +1,59 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; + +namespace ComputeSharp.D2D1Interop.SourceGenerators.Extensions; + +/// +/// Extension methods for . +/// +internal static class IEqualityComparerExtensions +{ + /// + /// Gets an for an sequence. + /// + /// The type of items to compare. + /// The compare for individual items. + public static IEqualityComparer> ForImmutableArray(this IEqualityComparer comparer) + { + return new Comparer(comparer); + } + + /// + /// An implementation for an value. + /// + public sealed class Comparer : IEqualityComparer> + { + /// + /// The comparer. + /// + private readonly IEqualityComparer comparer; + + /// + /// Creates a new instance with the specified parameters. + /// + /// The comparer. + public Comparer(IEqualityComparer comparer) + { + this.comparer = comparer; + } + + /// + public bool Equals(ImmutableArray x, ImmutableArray y) + { + return + x == y || + x.SequenceEqual(y, this.comparer); + } + + /// + public int GetHashCode(ImmutableArray obj) + { + HashCode hashCode = default; + + hashCode.AddRange(obj, this.comparer); + + return hashCode.ToHashCode(); + } + } +} diff --git a/src/ComputeSharp.D2D1Interop.SourceGenerators/Extensions/ISymbolExtensions.cs b/src/ComputeSharp.D2D1Interop.SourceGenerators/Extensions/ISymbolExtensions.cs new file mode 100644 index 00000000..035b3abe --- /dev/null +++ b/src/ComputeSharp.D2D1Interop.SourceGenerators/Extensions/ISymbolExtensions.cs @@ -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; + +/// +/// Extension methods for types. +/// +internal static class ISymbolExtensions +{ + /// + /// A custom instance with fully qualified style, without global::. + /// + public static readonly SymbolDisplayFormat FullyQualifiedWithoutGlobalFormat = new( + globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted, + typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, + genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters); + + /// + /// A custom instance with fully qualified style, without global:: and parameters. + /// + private static readonly SymbolDisplayFormat FullyQualifiedWithoutGlobalAndParametersFormat = + FullyQualifiedWithoutGlobalFormat + .WithMemberOptions(SymbolDisplayMemberOptions.IncludeContainingType) + .WithParameterOptions(SymbolDisplayParameterOptions.None); + + /// + /// Gets the full metadata name for a given instance. + /// + /// The input instance. + /// The full metadata name for . + 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(); + } + + /// + /// Gets the full metadata name for a given instance. + /// + /// The input instance. + /// Whether or not to also include parameter types. + /// The full metadata name for . + 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); + } + + /// + /// Gets the full metadata name for a given instance. + /// + /// The input instance. + /// The full metadata name for . + 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}"; + } + + /// + /// Gets the full metadata name for a given instance. + /// + /// The input instance. + /// The full metadata name for . + public static string GetFullMetadataName(this IFieldSymbol symbol) + { + return $"{symbol.ContainingType.GetFullMetadataName()}.{symbol.Name}"; + } + + /// + /// Gets a valid filename for a target symbol and generator type. + /// + /// The symbol being processed. + /// A filename in the form "<SYMBOL_FULLNAME>" + public static string GetGeneratedFileName(this INamedTypeSymbol symbol) + { + return symbol.GetFullMetadataName().Replace('`', '-').Replace('+', '.'); + } + + /// + /// Tracks an instance and returns an HLSL compatible object. + /// + /// The input instance to process. + /// The collection of currently discovered types. + /// A instance that represents a type compatible with HLSL. + public static TypeSyntax TrackType(this ITypeSymbol typeSymbol, ICollection discoveredTypes) + { + string typeName = typeSymbol.ToDisplayString(FullyQualifiedWithoutGlobalFormat); + + discoveredTypes.Add((INamedTypeSymbol)typeSymbol); + + if (HlslKnownTypes.TryGetMappedName(typeName, out string? mappedName)) + { + return ParseTypeName(mappedName!); + } + + return ParseTypeName(typeName.ToHlslIdentifierName()); + } +} diff --git a/src/ComputeSharp.D2D1Interop.SourceGenerators/Extensions/ImmutableArrayExtensions.cs b/src/ComputeSharp.D2D1Interop.SourceGenerators/Extensions/ImmutableArrayExtensions.cs new file mode 100644 index 00000000..319e4b18 --- /dev/null +++ b/src/ComputeSharp.D2D1Interop.SourceGenerators/Extensions/ImmutableArrayExtensions.cs @@ -0,0 +1,50 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; + +namespace ComputeSharp.D2D1Interop.SourceGenerators.Extensions; + +/// +/// Extension methods for . +/// +internal static class ImmutableArrayExtensions +{ + /// + /// Compares two sequences for equality. + /// + /// The items to compare. + /// The left sequence of items. + /// The right sequence of items. + /// Whether or not equals . + public static bool SequenceEqual(this ImmutableArray left, ImmutableArray right) + where T : IEquatable + { + return left.AsSpan().SequenceEqual(right.AsSpan()); + } + + /// + /// Compares two sequences for equality. + /// + /// The items to compare. + /// The left sequence of items. + /// The right sequence of items. + /// The instance used to compare items. + /// Whether or not equals . + public static bool SequenceEqual(this ImmutableArray left, ImmutableArray right, IEqualityComparer 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; + } +} diff --git a/src/ComputeSharp.D2D1Interop.SourceGenerators/Extensions/IncrementalValuesProviderExtensions.cs b/src/ComputeSharp.D2D1Interop.SourceGenerators/Extensions/IncrementalValuesProviderExtensions.cs new file mode 100644 index 00000000..1289cd94 --- /dev/null +++ b/src/ComputeSharp.D2D1Interop.SourceGenerators/Extensions/IncrementalValuesProviderExtensions.cs @@ -0,0 +1,143 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis; + +namespace ComputeSharp.D2D1Interop.SourceGenerators.Extensions; + +/// +/// Extension methods for . +/// +internal static class IncrementalValuesProviderExtensions +{ + /// + /// Creates a new instance with a gven pair of comparers. + /// + /// The type of left items in each tuple. + /// The type of right items in each tuple. + /// The input instance. + /// An instance for items. + /// An instance for items. + /// An with the specified comparers applied to each item. + public static IncrementalValuesProvider<(TLeft Left, TRight Right)> WithComparers( + this IncrementalValuesProvider<(TLeft Left, TRight Right)> source, + IEqualityComparer comparerLeft, + IEqualityComparer comparerRight) + { + return source.WithComparer(new Comparer(comparerLeft, comparerRight)); + } + + /// + /// Creates a new instance with a gven pair of comparers. + /// + /// The type of first items in each tuple. + /// The type of second items in each tuple. + /// The type of third items in each tuple. + /// The input instance. + /// An instance for items. + /// An instance for items. + /// An instance for items. + /// An with the specified comparers applied to each item. + public static IncrementalValuesProvider<(T1, T2, T3)> WithComparers( + this IncrementalValuesProvider<(T1, T2, T3)> source, + IEqualityComparer comparer1, + IEqualityComparer comparer2, + IEqualityComparer comparer3) + { + return source.WithComparer(new Comparer(comparer1, comparer2, comparer3)); + } + + /// + /// An implementation for a value tuple. + /// + public sealed class Comparer : IEqualityComparer<(TLeft Left, TRight Right)> + { + /// + /// The comparer. + /// + private readonly IEqualityComparer comparerLeft; + + /// + /// The comparer. + /// + private readonly IEqualityComparer comparerRight; + + /// + /// Creates a new instance with the specified parameters. + /// + /// The comparer. + /// The comparer. + public Comparer(IEqualityComparer comparerLeft, IEqualityComparer comparerRight) + { + this.comparerLeft = comparerLeft; + this.comparerRight = comparerRight; + } + + /// + 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); + } + + /// + public int GetHashCode((TLeft Left, TRight Right) obj) + { + return HashCode.Combine( + this.comparerLeft.GetHashCode(obj.Left), + this.comparerRight.GetHashCode(obj.Right)); + } + } + + /// + /// An implementation for a value tuple. + /// + public sealed class Comparer : IEqualityComparer<(T1, T2, T3)> + { + /// + /// The comparer. + /// + private readonly IEqualityComparer comparer1; + + /// + /// The comparer. + /// + private readonly IEqualityComparer comparer2; + + /// + /// The comparer. + /// + private readonly IEqualityComparer comparer3; + + /// + /// Creates a new instance with the specified parameters. + /// + /// The comparer. + /// The comparer. + /// The comparer. + public Comparer(IEqualityComparer comparer1, IEqualityComparer comparer2, IEqualityComparer comparer3) + { + this.comparer1 = comparer1; + this.comparer2 = comparer2; + this.comparer3 = comparer3; + } + + /// + 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); + } + + /// + 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)); + } + } +} diff --git a/src/ComputeSharp.D2D1Interop.SourceGenerators/Extensions/StringExtensions.cs b/src/ComputeSharp.D2D1Interop.SourceGenerators/Extensions/StringExtensions.cs new file mode 100644 index 00000000..66a215d7 --- /dev/null +++ b/src/ComputeSharp.D2D1Interop.SourceGenerators/Extensions/StringExtensions.cs @@ -0,0 +1,18 @@ + +namespace ComputeSharp.D2D1Interop.SourceGenerators.Extensions; + +/// +/// Extension methods for types. +/// +internal static class StringExtensions +{ + /// + /// Converts a given instance to a valid HLSL identifier name. + /// + /// The input instance to convert. + /// An valid HLSL identifier name from . + public static string ToHlslIdentifierName(this string text) + { + return text.Replace('.', '_').Replace('+', '_'); + } +} diff --git a/src/ComputeSharp.D2D1Interop.SourceGenerators/Extensions/SyntaxNodeExtensions.cs b/src/ComputeSharp.D2D1Interop.SourceGenerators/Extensions/SyntaxNodeExtensions.cs new file mode 100644 index 00000000..b39bec35 --- /dev/null +++ b/src/ComputeSharp.D2D1Interop.SourceGenerators/Extensions/SyntaxNodeExtensions.cs @@ -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; + +/// +/// A with some extension methods for C# syntax nodes. +/// +internal static class SyntaxNodeExtensions +{ + /// + /// Checks a value and replaces the value type to be HLSL compatible, if needed. + /// + /// The type of the input instance. + /// The input to check and modify if needed. + /// The source to use to get type into from . + /// The instance with info on the input tree. + /// The collection of currently discovered types. + /// A instance that represents a type compatible with HLSL. + public static TRoot ReplaceAndTrackType(this TRoot node, SyntaxNode sourceType, SemanticModel semanticModel, ICollection discoveredTypes) + where TRoot : TypeSyntax + { + return node.ReplaceAndTrackType(node, sourceType, semanticModel, discoveredTypes); + } + + /// + /// Checks a value and replaces the value type to be HLSL compatible, if needed. + /// + /// The type of the input instance. + /// The input to check and modify if needed. + /// The target node to replace. + /// The source to use to get type into from . + /// The instance with info on the input tree. + /// The collection of currently discovered types. + /// A instance that represents a type compatible with HLSL. + public static TRoot ReplaceAndTrackType(this TRoot node, TypeSyntax targetType, SyntaxNode sourceType, SemanticModel semanticModel, ICollection 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())); + } + + /// + /// Tracks the associated type for a value and returns the HLSL compatible . + /// + /// The input to check. + /// The instance with info on the input tree. + /// The collection of currently discovered types. + /// A instance that represents a type compatible with HLSL. + public static TypeSyntax TrackType(this SyntaxNode node, SemanticModel semanticModel, ICollection 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()); + } + + /// + /// Returns a with a block body. + /// + /// The input node. + /// A node like the one in input, but always with a block body. + 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; + } + + /// + /// Returns a as a method definition. + /// + /// The input node. + /// A node like the one in input, but just as a definition. + 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)); + } + + /// + /// Returns a with a block body. + /// + /// The input node. + /// A node like the one in input, but always with a block body. + /// + /// This method is the same as , 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. + /// + 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; + } + + /// + /// Returns a as a method definition. + /// + /// The input node. + /// A node like the one in input, but just as a definition. + 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)); + } + + /// + /// Returns a instance with no accessibility modifiers. + /// + /// The input node. + /// A node just like but with no accessibility modifiers. + 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())); + } +} diff --git a/src/ComputeSharp.D2D1Interop.SourceGenerators/Helpers/SemanticModelProvider.cs b/src/ComputeSharp.D2D1Interop.SourceGenerators/Helpers/SemanticModelProvider.cs new file mode 100644 index 00000000..0730b1bb --- /dev/null +++ b/src/ComputeSharp.D2D1Interop.SourceGenerators/Helpers/SemanticModelProvider.cs @@ -0,0 +1,47 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis; + +namespace ComputeSharp.D2D1Interop.SourceGenerators.Helpers; + +/// +/// A type providing instances for nodes. +/// +internal sealed class SemanticModelProvider +{ + /// + /// The source instance. + /// + private readonly Compilation compilation; + + /// + /// The map of loaded instances. + /// + private readonly Dictionary semanticModelsMap; + + /// + /// Creates a new instance with the specified parameters. + /// + /// The source instance. + public SemanticModelProvider(Compilation compilation) + { + this.compilation = compilation; + this.semanticModelsMap = new Dictionary(); + } + + /// + /// Gets a instance with info on a given . + /// + /// The input to get info for. + /// A instance containing info on . + 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; + } +} diff --git a/src/ComputeSharp.D2D1Interop.SourceGenerators/IShaderGenerator.Helpers.cs b/src/ComputeSharp.D2D1Interop.SourceGenerators/IShaderGenerator.Helpers.cs new file mode 100644 index 00000000..989f4db4 --- /dev/null +++ b/src/ComputeSharp.D2D1Interop.SourceGenerators/IShaderGenerator.Helpers.cs @@ -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; + +/// +public sealed partial class ID2D1ShaderGenerator +{ + /// + /// Gets the shader type for a given shader, if any. + /// + /// The input instance to check. + /// The instance for . + /// Whether or not implements . + 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; + } + + /// + /// Creates a instance wrapping the given method. + /// + /// The instance for the current type. + /// The item to insert. + /// Whether [SkipLocalsInit] can be used. + /// A object wrapping . + private static CompilationUnitSyntax GetCompilationUnitFromMethod( + HierarchyInfo hierarchyInfo, + MethodDeclarationSyntax methodDeclaration, + bool canUseSkipLocalsInit) + { + // Method attributes + List attributes = new() + { + AttributeList(SingletonSeparatedList( + Attribute(IdentifierName("global::System.CodeDom.Compiler.GeneratedCode")).AddArgumentListArguments( + AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(ID2D1ShaderGenerator).FullName))), + AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(ID2D1ShaderGenerator).Assembly.GetName().Version.ToString())))))), + AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Diagnostics.DebuggerNonUserCode")))), + AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage")))), + AttributeList(SingletonSeparatedList( + Attribute(IdentifierName("global::System.ComponentModel.EditorBrowsable")).AddArgumentListArguments( + AttributeArgument(ParseExpression("global::System.ComponentModel.EditorBrowsableState.Never"))))), + AttributeList(SingletonSeparatedList( + Attribute(IdentifierName("global::System.Obsolete")).AddArgumentListArguments( + AttributeArgument(LiteralExpression( + SyntaxKind.StringLiteralExpression, + Literal("This method is not intended to be used directly by user code")))))) + }; + + // Add [SkipLocalsInit] if 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 + // { + // + // } + 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 + // + // + 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 ; + // + // + return + CompilationUnit().AddMembers( + FileScopedNamespaceDeclaration(IdentifierName(hierarchyInfo.Namespace)) + .AddMembers(typeDeclarationSyntax) + .WithNamespaceKeyword(Token(TriviaList( + Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), + SyntaxKind.NamespaceKeyword, + TriviaList()))) + .NormalizeWhitespace(eol: "\n"); + } +} diff --git a/src/ComputeSharp.D2D1Interop.SourceGenerators/IShaderGenerator.cs b/src/ComputeSharp.D2D1Interop.SourceGenerators/IShaderGenerator.cs new file mode 100644 index 00000000..39f0acf7 --- /dev/null +++ b/src/ComputeSharp.D2D1Interop.SourceGenerators/IShaderGenerator.cs @@ -0,0 +1,16 @@ +using Microsoft.CodeAnalysis; + +namespace ComputeSharp.D2D1Interop.SourceGenerators; + +/// +/// A source generator creating data loaders for the type. +/// +[Generator] +public sealed partial class IShaderGenerator : IIncrementalGenerator +{ + /// + public void Initialize(IncrementalGeneratorInitializationContext context) + { + + } +} diff --git a/src/ComputeSharp.D2D1Interop.SourceGenerators/Mappings/HlslKnownKeywords.cs b/src/ComputeSharp.D2D1Interop.SourceGenerators/Mappings/HlslKnownKeywords.cs new file mode 100644 index 00000000..05692a11 --- /dev/null +++ b/src/ComputeSharp.D2D1Interop.SourceGenerators/Mappings/HlslKnownKeywords.cs @@ -0,0 +1,71 @@ +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using ComputeSharp.Core.Intrinsics.Attributes; + +namespace ComputeSharp.D2D1Interop.SourceGenerators.Mappings; + +/// +/// A that contains and maps known HLSL identifier names valid HLSL names. +/// +internal static class HlslKnownKeywords +{ + /// + /// The mapping of known HLSL keywords. + /// + private static readonly IReadOnlyCollection KnownKeywords = BuildKnownKeywordsMap(); + + /// + /// Builds the mapping of all known HLSL keywords. + /// + private static IReadOnlyCollection BuildKnownKeywordsMap() + { + // HLSL keywords + HashSet 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()?.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()?.Name ?? method.Name; + + knownKeywords.Add(name); + } + + return knownKeywords; + } + + /// + /// Tries to get the mapped HLSL-compatible identifier name for the input identifier name. + /// + /// The input identifier name. + /// The mapped identifier name, if a replacement is needed. + /// The HLSL-compatible identifier name that can be used in an HLSL shader. + public static bool TryGetMappedName(string name, out string? mapped) + { + mapped = KnownKeywords.Contains(name) switch + { + true => $"__reserved__{name}", + false => null + }; + + return mapped is not null; + } +} diff --git a/src/ComputeSharp.D2D1Interop.SourceGenerators/Mappings/HlslKnownMembers.cs b/src/ComputeSharp.D2D1Interop.SourceGenerators/Mappings/HlslKnownMembers.cs new file mode 100644 index 00000000..3800e858 --- /dev/null +++ b/src/ComputeSharp.D2D1Interop.SourceGenerators/Mappings/HlslKnownMembers.cs @@ -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; + +/// +/// A that contains and maps known HLSL member names to common .NET members. +/// +internal static class HlslKnownMembers +{ + /// + /// The mapping of supported known members to HLSL names. + /// + private static readonly IReadOnlyDictionary KnownMembers = BuildKnownMembersMap(); + + /// + /// Builds the mapping of supported known members to HLSL names. + /// + private static IReadOnlyDictionary BuildKnownMembersMap() + { + Dictionary 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; + } + + /// + /// The mapping of supported known members to HLSL names. + /// + private static readonly IReadOnlyCollection KnownMatrixIndexers = BuildKnownMatrixIndexers(); + + /// + /// Builds the mapping of swizzled matrix indexer properties. + /// + private static IReadOnlyCollection 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(); + } + + /// + /// The mapping of supported known members to HLSL names. + /// + private static readonly IReadOnlyCollection KnownMatrixIndices = BuildKnownMatrixIndices(); + + /// + /// Builds the mapping of swizzled matrix indices. + /// + private static IReadOnlyCollection BuildKnownMatrixIndices() + { + return ( + from name in Enum.GetNames(typeof(MatrixIndex)) + select $"{typeof(MatrixIndex).FullName}.{name}").ToImmutableHashSet(); + } + + /// + /// Checks whether or not a given property fullname matches a matrix swizzled indexer. + /// + /// The input fully qualified member name. + /// Whether or not is a matrix swizzled indexer. + public static bool IsKnownMatrixIndexer(string name) + { + return KnownMatrixIndexers.Contains(name); + } + + /// + /// Checks whether or not a given property fullname matches a matrix swizzled index. + /// + /// The input fully qualified member name. + /// Whether or not is a matrix swizzled index. + public static bool IsKnownMatrixIndex(string name) + { + return KnownMatrixIndices.Contains(name); + } + + /// + /// Tries to get the mapped HLSL-compatible member name for the input member name. + /// + /// The input fully qualified member name. + /// The mapped name, if one is found. + /// The HLSL-compatible member name that can be used in an HLSL shader. + public static bool TryGetMappedName(string name, out string? mapped) + { + return KnownMembers.TryGetValue(name, out mapped); + } +} diff --git a/src/ComputeSharp.D2D1Interop.SourceGenerators/Mappings/HlslKnownMethods.cs b/src/ComputeSharp.D2D1Interop.SourceGenerators/Mappings/HlslKnownMethods.cs new file mode 100644 index 00000000..2b1d389d --- /dev/null +++ b/src/ComputeSharp.D2D1Interop.SourceGenerators/Mappings/HlslKnownMethods.cs @@ -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; + +/// +/// A that contains and maps known HLSL method names to common .NET methods. +/// +internal static class HlslKnownMethods +{ + /// + /// The mapping of supported known methods to HLSL names. + /// + private static readonly IReadOnlyDictionary KnownMethods = BuildKnownMethodsMap(); + + /// + /// Builds the mapping of supported known methods to HLSL names. + /// + private static IReadOnlyDictionary BuildKnownMethodsMap() + { + Dictionary 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()?.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()?.Name ?? method.Name; + + knownMethods.Add($"{typeof(D2D1).FullName}{Type.Delimiter}{method.Name}", hlslName); + } + + return knownMethods; + } + + /// + /// Tries to get the mapped HLSL-compatible method name for the input method name. + /// + /// The input fully qualified method name. + /// The mapped name, if one is found. + /// The HLSL-compatible member name that can be used in an HLSL shader. + public static bool TryGetMappedName(string name, out string? mapped) + { + return KnownMethods.TryGetValue(name, out mapped); + } +} diff --git a/src/ComputeSharp.D2D1Interop.SourceGenerators/Mappings/HlslKnownSizes.cs b/src/ComputeSharp.D2D1Interop.SourceGenerators/Mappings/HlslKnownSizes.cs new file mode 100644 index 00000000..b1377e24 --- /dev/null +++ b/src/ComputeSharp.D2D1Interop.SourceGenerators/Mappings/HlslKnownSizes.cs @@ -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; + +/// +/// A that contains and maps known HLSL types to their alignment sizes. +/// +internal static class HlslKnownSizes +{ + /// + /// The mapping of supported known sizes to HLSL type names. + /// + private static readonly IReadOnlyDictionary KnownSizes = BuildKnownSizesMap(); + + /// + /// Builds the mapping of known type sizes and alignments. + /// + private static IReadOnlyDictionary BuildKnownSizesMap() + { + Dictionary 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; + } + + /// + /// Gets the size and alignment info for a specified primitive type. + /// + /// The type name to get info for. + /// The size and and alignment for the input type. + public static (int Size, int Pack) GetTypeInfo(string typeName) + { + return KnownSizes[typeName]; + } +} diff --git a/src/ComputeSharp.D2D1Interop.SourceGenerators/Mappings/HlslKnownTypes.cs b/src/ComputeSharp.D2D1Interop.SourceGenerators/Mappings/HlslKnownTypes.cs new file mode 100644 index 00000000..858c4c1a --- /dev/null +++ b/src/ComputeSharp.D2D1Interop.SourceGenerators/Mappings/HlslKnownTypes.cs @@ -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; + +/// +/// A that contains and maps known HLSL type names to common .NET types. +/// +internal static class HlslKnownTypes +{ + /// + /// Gets the set of HLSL vector types. + /// + public static IReadOnlyCollection 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) + }; + + /// + /// Gets the set of HLSL matrix types. + /// + public static IReadOnlyCollection 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) + }; + + /// + /// The mapping of supported known types to HLSL types. + /// + private static readonly IReadOnlyDictionary KnownHlslTypes = BuildKnownHlslTypes(); + + /// + /// Builds the mapping of known primitive types. + /// + private static IReadOnlyDictionary BuildKnownHlslTypes() + { + Dictionary 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; + } + + /// + /// Checks whether or not a given type name matches a known HLSL primitive type (scalar, vector or matrix). + /// + /// The input type name to check. + /// Whether or not represents a scalar, vector or matrix type. + public static bool IsKnownHlslType(string typeName) + { + return KnownHlslTypes.ContainsKey(typeName); + } + + /// + /// Checks whether or not a given type name matches a vector type. + /// + /// The input type name to check. + /// Whether or not represents a vector type. + public static bool IsVectorType(string typeName) + { + return KnownVectorTypes.Any(type => type.FullName == typeName); + } + + /// + /// Checks whether or not a given type name matches a matrix type. + /// + /// The input type name to check. + /// Whether or not represents a matrix type. + public static bool IsMatrixType(string typeName) + { + return KnownMatrixTypes.Any(type => type.FullName == typeName); + } + + /// + /// 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). + /// + /// The input type name to check. + /// The element name of the matrix type. + /// The number of rows in the matrix type. + /// The number of columns in the matrix type. + /// Whether or not represents a non linear matrix type. + 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; + } + + /// + /// Gets the mapped HLSL-compatible type name for the input type symbol. + /// + /// The input type to map. + /// The HLSL-compatible type name that can be used in an HLSL shader. + 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(); + } + + /// + /// Gets the mapped HLSL-compatible type name for the input element type symbol. + /// + /// The input type to map. + /// The HLSL-compatible type name that can be used in an HLSL shader. + public static string GetMappedElementName(IArrayTypeSymbol typeSymbol) + { + string elementTypeName = ((INamedTypeSymbol)typeSymbol.ElementType).GetFullMetadataName(); + + if (KnownHlslTypes.TryGetValue(elementTypeName, out string? mapped)) + { + return mapped; + } + + return elementTypeName.ToHlslIdentifierName(); + } + + /// + /// Gets the mapped HLSL-compatible type name for the input type name. + /// + /// The input type name to map. + /// The resulting mapped type name, if found. + /// The HLSL-compatible type name that can be used in an HLSL shader. + public static bool TryGetMappedName(string originalName, out string? mappedName) + { + return KnownHlslTypes.TryGetValue(originalName, out mappedName); + } + + /// + /// Gets the sequence of unique custom types from a collection of discovered types. + /// + /// The input collection of discovered types. + /// The list of unique custom types. + public static IEnumerable GetCustomTypes(IEnumerable discoveredTypes) + { + // Local function to recursively gather nested types + static void ExploreTypes(INamedTypeSymbol type, HashSet customTypes) + { + if (KnownHlslTypes.ContainsKey(type.GetFullMetadataName())) return; + + if (!customTypes.Add(type)) return; + + foreach (var field in type.GetMembers().OfType()) + { + if (field.IsStatic) continue; + + ExploreTypes((INamedTypeSymbol)field.Type, customTypes); + } + } + + HashSet customTypes = new(SymbolEqualityComparer.Default); + + // Explore all input types and their nested types + foreach (INamedTypeSymbol type in discoveredTypes) + { + ExploreTypes(type, customTypes); + } + + return OrderByDependency(customTypes); + } + + /// + /// Orders the input sequence of types so that they can be declared in HLSL successfully. + /// + /// The input collection of types to declare. + /// The same list as input, but in a valid HLSL declaration order. + private static IEnumerable OrderByDependency(IEnumerable types) + { + Queue<(INamedTypeSymbol Type, HashSet 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 dependencies = new(SymbolEqualityComparer.Default); + + // Only add other custom types as dependencies, and ignore HLSL types + foreach (var field in type.GetMembers().OfType()) + { + 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); + } + } +} diff --git a/src/ComputeSharp.D2D1Interop.SourceGenerators/Models/DiagnosticInfo.cs b/src/ComputeSharp.D2D1Interop.SourceGenerators/Models/DiagnosticInfo.cs new file mode 100644 index 00000000..cef1419a --- /dev/null +++ b/src/ComputeSharp.D2D1Interop.SourceGenerators/Models/DiagnosticInfo.cs @@ -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; + +/// +/// A model for a serializeable diagnostic provider. +/// +/// The wrapped instance. +/// The diagnostic args. +internal sealed record DiagnosticInfo(DiagnosticDescriptor Descriptor, params object[] Args) +{ + /// + /// An implementation for . + /// + public sealed class Comparer : IEqualityComparer + { + /// + /// The singleton instance. + /// + public static Comparer Default { get; } = new(); + + /// + 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); + } + + /// + public int GetHashCode(DiagnosticInfo obj) + { + HashCode hashCode = default; + + hashCode.Add(obj.Descriptor); + + foreach (object arg in obj.Args) + { + hashCode.Add(arg); + } + + return hashCode.ToHashCode(); + } + } +} diff --git a/src/ComputeSharp.D2D1Interop.SourceGenerators/Models/DispatchDataInfo.cs b/src/ComputeSharp.D2D1Interop.SourceGenerators/Models/DispatchDataInfo.cs new file mode 100644 index 00000000..00a4d8f9 --- /dev/null +++ b/src/ComputeSharp.D2D1Interop.SourceGenerators/Models/DispatchDataInfo.cs @@ -0,0 +1,73 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using ComputeSharp.D2D1Interop.SourceGenerators.Extensions; + +namespace ComputeSharp.D2D1Interop.SourceGenerators.Models; + +/// +/// A model representing gathered info on a shader dispatch data. +/// +/// The hierarchy data for the shader. +/// The shader interface type. +/// The description on shader instance fields. +/// The total number of captured resources. +/// The size of the shader root signature, in 32 bit constants. +internal sealed record DispatchDataInfo( + HierarchyInfo Hierarchy, + Type Type, + ImmutableArray FieldInfos, + int ResourceCount, + int Root32BitConstantCount) +{ + /// + /// An implementation for . + /// + public sealed class Comparer : IEqualityComparer + { + /// + /// The singleton instance. + /// + public static Comparer Default { get; } = new(); + + /// + 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; + } + + /// + 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(); + } + } +} diff --git a/src/ComputeSharp.D2D1Interop.SourceGenerators/Models/DispatchIdInfo.cs b/src/ComputeSharp.D2D1Interop.SourceGenerators/Models/DispatchIdInfo.cs new file mode 100644 index 00000000..4d0dd6fb --- /dev/null +++ b/src/ComputeSharp.D2D1Interop.SourceGenerators/Models/DispatchIdInfo.cs @@ -0,0 +1,55 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using ComputeSharp.D2D1Interop.SourceGenerators.Extensions; + +namespace ComputeSharp.D2D1Interop.SourceGenerators.Models; + +/// +/// A model representing gathered info on a shader dispatch id. +/// +/// The list of delegate field names for the shader. +internal sealed record DispatchIdInfo(ImmutableArray Delegates) +{ + /// + /// An implementation for . + /// + public sealed class Comparer : IEqualityComparer + { + /// + /// The singleton instance. + /// + public static Comparer Default { get; } = new(); + + /// + 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); + } + + /// + public int GetHashCode(DispatchIdInfo obj) + { + HashCode hashCode = default; + + hashCode.AddRange(obj.Delegates); + + return hashCode.ToHashCode(); + } + } +} diff --git a/src/ComputeSharp.D2D1Interop.SourceGenerators/Models/DispatchMetadataInfo.cs b/src/ComputeSharp.D2D1Interop.SourceGenerators/Models/DispatchMetadataInfo.cs new file mode 100644 index 00000000..490a7def --- /dev/null +++ b/src/ComputeSharp.D2D1Interop.SourceGenerators/Models/DispatchMetadataInfo.cs @@ -0,0 +1,65 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using ComputeSharp.D2D1Interop.SourceGenerators.Extensions; + +namespace ComputeSharp.D2D1Interop.SourceGenerators.Models; + +/// +/// A model containing info on shader dispatch metadata. +/// +/// The size of the shader root signature, in 32 bit constants. +/// Whether or not the static sampler is used. +/// The sequence of resource descriptors for the shader. +internal sealed record DispatchMetadataInfo( + int Root32BitConstantCount, + bool IsSamplerUsed, + ImmutableArray ResourceDescriptors) +{ + /// + /// An implementation for . + /// + public sealed class Comparer : IEqualityComparer + { + /// + /// The singleton instance. + /// + public static Comparer Default { get; } = new(); + + /// + 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); + } + + /// + 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(); + } + } +} \ No newline at end of file diff --git a/src/ComputeSharp.D2D1Interop.SourceGenerators/Models/EmbeddedBytecodeInfo.cs b/src/ComputeSharp.D2D1Interop.SourceGenerators/Models/EmbeddedBytecodeInfo.cs new file mode 100644 index 00000000..91a8c2b4 --- /dev/null +++ b/src/ComputeSharp.D2D1Interop.SourceGenerators/Models/EmbeddedBytecodeInfo.cs @@ -0,0 +1,65 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using ComputeSharp.D2D1Interop.SourceGenerators.Extensions; + +namespace ComputeSharp.D2D1Interop.SourceGenerators.Models; + +/// +/// A model representing a compiled shader bytecode, or none. +/// +/// The thread ids value for the X axis. +/// The thread ids value for the Y axis. +/// The thread ids value for the Z axis. +/// The compiled shader bytecode, if available. +internal sealed record EmbeddedBytecodeInfo(int X, int Y, int Z, ImmutableArray Bytecode) +{ + /// + /// An implementation for . + /// + public sealed class Comparer : IEqualityComparer + { + /// + /// The singleton instance. + /// + public static Comparer Default { get; } = new(); + + /// + 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); + } + + /// + 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(); + } + } +} diff --git a/src/ComputeSharp.D2D1Interop.SourceGenerators/Models/FieldInfo.cs b/src/ComputeSharp.D2D1Interop.SourceGenerators/Models/FieldInfo.cs new file mode 100644 index 00000000..74f70236 --- /dev/null +++ b/src/ComputeSharp.D2D1Interop.SourceGenerators/Models/FieldInfo.cs @@ -0,0 +1,137 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using ComputeSharp.D2D1Interop.SourceGenerators.Extensions; + +namespace ComputeSharp.D2D1Interop.SourceGenerators.Models; + +/// +/// A base type for a model describing a given captured field in a shader. +/// +internal abstract record FieldInfo +{ + /// + /// A captured resource (either a buffer or a texture). + /// + /// The name of the resource field. + /// The full metadata name for the resource type. + /// The offset for the resource within the root signature. + public sealed record Resource(string FieldName, string TypeName, int Offset) : FieldInfo; + + /// + /// A captured primitive value (either a scalar, a vector, or a linear matrix). + /// + /// The path of the field with respect to the shader instance. + /// The full metadata name for the primitive type. + /// The byte offset of the value within the root signature. + public sealed record Primitive(ImmutableArray FieldPath, string TypeName, int Offset) : FieldInfo; + + /// + /// A captured non linear matrix value. + /// + /// The path of the field with respect to the shader instance. + /// The full metadata name for the matrix type. + /// The name of each element in the matrix type. + /// The number of rows in the matrix. + /// The number of columns in the matrix. + /// The sequence of byte offsets for each row within the root signature. + public sealed record NonLinearMatrix( + ImmutableArray FieldPath, + string TypeName, + string ElementName, + int Rows, + int Columns, + ImmutableArray Offsets) : FieldInfo; + + /// + /// An implementation for . + /// + public sealed class Comparer : IEqualityComparer + { + /// + /// The singleton instance. + /// + public static Comparer Default { get; } = new(); + + /// + 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; + } + + /// + 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; + } + } + } +} diff --git a/src/ComputeSharp.D2D1Interop.SourceGenerators/Models/HierarchyInfo.cs b/src/ComputeSharp.D2D1Interop.SourceGenerators/Models/HierarchyInfo.cs new file mode 100644 index 00000000..1d574d09 --- /dev/null +++ b/src/ComputeSharp.D2D1Interop.SourceGenerators/Models/HierarchyInfo.cs @@ -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; + +/// +/// A model describing the hierarchy info for a specific type. +/// +/// The filename hint for the current type. +/// The metadata name for the current type. +/// Gets the namespace for the current type. +/// Gets the sequence of type definitions containing the current type. +internal sealed record HierarchyInfo(string FilenameHint, string MetadataName, string Namespace, ImmutableArray Names) +{ + /// + /// Creates a new instance from a given . + /// + /// The input instance to gather info for. + /// A instance describing . + public static HierarchyInfo From(INamedTypeSymbol typeSymbol) + { + ImmutableArray.Builder names = ImmutableArray.CreateBuilder(); + + 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()); + } + + /// + /// An implementation for . + /// + public sealed class Comparer : IEqualityComparer + { + /// + /// The singleton instance. + /// + public static Comparer Default { get; } = new(); + + /// + 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); + } + + /// + 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(); + } + } +} diff --git a/src/ComputeSharp.D2D1Interop.SourceGenerators/Models/HlslMethodSourceInfo.cs b/src/ComputeSharp.D2D1Interop.SourceGenerators/Models/HlslMethodSourceInfo.cs new file mode 100644 index 00000000..a2540c98 --- /dev/null +++ b/src/ComputeSharp.D2D1Interop.SourceGenerators/Models/HlslMethodSourceInfo.cs @@ -0,0 +1,73 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using ComputeSharp.D2D1Interop.SourceGenerators.Extensions; + +namespace ComputeSharp.D2D1Interop.SourceGenerators.Models; + +/// +/// A model for extracted info on a processed HLSL method. +/// +/// The metadata name for the method. +/// The meethod entry point. +/// The discovered declared types. +/// The discovered defined constants. +/// The dependent captured methods. +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) +{ + /// + /// An implementation for . + /// + public sealed class Comparer : IEqualityComparer + { + /// + /// The singleton instance. + /// + public static Comparer Default { get; } = new(); + + /// + 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); + } + + /// + 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(); + } + } +} diff --git a/src/ComputeSharp.D2D1Interop.SourceGenerators/Models/HlslShaderSourceInfo.cs b/src/ComputeSharp.D2D1Interop.SourceGenerators/Models/HlslShaderSourceInfo.cs new file mode 100644 index 00000000..59bee7da --- /dev/null +++ b/src/ComputeSharp.D2D1Interop.SourceGenerators/Models/HlslShaderSourceInfo.cs @@ -0,0 +1,109 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using ComputeSharp.D2D1Interop.SourceGenerators.Extensions; + +namespace ComputeSharp.D2D1Interop.SourceGenerators.Models; + +/// +/// A model for extracted info on a processed HLSL shader. +/// +/// The shader generated header and threadsX count declaration. +/// The threadsY count declaration. +/// The threadsZ count declaration. +/// The define statements, if any. +/// The static fields and declared types, if any. +/// The captured fields, and method forward declarations. +/// The captured method implementations. +/// The shader entry point. +/// The type of the implicit texture type, if any. +/// Whether or not the static sampler is used. +/// The names of declared types. +/// The names of defined constants. +/// The signatures for captured methods. +/// The list of delegate fields. +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 DefinedTypes, + ImmutableArray DefinedConstants, + ImmutableArray MethodSignatures, + ImmutableArray Delegates) +{ + /// + /// An implementation for . + /// + public sealed class Comparer : IEqualityComparer + { + /// + /// The singleton instance. + /// + public static Comparer Default { get; } = new(); + + /// + 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); + } + + /// + 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(); + } + } +} diff --git a/src/ComputeSharp.D2D1Interop.SourceGenerators/Models/ParameterInfo.cs b/src/ComputeSharp.D2D1Interop.SourceGenerators/Models/ParameterInfo.cs new file mode 100644 index 00000000..d6e2c9cd --- /dev/null +++ b/src/ComputeSharp.D2D1Interop.SourceGenerators/Models/ParameterInfo.cs @@ -0,0 +1,8 @@ +namespace ComputeSharp.D2D1Interop.SourceGenerators.Models; + +/// +/// A model describing info on a constructor parameter. +/// +/// The fully qualified type name. +/// The parameter name. +internal sealed record ParameterInfo(string Type, string Name); diff --git a/src/ComputeSharp.D2D1Interop.SourceGenerators/Models/ResourceDescriptor.cs b/src/ComputeSharp.D2D1Interop.SourceGenerators/Models/ResourceDescriptor.cs new file mode 100644 index 00000000..92d34da7 --- /dev/null +++ b/src/ComputeSharp.D2D1Interop.SourceGenerators/Models/ResourceDescriptor.cs @@ -0,0 +1,54 @@ +using System; +using System.Collections.Generic; + +namespace ComputeSharp.D2D1Interop.SourceGenerators.Models; + +/// +/// A resource descriptor for a captured resource in a shader. +/// +/// The type id for the resource. +/// The offset of the resource in its containing register. +/// The offset of the resource descriptor in the shader root signature. +internal sealed record ResourceDescriptor(int TypeId, int RegisterOffset, int Offset) +{ + /// + /// An implementation for . + /// + public sealed class Comparer : IEqualityComparer + { + /// + /// The singleton instance. + /// + public static Comparer Default { get; } = new(); + + /// + 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; + } + + /// + public int GetHashCode(ResourceDescriptor obj) + { + return HashCode.Combine(obj.TypeId, obj.RegisterOffset, obj.Offset); + } + } +} diff --git a/src/ComputeSharp.D2D1Interop.SourceGenerators/Models/Result{T}.cs b/src/ComputeSharp.D2D1Interop.SourceGenerators/Models/Result{T}.cs new file mode 100644 index 00000000..82b20a62 --- /dev/null +++ b/src/ComputeSharp.D2D1Interop.SourceGenerators/Models/Result{T}.cs @@ -0,0 +1,12 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis; + +namespace ComputeSharp.D2D1Interop.SourceGenerators.Models; + +/// +/// A model representing a value and an associated set of diagnostic errors. +/// +/// The type of the wrapped value. +/// The wrapped value for the current result. +/// The associated diagnostic errors, if any. +internal sealed record Result(TValue Value, ImmutableArray Errors); diff --git a/src/ComputeSharp.D2D1Interop.SourceGenerators/Models/ThreadIdsInfo.cs b/src/ComputeSharp.D2D1Interop.SourceGenerators/Models/ThreadIdsInfo.cs new file mode 100644 index 00000000..cb001432 --- /dev/null +++ b/src/ComputeSharp.D2D1Interop.SourceGenerators/Models/ThreadIdsInfo.cs @@ -0,0 +1,56 @@ +using System; +using System.Collections.Generic; + +namespace ComputeSharp.D2D1Interop.SourceGenerators.Models; + +/// +/// A model representing gathered info on a embedded thread ids. +/// +/// Whether the values are diascarded. +/// The thread ids value for the X axis. +/// The thread ids value for the Y axis. +/// The thread ids value for the Z axis. +internal sealed record ThreadIdsInfo(bool IsDefault, int X, int Y, int Z) +{ + /// + /// An implementation for . + /// + public sealed class Comparer : IEqualityComparer + { + /// + /// The singleton instance. + /// + public static Comparer Default { get; } = new(); + + /// + 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; + } + + /// + public int GetHashCode(ThreadIdsInfo obj) + { + return HashCode.Combine(obj.IsDefault, obj.X, obj.Y, obj.Z); + } + } +} diff --git a/src/ComputeSharp.D2D1Interop.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.Diagnostics.cs b/src/ComputeSharp.D2D1Interop.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.Diagnostics.cs new file mode 100644 index 00000000..e031383f --- /dev/null +++ b/src/ComputeSharp.D2D1Interop.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.Diagnostics.cs @@ -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; + +/// +internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter +{ + /// + public override SyntaxNode? VisitAnonymousObjectCreationExpression(AnonymousObjectCreationExpressionSyntax node) + { + var updatedNode = (AnonymousObjectCreationExpressionSyntax)base.VisitAnonymousObjectCreationExpression(node)!; + + Diagnostics.Add(AnonymousObjectCreationExpression, node); + + return updatedNode; + } + + /// + public override SyntaxNode? VisitAwaitExpression(AwaitExpressionSyntax node) + { + Diagnostics.Add(AwaitExpression, node); + + return base.VisitAwaitExpression(node); + } + + /// + public override SyntaxNode? VisitCheckedExpression(CheckedExpressionSyntax node) + { + Diagnostics.Add(CheckedExpression, node); + + return base.VisitCheckedExpression(node); + } + + /// + public override SyntaxNode? VisitCheckedStatement(CheckedStatementSyntax node) + { + Diagnostics.Add(CheckedStatement, node); + + return base.VisitCheckedStatement(node); + } + + /// + public override SyntaxNode? VisitFixedStatement(FixedStatementSyntax node) + { + Diagnostics.Add(FixedStatement, node); + + return base.VisitFixedStatement(node); + } + + /// + public override SyntaxNode? VisitForEachStatement(ForEachStatementSyntax node) + { + Diagnostics.Add(ForEachStatement, node); + + return base.VisitForEachStatement(node); + } + + /// + public override SyntaxNode? VisitForEachVariableStatement(ForEachVariableStatementSyntax node) + { + Diagnostics.Add(ForEachStatement, node); + + return base.VisitForEachVariableStatement(node); + } + + /// + public override SyntaxNode? VisitLockStatement(LockStatementSyntax node) + { + Diagnostics.Add(LockStatement, node); + + return base.VisitLockStatement(node); + } + + /// + public override SyntaxNode? VisitQueryExpression(QueryExpressionSyntax node) + { + Diagnostics.Add(QueryExpression, node); + + return base.VisitQueryExpression(node); + } + + /// + public override SyntaxNode? VisitRangeExpression(RangeExpressionSyntax node) + { + Diagnostics.Add(RangeExpression, node); + + return base.VisitRangeExpression(node); + } + + /// + public override SyntaxNode? VisitRecursivePattern(RecursivePatternSyntax node) + { + Diagnostics.Add(RecursivePattern, node); + + return base.VisitRecursivePattern(node); + } + + /// + public override SyntaxNode? VisitRefType(RefTypeSyntax node) + { + Diagnostics.Add(RefType, node); + + return base.VisitRefType(node); + } + + /// + public override SyntaxNode? VisitRelationalPattern(RelationalPatternSyntax node) + { + Diagnostics.Add(RelationalPattern, node); + + return base.VisitRelationalPattern(node); + } + + /// + public override SyntaxNode? VisitSizeOfExpression(SizeOfExpressionSyntax node) + { + Diagnostics.Add(SizeOfExpression, node); + + return base.VisitSizeOfExpression(node); + } + + /// + public override SyntaxNode? VisitStackAllocArrayCreationExpression(StackAllocArrayCreationExpressionSyntax node) + { + Diagnostics.Add(StackAllocArrayCreationExpression, node); + + return base.VisitStackAllocArrayCreationExpression(node); + } + + /// + public override SyntaxNode? VisitThrowExpression(ThrowExpressionSyntax node) + { + Diagnostics.Add(ThrowExpressionOrStatement, node); + + return base.VisitThrowExpression(node); + } + + /// + public override SyntaxNode? VisitThrowStatement(ThrowStatementSyntax node) + { + Diagnostics.Add(ThrowExpressionOrStatement, node); + + return base.VisitThrowStatement(node); + } + + /// + public override SyntaxNode? VisitTryStatement(TryStatementSyntax node) + { + Diagnostics.Add(TryStatement, node); + + return base.VisitTryStatement(node); + } + + /// + public override SyntaxNode? VisitTupleType(TupleTypeSyntax node) + { + Diagnostics.Add(TupleType, node); + + return base.VisitTupleType(node); + } + + /// + public override SyntaxNode? VisitUsingStatement(UsingStatementSyntax node) + { + Diagnostics.Add(UsingStatementOrDeclaration, node); + + return base.VisitUsingStatement(node); + } + + /// + public override SyntaxNode? VisitYieldStatement(YieldStatementSyntax node) + { + Diagnostics.Add(YieldStatement, node); + + return base.VisitYieldStatement(node); + } + + /// + public override SyntaxNode? VisitFunctionPointerType(FunctionPointerTypeSyntax node) + { + Diagnostics.Add(FunctionPointer, node); + + return base.VisitFunctionPointerType(node); + } + + /// + public override SyntaxNode? VisitPointerType(PointerTypeSyntax node) + { + Diagnostics.Add(PointerType, node); + + return base.VisitPointerType(node); + } + + /// + public override SyntaxNode? VisitUnsafeStatement(UnsafeStatementSyntax node) + { + Diagnostics.Add(UnsafeStatement, node); + + return base.VisitUnsafeStatement(node); + } +} diff --git a/src/ComputeSharp.D2D1Interop.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.cs b/src/ComputeSharp.D2D1Interop.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.cs new file mode 100644 index 00000000..7190d50c --- /dev/null +++ b/src/ComputeSharp.D2D1Interop.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.cs @@ -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; + +/// +/// A base type that processes C# source to convert to HLSL compliant code. +/// This class contains only the shared logic for all derived HLSL source rewriters. +/// +internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter +{ + /// + /// The instance with semantic info on the target syntax tree. + /// + protected readonly SemanticModelProvider SemanticModel; + + /// + /// The collection of discovered custom types. + /// + protected readonly ICollection DiscoveredTypes; + + /// + /// The collection of discovered constant definitions. + /// + protected readonly IDictionary ConstantDefinitions; + + /// + /// The collection of produced instances. + /// + protected readonly ImmutableArray.Builder Diagnostics; + + /// + /// Creates a new instance with the specified parameters. + /// + /// The instance for the target syntax tree. + /// The set of discovered custom types. + /// The collection of discovered constant definitions. + /// The collection of produced instances. + protected HlslSourceRewriter( + SemanticModelProvider semanticModel, + ICollection discoveredTypes, + IDictionary constantDefinitions, + ImmutableArray.Builder diagnostics) + { + SemanticModel = semanticModel; + DiscoveredTypes = discoveredTypes; + ConstantDefinitions = constantDefinitions; + Diagnostics = diagnostics; + } + + /// + public override SyntaxNode VisitCastExpression(CastExpressionSyntax node) + { + var updatedNode = (CastExpressionSyntax)base.VisitCastExpression(node)!; + + return updatedNode.ReplaceAndTrackType(updatedNode.Type, node.Type, SemanticModel.For(node), DiscoveredTypes); + } + + /// + 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; + } + + /// + 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!); + } + + /// + 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); + } + + /// + 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))); + } + + /// + 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; + } + + /// + 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; + } + + /// + 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; + } + + /// + 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(); + } +} diff --git a/src/ComputeSharp.D2D1Interop.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs b/src/ComputeSharp.D2D1Interop.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs new file mode 100644 index 00000000..5eafdbcf --- /dev/null +++ b/src/ComputeSharp.D2D1Interop.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs @@ -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; + +/// +/// A custom type that processes C# methods to convert to HLSL compliant code. +/// +internal sealed class ShaderSourceRewriter : HlslSourceRewriter +{ + /// + /// The type symbol for the shader type. + /// + private readonly INamedTypeSymbol? shaderType; + + /// + /// The collection of discovered static methods. + /// + private readonly IDictionary staticMethods; + + /// + /// The collection of processed local functions in the current tree. + /// + private readonly Dictionary localFunctions; + + /// + /// The list of implicit variables to declare at the start of the body. + /// + private readonly List implicitVariables; + + /// + /// The current tree being visited. + /// + private MethodDeclarationSyntax? currentMethod; + + /// + /// Creates a new instance with the specified parameters. + /// + /// The type symbol for the shader type. + /// The instance for the target syntax tree. + /// The set of discovered custom types. + /// The set of discovered and processed static methods. + /// The collection of discovered constant definitions. + /// The collection of produced instances. + public ShaderSourceRewriter( + INamedTypeSymbol shaderType, + SemanticModelProvider semanticModel, + ICollection discoveredTypes, + IDictionary staticMethods, + IDictionary constantDefinitions, + ImmutableArray.Builder diagnostics) + : base(semanticModel, discoveredTypes, constantDefinitions, diagnostics) + { + this.shaderType = shaderType; + this.staticMethods = staticMethods; + this.localFunctions = new(); + this.implicitVariables = new(); + } + + /// + /// Creates a new instance with the specified parameters. + /// + /// The instance for the target syntax tree. + /// The set of discovered custom types. + /// The set of discovered and processed static methods. + /// The collection of discovered constant definitions. + /// The collection of produced instances. + public ShaderSourceRewriter( + SemanticModelProvider semanticModel, + ICollection discoveredTypes, + IDictionary staticMethods, + IDictionary constantDefinitions, + ImmutableArray.Builder diagnostics) + : base(semanticModel, discoveredTypes, constantDefinitions, diagnostics) + { + this.staticMethods = staticMethods; + this.implicitVariables = new(); + this.localFunctions = new(); + } + + /// + /// Gets the collection of processed local functions in the current tree. + /// + public IReadOnlyDictionary LocalFunctions => this.localFunctions; + + /// + 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; + } + + /// + 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)); + } + + /// + 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); + } + + /// + 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()); + } + + /// + public override SyntaxNode? VisitMethodDeclaration(MethodDeclarationSyntax node) + { + return + ((MethodDeclarationSyntax)base.VisitMethodDeclaration(node)!) + .WithBlockBody() + .WithoutAccessibilityModifiers() + .WithAttributeLists(List()); + } + + /// + public override SyntaxNode? VisitLocalFunctionStatement(LocalFunctionStatementSyntax node) + { + var updatedNode = + ((LocalFunctionStatementSyntax)base.VisitLocalFunctionStatement(node)!) + .WithBlockBody() + .WithAttributeLists(List()) + .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: "____". + this.localFunctions.Add(updatedNode.Identifier.Text, updatedNode); + + return null; + } + + /// + 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; + } + + /// + 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; + } + + /// + 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; + } +} diff --git a/src/ComputeSharp.D2D1Interop.SourceGenerators/SyntaxRewriters/StaticFieldRewriter.cs b/src/ComputeSharp.D2D1Interop.SourceGenerators/SyntaxRewriters/StaticFieldRewriter.cs new file mode 100644 index 00000000..d8706772 --- /dev/null +++ b/src/ComputeSharp.D2D1Interop.SourceGenerators/SyntaxRewriters/StaticFieldRewriter.cs @@ -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; + +/// +/// A custom type that processes C# static field to convert to HLSL static fields (possibly constant). +/// +internal sealed class StaticFieldRewriter : HlslSourceRewriter +{ + /// + /// Creates a new instance with the specified parameters. + /// + /// The instance for the target syntax tree. + /// The set of discovered custom types. + /// The collection of discovered constant definitions. + /// The collection of produced instances. + public StaticFieldRewriter( + SemanticModelProvider semanticModel, + ICollection discoveredTypes, + IDictionary constantDefinitions, + ImmutableArray.Builder diagnostics) + : base(semanticModel, discoveredTypes, constantDefinitions, diagnostics) + { + } + + /// + public ExpressionSyntax? Visit(VariableDeclaratorSyntax? node) + { + if (node?.Initializer is EqualsValueClauseSyntax fieldInitializer) + { + return ((EqualsValueClauseSyntax)Visit(fieldInitializer))!.Value; + } + + return null; + } + + /// + 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; + } + + /// + 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; + } + + /// + public override SyntaxNode? VisitArgument(ArgumentSyntax node) + { + var updatedNode = (ArgumentSyntax)base.VisitArgument(node)!; + + updatedNode = updatedNode.WithRefKindKeyword(Token(SyntaxKind.None)); + + return updatedNode; + } +} diff --git a/src/ComputeSharp.D2D1Interop.SourceGenerators/System.Runtime.CompilerServices/IsExternalInit.cs b/src/ComputeSharp.D2D1Interop.SourceGenerators/System.Runtime.CompilerServices/IsExternalInit.cs new file mode 100644 index 00000000..a914bf06 --- /dev/null +++ b/src/ComputeSharp.D2D1Interop.SourceGenerators/System.Runtime.CompilerServices/IsExternalInit.cs @@ -0,0 +1,12 @@ +using System.ComponentModel; + +namespace System.Runtime.CompilerServices; + +/// +/// Reserved to be used by the compiler for tracking metadata. +/// This class should not be used by developers in source code. +/// +[EditorBrowsable(EditorBrowsableState.Never)] +internal static class IsExternalInit +{ +} diff --git a/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Shipped.md b/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Shipped.md index 1e3bcdee..70dd2866 100644 --- a/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Shipped.md +++ b/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Shipped.md @@ -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) diff --git a/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs b/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs index 7f6e4f12..e32a8062 100644 --- a/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs +++ b/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs @@ -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).", diff --git a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownSizes.cs b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownSizes.cs index ab74da12..dc858f9c 100644 --- a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownSizes.cs +++ b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownSizes.cs @@ -14,7 +14,7 @@ internal static class HlslKnownSizes /// /// The mapping of supported known sizes to HLSL type names. /// - private static IReadOnlyDictionary KnownSizes = BuildKnownSizesMap(); + private static readonly IReadOnlyDictionary KnownSizes = BuildKnownSizesMap(); /// /// Builds the mapping of known type sizes and alignments.