diff --git a/src/ComputeSharp.Shaders/ShaderRunner{T}.cs b/src/ComputeSharp.Shaders/ShaderRunner{T}.cs index a4c85b2d..1ebb6005 100644 --- a/src/ComputeSharp.Shaders/ShaderRunner{T}.cs +++ b/src/ComputeSharp.Shaders/ShaderRunner{T}.cs @@ -89,7 +89,7 @@ namespace ComputeSharp.Shaders ShaderBytecode shaderBytecode = ShaderCompiler.CompileShader(shaderSource); // Cache for later use - ShadersCache.GetOrAddValueRef(key) = new CachedShader(shaderLoader, shaderBytecode); + ShadersCache.GetOrAddValueRef(key) = shaderData = new CachedShader(shaderLoader, shaderBytecode); } } diff --git a/src/ComputeSharp.Shaders/Translation/Enums/MethodType.cs b/src/ComputeSharp.Shaders/Translation/Enums/MethodType.cs index 7df4f830..c3c188e8 100644 --- a/src/ComputeSharp.Shaders/Translation/Enums/MethodType.cs +++ b/src/ComputeSharp.Shaders/Translation/Enums/MethodType.cs @@ -6,9 +6,9 @@ internal enum MethodType { /// - /// An instance method that belongs to a closure class + /// The instance method on some shader type /// - Closure, + Execute, /// /// A standalone, static method diff --git a/src/ComputeSharp.Shaders/Translation/MethodDecompiler.cs b/src/ComputeSharp.Shaders/Translation/MethodDecompiler.cs index 5c10cd5b..b4bd6bef 100644 --- a/src/ComputeSharp.Shaders/Translation/MethodDecompiler.cs +++ b/src/ComputeSharp.Shaders/Translation/MethodDecompiler.cs @@ -6,7 +6,6 @@ using System.IO; using System.Linq; using System.Reflection; using System.Reflection.Metadata; -using System.Text; using System.Text.RegularExpressions; using ComputeSharp.Shaders.Mappings; using ComputeSharp.Shaders.Translation.Enums; @@ -138,7 +137,7 @@ namespace ComputeSharp.Shaders.Translation { string sourceCode = methodType switch { - MethodType.Closure => GetSyntaxTreeForClosureMethod(methodInfo), + MethodType.Execute => GetSyntaxTreeForClosureMethod(methodInfo), MethodType.Static => GetSyntaxTreeForStaticMethod(methodInfo), _ => throw new ArgumentOutOfRangeException(nameof(methodType), $"Invalid method type: {methodType}") }; @@ -147,7 +146,11 @@ namespace ComputeSharp.Shaders.Translation SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(sourceCode); // Get the root node to return - rootNode = syntaxTree.GetRoot().DescendantNodes().OfType().First(node => node.GetLeadingTrivia().ToFullString().Contains(methodInfo.Name)); + rootNode = syntaxTree + .GetRoot() + .DescendantNodes() + .OfType() + .First(node => node.Identifier.ToString().Equals(methodInfo.Name)); // Update the incremental compilation and retrieve the syntax tree for the method Compilation compilation = _Compilation.AddSyntaxTrees(syntaxTree); @@ -161,29 +164,11 @@ namespace ComputeSharp.Shaders.Translation [Pure] private string GetSyntaxTreeForClosureMethod(MethodInfo methodInfo) { - // Decompile the method source and fix the method declaration for local methods converted to lambdas - string - sourceCode = DecompileMethodOrDeclaringType(methodInfo), - typeFixedCode = ClosureTypeDeclarationRegex.Replace(sourceCode, "Shader"), - methodFixedCode = LambdaMethodDeclarationRegex.Replace(typeFixedCode, m => $"// {m.Value}{Environment.NewLine} internal void Main"); - - // Workaround for some local methods not being decompiled correctly - if (!methodFixedCode.Contains("internal void Main")) - { - string - methodOnlySourceCode = DecompileMethodOrDeclaringType(methodInfo, true), - methodOnlyFixedSourceCode = LambdaMethodDeclarationRegex.Replace(methodOnlySourceCode, m => $"// {m.Value}{Environment.NewLine} internal void Main"), - methodOnlyIndentedSourceCode = $" {methodOnlyFixedSourceCode.Replace(Environment.NewLine, $"{Environment.NewLine} ")}"; - - int lastClosedBracketsIndex = methodFixedCode.LastIndexOf('}'); - methodFixedCode = methodFixedCode.Insert(lastClosedBracketsIndex, methodOnlyIndentedSourceCode); - } - - // Unwrap the nested fields - string unwrappedSourceCode = UnwrapSyntaxTree(methodFixedCode); + // Decompile the method source + string sourceCode = DecompileMethodOrDeclaringType(methodInfo); // Remove the in keyword from the source - string inFixedSourceCode = Regex.Replace(unwrappedSourceCode, @"(? - /// A used to preprocess the closure type declarations for both lambda expressions and local methods - /// - private static readonly Regex ClosureTypeDeclarationRegex = new Regex(@"(?<=private sealed class )<\w*>[\w_]+", RegexOptions.Compiled); - - /// - /// A used to preprocess the entry point declaration for both lambda expressions and local methods - /// - private static readonly Regex LambdaMethodDeclarationRegex = new Regex(@"(?:private|internal) void <\w+>[\w_|]+(?=\()", RegexOptions.Compiled); - - /// - /// A used to find fields that represent nested closure types - /// - private static readonly Regex NestedClosureFieldRegex = new Regex(@"(?<=public )((?:\w+\.)+<>[\w_]+) (CS\$<>[\w_]+)(?=;)", RegexOptions.Compiled); - - /// - /// A used to identify compiler generated fields - /// - private static readonly Regex CompilerGeneratedFieldRegex = new Regex(@"CS\$<>[\w_]+\.", RegexOptions.Compiled); - - /// - /// Unwraps all the nested captured fields in the given source code, moving them to the top level - /// - /// The input source code to process - [Pure] - private string UnwrapSyntaxTree(string source) - { - List parsedFields = new List(); - - // Local function to recursively extract all the nested fields - void ParseNestedFields(string typeSource) - { - // Find the field declarations - Match match = NestedClosureFieldRegex.Match(typeSource); - if (!match.Success) return; - - // Load the nested closure type - string fullname = match.Groups[1].Value.Replace(".<>", "+<>"); // Fullname of a nested type - Type type = AppDomain.CurrentDomain.GetAssemblies().Select(a => a.GetType(fullname)).First(t => t != null); - - // Decompile the type and get a readable source code - EntityHandle typeHandle = MetadataTokenHelpers.TryAsEntityHandle(type.MetadataToken) ?? throw new InvalidOperationException(); - CSharpDecompiler decompiler = Decompilers[type.Assembly.Location]; - string - sourceCode = decompiler.DecompileAsString(typeHandle), - typeFixedCode = ClosureTypeDeclarationRegex.Replace(sourceCode, "Scope"); - - // Load the syntax tree and retrieve the list of fields - SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(typeFixedCode); - FieldDeclarationSyntax[] fields = syntaxTree.GetRoot().DescendantNodes().OfType().First().ChildNodes().OfType().ToArray(); - - // Add the captured fields - foreach (FieldDeclarationSyntax field in fields) - if (!field.Declaration.Variables.ToFullString().StartsWith("CS$<>")) - parsedFields.Add(field); - - // Explore the new decompiled type - ParseNestedFields(typeFixedCode); - } - - ParseNestedFields(source); - - if (parsedFields.Count > 0) - { - // Build the aggregated string with all the captured fields - StringBuilder builder = new StringBuilder(); - foreach (FieldDeclarationSyntax field in parsedFields) - builder.AppendLine(field.ToFullString()); - string fields = builder.ToString().TrimEnd(' ', '\r', '\n'); - - // Replace the field declarations - Match match = NestedClosureFieldRegex.Match(source); - source = source.Remove(match.Index - 11, match.Length + 12); // leading " public " and trailing ";" - source = source.Insert(match.Index - 11, fields); - - // Adjust the method body to remove references to compiler generated fields - source = CompilerGeneratedFieldRegex.Replace(source, string.Empty); - } - - return source; - } - /// /// Refactors all the inline out expressions with a variable declaration /// @@ -308,7 +211,11 @@ namespace ComputeSharp.Shaders.Translation // Load the syntax tree and the entry node SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(source); - MethodDeclarationSyntax rootNode = syntaxTree.GetRoot().DescendantNodes().OfType().First(node => node.GetLeadingTrivia().ToFullString().Contains(entryPoint)); + MethodDeclarationSyntax rootNode = syntaxTree + .GetRoot() + .DescendantNodes() + .OfType() + .First(node => node.Identifier.ToString().Equals(entryPoint)); // Get the out declarations to replace var outs = ( diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs index fbf49dc5..9c8df435 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs @@ -232,7 +232,7 @@ namespace ComputeSharp.Shaders.Translation private void LoadMethodSource() { // Decompile the shader method - MethodDecompiler.Instance.GetSyntaxTree(Action.Method, MethodType.Closure, out MethodDeclarationSyntax root, out SemanticModel semanticModel); + MethodDecompiler.Instance.GetSyntaxTree(Action.Method, MethodType.Execute, out MethodDeclarationSyntax root, out SemanticModel semanticModel); // Rewrite the shader method (eg. to fix the type declarations) ShaderSyntaxRewriter syntaxRewriter = new ShaderSyntaxRewriter(semanticModel, ShaderType); diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs index a9e9ddef..5b52b14b 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs @@ -208,7 +208,7 @@ namespace ComputeSharp.Shaders.Translation { // Decompile the shader method MethodInfo methodInfo = typeof(T).GetMethod(nameof(IComputeShader.Execute)); - MethodDecompiler.Instance.GetSyntaxTree(methodInfo, MethodType.Closure, out MethodDeclarationSyntax root, out SemanticModel semanticModel); + MethodDecompiler.Instance.GetSyntaxTree(methodInfo, MethodType.Execute, out MethodDeclarationSyntax root, out SemanticModel semanticModel); // Rewrite the shader method (eg. to fix the type declarations) ShaderSyntaxRewriter syntaxRewriter = new ShaderSyntaxRewriter(semanticModel, typeof(T));