diff --git a/src/ComputeSharp.Dynamic/Attributes/Extensions/MethodInfoExtensions.cs b/src/ComputeSharp.Dynamic/Attributes/Extensions/MethodInfoExtensions.cs deleted file mode 100644 index 17279abd..00000000 --- a/src/ComputeSharp.Dynamic/Attributes/Extensions/MethodInfoExtensions.cs +++ /dev/null @@ -1,39 +0,0 @@ -using System.Linq; -using System.Reflection; -using System.Text.RegularExpressions; - -namespace ComputeSharp.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. - public static string GetFullyQualifiedName(this MethodInfo method) - { - string parameters = string.Join(", ", method.GetParameters().Select(static p => p.ParameterType.FullName)); - - // Fixup the method name for static local functions in global statements. This only needs to - // be done when the method is in a type with fully qualified name "Program", as that's the only - // case where it might happen. If the declaring type has a name, it can't be that for sure. - (string declaringType, string methodName) = (method.DeclaringType!.FullName!, method.Name) switch - { - ("Program", var name) => ("Program", Regex.Replace(name, @"<
\$>g__(\w+)\|\d+_\d+", static m => m.Groups[1].Value)), - (var type, var name) => (type, name) - }; - - if (method.IsGenericMethod) - { - string arguments = string.Join(", ", method.GetGenericArguments().Select(static t => t.FullName)); - - return $"{declaringType}.{methodName}<{arguments}>({parameters})"; - } - - return $"{declaringType}.{methodName}({parameters})"; - } -} \ No newline at end of file diff --git a/src/ComputeSharp.Dynamic/Attributes/ShaderMethodAttribute.cs b/src/ComputeSharp.Dynamic/Attributes/ShaderMethodAttribute.cs deleted file mode 100644 index 84a5afbd..00000000 --- a/src/ComputeSharp.Dynamic/Attributes/ShaderMethodAttribute.cs +++ /dev/null @@ -1,21 +0,0 @@ -using System; -using System.ComponentModel; - -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, AllowMultiple = false)] -[EditorBrowsable(EditorBrowsableState.Never)] -[Obsolete( - "This API (and shader metaprogramming in general) is being removed in a future version of ComputeSharp. " + - "If you're relying on this functionality, consider manually implementing different shader variants. " + - "It is possible to still reuse code by moving it to helper methods that are used by multiple shaders.")] -public sealed class ShaderMethodAttribute : Attribute -{ -} \ No newline at end of file diff --git a/src/ComputeSharp.Dynamic/Attributes/__Internals/ShaderMethodSourceAttribute.HlslGeneration.cs b/src/ComputeSharp.Dynamic/Attributes/__Internals/ShaderMethodSourceAttribute.HlslGeneration.cs deleted file mode 100644 index 2bc68b06..00000000 --- a/src/ComputeSharp.Dynamic/Attributes/__Internals/ShaderMethodSourceAttribute.HlslGeneration.cs +++ /dev/null @@ -1,93 +0,0 @@ -using System; -using System.Collections.Generic; - -namespace ComputeSharp.__Internals; - -/// -partial class ShaderMethodSourceAttribute : Attribute -{ - /// - /// Appends the mapped source code for the current method. - /// - /// The target instance to write to. - /// The mapping of already discovered constant names. - public void AppendConstants(ref ArrayPoolStringBuilder builder, HashSet mapping) - { - foreach (KeyValuePair constant in this.constants) - { - if (mapping.Add(constant.Key)) - { - builder.Append('\n'); - builder.Append("#define "); - builder.Append(constant.Key); - builder.Append(' '); - builder.Append(constant.Value); - builder.Append('\n'); - } - } - } - - /// - /// Appends the discovered types for the current method. - /// - /// The target instance to write to. - /// The mapping of already discovered type names. - public void AppendTypes(ref ArrayPoolStringBuilder builder, HashSet mapping) - { - foreach (KeyValuePair type in this.types) - { - if (mapping.Add(type.Key)) - { - builder.Append('\n'); - builder.Append(type.Value); - builder.Append('\n'); - } - } - } - - /// - /// Appends the discovered forward declarations for the current method. - /// - /// The target instance to write to. - /// The mapping of already discovered type names. - public void AppendForwardDeclarations(ref ArrayPoolStringBuilder builder, HashSet mapping) - { - foreach (KeyValuePair method in this.methods) - { - if (mapping.Add(method.Key)) - { - builder.Append('\n'); - builder.Append(method.Key); - builder.Append('\n'); - } - } - } - - /// - /// Appends the discovered methods for the current method. - /// - /// The target instance to write to. - /// The mapping of already discovered type names. - public void AppendMethods(ref ArrayPoolStringBuilder builder, HashSet mapping) - { - foreach (KeyValuePair method in this.methods) - { - if (mapping.Remove(method.Key)) - { - builder.Append('\n'); - builder.Append(method.Value); - builder.Append('\n'); - } - } - } - - /// - /// Appends the mapped source code for the current method. - /// - /// The target instance to write to. - /// The name to bind the method to. - public void AppendMappedInvokeMethod(ref ArrayPoolStringBuilder builder, string name) - { - builder.Append(this.invokeMethod.Replace(InvokeMethodIdentifier, name)); - } -} \ No newline at end of file diff --git a/src/ComputeSharp.Dynamic/Attributes/__Internals/ShaderMethodSourceAttribute.cs b/src/ComputeSharp.Dynamic/Attributes/__Internals/ShaderMethodSourceAttribute.cs deleted file mode 100644 index 74c0b631..00000000 --- a/src/ComputeSharp.Dynamic/Attributes/__Internals/ShaderMethodSourceAttribute.cs +++ /dev/null @@ -1,113 +0,0 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Linq; -using System.Reflection; -using ComputeSharp.Extensions; - -#pragma warning disable IDE0052 - -namespace ComputeSharp.__Internals; - -/// -/// 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 not intended to be used directly by user code")] -public sealed partial class ShaderMethodSourceAttribute : Attribute -{ - /// - /// The identifier for the invoke method, for late binding. - /// - internal const string InvokeMethodIdentifier = "____"; - - /// - /// The fully qualified name of the current method. - /// - private readonly string methodName; - - /// - /// The source code for the target entry point method. - /// - private readonly string invokeMethod; - - /// - /// The collection of custom types. - /// - private readonly Dictionary types; - - /// - /// The collection of processed methods. - /// - private readonly Dictionary methods; - - /// - /// The collection of discovered constants. - /// - private readonly Dictionary constants; - - /// - /// Creates a new instance with the specified parameters. - /// - /// The fully qualified name of the current method. - /// The source code for the target entry point method. - /// The collection of custom types. - /// The collection of processed methods. - /// The collection of discovered constants. - public ShaderMethodSourceAttribute(string methodName, string invokeMethod, object[] types, object[] methods, object[] constants) - { - this.methodName = methodName; - this.invokeMethod = invokeMethod; - this.types = types.Cast().ToDictionary(static c => c[0], static c => c[1]); - this.methods = methods.Cast().ToDictionary(static c => c[0], static c => c[1]); - this.constants = constants.Cast().ToDictionary(static c => c[0], static c => c[1]); - } - - /// - /// Gets the associated instance for a specified delegate. - /// - /// The input instance to get info for. - /// The name of the shader field containing . - /// The associated instance for the given delegate. - public static ShaderMethodSourceAttribute GetForDelegate(Delegate function, string name) - { - if (!function.Method.IsStatic) - { - return ThrowArgumentExceptionForNonStaticMethod(name); - } - - IEnumerable attributes = function.Method.DeclaringType!.Assembly.GetCustomAttributes(); - string methodName = function.Method.GetFullyQualifiedName(); - - foreach (ShaderMethodSourceAttribute attribute in attributes) - { - if (attribute.methodName.Equals(methodName)) - { - return attribute; - } - } - - return ThrowArgumentExceptionForMissingShaderMethodAttribute(name); - } - - /// - /// Throws an when a given is not static. - /// - /// The name of the shader field containing the invalid method. - private static ShaderMethodSourceAttribute ThrowArgumentExceptionForNonStaticMethod(string name) - { - throw new ArgumentException($"The captured delegate \"{name}\" was wrapping a non static method (only static methods are supported for captured delegates).", name); - } - - /// - /// Throws an when a given doesn't have applied to it. - /// - /// The name of the shader field containing the invalid method. - private static ShaderMethodSourceAttribute ThrowArgumentExceptionForMissingShaderMethodAttribute(string name) - { - throw new ArgumentException($"The captured delegate \"{name}\" was wrapping a method without the [ShaderMethod] attribute applied to it.", name); - } -} \ No newline at end of file diff --git a/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj b/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj index 4e026855..ae2b90c9 100644 --- a/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj +++ b/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj @@ -57,9 +57,6 @@ - - - diff --git a/src/ComputeSharp.SourceGenerators/Helpers/SyntaxFactoryHelper.cs b/src/ComputeSharp.SourceGenerators/Helpers/SyntaxFactoryHelper.cs deleted file mode 100644 index 166c6579..00000000 --- a/src/ComputeSharp.SourceGenerators/Helpers/SyntaxFactoryHelper.cs +++ /dev/null @@ -1,41 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Syntax; -using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; - -namespace ComputeSharp.SourceGenerators.Helpers; - -/// -/// A class containing additional factory methods for constructing syntax nodes, tokens and trivia. -/// -internal static class SyntaxFactoryHelper -{ - /// - /// Creates an [] array expression with the nested groups in the input sequence. - /// - /// That it, it applies the following transformation: - /// - /// { ("K1", "V1"), ("K2", "V2") } => new object[] { new string[] { "K1", "V1" }, new string[] { "K2", "V2" } } - /// - /// - /// - /// The input sequence of groups. - /// An instance with the described contents. - public static ArrayCreationExpressionSyntax NestedArrayExpression(IEnumerable<(string A, string B)> groups) - { - return - ArrayCreationExpression( - ArrayType(PredefinedType(Token(SyntaxKind.ObjectKeyword))) - .AddRankSpecifiers(ArrayRankSpecifier(SingletonSeparatedList(OmittedArraySizeExpression())))) - .WithInitializer(InitializerExpression(SyntaxKind.ArrayInitializerExpression) - .AddExpressions(groups.Select(static group => - ArrayCreationExpression( - ArrayType(PredefinedType(Token(SyntaxKind.StringKeyword))) - .AddRankSpecifiers(ArrayRankSpecifier(SingletonSeparatedList(OmittedArraySizeExpression())))) - .WithInitializer(InitializerExpression(SyntaxKind.ArrayInitializerExpression) - .AddExpressions( - LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(group.A)), - LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(group.B))))).ToArray())); - } -} \ No newline at end of file diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.cs index 6d888905..adffa7b0 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.cs @@ -421,7 +421,7 @@ partial class IShaderGenerator /// /// The collection of discovered constant definitions. /// A sequence of discovered constants to declare in the shader. - internal static ImmutableArray<(string Name, string Value)> GetDefinedConstants(IReadOnlyDictionary constantDefinitions) + private static ImmutableArray<(string Name, string Value)> GetDefinedConstants(IReadOnlyDictionary constantDefinitions) { using ImmutableArrayBuilder<(string, string)> builder = new(); @@ -444,7 +444,7 @@ partial class IShaderGenerator /// The sequence of discovered custom types. /// The collection of discovered instance methods for custom struct types. /// A sequence of custom type definitions to add to the shader source. - internal static ImmutableArray<(string Name, string Definition)> GetDeclaredTypes( + private static ImmutableArray<(string Name, string Definition)> GetDeclaredTypes( ImmutableArrayBuilder diagnostics, ISymbol sourceSymbol, IEnumerable types, diff --git a/src/ComputeSharp.SourceGenerators/Models/HlslMethodSourceInfo.cs b/src/ComputeSharp.SourceGenerators/Models/HlslMethodSourceInfo.cs deleted file mode 100644 index 78b83804..00000000 --- a/src/ComputeSharp.SourceGenerators/Models/HlslMethodSourceInfo.cs +++ /dev/null @@ -1,18 +0,0 @@ -using ComputeSharp.SourceGeneration.Helpers; - -namespace ComputeSharp.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, - EquatableArray<(string Name, string Definition)> DefinedTypes, - EquatableArray<(string Name, string Value)> DefinedConstants, - EquatableArray<(string Signature, string Definition)> DependentMethods); \ No newline at end of file diff --git a/src/ComputeSharp.SourceGenerators/Models/ShaderMethodInfo.cs b/src/ComputeSharp.SourceGenerators/Models/ShaderMethodInfo.cs deleted file mode 100644 index f2745cc3..00000000 --- a/src/ComputeSharp.SourceGenerators/Models/ShaderMethodInfo.cs +++ /dev/null @@ -1,11 +0,0 @@ -using ComputeSharp.SourceGeneration.Helpers; -using ComputeSharp.SourceGeneration.Models; - -namespace ComputeSharp.SourceGenerators.Models; - -/// -/// A model representing all necessary info for a full generation pass for a shader method. -/// -/// The processed HLSL source for the shader method. -/// The discovered diagnostics, if any. -internal sealed record ShaderMethodInfo(HlslMethodSourceInfo HlslMethodSource, EquatableArray Diagnostcs); \ No newline at end of file diff --git a/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs b/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs deleted file mode 100644 index 1a97cf1f..00000000 --- a/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs +++ /dev/null @@ -1,190 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Collections.Immutable; -using System.Linq; -using System.Text; -using ComputeSharp.__Internals; -using ComputeSharp.SourceGeneration.Extensions; -using ComputeSharp.SourceGeneration.Helpers; -using ComputeSharp.SourceGeneration.Models; -using ComputeSharp.SourceGeneration.SyntaxRewriters; -using ComputeSharp.SourceGenerators.Models; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Syntax; -using static ComputeSharp.SourceGenerators.Helpers.SyntaxFactoryHelper; -using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; - -#pragma warning disable CS0618 - -namespace ComputeSharp.SourceGenerators; - -/// -/// A source generator for processing static methods referenced from compute shaders. -/// -[Generator(LanguageNames.CSharp)] -public sealed partial class ShaderMethodSourceGenerator : IIncrementalGenerator -{ - /// - public void Initialize(IncrementalGeneratorInitializationContext context) - { - // Get all declared methods (including global function declarations) with the [ShaderMethod] attribute, and their info - IncrementalValuesProvider methodInfoWithErrors = - context.SyntaxProvider - .ForAttributeWithMetadataName( - typeof(ShaderMethodAttribute).FullName, - static (node, _) => node is MethodDeclarationSyntax { AttributeLists.Count: > 0 } or LocalFunctionStatementSyntax { Parent: GlobalStatementSyntax { Parent: CompilationUnitSyntax } }, - static (context, token) => - { - HlslMethodSourceInfo hlslMethodSourceInfo = Execute.GetData( - context.SemanticModel.Compilation, - (CSharpSyntaxNode)context.TargetNode, - (IMethodSymbol)context.TargetSymbol, - out ImmutableArray diagnostics); - - return new ShaderMethodInfo(hlslMethodSourceInfo, diagnostics); - }); - - // Output the diagnostics, if any - context.ReportDiagnostics( - methodInfoWithErrors - .Select(static (item, _) => item.Diagnostcs)); - - // Generate the [ShaderMethodSource] attributes - context.RegisterSourceOutput(methodInfoWithErrors, static (context, item) => - { - CompilationUnitSyntax compilationUnit = Execute.GetSyntax(item.HlslMethodSource); - string filename = item.HlslMethodSource.MetadataName.Replace('`', '-').Replace('+', '.'); - - context.AddSource($"{filename}.g.cs", compilationUnit.GetText(Encoding.UTF8)); - }); - } - - /// - /// A helper with all logic to generate the attribute declarations. - /// - private static class Execute - { - /// - /// Processes a given target method. - /// - /// The input object currently in use. - /// The or node to process. - /// The instance for the current method. - /// The resulting diagnostics from the processing operation. - public static HlslMethodSourceInfo GetData( - Compilation compilation, - CSharpSyntaxNode methodDeclaration, - IMethodSymbol methodSymbol, - out ImmutableArray diagnostics) - { - using ImmutableArrayBuilder builder = new(); - - // We need to sets to track all discovered custom types and static methods - HashSet discoveredTypes = new(SymbolEqualityComparer.Default); - Dictionary constantDefinitions = new(SymbolEqualityComparer.Default); - Dictionary instanceMethods = new(SymbolEqualityComparer.Default); // Unused in this generator - - // Explore the syntax tree and extract the processed info - SemanticModelProvider semanticModel = new(compilation); - (string entryPoint, ImmutableArray<(string Signature, string Definition)> dependentMethods) = GetProcessedMethods(builder, methodDeclaration, semanticModel, discoveredTypes, constantDefinitions); - ImmutableArray<(string Name, string Definition)> definedTypes = IShaderGenerator.BuildHlslSource.GetDeclaredTypes(builder, methodSymbol, discoveredTypes, instanceMethods); - ImmutableArray<(string Name, string Value)> definedConstants = IShaderGenerator.BuildHlslSource.GetDefinedConstants(constantDefinitions); - - diagnostics = builder.ToImmutable(); - - return new( - methodSymbol.GetFullyQualifiedMetadataName(includeParameters: true), - entryPoint, - definedTypes, - definedConstants, - dependentMethods); - } - - /// - /// Gets a sequence of processed methods from a target method declaration. - /// - /// The collection of produced instances. - /// The or instance for the current method. - /// The instance for the method to process. - /// The collection of currently discovered types. - /// The collection of discovered constant definitions. - /// A sequence of processed methods in (main method and all captured methods). - private static (string TargetMethod, ImmutableArray<(string Signature, string Definition)> DependentMethods) GetProcessedMethods( - ImmutableArrayBuilder diagnostics, - CSharpSyntaxNode methodDeclaration, - SemanticModelProvider semanticModel, - ICollection discoveredTypes, - IDictionary constantDefinitions) - { - Dictionary staticMethods = new(SymbolEqualityComparer.Default); - Dictionary instanceMethods = new(SymbolEqualityComparer.Default); - - ShaderSourceRewriter shaderSourceRewriter = new(semanticModel, discoveredTypes, staticMethods, instanceMethods, constantDefinitions, diagnostics); - - // Process the possible syntax nodes - SyntaxNode visitedMethod = methodDeclaration switch - { - MethodDeclarationSyntax methodDeclarationSyntax => shaderSourceRewriter.Visit(methodDeclarationSyntax)!.WithIdentifier(Identifier(ShaderMethodSourceAttribute.InvokeMethodIdentifier)), - LocalFunctionStatementSyntax functionStatementSyntax => shaderSourceRewriter.Visit(functionStatementSyntax)!.WithIdentifier(Identifier(ShaderMethodSourceAttribute.InvokeMethodIdentifier)), - _ => throw new ArgumentException("Invalid method declaration syntax node type.") - }; - - // Rewrite the method syntax tree - string targetMethod = visitedMethod - .WithoutTrivia() - .NormalizeWhitespace(eol: "\n") - .ToFullString(); - - using ImmutableArrayBuilder<(string, string)> methods = new(); - - // Emit the extracted local functions - foreach (KeyValuePair localFunction in shaderSourceRewriter.LocalFunctions) - { - methods.Add(( - localFunction.Value.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(), - localFunction.Value.NormalizeWhitespace(eol: "\n").ToFullString())); - } - - // Emit the discovered static methods - foreach (MethodDeclarationSyntax staticMethod in staticMethods.Values) - { - methods.Add(( - staticMethod.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(), - staticMethod.NormalizeWhitespace(eol: "\n").ToFullString())); - } - - return (targetMethod, methods.ToImmutable()); - } - - /// - /// Creates a instance with the processed attribute. - /// - /// The input instance to use. - public static CompilationUnitSyntax GetSyntax(HlslMethodSourceInfo methodSourceInfo) - { - // This produces an assembly attribute declaration as follows: - // - // // - // #pragma warning disable - // [assembly: global::ComputeSharp.ShaderMethodSourceAttribute()] - return - CompilationUnit().AddAttributeLists( - AttributeList(SingletonSeparatedList( - Attribute(IdentifierName($"global::{typeof(ShaderMethodSourceAttribute).FullName}")).AddArgumentListArguments( - AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(methodSourceInfo.MetadataName))), - AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(methodSourceInfo.EntryPoint))), - AttributeArgument(NestedArrayExpression(methodSourceInfo.DefinedTypes)), - AttributeArgument(NestedArrayExpression(methodSourceInfo.DependentMethods)), - AttributeArgument(NestedArrayExpression(methodSourceInfo.DefinedConstants))))) - .WithOpenBracketToken(Token(TriviaList(Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), SyntaxKind.OpenBracketToken, TriviaList())) - .WithOpenBracketToken(Token(TriviaList( - Comment("// "), - Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), - SyntaxKind.OpenBracketToken, - TriviaList())) - .WithTarget(AttributeTargetSpecifier(Token(SyntaxKind.AssemblyKeyword)))) - .NormalizeWhitespace(eol: "\n"); - } - } -} \ No newline at end of file