From bfec782b56ddd21793aaf0bce2e3799ca440ba77 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Fri, 16 Aug 2019 11:54:29 +0200 Subject: [PATCH] Added support for static readonly scalar fields --- .../Extensions/SyntaxNodeExtensions.cs | 29 ++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/src/ComputeSharp.Shaders/Extensions/SyntaxNodeExtensions.cs b/src/ComputeSharp.Shaders/Extensions/SyntaxNodeExtensions.cs index 55a87c5a..db8cf28b 100644 --- a/src/ComputeSharp.Shaders/Extensions/SyntaxNodeExtensions.cs +++ b/src/ComputeSharp.Shaders/Extensions/SyntaxNodeExtensions.cs @@ -1,5 +1,8 @@ -using System.Diagnostics.Contracts; +using System; +using System.Diagnostics.Contracts; +using System.Globalization; using System.Linq; +using System.Reflection; using ComputeSharp.Shaders.Mappings; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; @@ -55,6 +58,30 @@ namespace ComputeSharp.Shaders.Extensions return node; } + // Handle static fields as a special case + if (memberSymbol.Kind == SymbolKind.Field && + memberSymbol.IsStatic) + { + // Retrieve the field info + string + typeFullname = memberSymbol.ContainingType.ToString(), + assemblyFullname = memberSymbol.ContainingAssembly.ToString(); + Type fieldDeclaringType = Type.GetType($"{typeFullname}, {assemblyFullname}"); + FieldInfo fieldInfo = fieldDeclaringType.GetField(memberSymbol.Name, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); + + // Constant replacement if the field is a static readonly field + if (fieldInfo.IsInitOnly && HlslKnownTypes.IsKnownScalarType(fieldInfo.FieldType)) + { + return fieldInfo.GetValue(null) switch + { + true => SyntaxFactory.LiteralExpression(SyntaxKind.TrueLiteralExpression, SyntaxFactory.Token(SyntaxKind.TrueKeyword)), + false => SyntaxFactory.LiteralExpression(SyntaxKind.TrueLiteralExpression, SyntaxFactory.Token(SyntaxKind.TrueKeyword)), + IFormattable scalar => SyntaxFactory.LiteralExpression(SyntaxKind.NumericLiteralExpression, SyntaxFactory.ParseToken(scalar.ToString(null, CultureInfo.InvariantCulture))), + _ => throw new InvalidOperationException($"Invalid field of type {fieldInfo.FieldType}") + }; + } + } + // Process the input node if it's a known method invocation if (HlslKnownMethods.TryGetMappedName(containingMemberSymbolInfo.Symbol, memberSymbol) is string value) {