From 3a7e7559c3d28f4213ea947bd395ef85c1108331 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 1 Dec 2020 01:08:17 +0100 Subject: [PATCH 1/9] Added initial attributes to track methods --- .../Attributes/AutoConstructorAttribute.cs | 2 +- .../IComputeShaderSourceAttribute.cs | 4 +- .../Attributes/ShaderMethodAttribute.cs | 16 +++++ .../Attributes/ShaderMethodSourceAttribute.cs | 68 +++++++++++++++++++ .../IComputeShaderSourceGenerator.cs | 4 ++ 5 files changed, 91 insertions(+), 3 deletions(-) create mode 100644 src/ComputeSharp.Core/Attributes/ShaderMethodAttribute.cs create mode 100644 src/ComputeSharp.Core/Attributes/ShaderMethodSourceAttribute.cs diff --git a/src/ComputeSharp.Core/Attributes/AutoConstructorAttribute.cs b/src/ComputeSharp.Core/Attributes/AutoConstructorAttribute.cs index c5db9978..bd4dc3e7 100644 --- a/src/ComputeSharp.Core/Attributes/AutoConstructorAttribute.cs +++ b/src/ComputeSharp.Core/Attributes/AutoConstructorAttribute.cs @@ -5,7 +5,7 @@ namespace ComputeSharp /// /// An attribute that indicates that a target shader type should get an automatic constructor for all fields. /// - [AttributeUsage(AttributeTargets.Struct, AllowMultiple = false)] + [AttributeUsage(AttributeTargets.Struct)] public sealed class AutoConstructorAttribute : Attribute { } diff --git a/src/ComputeSharp.Core/Attributes/IComputeShaderSourceAttribute.cs b/src/ComputeSharp.Core/Attributes/IComputeShaderSourceAttribute.cs index 78a86340..b1db45a8 100644 --- a/src/ComputeSharp.Core/Attributes/IComputeShaderSourceAttribute.cs +++ b/src/ComputeSharp.Core/Attributes/IComputeShaderSourceAttribute.cs @@ -8,9 +8,9 @@ using System.Reflection; namespace ComputeSharp { /// - /// An attribute that indicates that a target shader type should get an automatic constructor for all fields. - /// This attribute is not meant to be directly used by applications using ComputeSharp. + /// An attribute that contains info on a processed compute shader that can be executed. /// + /// This attribute is not meant to be directly used by applications using ComputeSharp. [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("This attribute is meant to be used from the source generator only")] diff --git a/src/ComputeSharp.Core/Attributes/ShaderMethodAttribute.cs b/src/ComputeSharp.Core/Attributes/ShaderMethodAttribute.cs new file mode 100644 index 00000000..9eae4f37 --- /dev/null +++ b/src/ComputeSharp.Core/Attributes/ShaderMethodAttribute.cs @@ -0,0 +1,16 @@ +using System; + +namespace ComputeSharp +{ + /// + /// An attribute that indicates that a method will be indirectly used in a compute shader. + /// This method is necessary for methods that are captured and used within a given shader + /// through a field (of some custom type). In order to be processed + /// correctly, wrapped methods need to have this attribute manually applied to them. + /// Methods also need to be static, though this can only be tested at runtime. + /// + [AttributeUsage(AttributeTargets.Method)] + public sealed class ShaderMethodAttribute : Attribute + { + } +} \ No newline at end of file diff --git a/src/ComputeSharp.Core/Attributes/ShaderMethodSourceAttribute.cs b/src/ComputeSharp.Core/Attributes/ShaderMethodSourceAttribute.cs new file mode 100644 index 00000000..32eec734 --- /dev/null +++ b/src/ComputeSharp.Core/Attributes/ShaderMethodSourceAttribute.cs @@ -0,0 +1,68 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics.Contracts; +using System.Linq; +using System.Reflection; +using Microsoft.Toolkit.Diagnostics; + +namespace ComputeSharp +{ + /// + /// An attribute that contains info on a processed shader method that can be executed within a shader. + /// Instances of this attribute are generated from method annotated with . + /// + /// This attribute is not meant to be directly used by applications using ComputeSharp. + [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("This attribute is meant to be used from the source generator only")] + public sealed class ShaderMethodSourceAttribute : Attribute + { + /// + /// Creates a new instance with the specified parameters. + /// + /// The fully qualified name of the current method. + /// The collection of custom types. + /// The collection of processed methods. + public ShaderMethodSourceAttribute(string methodName, string[] types, string[] methods) + { + MethodName = methodName; + Types = types; + Methods = methods; + } + + /// + /// Gets the fully qualified name of the shader type. + /// + internal string MethodName { get; } + + /// + /// Gets the collection of processed custom types. + /// + internal IReadOnlyCollection Types { get; } + + /// + /// Gets the collection of processed methods. + /// + internal IReadOnlyCollection Methods { get; } + + /// + /// Gets the associated instance for a specified type. + /// + /// The shader type to get the attribute for. + /// The associated instance for type . + [Pure] + internal static ShaderMethodSourceAttribute GetForDelegate(Delegate function) + { + Guard.IsTrue(function.Method.IsStatic, "Captured delegates need to wrap static methods"); + + Type declaringType = function.Method.DeclaringType; + string methodName = $"{declaringType.FullName}.{function.Method.Name}"; + + return ( + from attribute in function.Method.DeclaringType.Assembly.GetCustomAttributes() + where attribute.MethodName == methodName + select attribute).Single(); + } + } +} \ No newline at end of file diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs index ea60def7..fdf653bb 100644 --- a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs @@ -111,6 +111,10 @@ namespace ComputeSharp.SourceGenerators foreach (var fieldSymbol in structDeclarationSymbol.GetMembers().OfType()) { INamedTypeSymbol typeSymbol = (INamedTypeSymbol)fieldSymbol.Type; + + // Delegate types are not included and are processed separately + if (typeSymbol.TypeKind == TypeKind.Delegate) continue; + string typeName = HlslKnownTypes.GetMappedName(typeSymbol); _ = HlslKnownKeywords.TryGetMappedName(fieldSymbol.Name, out string? mapping); From 85967771cf094103ffa3640581fb2590d0d0be21 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 1 Dec 2020 12:23:30 +0100 Subject: [PATCH 2/9] Stripped attributes from processed methods --- .../SyntaxRewriters/ShaderSourceRewriter.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs index 135745fc..5382cafa 100644 --- a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs +++ b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs @@ -162,7 +162,8 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters return ((MethodDeclarationSyntax)base.VisitMethodDeclaration(node)!) .WithBlockBody() - .WithoutAccessibilityModifiers(); + .WithoutAccessibilityModifiers() + .WithAttributeLists(List()); } /// @@ -171,6 +172,7 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters var updatedNode = ((LocalFunctionStatementSyntax)base.VisitLocalFunctionStatement(node)!) .WithBlockBody() + .WithAttributeLists(List()) .WithIdentifier(Identifier($"__{this.currentMethod!.Identifier.Text}__{node.Identifier.Text}")); // HLSL doesn't support local functions, so we first process them as usual and then remove From dea3a477ef9853e3a86ea97864df9ed2d8d86171 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 1 Dec 2020 12:24:01 +0100 Subject: [PATCH 3/9] Added initial ShaderMethodSourceGenerator type --- .../Extensions/ISymbolExtensions.cs | 27 +++- .../IComputeShaderSourceGenerator.cs | 2 +- .../ShaderMethodSourceGenerator.cs | 116 ++++++++++++++++++ 3 files changed, 143 insertions(+), 2 deletions(-) create mode 100644 src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs diff --git a/src/ComputeSharp.SourceGenerators/Extensions/ISymbolExtensions.cs b/src/ComputeSharp.SourceGenerators/Extensions/ISymbolExtensions.cs index 49f6bb66..4cdc55aa 100644 --- a/src/ComputeSharp.SourceGenerators/Extensions/ISymbolExtensions.cs +++ b/src/ComputeSharp.SourceGenerators/Extensions/ISymbolExtensions.cs @@ -1,4 +1,5 @@ using System.Diagnostics.Contracts; +using System.Linq; using System.Text; using Microsoft.CodeAnalysis; @@ -48,10 +49,18 @@ namespace ComputeSharp.SourceGenerators.Extensions /// 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 . [Pure] - public static string GetFullMetadataName(this IMethodSymbol symbol) + 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); } @@ -70,5 +79,21 @@ namespace ComputeSharp.SourceGenerators.Extensions return $"[{nameof(ComputeSharp)}]_[{typeof(TGenerator).Name}]_[{fixedName}]"; } + + /// + /// Gets a valid filename for a target symbol and generator type. + /// + /// The generator type processing the input symbol. + /// The symbol being processed. + /// A filename in the form "[ComputeSharp]_[<TGENERATOR>]_[<SYMBOL_FULLNAME>]" + [Pure] + public static string GetGeneratedFileName(this IMethodSymbol symbol) + { + string + metadataName = symbol.GetFullMetadataName(true), + fixedName = metadataName.Replace('`', '-').Replace('+', '.'); + + return $"[{nameof(ComputeSharp)}]_[{typeof(TGenerator).Name}]_[{fixedName}]"; + } } } diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs index fdf653bb..cb8cefa9 100644 --- a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs @@ -192,7 +192,7 @@ namespace ComputeSharp.SourceGenerators /// /// The sequence of discovered custom types. /// A sequence of custom type definitions to add to the shader source. - public static IEnumerable GetProcessedTypes(IEnumerable types) + internal static IEnumerable GetProcessedTypes(IEnumerable types) { foreach (var type in HlslKnownTypes.GetCustomTypes(types)) { diff --git a/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs b/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs new file mode 100644 index 00000000..d8fa31ad --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs @@ -0,0 +1,116 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics; +using System.Diagnostics.Contracts; +using System.Linq; +using System.Text; +using ComputeSharp.SourceGenerators.Extensions; +using ComputeSharp.SourceGenerators.Mappings; +using ComputeSharp.SourceGenerators.SyntaxRewriters; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Text; +using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; + +#pragma warning disable CS0618 + +namespace ComputeSharp.SourceGenerators +{ + [Generator] + public class ShaderMethodSourceGenerator : ISourceGenerator + { + /// + public void Initialize(GeneratorInitializationContext context) + { + } + + /// + public void Execute(GeneratorExecutionContext context) + { + Debugger.Launch(); + + // Find all the [ShaderMethod] usages and retrieve the target methods + ImmutableArray methods = ( + from tree in context.Compilation.SyntaxTrees + from attribute in tree.GetRoot().DescendantNodes().OfType() + let symbol = context.Compilation.GetSemanticModel(attribute.SyntaxTree) + let typeInfo = symbol.GetTypeInfo(attribute) + where typeInfo.Type is { Name: nameof(ShaderMethodAttribute) } + select attribute.FirstAncestorOrSelf()).ToImmutableArray(); + + foreach (MethodDeclarationSyntax methodDeclaration in methods) + { + SemanticModel semanticModel = context.Compilation.GetSemanticModel(methodDeclaration.SyntaxTree); + IMethodSymbol methodDeclarationSymbol = semanticModel.GetDeclaredSymbol(methodDeclaration)!; + + // We need to sets to track all discovered custom types and static methods + HashSet discoveredTypes = new(SymbolEqualityComparer.Default); + Dictionary staticMethods = new(SymbolEqualityComparer.Default); + + // Explore the syntax tree and extract the processed info + var processedMethods = GetProcessedMethods(methodDeclaration, semanticModel, discoveredTypes, staticMethods).ToArray(); + var processedTypes = IComputeShaderSourceGenerator.GetProcessedTypes(discoveredTypes).ToArray(); + + // Helper that converts a sequence of strings into an array expression. + // That is, this applies the following transformation: + // - { "S1", "S2" } => new string[] { "S1", "S2" } + static ArrayCreationExpressionSyntax ArrayExpression(IEnumerable values) + { + return + ArrayCreationExpression( + ArrayType(PredefinedType(Token(SyntaxKind.StringKeyword))) + .AddRankSpecifiers(ArrayRankSpecifier(SingletonSeparatedList(OmittedArraySizeExpression())))) + .WithInitializer(InitializerExpression(SyntaxKind.ArrayInitializerExpression) + .AddExpressions(values.Select(static value => LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(value))).ToArray())); + } + + // Create the compilation unit with the source attribute + var source = + CompilationUnit().AddAttributeLists( + AttributeList(SingletonSeparatedList( + Attribute(IdentifierName(typeof(ShaderMethodSourceAttribute).FullName)).AddArgumentListArguments( + AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(methodDeclarationSymbol.GetFullMetadataName(true)))), + AttributeArgument(ArrayExpression(processedTypes)), + AttributeArgument(ArrayExpression(processedMethods))))) + .WithOpenBracketToken(Token(TriviaList(Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), SyntaxKind.OpenBracketToken, TriviaList())) + .WithTarget(AttributeTargetSpecifier(Token(SyntaxKind.AssemblyKeyword)))) + .NormalizeWhitespace() + .ToFullString(); + + // Add the method source attribute + context.AddSource(methodDeclarationSymbol.GetGeneratedFileName(), SourceText.From(source, Encoding.UTF8)); + } + } + + /// + /// Gets a sequence of processed methods from a target method declaration. + /// + /// The instance for the current method. + /// The instance for the method to process. + /// The collection of currently discovered types. + /// The set of discovered and processed static methods. + /// A sequence of processed methods in . + [Pure] + private static IEnumerable GetProcessedMethods( + MethodDeclarationSyntax methodDeclaration, + SemanticModel semanticModel, + ICollection discoveredTypes, + IDictionary staticMethods) + { + ShaderSourceRewriter shaderSourceRewriter = new(semanticModel, discoveredTypes, staticMethods); + + // Rewrite the method syntax tree + var processedMethod = shaderSourceRewriter.Visit(methodDeclaration)!.WithoutTrivia(); + + yield return processedMethod.NormalizeWhitespace().ToFullString(); + + // Emit the extracted local functions + foreach (var localFunction in shaderSourceRewriter.LocalFunctions) + { + yield return localFunction.Value.NormalizeWhitespace().ToFullString(); + } + } + } +} + From 0714dedf1f4cd0762013a52a74dcbb55d5845662 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 1 Dec 2020 12:47:23 +0100 Subject: [PATCH 4/9] Removed unnecessary code --- .../Extensions/ILGeneratorExtensions.cs | 7 ++- .../Extensions/StringExtensions.cs | 27 ----------- .../Extensions/TypeExtensions.cs | 46 +++---------------- .../Translation/ShaderHashCodeProvider.cs | 1 + .../Translation/ShaderLoader{T}.IL.cs | 1 + .../Translation/ShaderLoader{T}.cs | 7 +-- 6 files changed, 15 insertions(+), 74 deletions(-) delete mode 100644 src/ComputeSharp.Shaders/Extensions/StringExtensions.cs diff --git a/src/ComputeSharp.Shaders/Extensions/ILGeneratorExtensions.cs b/src/ComputeSharp.Shaders/Extensions/ILGeneratorExtensions.cs index 1770ad27..26bfe745 100644 --- a/src/ComputeSharp.Shaders/Extensions/ILGeneratorExtensions.cs +++ b/src/ComputeSharp.Shaders/Extensions/ILGeneratorExtensions.cs @@ -1,8 +1,11 @@ -using System.Runtime.CompilerServices; +using System; +using System.Reflection; +using System.Reflection.Emit; +using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Microsoft.Toolkit.Diagnostics; -namespace System.Reflection.Emit +namespace ComputeSharp.Shaders.Extensions { /// /// A that provides extension methods for the type diff --git a/src/ComputeSharp.Shaders/Extensions/StringExtensions.cs b/src/ComputeSharp.Shaders/Extensions/StringExtensions.cs deleted file mode 100644 index 16f21407..00000000 --- a/src/ComputeSharp.Shaders/Extensions/StringExtensions.cs +++ /dev/null @@ -1,27 +0,0 @@ -using System.Diagnostics.Contracts; -using System.Linq; -using System.Text.RegularExpressions; - -namespace System -{ - /// - /// A that provides extension methods for the type - /// - internal static class StringExtensions - { - /// - /// Removes the left padding for an input multiline - /// - /// The input to process - /// A left-aligned with the same text as the input - [Pure] - public static string RemoveLeftPadding(this string text) - { - string[] lines = text.Split(Environment.NewLine); - int spaces = text.TakeWhile(c => c == ' ').Count(); - Regex regex = new Regex($"^{new string(Enumerable.Repeat(' ', spaces).ToArray())}"); - - return lines.Aggregate(string.Empty, (result, line) => $"{result}{Environment.NewLine}{regex.Replace(line, string.Empty)}"); - } - } -} diff --git a/src/ComputeSharp.Shaders/Extensions/TypeExtensions.cs b/src/ComputeSharp.Shaders/Extensions/TypeExtensions.cs index 081a27c0..72771697 100644 --- a/src/ComputeSharp.Shaders/Extensions/TypeExtensions.cs +++ b/src/ComputeSharp.Shaders/Extensions/TypeExtensions.cs @@ -1,53 +1,21 @@ -using System.Diagnostics.CodeAnalysis; +using System; using System.Diagnostics.Contracts; -using System.Reflection; -using System.Runtime.CompilerServices; -namespace System +namespace ComputeSharp.Shaders.Extensions { /// - /// A that provides extension methods for the type + /// A that provides extension methods for the type. /// internal static class TypeExtensions { /// - /// Gets whether or not the input represents a + /// Gets whether or not the input represents a . /// - /// The input type to analyze + /// The input type to analyze. [Pure] - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static bool IsDelegate(this Type type) => type.IsClass && - type.IsSubclassOf(typeof(Delegate)); - - /// - /// Gets whether or not the input represents a with no captured variables - /// - /// The input type to analyze - [Pure] - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static bool IsStatelessDelegateContainer(this Type type) => type.GetFields(BindingFlags.Static | BindingFlags.Public).Length > 0; - - /// - /// Tries to find an ancestor member starting from the input - /// - /// The input type to start the search from - /// The name of the member to retrieve - /// A bitmask comprised of one or more that specify how the search is conducted - /// when a member with the given name is found, otherwise - public static bool TryFindAncestorMember(this Type type, string name, BindingFlags bindingAttr, [NotNullWhen(true)] out (Type DeclaringType, MemberInfo MemberInfo)? result) + public static bool IsDelegate(this Type type) { - while ((type = type.DeclaringType!) != null) - { - MemberInfo[] memberInfos = type.GetMember(name, bindingAttr); - if (memberInfos.Length > 0) - { - result = (type, memberInfos[0]); - return true; - } - } - - result = null; - return false; + return type.IsSubclassOf(typeof(Delegate)); } } } diff --git a/src/ComputeSharp.Shaders/Translation/ShaderHashCodeProvider.cs b/src/ComputeSharp.Shaders/Translation/ShaderHashCodeProvider.cs index 955ca45e..d4e617f3 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderHashCodeProvider.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderHashCodeProvider.cs @@ -5,6 +5,7 @@ using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; +using ComputeSharp.Shaders.Extensions; namespace ComputeSharp.Shaders.Translation { diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.IL.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.IL.cs index 781fa8d7..7da9b114 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.IL.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.IL.cs @@ -8,6 +8,7 @@ using System.Runtime.InteropServices; using ComputeSharp.Core.Interop; using ComputeSharp.Graphics; using ComputeSharp.Graphics.Buffers.Abstract; +using ComputeSharp.Shaders.Extensions; using ComputeSharp.Shaders.Mappings; using ComputeSharp.Shaders.Translation.Models; using Microsoft.Toolkit.Diagnostics; diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs index 347bbcfc..091a1215 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs @@ -178,12 +178,7 @@ namespace ComputeSharp.Shaders.Translation this.capturedFields.Add(fieldInfo); this.fieldsInfo.Add(new CapturedFieldInfo(hlslType, hlslName)); } - else if (fieldType.IsDelegate() && - fieldInfo.GetValue(shader) is Delegate func && - (func.Method.IsStatic || func.Method.DeclaringType!.IsStatelessDelegateContainer()) && - (HlslKnownTypes.IsKnownScalarType(func.Method.ReturnType) || HlslKnownTypes.IsKnownVectorType(func.Method.ReturnType)) && - fieldType.GenericTypeArguments.All(type => HlslKnownTypes.IsKnownScalarType(type) || - HlslKnownTypes.IsKnownVectorType(type))) + else if (fieldInfo.GetValue(shader) is Delegate { Method: { IsStatic: true } } func) { // Captured static delegates with a return type throw new NotImplementedException(); From df02a534ea3f64eb83acaa4d42409122188522ab Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 1 Dec 2020 13:07:49 +0100 Subject: [PATCH 5/9] Removed leftover debugging hook --- .../ShaderMethodSourceGenerator.cs | 4 ---- 1 file changed, 4 deletions(-) diff --git a/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs b/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs index d8fa31ad..0d158099 100644 --- a/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs @@ -1,11 +1,9 @@ using System.Collections.Generic; using System.Collections.Immutable; -using System.Diagnostics; using System.Diagnostics.Contracts; using System.Linq; using System.Text; using ComputeSharp.SourceGenerators.Extensions; -using ComputeSharp.SourceGenerators.Mappings; using ComputeSharp.SourceGenerators.SyntaxRewriters; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; @@ -28,8 +26,6 @@ namespace ComputeSharp.SourceGenerators /// public void Execute(GeneratorExecutionContext context) { - Debugger.Launch(); - // Find all the [ShaderMethod] usages and retrieve the target methods ImmutableArray methods = ( from tree in context.Compilation.SyntaxTrees From c231e8506ab3bfc7a20ee5560b00dbca05b7a4cd Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 1 Dec 2020 14:07:31 +0100 Subject: [PATCH 6/9] Implemented working version of metaprogramming --- .../Attributes/ShaderMethodSourceAttribute.cs | 13 +++++++--- .../Extensions/MethodInfoExtensions.cs | 25 +++++++++++++++++++ .../Translation/ShaderLoader{T}.cs | 25 +++++++++++++++---- .../Extensions/ISymbolExtensions.cs | 2 +- .../IComputeShaderSourceGenerator.cs | 3 --- .../Mappings/HlslKnownTypes.cs | 5 ++++ .../ShaderMethodSourceGenerator.cs | 18 +++++++++---- 7 files changed, 74 insertions(+), 17 deletions(-) create mode 100644 src/ComputeSharp.Core/Extensions/MethodInfoExtensions.cs diff --git a/src/ComputeSharp.Core/Attributes/ShaderMethodSourceAttribute.cs b/src/ComputeSharp.Core/Attributes/ShaderMethodSourceAttribute.cs index 32eec734..db6ce1d1 100644 --- a/src/ComputeSharp.Core/Attributes/ShaderMethodSourceAttribute.cs +++ b/src/ComputeSharp.Core/Attributes/ShaderMethodSourceAttribute.cs @@ -4,6 +4,7 @@ using System.ComponentModel; using System.Diagnostics.Contracts; using System.Linq; using System.Reflection; +using ComputeSharp.Core.Extensions; using Microsoft.Toolkit.Diagnostics; namespace ComputeSharp @@ -23,11 +24,13 @@ namespace ComputeSharp /// /// The fully qualified name of the current method. /// The collection of custom types. + /// The source code for the target entry point method. /// The collection of processed methods. - public ShaderMethodSourceAttribute(string methodName, string[] types, string[] methods) + public ShaderMethodSourceAttribute(string methodName, string[] types, string invokeMethod, string[] methods) { MethodName = methodName; Types = types; + InvokeMethod = invokeMethod; Methods = methods; } @@ -41,6 +44,11 @@ namespace ComputeSharp /// internal IReadOnlyCollection Types { get; } + /// + /// Gets the source code for the target entry point method. + /// + internal string InvokeMethod { get; } + /// /// Gets the collection of processed methods. /// @@ -56,8 +64,7 @@ namespace ComputeSharp { Guard.IsTrue(function.Method.IsStatic, "Captured delegates need to wrap static methods"); - Type declaringType = function.Method.DeclaringType; - string methodName = $"{declaringType.FullName}.{function.Method.Name}"; + string methodName = function.Method.GetFullName(); return ( from attribute in function.Method.DeclaringType.Assembly.GetCustomAttributes() diff --git a/src/ComputeSharp.Core/Extensions/MethodInfoExtensions.cs b/src/ComputeSharp.Core/Extensions/MethodInfoExtensions.cs new file mode 100644 index 00000000..1a09359b --- /dev/null +++ b/src/ComputeSharp.Core/Extensions/MethodInfoExtensions.cs @@ -0,0 +1,25 @@ +using System.Diagnostics.Contracts; +using System.Linq; +using System.Reflection; + +namespace ComputeSharp.Core.Extensions +{ + /// + /// A that provides extension methods for the type. + /// + internal static class MethodInfoExtensions + { + /// + /// Gets a fully qualified name for the input method, including parameters. + /// + /// The input instance. + /// A fully qualified name for , including parameters. + [Pure] + public static string GetFullName(this MethodInfo method) + { + var parameters = string.Join(", ", method.GetParameters().Select(static p => p.ParameterType.FullName)); + + return $"{method.DeclaringType!.FullName}.{method.Name}({parameters})"; + } + } +} diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs index 091a1215..97987103 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs @@ -56,6 +56,16 @@ namespace ComputeSharp.Shaders.Translation /// private readonly List fieldsInfo = new(); + /// + /// The with the collected methods for the shader. + /// + private readonly List methodsInfo = new(); + + /// + /// The with the collected declared types for the shader. + /// + private readonly List declaredTypes = new(); + /// /// Creates a new instance. /// @@ -81,10 +91,10 @@ namespace ComputeSharp.Shaders.Translation public IReadOnlyList FieldsInfo => this.fieldsInfo; /// - public IReadOnlyCollection MethodsInfo { get; private set; } + public IReadOnlyCollection MethodsInfo => this.methodsInfo; /// - public IReadOnlyCollection DeclaredTypes { get; private set; } + public IReadOnlyCollection DeclaredTypes => this.declaredTypes; /// /// Loads and processes an input shadeer @@ -181,7 +191,11 @@ namespace ComputeSharp.Shaders.Translation else if (fieldInfo.GetValue(shader) is Delegate { Method: { IsStatic: true } } func) { // Captured static delegates with a return type - throw new NotImplementedException(); + var methodSource = ShaderMethodSourceAttribute.GetForDelegate(func); + + this.declaredTypes.AddRange(methodSource.Types); + this.methodsInfo.Add(methodSource.InvokeMethod.Replace("____", hlslName)); + this.methodsInfo.AddRange(methodSource.Methods); } else ThrowHelper.ThrowArgumentException("Invalid captured variable"); } @@ -191,9 +205,10 @@ namespace ComputeSharp.Shaders.Translation /// private void LoadMethodMetadata() { - DeclaredTypes = Attribute.Types; EntryPoint = Attribute.ExecuteMethod; - MethodsInfo = Attribute.Methods; + + this.methodsInfo.AddRange(Attribute.Methods); + this.declaredTypes.AddRange(Attribute.Types); } } } diff --git a/src/ComputeSharp.SourceGenerators/Extensions/ISymbolExtensions.cs b/src/ComputeSharp.SourceGenerators/Extensions/ISymbolExtensions.cs index 4cdc55aa..392a250c 100644 --- a/src/ComputeSharp.SourceGenerators/Extensions/ISymbolExtensions.cs +++ b/src/ComputeSharp.SourceGenerators/Extensions/ISymbolExtensions.cs @@ -56,7 +56,7 @@ namespace ComputeSharp.SourceGenerators.Extensions { if (includeParameters) { - var parameters = $"{string.Join(", ", symbol.Parameters.Select(static p => ((INamedTypeSymbol)p.Type).GetFullMetadataName()))}"; + var parameters = string.Join(", ", symbol.Parameters.Select(static p => ((INamedTypeSymbol)p.Type).GetFullMetadataName())); return $"{symbol.ToDisplayString(FullyQualifiedWithoutGlobalAndParametersFormat)}({parameters})"; } diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs index cb8cefa9..59368f90 100644 --- a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs @@ -112,9 +112,6 @@ namespace ComputeSharp.SourceGenerators { INamedTypeSymbol typeSymbol = (INamedTypeSymbol)fieldSymbol.Type; - // Delegate types are not included and are processed separately - if (typeSymbol.TypeKind == TypeKind.Delegate) continue; - string typeName = HlslKnownTypes.GetMappedName(typeSymbol); _ = HlslKnownKeywords.TryGetMappedName(fieldSymbol.Name, out string? mapping); diff --git a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs index 6969ffc1..39cfc05a 100644 --- a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs +++ b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs @@ -73,8 +73,13 @@ namespace ComputeSharp.SourceGenerators.Mappings /// /// The input type to map. /// The HLSL-compatible type name that can be used in an HLSL shader. + [Pure] public static string GetMappedName(INamedTypeSymbol typeSymbol) { + // Delegate types just return an empty string, as they're not actually + // used in the generated shaders, but just mapped to a function at runtime. + if (typeSymbol.TypeKind == TypeKind.Delegate) return ""; + string typeName = typeSymbol.GetFullMetadataName(); // Special case for the structured buffer types diff --git a/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs b/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs index 0d158099..7e6dae24 100644 --- a/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs @@ -45,7 +45,7 @@ namespace ComputeSharp.SourceGenerators Dictionary staticMethods = new(SymbolEqualityComparer.Default); // Explore the syntax tree and extract the processed info - var processedMethods = GetProcessedMethods(methodDeclaration, semanticModel, discoveredTypes, staticMethods).ToArray(); + var (invokeMethod, processedMethods) = GetProcessedMethods(methodDeclaration, semanticModel, discoveredTypes, staticMethods); var processedTypes = IComputeShaderSourceGenerator.GetProcessedTypes(discoveredTypes).ToArray(); // Helper that converts a sequence of strings into an array expression. @@ -68,6 +68,7 @@ namespace ComputeSharp.SourceGenerators Attribute(IdentifierName(typeof(ShaderMethodSourceAttribute).FullName)).AddArgumentListArguments( AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(methodDeclarationSymbol.GetFullMetadataName(true)))), AttributeArgument(ArrayExpression(processedTypes)), + AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(invokeMethod))), AttributeArgument(ArrayExpression(processedMethods))))) .WithOpenBracketToken(Token(TriviaList(Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), SyntaxKind.OpenBracketToken, TriviaList())) .WithTarget(AttributeTargetSpecifier(Token(SyntaxKind.AssemblyKeyword)))) @@ -88,7 +89,7 @@ namespace ComputeSharp.SourceGenerators /// The set of discovered and processed static methods. /// A sequence of processed methods in . [Pure] - private static IEnumerable GetProcessedMethods( + private static (string InvokeMethod, IEnumerable Methods) GetProcessedMethods( MethodDeclarationSyntax methodDeclaration, SemanticModel semanticModel, ICollection discoveredTypes, @@ -97,15 +98,22 @@ namespace ComputeSharp.SourceGenerators ShaderSourceRewriter shaderSourceRewriter = new(semanticModel, discoveredTypes, staticMethods); // Rewrite the method syntax tree - var processedMethod = shaderSourceRewriter.Visit(methodDeclaration)!.WithoutTrivia(); + var processedMethod = shaderSourceRewriter + .Visit(methodDeclaration)! + .WithIdentifier(Identifier("____")) + .WithoutTrivia() + .NormalizeWhitespace() + .ToFullString(); - yield return processedMethod.NormalizeWhitespace().ToFullString(); + List methods = new(shaderSourceRewriter.LocalFunctions.Count); // Emit the extracted local functions foreach (var localFunction in shaderSourceRewriter.LocalFunctions) { - yield return localFunction.Value.NormalizeWhitespace().ToFullString(); + methods.Add(localFunction.Value.NormalizeWhitespace().ToFullString()); } + + return (processedMethod, methods); } } } From f4bd3f87b9df6f0229436c4094d343dd87067bcf Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 1 Dec 2020 14:12:13 +0100 Subject: [PATCH 7/9] Minor code refactoring --- .../Attributes/ShaderMethodSourceAttribute.cs | 29 +++++++++++++++---- .../Translation/ShaderLoader{T}.cs | 2 +- .../ShaderMethodSourceGenerator.cs | 2 +- 3 files changed, 25 insertions(+), 8 deletions(-) diff --git a/src/ComputeSharp.Core/Attributes/ShaderMethodSourceAttribute.cs b/src/ComputeSharp.Core/Attributes/ShaderMethodSourceAttribute.cs index db6ce1d1..508758f1 100644 --- a/src/ComputeSharp.Core/Attributes/ShaderMethodSourceAttribute.cs +++ b/src/ComputeSharp.Core/Attributes/ShaderMethodSourceAttribute.cs @@ -19,6 +19,16 @@ namespace ComputeSharp [Obsolete("This attribute is meant to be used from the source generator only")] public sealed class ShaderMethodSourceAttribute : Attribute { + /// + /// The identifier for the invoke method, for late binding. + /// + internal const string InvokeMethodIdentifier = "____"; + + /// + /// The source code for the target entry point method. + /// + private readonly string invokeMethod; + /// /// Creates a new instance with the specified parameters. /// @@ -28,9 +38,10 @@ namespace ComputeSharp /// The collection of processed methods. public ShaderMethodSourceAttribute(string methodName, string[] types, string invokeMethod, string[] methods) { + this.invokeMethod = invokeMethod; + MethodName = methodName; Types = types; - InvokeMethod = invokeMethod; Methods = methods; } @@ -44,16 +55,22 @@ namespace ComputeSharp /// internal IReadOnlyCollection Types { get; } - /// - /// Gets the source code for the target entry point method. - /// - internal string InvokeMethod { get; } - /// /// Gets the collection of processed methods. /// internal IReadOnlyCollection Methods { get; } + /// + /// Gets the mapped source code for the current method. + /// + /// The name to bind the method to. + /// The mapped source code for the current mehtod. + [Pure] + internal string GetMappedInvokeMethod(string name) + { + return this.invokeMethod.Replace(InvokeMethodIdentifier, name); + } + /// /// Gets the associated instance for a specified type. /// diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs index 97987103..51ad4b88 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs @@ -194,7 +194,7 @@ namespace ComputeSharp.Shaders.Translation var methodSource = ShaderMethodSourceAttribute.GetForDelegate(func); this.declaredTypes.AddRange(methodSource.Types); - this.methodsInfo.Add(methodSource.InvokeMethod.Replace("____", hlslName)); + this.methodsInfo.Add(methodSource.GetMappedInvokeMethod(hlslName)); this.methodsInfo.AddRange(methodSource.Methods); } else ThrowHelper.ThrowArgumentException("Invalid captured variable"); diff --git a/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs b/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs index 7e6dae24..277ec2c5 100644 --- a/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs @@ -100,7 +100,7 @@ namespace ComputeSharp.SourceGenerators // Rewrite the method syntax tree var processedMethod = shaderSourceRewriter .Visit(methodDeclaration)! - .WithIdentifier(Identifier("____")) + .WithIdentifier(Identifier(ShaderMethodSourceAttribute.InvokeMethodIdentifier)) .WithoutTrivia() .NormalizeWhitespace() .ToFullString(); From d1e91d71abd0bff929d88be0b0a9624a66afe497 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 1 Dec 2020 18:16:44 +0100 Subject: [PATCH 8/9] Added dedicated exception for missing method source --- .../Attributes/ShaderMethodSourceAttribute.cs | 16 ++++-- .../InvalidExecutionContextException.cs | 5 +- .../MissingMethodSourceException.cs | 52 +++++++++++++++++++ .../Extensions/MethodInfoExtensions.cs | 7 +++ .../GraphicsDeviceMismatchException.cs | 2 +- 5 files changed, 75 insertions(+), 7 deletions(-) create mode 100644 src/ComputeSharp.Core/Exceptions/MissingMethodSourceException.cs diff --git a/src/ComputeSharp.Core/Attributes/ShaderMethodSourceAttribute.cs b/src/ComputeSharp.Core/Attributes/ShaderMethodSourceAttribute.cs index 508758f1..9fd1fbd1 100644 --- a/src/ComputeSharp.Core/Attributes/ShaderMethodSourceAttribute.cs +++ b/src/ComputeSharp.Core/Attributes/ShaderMethodSourceAttribute.cs @@ -2,9 +2,9 @@ using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics.Contracts; -using System.Linq; using System.Reflection; using ComputeSharp.Core.Extensions; +using ComputeSharp.Exceptions; using Microsoft.Toolkit.Diagnostics; namespace ComputeSharp @@ -81,12 +81,18 @@ namespace ComputeSharp { Guard.IsTrue(function.Method.IsStatic, "Captured delegates need to wrap static methods"); + var attributes = function.Method.DeclaringType.Assembly.GetCustomAttributes(); string methodName = function.Method.GetFullName(); - return ( - from attribute in function.Method.DeclaringType.Assembly.GetCustomAttributes() - where attribute.MethodName == methodName - select attribute).Single(); + foreach (var attribute in attributes) + { + if (attribute.MethodName.Equals(methodName)) + { + return attribute; + } + } + + return MissingMethodSourceException.Throw(function); } } } \ No newline at end of file diff --git a/src/ComputeSharp.Core/Exceptions/InvalidExecutionContextException.cs b/src/ComputeSharp.Core/Exceptions/InvalidExecutionContextException.cs index 00a70c3e..d7401c19 100644 --- a/src/ComputeSharp.Core/Exceptions/InvalidExecutionContextException.cs +++ b/src/ComputeSharp.Core/Exceptions/InvalidExecutionContextException.cs @@ -11,6 +11,9 @@ namespace ComputeSharp.Exceptions /// Creates a new instance /// /// The name of the caller API - internal InvalidExecutionContextException(string name) : base($"The API {name} can only be used from within an HLSL shader") { } + internal InvalidExecutionContextException(string name) + : base($"The API {name} can only be used from within an HLSL shader.") + { + } } } diff --git a/src/ComputeSharp.Core/Exceptions/MissingMethodSourceException.cs b/src/ComputeSharp.Core/Exceptions/MissingMethodSourceException.cs new file mode 100644 index 00000000..ddb6232e --- /dev/null +++ b/src/ComputeSharp.Core/Exceptions/MissingMethodSourceException.cs @@ -0,0 +1,52 @@ +using System; +using System.Diagnostics.Contracts; +using System.Text; +using ComputeSharp.Core.Extensions; + +#pragma warning disable CS0618 + +namespace ComputeSharp.Exceptions +{ + /// + /// A custom that indicates when an HLSL-only API is called from C# + /// + public sealed class MissingMethodSourceException : InvalidOperationException + { + /// + /// Creates a new instance. + /// + /// The exception message to display. + private MissingMethodSourceException(string message) + : base(message) + { + } + + /// + /// Creates a new instance from the specified parameters. + /// + /// The target that couldn't be processed. + /// A new instance with a formatted error message. + [Pure] + private static MissingMethodSourceException Create(Delegate method) + { + StringBuilder builder = new(512); + + builder.AppendLine("The processed source for a method captured as a delegate in a shader was not found."); + builder.AppendLine($"The delegate was of type {method.GetType()} and it was wrapping the method {method.Method.GetFullName()}."); + builder.Append($"Make sure that the target method is annotated with [{nameof(ShaderMethodAttribute)}]."); + builder.ToString(); + + return new(builder.ToString()); + } + + /// + /// Throws a new for a given delegate. + /// + /// The target that couldn't be processed. + /// This method always throws and never actually returns anything. + internal static ShaderMethodSourceAttribute Throw(Delegate method) + { + throw Create(method); + } + } +} diff --git a/src/ComputeSharp.Core/Extensions/MethodInfoExtensions.cs b/src/ComputeSharp.Core/Extensions/MethodInfoExtensions.cs index 1a09359b..b413e1b3 100644 --- a/src/ComputeSharp.Core/Extensions/MethodInfoExtensions.cs +++ b/src/ComputeSharp.Core/Extensions/MethodInfoExtensions.cs @@ -19,6 +19,13 @@ namespace ComputeSharp.Core.Extensions { var parameters = string.Join(", ", method.GetParameters().Select(static p => p.ParameterType.FullName)); + if (method.IsGenericMethod) + { + var arguments = string.Join(", ", method.GetGenericArguments().Select(static t => t.FullName)); + + return $"{method.DeclaringType!.FullName}.{method.Name}<{arguments}>({parameters})"; + } + return $"{method.DeclaringType!.FullName}.{method.Name}({parameters})"; } } diff --git a/src/ComputeSharp.Graphics/Exceptions/GraphicsDeviceMismatchException.cs b/src/ComputeSharp.Graphics/Exceptions/GraphicsDeviceMismatchException.cs index 9fb31b09..edf3b8fe 100644 --- a/src/ComputeSharp.Graphics/Exceptions/GraphicsDeviceMismatchException.cs +++ b/src/ComputeSharp.Graphics/Exceptions/GraphicsDeviceMismatchException.cs @@ -36,7 +36,7 @@ namespace ComputeSharp.Exceptions builder.AppendLine("Invalid pairing of graphics devices used to run a compute shader and allocate memory buffers."); builder.AppendLine($"The target device to run the compute shader is \"{device}\"."); builder.AppendLine($"The buffer of type {buffer.GetType()} was allocated on device \"{buffer.GraphicsDevice}\"."); - builder.AppendLine("Make sure to always allocate buffers on the same device used to actually run the code that accesses them."); + builder.Append("Make sure to always allocate buffers on the same device used to actually run the code that accesses them."); builder.ToString(); return new(builder.ToString()); From fcb2b5995642f2540f78175815634a2d0e1a96f7 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 1 Dec 2020 18:30:15 +0100 Subject: [PATCH 9/9] Minor code tweaks --- .../Buffers/Abstract/Buffer{T}.cs | 4 +--- .../GraphicsDeviceMismatchException.cs | 17 +++++++++++++++-- .../Exceptions/HlslCompilationException.cs | 17 ++++++++++++----- 3 files changed, 28 insertions(+), 10 deletions(-) diff --git a/src/ComputeSharp.Graphics/Buffers/Abstract/Buffer{T}.cs b/src/ComputeSharp.Graphics/Buffers/Abstract/Buffer{T}.cs index 7e9d13cf..e4880443 100644 --- a/src/ComputeSharp.Graphics/Buffers/Abstract/Buffer{T}.cs +++ b/src/ComputeSharp.Graphics/Buffers/Abstract/Buffer{T}.cs @@ -279,9 +279,7 @@ namespace ComputeSharp.Graphics.Buffers.Abstract { if (GraphicsDevice != device) { - void Throw() => throw GraphicsDeviceMismatchException.Create(this, device); - - Throw(); + GraphicsDeviceMismatchException.Throw(this, device); } } } diff --git a/src/ComputeSharp.Graphics/Exceptions/GraphicsDeviceMismatchException.cs b/src/ComputeSharp.Graphics/Exceptions/GraphicsDeviceMismatchException.cs index edf3b8fe..fe2c4490 100644 --- a/src/ComputeSharp.Graphics/Exceptions/GraphicsDeviceMismatchException.cs +++ b/src/ComputeSharp.Graphics/Exceptions/GraphicsDeviceMismatchException.cs @@ -7,7 +7,7 @@ using ComputeSharp.Graphics.Buffers.Abstract; namespace ComputeSharp.Exceptions { /// - /// A custom that indicates when mismatched devices are being used. + /// A custom that indicates when mismatched devices are being used. /// public sealed class GraphicsDeviceMismatchException : InvalidOperationException { @@ -28,7 +28,7 @@ namespace ComputeSharp.Exceptions /// The target instance that was used. /// A new instance with a formatted error message. [Pure] - public static GraphicsDeviceMismatchException Create(Buffer buffer, GraphicsDevice device) + private static GraphicsDeviceMismatchException Create(Buffer buffer, GraphicsDevice device) where T : unmanaged { StringBuilder builder = new(512); @@ -41,5 +41,18 @@ namespace ComputeSharp.Exceptions return new(builder.ToString()); } + + /// + /// Throws a new instance from the specified parameters. + /// + /// The type of values in the input buffer. + /// The input that was used. + /// The target instance that was used. + [Pure] + internal static void Throw(Buffer buffer, GraphicsDevice device) + where T : unmanaged + { + throw Create(buffer, device); + } } } \ No newline at end of file diff --git a/src/ComputeSharp.Shaders/Exceptions/HlslCompilationException.cs b/src/ComputeSharp.Shaders/Exceptions/HlslCompilationException.cs index 840db2e6..bb94d393 100644 --- a/src/ComputeSharp.Shaders/Exceptions/HlslCompilationException.cs +++ b/src/ComputeSharp.Shaders/Exceptions/HlslCompilationException.cs @@ -5,17 +5,24 @@ using System.Text; namespace ComputeSharp.Exceptions { /// - /// A custom that indicates when mismatched devices are being used + /// A custom type that indicates when a shader compilation with the DXC compiler has failed. /// public sealed class HlslCompilationException : Exception { /// - /// Creates a new instance + /// Creates a new instance /// - /// The error message produced by the Dxc compiler - internal HlslCompilationException(string error) : base(GetExceptionMessage(error)) { } + /// The error message produced by the DXC compiler + internal HlslCompilationException(string error) + : base(GetExceptionMessage(error)) + { + } - // Gets a proper exception message for a given compilation error + /// + /// Gets a formatted exception message for a given compilation error. + /// + /// The input compilatin error message from the DXC compiler. + /// A formatted error message for a new instance. [Pure] private static string GetExceptionMessage(string error) {