From 1f694466e67a5cc3f43c0550e9debd0c1498fa6e Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Wed, 4 Sep 2019 10:03:39 +0200 Subject: [PATCH 01/19] Minor code refactoring --- .../Translation/MethodDecompiler.cs | 40 ++++++++++++------- 1 file changed, 26 insertions(+), 14 deletions(-) diff --git a/src/ComputeSharp.Shaders/Translation/MethodDecompiler.cs b/src/ComputeSharp.Shaders/Translation/MethodDecompiler.cs index b96e6d2e..5a815988 100644 --- a/src/ComputeSharp.Shaders/Translation/MethodDecompiler.cs +++ b/src/ComputeSharp.Shaders/Translation/MethodDecompiler.cs @@ -107,6 +107,30 @@ namespace ComputeSharp.Shaders.Translation return new CSharpDecompiler(assemblyPath, resolver, decompilerSettings); } + /// + /// Decompiles a method or the whole declaring type + /// + /// The target to decompile + /// Specifies whether or not to force the decompilation of just the given method, even if not static + /// The decompiled source code + [Pure] + private string DecompileMethodOrDeclaringType(MethodInfo methodInfo, bool methodOnly = false) + { + // Get the handle of the containing type method + string assemblyPath = methodInfo.DeclaringType?.Assembly.Location ?? throw new InvalidOperationException(); + int metadataToken = methodInfo.IsStatic || methodOnly ? methodInfo.MetadataToken : methodInfo.DeclaringType.MetadataToken; + EntityHandle typeHandle = MetadataTokenHelpers.TryAsEntityHandle(metadataToken) ?? throw new InvalidOperationException(); + + // Get or create a decompiler for the target assembly, and decompile the type + if (!Decompilers.TryGetValue(assemblyPath, out CSharpDecompiler decompiler)) + { + decompiler = CreateDecompiler(assemblyPath); + Decompilers.Add(assemblyPath, decompiler); + } + + return decompiler.DecompileAsString(typeHandle); + } + /// /// A used to preprocess the closure type declarations for both lambda expressions and local methods /// @@ -127,29 +151,17 @@ namespace ComputeSharp.Shaders.Translation { lock (Lock) { - // Get the handle of the containing type method - string assemblyPath = methodInfo.DeclaringType?.Assembly.Location ?? throw new InvalidOperationException(); - EntityHandle typeHandle = MetadataTokenHelpers.TryAsEntityHandle(methodInfo.DeclaringType.MetadataToken) ?? throw new InvalidOperationException(); - - // Get or create a decompiler for the target assembly, and decompile the type - if (!Decompilers.TryGetValue(assemblyPath, out CSharpDecompiler decompiler)) - { - decompiler = CreateDecompiler(assemblyPath); - Decompilers.Add(assemblyPath, decompiler); - } - // Decompile the method source and fix the method declaration for local methods converted to lambdas string - sourceCode = decompiler.DecompileAsString(typeHandle), + 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")) { - EntityHandle methodHandle = MetadataTokenHelpers.TryAsEntityHandle(methodInfo.MetadataToken) ?? throw new InvalidOperationException(); string - methodOnlySourceCode = decompiler.DecompileAsString(methodHandle), + methodOnlySourceCode = DecompileMethodOrDeclaringType(methodInfo, true), methodOnlyFixedSourceCode = LambdaMethodDeclarationRegex.Replace(methodOnlySourceCode, m => $"// {m.Value}{Environment.NewLine} internal void Main"), methodOnlyIndentedSourceCode = $" {methodOnlyFixedSourceCode.Replace(Environment.NewLine, $"{Environment.NewLine} ")}"; From aa5b76bec98e04e8e1f77e6b62848d5cc3b37ecd Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Wed, 4 Sep 2019 10:22:48 +0200 Subject: [PATCH 02/19] Added initial code to decompile static methods --- .../Translation/Enums/MethodType.cs | 18 +++ .../Translation/MethodDecompiler.cs | 108 ++++++++++++------ .../Translation/ShaderLoader.cs | 3 +- 3 files changed, 91 insertions(+), 38 deletions(-) create mode 100644 src/ComputeSharp.Shaders/Translation/Enums/MethodType.cs diff --git a/src/ComputeSharp.Shaders/Translation/Enums/MethodType.cs b/src/ComputeSharp.Shaders/Translation/Enums/MethodType.cs new file mode 100644 index 00000000..7df4f830 --- /dev/null +++ b/src/ComputeSharp.Shaders/Translation/Enums/MethodType.cs @@ -0,0 +1,18 @@ +namespace ComputeSharp.Shaders.Translation.Enums +{ + /// + /// An that indicates a type of method to decompile + /// + internal enum MethodType + { + /// + /// An instance method that belongs to a closure class + /// + Closure, + + /// + /// A standalone, static method + /// + Static + } +} diff --git a/src/ComputeSharp.Shaders/Translation/MethodDecompiler.cs b/src/ComputeSharp.Shaders/Translation/MethodDecompiler.cs index 5a815988..2c1ea26a 100644 --- a/src/ComputeSharp.Shaders/Translation/MethodDecompiler.cs +++ b/src/ComputeSharp.Shaders/Translation/MethodDecompiler.cs @@ -9,6 +9,7 @@ using System.Reflection.Metadata; using System.Text; using System.Text.RegularExpressions; using ComputeSharp.Shaders.Mappings; +using ComputeSharp.Shaders.Translation.Enums; using ICSharpCode.Decompiler; using ICSharpCode.Decompiler.CSharp; using ICSharpCode.Decompiler.Metadata; @@ -131,55 +132,26 @@ namespace ComputeSharp.Shaders.Translation return decompiler.DecompileAsString(typeHandle); } - /// - /// 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); - /// /// Decompiles a target method and returns its and info /// /// The input to inspect + /// The type of method to decompile /// The root node for the syntax tree of the input method /// The semantic model for the input method - public void GetSyntaxTree(MethodInfo methodInfo, out MethodDeclarationSyntax rootNode, out SemanticModel semanticModel) + public void GetSyntaxTree(MethodInfo methodInfo, MethodType methodType, out MethodDeclarationSyntax rootNode, out SemanticModel semanticModel) { lock (Lock) { - // 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 sourceCode = methodType switch { - 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); - - // Remove the in keyword from the source - string inFixedSourceCode = Regex.Replace(unwrappedSourceCode, @"(? GetSyntaxTreeForClosureMethod(methodInfo), + MethodType.Static => GetSyntaxTreeForStaticMethod(methodInfo), + _ => throw new ArgumentOutOfRangeException(nameof(methodType), $"Invalid method type: {methodType}") + }; // Load the type syntax tree - SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(outFixedSourceCode); + SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(sourceCode); // Get the root node to return rootNode = syntaxTree.GetRoot().DescendantNodes().OfType().First(node => node.GetLeadingTrivia().ToFullString().Contains(methodInfo.Name)); @@ -190,6 +162,68 @@ namespace ComputeSharp.Shaders.Translation } } + /// + /// Decompiles a target closure method + /// + /// The input to inspect + [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); + + // Remove the in keyword from the source + string inFixedSourceCode = Regex.Replace(unwrappedSourceCode, @"(? + /// Decompiles a target method and returns its and info + /// + /// The input to inspect + [Pure] + private string GetSyntaxTreeForStaticMethod(MethodInfo methodInfo) + { + string + sourceCode = DecompileMethodOrDeclaringType(methodInfo), + inFixedSourceCode = Regex.Replace(sourceCode, @"(? + /// 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 /// diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs index 599ade23..b4654506 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs @@ -8,6 +8,7 @@ using ComputeSharp.Graphics.Buffers.Abstract; using ComputeSharp.Shaders.Mappings; using ComputeSharp.Shaders.Renderer.Models.Fields; using ComputeSharp.Shaders.Renderer.Models.Fields.Abstract; +using ComputeSharp.Shaders.Translation.Enums; using ComputeSharp.Shaders.Translation.Models; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; @@ -243,7 +244,7 @@ namespace ComputeSharp.Shaders.Translation private void LoadMethodSource() { // Decompile the shader method - MethodDecompiler.Instance.GetSyntaxTree(Action.Method, out MethodDeclarationSyntax root, out SemanticModel semanticModel); + MethodDecompiler.Instance.GetSyntaxTree(Action.Method, MethodType.Closure, out MethodDeclarationSyntax root, out SemanticModel semanticModel); // Rewrite the shader method (eg. to fix the type declarations) ShaderSyntaxRewriter syntaxRewriter = new ShaderSyntaxRewriter(semanticModel); From 41e1d4bc425ab447b7a3150b2d89e71455e89f79 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Wed, 4 Sep 2019 11:10:40 +0200 Subject: [PATCH 03/19] Added missing trailing comment for static methods --- src/ComputeSharp.Shaders/Translation/MethodDecompiler.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/ComputeSharp.Shaders/Translation/MethodDecompiler.cs b/src/ComputeSharp.Shaders/Translation/MethodDecompiler.cs index 2c1ea26a..e29793c4 100644 --- a/src/ComputeSharp.Shaders/Translation/MethodDecompiler.cs +++ b/src/ComputeSharp.Shaders/Translation/MethodDecompiler.cs @@ -208,7 +208,8 @@ namespace ComputeSharp.Shaders.Translation { string sourceCode = DecompileMethodOrDeclaringType(methodInfo), - inFixedSourceCode = Regex.Replace(sourceCode, @"(? Date: Wed, 4 Sep 2019 11:34:06 +0200 Subject: [PATCH 04/19] Added partial handling of static methods --- .../Extensions/SyntaxNodeExtensions.cs | 57 ++++++++++++------- .../Translation/ShaderSyntaxRewriter.cs | 16 +++++- 2 files changed, 49 insertions(+), 24 deletions(-) diff --git a/src/ComputeSharp.Shaders/Extensions/SyntaxNodeExtensions.cs b/src/ComputeSharp.Shaders/Extensions/SyntaxNodeExtensions.cs index 1aa1122d..8628734b 100644 --- a/src/ComputeSharp.Shaders/Extensions/SyntaxNodeExtensions.cs +++ b/src/ComputeSharp.Shaders/Extensions/SyntaxNodeExtensions.cs @@ -42,12 +42,14 @@ namespace ComputeSharp.Shaders.Extensions /// The input to check and modify if needed /// The to use to load symbols for the input node /// The info on parsed static members, if any + /// The info on parsed static methods, if any /// A instance that is compatible with HLSL [Pure] - public static SyntaxNode ReplaceMember(this MemberAccessExpressionSyntax node, SemanticModel semanticModel, out (string Name, ReadableMember MemberInfo)? variable) + public static SyntaxNode ReplaceMember(this MemberAccessExpressionSyntax node, SemanticModel semanticModel, out (string Name, ReadableMember MemberInfo)? variable, out (string Name, MethodInfo MethodInfo)? method) { - // Set the variable to null, replace it later on if needed + // Set the out parameters to null, replace them later on if needed variable = null; + method = null; SymbolInfo containingMemberSymbolInfo; ISymbol? memberSymbol; @@ -115,37 +117,48 @@ namespace ComputeSharp.Shaders.Extensions return SyntaxFactory.IdentifierName(expression).WithLeadingTrivia(node.GetLeadingTrivia()).WithTrailingTrivia(node.GetTrailingTrivia()); } - // Handle static fields as a special case + // Handle static members as a special case if (memberSymbol.IsStatic && ( memberSymbol.Kind == SymbolKind.Field || - memberSymbol.Kind == SymbolKind.Property)) + memberSymbol.Kind == SymbolKind.Property || + memberSymbol.Kind == SymbolKind.Method)) { // Get the containing type string typeFullname = memberSymbol.ContainingType.ToString(), assemblyFullname = memberSymbol.ContainingAssembly.ToString(); - Type fieldDeclaringType = Type.GetType($"{typeFullname}, {assemblyFullname}"); + Type memberDeclaringType = Type.GetType($"{typeFullname}, {assemblyFullname}"); - // Retrieve the field or property info - bool isReadonly; - ReadableMember memberInfo; - switch (memberSymbol.Kind) + // Static field or property + if (memberSymbol.Kind == SymbolKind.Field || memberSymbol.Kind == SymbolKind.Property) { - case SymbolKind.Field: - FieldInfo fieldInfo = fieldDeclaringType.GetField(memberSymbol.Name, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); - isReadonly = fieldInfo.IsInitOnly; - memberInfo = fieldInfo; - break; - case SymbolKind.Property: - PropertyInfo propertyInfo = fieldDeclaringType.GetProperty(memberSymbol.Name, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); - isReadonly = !propertyInfo.CanWrite; - memberInfo = propertyInfo; - break; - default: throw new InvalidOperationException($"Invalid symbol kind: {memberSymbol.Kind}"); + bool isReadonly; + ReadableMember memberInfo; + switch (memberSymbol.Kind) + { + case SymbolKind.Field: + FieldInfo fieldInfo = memberDeclaringType.GetField(memberSymbol.Name, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); + isReadonly = fieldInfo.IsInitOnly; + memberInfo = fieldInfo; + break; + case SymbolKind.Property: + PropertyInfo propertyInfo = memberDeclaringType.GetProperty(memberSymbol.Name, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); + isReadonly = !propertyInfo.CanWrite; + memberInfo = propertyInfo; + break; + default: throw new InvalidOperationException($"Invalid symbol kind: {memberSymbol.Kind}"); + } + + // Handle the loaded info + return ProcessStaticMember(node, memberInfo, isReadonly, ref variable); } - // Handle the loaded info - return ProcessStaticMember(node, memberInfo, isReadonly, ref variable); + // Static method + MethodInfo methodInfo = memberDeclaringType.GetMethod(memberSymbol.Name, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); + string name = $"{methodInfo.DeclaringType.Name}_{methodInfo.Name}"; + method = (name, methodInfo); + + return SyntaxFactory.IdentifierName(name).WithLeadingTrivia(node.GetLeadingTrivia()).WithTrailingTrivia(node.GetTrailingTrivia()); } return node; diff --git a/src/ComputeSharp.Shaders/Translation/ShaderSyntaxRewriter.cs b/src/ComputeSharp.Shaders/Translation/ShaderSyntaxRewriter.cs index 0cb3f121..b82f38b7 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderSyntaxRewriter.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderSyntaxRewriter.cs @@ -1,4 +1,5 @@ using System.Collections.Generic; +using System.Reflection; using ComputeSharp.Shaders.Extensions; using ComputeSharp.Shaders.Translation.Models; using Microsoft.CodeAnalysis; @@ -30,6 +31,13 @@ namespace ComputeSharp.Shaders.Translation /// public IReadOnlyDictionary StaticMembers => _StaticMembers; + private readonly Dictionary _StaticMethods = new Dictionary(); + + /// + /// Gets the mapping of captured static methods used by the target code + /// + public IReadOnlyDictionary StaticMethods => _StaticMethods; + /// public override SyntaxNode VisitParameter(ParameterSyntax node) { @@ -83,13 +91,17 @@ namespace ComputeSharp.Shaders.Translation public override SyntaxNode VisitMemberAccessExpression(MemberAccessExpressionSyntax node) { node = (MemberAccessExpressionSyntax)base.VisitMemberAccessExpression(node); - SyntaxNode syntaxNode = node.ReplaceMember(SemanticModel, out var variable); + SyntaxNode syntaxNode = node.ReplaceMember(SemanticModel, out var variable, out var method); - // Register the captured member, if any + // Register the captured members, if any if (variable.HasValue && !_StaticMembers.ContainsKey(variable.Value.Name)) { _StaticMembers.Add(variable.Value.Name, variable.Value.MemberInfo); } + if (method.HasValue && !_StaticMethods.ContainsKey(method.Value.Name)) + { + _StaticMethods.Add(method.Value.Name, method.Value.MethodInfo); + } return syntaxNode; } From 22d281eee80cd72de35e9e6cbba98883e2c4e91c Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Wed, 4 Sep 2019 11:58:07 +0200 Subject: [PATCH 05/19] Added new template models for static functions --- .../Renderer/Models/Functions/FunctionInfo.cs | 66 +++++++++++++++++++ .../Models/Functions/ParameterInfo.cs | 36 ++++++++++ 2 files changed, 102 insertions(+) create mode 100644 src/ComputeSharp.Shaders/Renderer/Models/Functions/FunctionInfo.cs create mode 100644 src/ComputeSharp.Shaders/Renderer/Models/Functions/ParameterInfo.cs diff --git a/src/ComputeSharp.Shaders/Renderer/Models/Functions/FunctionInfo.cs b/src/ComputeSharp.Shaders/Renderer/Models/Functions/FunctionInfo.cs new file mode 100644 index 00000000..e0c38deb --- /dev/null +++ b/src/ComputeSharp.Shaders/Renderer/Models/Functions/FunctionInfo.cs @@ -0,0 +1,66 @@ +using System; +using ComputeSharp.Shaders.Extensions; + +namespace ComputeSharp.Shaders.Renderer.Models.Functions +{ + /// + /// A that contains info on a shader function + /// + internal class FunctionInfo + { + /// + /// Gets the return type of the current function in the C# source + /// + public string FunctionCsharpReturnType { get; } + + /// + /// Gets the fullname of the current function in the C# source + /// + public string FunctionFullName { get; } + + /// + /// Gets the parameters of the function in the C# source + /// + public string FunctionCsharpParameters { get; } + + /// + /// Gets the return type of the current function + /// + public string ReturnType { get; } + + /// + /// Gets the name of the current function + /// + public string FunctionName { get; } + + /// + /// Gets the body of the current function + /// + public string FunctionBody { get; } + + /// + /// Creates a new instance with the specified parameters + /// + /// The concrete return type for the function + /// The fullname of the function in the C# source + /// The parameters of the function in the C# source + /// The return type of the current function + /// The name of the current function + /// The current function + public FunctionInfo( + Type functionCsharpType, + string functionFullname, + string functionCsharpParameters, + string returnType, + string functionName, + string functionBody) + { + FunctionCsharpReturnType = functionCsharpType.ToFriendlyString(); + FunctionFullName = functionFullname; + FunctionCsharpParameters = functionCsharpParameters; + ReturnType = returnType; + FunctionName = functionName; + FunctionBody = functionBody; + } + } +} diff --git a/src/ComputeSharp.Shaders/Renderer/Models/Functions/ParameterInfo.cs b/src/ComputeSharp.Shaders/Renderer/Models/Functions/ParameterInfo.cs new file mode 100644 index 00000000..dce851ef --- /dev/null +++ b/src/ComputeSharp.Shaders/Renderer/Models/Functions/ParameterInfo.cs @@ -0,0 +1,36 @@ +namespace ComputeSharp.Shaders.Renderer.Models.Functions +{ + /// + /// A that contains info on a function parameter + /// + internal class ParameterInfo + { + /// + /// Gets the type of the current parameter + /// + public string ParameterType { get; } + + /// + /// Gets the name to use for the current parameter + /// + public string ParameterName { get; } + + /// + /// Gets whether or not the current parameter is the last one for the parent function + /// + public bool IsLastParameter { get; } + + /// + /// Creates a new instance with the specified parameters + /// + /// The type of the current parameter + /// The name of the current parameter + /// Indicates whether or not the current parameter is the last one + public ParameterInfo(string parameterType, string parameterName, bool last) + { + ParameterType = parameterType; + ParameterName = parameterName; + IsLastParameter = last; + } + } +} From 337be904a350700134bf42ae2211470c0771c7de Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Wed, 4 Sep 2019 11:58:19 +0200 Subject: [PATCH 06/19] Updated mustache template to support functions --- .../Renderer/Templates/ShaderTemplate.mustache | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/ComputeSharp.Shaders/Renderer/Templates/ShaderTemplate.mustache b/src/ComputeSharp.Shaders/Renderer/Templates/ShaderTemplate.mustache index 8375efb6..392223bb 100644 --- a/src/ComputeSharp.Shaders/Renderer/Templates/ShaderTemplate.mustache +++ b/src/ComputeSharp.Shaders/Renderer/Templates/ShaderTemplate.mustache @@ -50,3 +50,13 @@ void CSMain(uint3 {{ThreadsIdsVariableName}} : SV_DispatchThreadId) {{ThreadsIdsVariableName}}.z < __z__) // Automatic bounds check {{&ShaderBody}} } + +{{!Shader private functions}} +{{#FunctionsList}} +// {{FunctionCsharpReturnType}} {{FunctionFullName}}({{FunctionCsharpParameters}}) +{{ReturnType}} {{FunctionName}}( + {{#ParametersList}} + {{ParameterHlslType}} {{ParameterName}} {{^IsLastParameter}},{{/IsLastParameter}} + {{/ParametersList}}) +{{FunctionBody}} +{{/FunctionsList}} From 817436f88c9aafb8bb529c8ee97d79e6983deb45 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Wed, 4 Sep 2019 12:01:30 +0200 Subject: [PATCH 07/19] Fixed mustache models --- .../Renderer/Models/Functions/FunctionInfo.cs | 9 +++++++++ src/ComputeSharp.Shaders/Renderer/Models/ShaderInfo.cs | 10 ++++++++-- 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/src/ComputeSharp.Shaders/Renderer/Models/Functions/FunctionInfo.cs b/src/ComputeSharp.Shaders/Renderer/Models/Functions/FunctionInfo.cs index e0c38deb..3af27abe 100644 --- a/src/ComputeSharp.Shaders/Renderer/Models/Functions/FunctionInfo.cs +++ b/src/ComputeSharp.Shaders/Renderer/Models/Functions/FunctionInfo.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using ComputeSharp.Shaders.Extensions; namespace ComputeSharp.Shaders.Renderer.Models.Functions @@ -33,6 +34,11 @@ namespace ComputeSharp.Shaders.Renderer.Models.Functions /// public string FunctionName { get; } + /// + /// Gets the list of parameters for the current function + /// + public IReadOnlyList ParametersList { get; } + /// /// Gets the body of the current function /// @@ -46,6 +52,7 @@ namespace ComputeSharp.Shaders.Renderer.Models.Functions /// The parameters of the function in the C# source /// The return type of the current function /// The name of the current function + /// The function parameters, if any /// The current function public FunctionInfo( Type functionCsharpType, @@ -53,6 +60,7 @@ namespace ComputeSharp.Shaders.Renderer.Models.Functions string functionCsharpParameters, string returnType, string functionName, + IReadOnlyList parameters, string functionBody) { FunctionCsharpReturnType = functionCsharpType.ToFriendlyString(); @@ -60,6 +68,7 @@ namespace ComputeSharp.Shaders.Renderer.Models.Functions FunctionCsharpParameters = functionCsharpParameters; ReturnType = returnType; FunctionName = functionName; + ParametersList = parameters; FunctionBody = functionBody; } } diff --git a/src/ComputeSharp.Shaders/Renderer/Models/ShaderInfo.cs b/src/ComputeSharp.Shaders/Renderer/Models/ShaderInfo.cs index 8dc33e8b..306dd3f7 100644 --- a/src/ComputeSharp.Shaders/Renderer/Models/ShaderInfo.cs +++ b/src/ComputeSharp.Shaders/Renderer/Models/ShaderInfo.cs @@ -1,6 +1,7 @@ using System.Collections.Generic; using ComputeSharp.Shaders.Renderer.Models.Fields; using ComputeSharp.Shaders.Renderer.Models.Fields.Abstract; +using ComputeSharp.Shaders.Renderer.Models.Functions; #pragma warning disable CS8618 // Non-nullable field is uninitialized @@ -12,12 +13,12 @@ namespace ComputeSharp.Shaders.Renderer.Models internal sealed class ShaderInfo { /// - /// Gets the list of captured buffers being present in the current shader + /// Gets or sets the list of captured buffers being present in the current shader /// public IReadOnlyList BuffersList { get; set; } /// - /// Gets the list of captured variables being present in the current shader + /// Gets or sets the list of captured variables being present in the current shader /// public IReadOnlyList FieldsList { get; set; } @@ -45,5 +46,10 @@ namespace ComputeSharp.Shaders.Renderer.Models /// Gets or sets the shader body to compile /// public string ShaderBody { get; set; } + + /// + /// Gets or sets the list of static functions used by the shader + /// + public IReadOnlyList FunctionsList { get; set; } } } From ae5386cce847035bd842a8bf831e78c0465268ff Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Wed, 4 Sep 2019 12:19:04 +0200 Subject: [PATCH 08/19] Added code to load static methods in the shader source --- src/ComputeSharp.Shaders/ShaderRunner.cs | 3 +- .../Translation/ShaderLoader.cs | 75 ++++++++++++++++++- 2 files changed, 74 insertions(+), 4 deletions(-) diff --git a/src/ComputeSharp.Shaders/ShaderRunner.cs b/src/ComputeSharp.Shaders/ShaderRunner.cs index a2a31153..2815ce8b 100644 --- a/src/ComputeSharp.Shaders/ShaderRunner.cs +++ b/src/ComputeSharp.Shaders/ShaderRunner.cs @@ -76,7 +76,8 @@ namespace ComputeSharp.Shaders NumThreadsY = threadsY, NumThreadsZ = threadsZ, ThreadsIdsVariableName = shaderLoader.ThreadsIdsVariableName, - ShaderBody = shaderLoader.MethodBody + ShaderBody = shaderLoader.MethodBody, + FunctionsList = shaderLoader.FunctionsList }; string shaderSource = ShaderRenderer.Instance.Render(shaderInfo); diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs index b4654506..641dde83 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs @@ -5,14 +5,17 @@ using System.Linq; using System.Reflection; using System.Text.RegularExpressions; using ComputeSharp.Graphics.Buffers.Abstract; +using ComputeSharp.Shaders.Extensions; using ComputeSharp.Shaders.Mappings; using ComputeSharp.Shaders.Renderer.Models.Fields; using ComputeSharp.Shaders.Renderer.Models.Fields.Abstract; +using ComputeSharp.Shaders.Renderer.Models.Functions; using ComputeSharp.Shaders.Translation.Enums; using ComputeSharp.Shaders.Translation.Models; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; using Vortice.Direct3D12; +using ParameterInfo = ComputeSharp.Shaders.Renderer.Models.Functions.ParameterInfo; #pragma warning disable CS8618 // Non-nullable field is uninitialized @@ -138,6 +141,13 @@ namespace ComputeSharp.Shaders.Translation /// public string MethodBody { get; private set; } + private readonly List _FunctionsList = new List(); + + /// + /// Gets the collection of items for the shader + /// + public IReadOnlyList FunctionsList => _FunctionsList; + /// /// Loads and processes an input /// @@ -250,10 +260,16 @@ namespace ComputeSharp.Shaders.Translation ShaderSyntaxRewriter syntaxRewriter = new ShaderSyntaxRewriter(semanticModel); root = (MethodDeclarationSyntax)syntaxRewriter.Visit(root); - // Register the captured static fields - foreach (var item in syntaxRewriter.StaticMembers) + // Register the captured static members + foreach (var member in syntaxRewriter.StaticMembers) { - LoadFieldInfo(item.Value, item.Key); + LoadFieldInfo(member.Value, member.Key); + } + + // Register the captured static methods + foreach (var method in syntaxRewriter.StaticMethods) + { + LoadStaticMethodSource(method.Key, method.Value); } // Get the thread ids identifier name and shader method body @@ -265,5 +281,58 @@ namespace ComputeSharp.Shaders.Translation MethodBody = MethodBody.TrimEnd('\n', '\r', ' '); MethodBody = HlslKnownKeywords.GetMappedText(MethodBody); } + + /// + /// Loads additional static methods used by the shader + /// + /// The HLSL name of the new method to load + /// The instance for the method to load + private void LoadStaticMethodSource(string name, MethodInfo methodInfo) + { + // Decompile the target method + MethodDecompiler.Instance.GetSyntaxTree(methodInfo, MethodType.Static, out MethodDeclarationSyntax root, out SemanticModel semanticModel); + + // Rewrite the method + ShaderSyntaxRewriter syntaxRewriter = new ShaderSyntaxRewriter(semanticModel); + root = (MethodDeclarationSyntax)syntaxRewriter.Visit(root); + + // Register the captured static members + foreach (var member in syntaxRewriter.StaticMembers) + { + LoadFieldInfo(member.Value, member.Key); + } + + // Register the captured static methods + foreach (var method in syntaxRewriter.StaticMethods) + { + LoadStaticMethodSource(method.Key, method.Value); + } + + // Get the function parameters + IReadOnlyList parameters = ( + from parameter in root.ParameterList.Parameters.Select((p, i) => (Node: p, Index: i)) + let type = parameter.Node.Type.ToFullString() + let parameterName = parameter.Node.Identifier.ToFullString() + let last = parameter.Index == root.ParameterList.Parameters.Count - 1 + select new ParameterInfo(type, parameterName, last)).ToArray(); + + // Get the function body + string body = root.Body.ToFullString(); + body = Regex.Replace(body, @"(?<=\W)(\d+)[fFdD]", m => m.Groups[1].Value); + body = body.TrimEnd('\n', '\r', ' '); + body = HlslKnownKeywords.GetMappedText(body); + + // Get the final function info instance + FunctionInfo functionInfo = new FunctionInfo( + methodInfo.ReturnType, + name, + string.Join(", ", methodInfo.GetParameters().Select(p => $"{p.ParameterType.ToFriendlyString()} {p.Name}")), + root.ReturnType.ToFullString(), + name, + parameters, + body); + + _FunctionsList.Add(functionInfo); + } } } From 590adf3c8937c5eb177f46611bc3d7a8013b89a6 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Wed, 4 Sep 2019 12:28:37 +0200 Subject: [PATCH 09/19] Bug fixes in the static methods loading --- .../Templates/ShaderTemplate.mustache | 21 ++++++++++--------- .../Translation/ShaderLoader.cs | 2 +- 2 files changed, 12 insertions(+), 11 deletions(-) diff --git a/src/ComputeSharp.Shaders/Renderer/Templates/ShaderTemplate.mustache b/src/ComputeSharp.Shaders/Renderer/Templates/ShaderTemplate.mustache index 392223bb..2f8c7439 100644 --- a/src/ComputeSharp.Shaders/Renderer/Templates/ShaderTemplate.mustache +++ b/src/ComputeSharp.Shaders/Renderer/Templates/ShaderTemplate.mustache @@ -39,6 +39,17 @@ cbuffer _{{FieldName}} : register(b{{BufferIndex}}) {{/IsReadWriteBuffer}} {{/BuffersList}} +{{!Shader private functions}} +{{#FunctionsList}} +// {{FunctionCsharpReturnType}} {{FunctionFullName}}({{FunctionCsharpParameters}}) +{{ReturnType}} {{FunctionName}}( + {{#ParametersList}} + {{ParameterType}} {{ParameterName}} {{^IsLastParameter}},{{/IsLastParameter}} + {{/ParametersList}} + ) +{{FunctionBody}} +{{/FunctionsList}} + {{!Shader entry point}} // Shader body [Shader("compute")] @@ -50,13 +61,3 @@ void CSMain(uint3 {{ThreadsIdsVariableName}} : SV_DispatchThreadId) {{ThreadsIdsVariableName}}.z < __z__) // Automatic bounds check {{&ShaderBody}} } - -{{!Shader private functions}} -{{#FunctionsList}} -// {{FunctionCsharpReturnType}} {{FunctionFullName}}({{FunctionCsharpParameters}}) -{{ReturnType}} {{FunctionName}}( - {{#ParametersList}} - {{ParameterHlslType}} {{ParameterName}} {{^IsLastParameter}},{{/IsLastParameter}} - {{/ParametersList}}) -{{FunctionBody}} -{{/FunctionsList}} diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs index 641dde83..bec451e6 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs @@ -325,7 +325,7 @@ namespace ComputeSharp.Shaders.Translation // Get the final function info instance FunctionInfo functionInfo = new FunctionInfo( methodInfo.ReturnType, - name, + $"{methodInfo.DeclaringType.FullName}{Type.Delimiter}{methodInfo.Name}", string.Join(", ", methodInfo.GetParameters().Select(p => $"{p.ParameterType.ToFriendlyString()} {p.Name}")), root.ReturnType.ToFullString(), name, From 067a89c7b3177c88a4847e1f03786bb702aadad4 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Wed, 4 Sep 2019 12:29:40 +0200 Subject: [PATCH 10/19] Minor tweaks to the mustache template --- .../Renderer/Templates/ShaderTemplate.mustache | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/src/ComputeSharp.Shaders/Renderer/Templates/ShaderTemplate.mustache b/src/ComputeSharp.Shaders/Renderer/Templates/ShaderTemplate.mustache index 2f8c7439..0e058d76 100644 --- a/src/ComputeSharp.Shaders/Renderer/Templates/ShaderTemplate.mustache +++ b/src/ComputeSharp.Shaders/Renderer/Templates/ShaderTemplate.mustache @@ -42,11 +42,7 @@ cbuffer _{{FieldName}} : register(b{{BufferIndex}}) {{!Shader private functions}} {{#FunctionsList}} // {{FunctionCsharpReturnType}} {{FunctionFullName}}({{FunctionCsharpParameters}}) -{{ReturnType}} {{FunctionName}}( - {{#ParametersList}} - {{ParameterType}} {{ParameterName}} {{^IsLastParameter}},{{/IsLastParameter}} - {{/ParametersList}} - ) +{{ReturnType}} {{FunctionName}}({{#ParametersList}}{{ParameterType}} {{ParameterName}}{{^IsLastParameter}}, {{/IsLastParameter}}{{/ParametersList}}) {{FunctionBody}} {{/FunctionsList}} From 77f6b4dd243c4831ca9f60671020ffd48258c832 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Wed, 4 Sep 2019 14:50:21 +0200 Subject: [PATCH 11/19] Fixed mapping of return types for static methods --- .../Translation/ShaderSyntaxRewriter.cs | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/src/ComputeSharp.Shaders/Translation/ShaderSyntaxRewriter.cs b/src/ComputeSharp.Shaders/Translation/ShaderSyntaxRewriter.cs index b82f38b7..c00a0c82 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderSyntaxRewriter.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderSyntaxRewriter.cs @@ -105,5 +105,19 @@ namespace ComputeSharp.Shaders.Translation return syntaxNode; } + + /// + public override SyntaxNode VisitMethodDeclaration(MethodDeclarationSyntax node) + { + node = (MethodDeclarationSyntax)base.VisitMethodDeclaration(node); + + // Replace the return type node, if needed + if (!node.ReturnType.ToString().Equals("void")) + { + return node.ReplaceType(node.ReturnType); + } + + return node; + } } } From b666d48678f8fa269b7bc4e7362e030c72e81f31 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Wed, 4 Sep 2019 14:50:33 +0200 Subject: [PATCH 12/19] Added tests for static methods in the shader body --- tests/ComputeSharp.Tests/StaticMethodTests.cs | 51 +++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 tests/ComputeSharp.Tests/StaticMethodTests.cs diff --git a/tests/ComputeSharp.Tests/StaticMethodTests.cs b/tests/ComputeSharp.Tests/StaticMethodTests.cs new file mode 100644 index 00000000..a93ddbeb --- /dev/null +++ b/tests/ComputeSharp.Tests/StaticMethodTests.cs @@ -0,0 +1,51 @@ +using System; +using System.Diagnostics.Contracts; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace ComputeSharp.Tests +{ + /// + /// A container for static methods to test + /// + public static class StaticMethodsContainer + { + [Pure] + public static float Square(float x) => x * x; + + [Pure] + public static Float4 Range(float x) => new Float4(x, x + 1, x + 2, x + 3); + } + + [TestClass] + [TestCategory("StaticMethodTests")] + public class StaticMethodTests + { + [TestMethod] + public void FloatToFloatFunc() + { + using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(1); + + Gpu.Default.For(1, id => buffer[0] = StaticMethodsContainer.Square(3)); + + float[] result = buffer.GetData(); + + Assert.IsTrue(MathF.Abs(result[0] - 9) < 0.0001f); + } + + [TestMethod] + public void FloatToFloat4Func() + { + using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(1); + + Gpu.Default.For(1, id => buffer[0] = StaticMethodsContainer.Range(3)); + + Float4[] result = buffer.GetData(); + + Assert.IsTrue(MathF.Abs(result[0].X - 3) < 0.0001f); + Assert.IsTrue(MathF.Abs(result[0].Y - 4) < 0.0001f); + Assert.IsTrue(MathF.Abs(result[0].Z - 5) < 0.0001f); + Assert.IsTrue(MathF.Abs(result[0].W - 6) < 0.0001f); + } + } +} + From a3bc07e88d7d131ff258eeec81b7eccb02e1b61f Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Wed, 4 Sep 2019 15:40:13 +0200 Subject: [PATCH 13/19] Added a test for a static method that takes an HLSL vector type --- tests/ComputeSharp.Tests/StaticMethodTests.cs | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/tests/ComputeSharp.Tests/StaticMethodTests.cs b/tests/ComputeSharp.Tests/StaticMethodTests.cs index a93ddbeb..dcc8be58 100644 --- a/tests/ComputeSharp.Tests/StaticMethodTests.cs +++ b/tests/ComputeSharp.Tests/StaticMethodTests.cs @@ -14,6 +14,9 @@ namespace ComputeSharp.Tests [Pure] public static Float4 Range(float x) => new Float4(x, x + 1, x + 2, x + 3); + + [Pure] + public static int Sum(Float4 x) => (int)(x.X + x.Y + x.Z + x.W); } [TestClass] @@ -46,6 +49,18 @@ namespace ComputeSharp.Tests Assert.IsTrue(MathF.Abs(result[0].Z - 5) < 0.0001f); Assert.IsTrue(MathF.Abs(result[0].W - 6) < 0.0001f); } + + [TestMethod] + public void Float4ToIntFunc() + { + using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(1); + + Gpu.Default.For(1, id => buffer[0] = StaticMethodsContainer.Sum(new Float4(1, 2, 3, 14))); + + int[] result = buffer.GetData(); + + Assert.IsTrue(result[0] == 20); + } } } From 131123ec329294ec48077a92967604072f788bc7 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Wed, 4 Sep 2019 23:21:42 +0200 Subject: [PATCH 14/19] Updated mustache template to support argument modifiers --- .../Renderer/Models/Functions/ParameterInfo.cs | 9 ++++++++- .../Renderer/Templates/ShaderTemplate.mustache | 2 +- src/ComputeSharp.Shaders/Translation/ShaderLoader.cs | 4 +++- 3 files changed, 12 insertions(+), 3 deletions(-) diff --git a/src/ComputeSharp.Shaders/Renderer/Models/Functions/ParameterInfo.cs b/src/ComputeSharp.Shaders/Renderer/Models/Functions/ParameterInfo.cs index dce851ef..2c6b4f5b 100644 --- a/src/ComputeSharp.Shaders/Renderer/Models/Functions/ParameterInfo.cs +++ b/src/ComputeSharp.Shaders/Renderer/Models/Functions/ParameterInfo.cs @@ -5,6 +5,11 @@ /// internal class ParameterInfo { + /// + /// Gets the modifier to use for the current parameter + /// + public string ParameterModifier { get; } + /// /// Gets the type of the current parameter /// @@ -23,11 +28,13 @@ /// /// Creates a new instance with the specified parameters /// + /// The modifier to use for the current parameter /// The type of the current parameter /// The name of the current parameter /// Indicates whether or not the current parameter is the last one - public ParameterInfo(string parameterType, string parameterName, bool last) + public ParameterInfo(string parameterModifier, string parameterType, string parameterName, bool last) { + ParameterModifier = parameterModifier; ParameterType = parameterType; ParameterName = parameterName; IsLastParameter = last; diff --git a/src/ComputeSharp.Shaders/Renderer/Templates/ShaderTemplate.mustache b/src/ComputeSharp.Shaders/Renderer/Templates/ShaderTemplate.mustache index 0e058d76..14c5d075 100644 --- a/src/ComputeSharp.Shaders/Renderer/Templates/ShaderTemplate.mustache +++ b/src/ComputeSharp.Shaders/Renderer/Templates/ShaderTemplate.mustache @@ -42,7 +42,7 @@ cbuffer _{{FieldName}} : register(b{{BufferIndex}}) {{!Shader private functions}} {{#FunctionsList}} // {{FunctionCsharpReturnType}} {{FunctionFullName}}({{FunctionCsharpParameters}}) -{{ReturnType}} {{FunctionName}}({{#ParametersList}}{{ParameterType}} {{ParameterName}}{{^IsLastParameter}}, {{/IsLastParameter}}{{/ParametersList}}) +{{ReturnType}} {{FunctionName}}({{#ParametersList}}{{ParameterModifier}} {{ParameterType}} {{ParameterName}}{{^IsLastParameter}}, {{/IsLastParameter}}{{/ParametersList}}) {{FunctionBody}} {{/FunctionsList}} diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs index bec451e6..e0a547c3 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs @@ -13,6 +13,7 @@ using ComputeSharp.Shaders.Renderer.Models.Functions; using ComputeSharp.Shaders.Translation.Enums; using ComputeSharp.Shaders.Translation.Models; using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Vortice.Direct3D12; using ParameterInfo = ComputeSharp.Shaders.Renderer.Models.Functions.ParameterInfo; @@ -311,10 +312,11 @@ namespace ComputeSharp.Shaders.Translation // Get the function parameters IReadOnlyList parameters = ( from parameter in root.ParameterList.Parameters.Select((p, i) => (Node: p, Index: i)) + let modifier = parameter.Node.Modifiers.Any(token => token.IsKind(SyntaxKind.OutKeyword)) ? "out" : "in" let type = parameter.Node.Type.ToFullString() let parameterName = parameter.Node.Identifier.ToFullString() let last = parameter.Index == root.ParameterList.Parameters.Count - 1 - select new ParameterInfo(type, parameterName, last)).ToArray(); + select new ParameterInfo(modifier, type, parameterName, last)).ToArray(); // Get the function body string body = root.Body.ToFullString(); From 673522fda1800dbb4086472b8c1f858e92aaebf5 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Wed, 4 Sep 2019 23:21:53 +0200 Subject: [PATCH 15/19] Fixed handling of static methods with out parameters --- .../Translation/MethodDecompiler.cs | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/src/ComputeSharp.Shaders/Translation/MethodDecompiler.cs b/src/ComputeSharp.Shaders/Translation/MethodDecompiler.cs index e29793c4..a6a0b3dc 100644 --- a/src/ComputeSharp.Shaders/Translation/MethodDecompiler.cs +++ b/src/ComputeSharp.Shaders/Translation/MethodDecompiler.cs @@ -208,11 +208,16 @@ namespace ComputeSharp.Shaders.Translation { string sourceCode = DecompileMethodOrDeclaringType(methodInfo), + prototype = sourceCode.Split(Environment.NewLine)[0], commentedSourceCode = $"// {methodInfo.Name}{Environment.NewLine}{sourceCode}", inFixedSourceCode = Regex.Replace(commentedSourceCode, @"(?().First(); + + return $"// {methodInfo.Name}{Environment.NewLine}{prototype}{Environment.NewLine}{block.ToFullString()}"; } /// @@ -319,14 +324,14 @@ namespace ComputeSharp.Shaders.Translation argument.Expression.IsKind(SyntaxKind.DeclarationExpression) let match = Regex.Match(argument.Expression.ToFullString(), @"([\w.]+) ([\w_]+)") let mappedType = HlslKnownTypes.GetMappedName(match.Groups[1].Value) - let declatation = $"{mappedType} {match.Groups[2].Value} = ({mappedType})0;" - select (match.Groups[1].Value, match.Groups[2].Value, declatation)).ToArray(); + let declaration = $"{mappedType} {match.Groups[2].Value} = ({mappedType})0;" + select declaration).ToArray(); // Insert the explicit declarations at the start of the method int start = rootNode.Body.ChildNodes().First().SpanStart; - foreach (var item in outs.Reverse()) + foreach (var declaration in outs.Reverse()) { - source = source.Insert(start, $"{item.declatation}{Environment.NewLine} "); + source = source.Insert(start, $"{declaration}{Environment.NewLine} "); } // Remove the out keyword from the source From 3984550a16d7a8961d249686168c65fdf82f2e8b Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Wed, 4 Sep 2019 23:22:02 +0200 Subject: [PATCH 16/19] Added tests for static methods with out parameters --- ...ticMethodTests.cs => StaticMethodsTests.cs} | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) rename tests/ComputeSharp.Tests/{StaticMethodTests.cs => StaticMethodsTests.cs} (79%) diff --git a/tests/ComputeSharp.Tests/StaticMethodTests.cs b/tests/ComputeSharp.Tests/StaticMethodsTests.cs similarity index 79% rename from tests/ComputeSharp.Tests/StaticMethodTests.cs rename to tests/ComputeSharp.Tests/StaticMethodsTests.cs index dcc8be58..4c1909c5 100644 --- a/tests/ComputeSharp.Tests/StaticMethodTests.cs +++ b/tests/ComputeSharp.Tests/StaticMethodsTests.cs @@ -17,11 +17,13 @@ namespace ComputeSharp.Tests [Pure] public static int Sum(Float4 x) => (int)(x.X + x.Y + x.Z + x.W); + + public static void Assign(int x, out int y) => y = x; } [TestClass] - [TestCategory("StaticMethodTests")] - public class StaticMethodTests + [TestCategory("StaticMethodsTests")] + public class StaticMethodsTests { [TestMethod] public void FloatToFloatFunc() @@ -61,6 +63,18 @@ namespace ComputeSharp.Tests Assert.IsTrue(result[0] == 20); } + + [TestMethod] + public void IntToOutIntFunc() + { + using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(1); + + Gpu.Default.For(1, id => StaticMethodsContainer.Assign(7, out buffer[0])); + + int[] result = buffer.GetData(); + + Assert.IsTrue(result[0] == 7); + } } } From 421ab218b6993e6489c729ba63dc7f8ea20f87d2 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Wed, 4 Sep 2019 23:57:29 +0200 Subject: [PATCH 17/19] Updated syntax rewriter to remove ref keywords from arguments --- .../Translation/ShaderSyntaxRewriter.cs | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/src/ComputeSharp.Shaders/Translation/ShaderSyntaxRewriter.cs b/src/ComputeSharp.Shaders/Translation/ShaderSyntaxRewriter.cs index c00a0c82..c92b2e37 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderSyntaxRewriter.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderSyntaxRewriter.cs @@ -48,6 +48,19 @@ namespace ComputeSharp.Shaders.Translation return node; } + /// + public override SyntaxNode VisitArgument(ArgumentSyntax node) + { + node = (ArgumentSyntax)base.VisitArgument(node); + + if (node.RefKindKeyword.IsKind(SyntaxKind.RefKeyword)) + { + node = node.WithRefKindKeyword(SyntaxFactory.Token(SyntaxKind.None)); + } + + return node; + } + /// public override SyntaxNode VisitCastExpression(CastExpressionSyntax node) { From 07f7d855b3b263186b36ac697f4ca1147cb6bf9b Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Wed, 4 Sep 2019 23:57:48 +0200 Subject: [PATCH 18/19] Added support for ref/inout parameters in static functions --- .../Renderer/Models/Functions/ParameterInfo.cs | 17 +++++++++++++---- .../Translation/ShaderLoader.cs | 4 ++-- 2 files changed, 15 insertions(+), 6 deletions(-) diff --git a/src/ComputeSharp.Shaders/Renderer/Models/Functions/ParameterInfo.cs b/src/ComputeSharp.Shaders/Renderer/Models/Functions/ParameterInfo.cs index 2c6b4f5b..f5cc5172 100644 --- a/src/ComputeSharp.Shaders/Renderer/Models/Functions/ParameterInfo.cs +++ b/src/ComputeSharp.Shaders/Renderer/Models/Functions/ParameterInfo.cs @@ -1,4 +1,9 @@ -namespace ComputeSharp.Shaders.Renderer.Models.Functions +using System.Collections.Generic; +using System.Linq; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; + +namespace ComputeSharp.Shaders.Renderer.Models.Functions { /// /// A that contains info on a function parameter @@ -28,13 +33,17 @@ /// /// Creates a new instance with the specified parameters /// - /// The modifier to use for the current parameter + /// The modifiers used in the current parameter /// The type of the current parameter /// The name of the current parameter /// Indicates whether or not the current parameter is the last one - public ParameterInfo(string parameterModifier, string parameterType, string parameterName, bool last) + public ParameterInfo(IReadOnlyList parameterModifiers, string parameterType, string parameterName, bool last) { - ParameterModifier = parameterModifier; + if (parameterModifiers.Count == 0) ParameterModifier = "in"; + else if (parameterModifiers.First().IsKind(SyntaxKind.OutKeyword)) ParameterModifier = "out"; + else if (parameterModifiers.Any(m => m.IsKind(SyntaxKind.RefKeyword)) && !parameterModifiers.Any(m => m.IsKind(SyntaxKind.ReadOnlyKeyword))) ParameterModifier = "inout"; + else ParameterModifier = "in"; + ParameterType = parameterType; ParameterName = parameterName; IsLastParameter = last; diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs index e0a547c3..1c3c24cc 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs @@ -312,11 +312,11 @@ namespace ComputeSharp.Shaders.Translation // Get the function parameters IReadOnlyList parameters = ( from parameter in root.ParameterList.Parameters.Select((p, i) => (Node: p, Index: i)) - let modifier = parameter.Node.Modifiers.Any(token => token.IsKind(SyntaxKind.OutKeyword)) ? "out" : "in" + let modifiers = parameter.Node.Modifiers let type = parameter.Node.Type.ToFullString() let parameterName = parameter.Node.Identifier.ToFullString() let last = parameter.Index == root.ParameterList.Parameters.Count - 1 - select new ParameterInfo(modifier, type, parameterName, last)).ToArray(); + select new ParameterInfo(modifiers, type, parameterName, last)).ToArray(); // Get the function body string body = root.Body.ToFullString(); From d281236691f68c694b003acb09540da1860fba43 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Wed, 4 Sep 2019 23:57:59 +0200 Subject: [PATCH 19/19] Added test method for ref parameters --- tests/ComputeSharp.Tests/StaticMethodsTests.cs | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/tests/ComputeSharp.Tests/StaticMethodsTests.cs b/tests/ComputeSharp.Tests/StaticMethodsTests.cs index 4c1909c5..38103f08 100644 --- a/tests/ComputeSharp.Tests/StaticMethodsTests.cs +++ b/tests/ComputeSharp.Tests/StaticMethodsTests.cs @@ -19,6 +19,8 @@ namespace ComputeSharp.Tests public static int Sum(Float4 x) => (int)(x.X + x.Y + x.Z + x.W); public static void Assign(int x, out int y) => y = x; + + public static void ReadAndSquare(ref int x) => x *= x; } [TestClass] @@ -75,6 +77,19 @@ namespace ComputeSharp.Tests Assert.IsTrue(result[0] == 7); } + + [TestMethod] + public void IntToRefIntFunc() + { + int[] data = { 3 }; + using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(data); + + Gpu.Default.For(1, id => StaticMethodsContainer.ReadAndSquare(ref buffer[0])); + + buffer.GetData(data); + + Assert.IsTrue(data[0] == 9); + } } }