Path: redb-route/redb.Route/Expressions/ExpressionResolver.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route/Expressions/ExpressionResolver.cs
----
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
using Microsoft.Extensions.Logging;
using redb.Route.Abstractions;
using redb.Route.Expressions.Ast;
using SysExpression = System.Linq.Expressions.Expression;
namespace redb.Route.Expressions;
///
/// Expression resolver with compiled lambda caching for performance optimization.
///
public static partial class ExpressionResolver
{
///
/// Delegate for expressions that resolve a value from an .
///
private delegate object? ExpressionDelegate(IExchange exchange);
// Caches for compiled expressions
private static readonly ConcurrentDictionary> _templateCache = new();
private static readonly ConcurrentDictionary> _propertyResolverCache = new();
private static readonly ConcurrentDictionary> _valueExpressionCache = new();
///
/// Builds a cache key from an optional context ID and expression.
/// When contextId is provided, returns "{contextId}:{expression}"; otherwise returns the expression as-is.
///
private static string BuildCacheKey(string? contextId, string expression)
=> contextId is null ? expression : $"{contextId}:{expression}";
// Regular expressions for parsing
private static readonly Regex UnaryOperationRegex = new(@"^([!+\-])(.+)$", RegexOptions.Compiled);
// Regular expression for prefix increment/decrement
private static readonly Regex PrefixIncrementDecrementRegex = new(@"^(\+\+|--)(.+)$", RegexOptions.Compiled);
// Regular expression for postfix increment/decrement
private static readonly Regex PostfixIncrementDecrementRegex = new(@"^(.+)(\+\+|--)$", RegexOptions.Compiled);
// Regular expression for binary operations
private static readonly Regex BinaryOperationRegex = new(@"^(.+?)\s*([+\-])\s*(.+)$", RegexOptions.Compiled);
// Regular expression for high-priority binary operations
private static readonly Regex BinaryHighPriorityOperationRegex = new(@"^(.+?)\s*([*/])\s*(.+)$", RegexOptions.Compiled);
// Regular expression for jpath function — lazy quantifier to avoid greedy capture across nested calls
private static readonly Regex JPathFunctionRegex = new(@"jpath\((.*?)\)", RegexOptions.Compiled);
// Regular expression for xpath function — lazy quantifier to avoid greedy capture across nested calls
private static readonly Regex XPathFunctionRegex = new(@"xpath\((.*?)\)", RegexOptions.Compiled);
// Prefixes for property types
private const string PROPERTY_PREFIX = "property.";
private const string HEADER_PREFIX = "header.";
private const string BODY_PREFIX = "body.";
private const string EXCEPTION_PREFIX = "exception.";
// Debug flag
private static bool _debugEnabled = false;
// Optional logger for expression resolution warnings
private static ILogger? _logger;
///
/// Sets an optional logger for expression resolution warnings (missing headers, properties, etc.).
///
public static void SetLogger(ILogger? logger) => _logger = logger;
///
/// Sets an optional logger factory; creates a logger named "redb.Route.Expressions".
///
public static void SetLoggerFactory(ILoggerFactory? factory)
=> _logger = factory?.CreateLogger("redb.Route.Expressions");
///
/// Reports whether a string is a ${...} template rather than a bare expression.
/// The two are different positions in the language: a template is interpolated into a string,
/// while a bare expression is compiled and evaluated.
///
/// The string to inspect.
/// true when the string contains at least one ${...} placeholder.
public static bool IsTemplate(string expression)
{
ArgumentNullException.ThrowIfNull(expression);
return TemplateScanner.HasPlaceholder(expression);
}
// Counters for caching metrics
private static long _templateHits = 0;
private static long _templateMisses = 0;
private static long _propertyResolverHits = 0;
private static long _propertyResolverMisses = 0;
private static long _valueExpressionHits = 0;
private static long _valueExpressionMisses = 0;
#region Debug methods
///
/// Enables or disables debug output.
///
/// true to enable debug logging; false to disable it.
public static void SetDebugMode(bool enabled)
{
_debugEnabled = enabled;
}
///
/// Writes a debug message to the console when debug mode is enabled.
///
/// The message to output.
public static void DebugLog(string message)
{
if (_debugEnabled)
{
Console.WriteLine($"[ExpressionResolver DEBUG] {message}");
}
}
///
/// Prints an expression tree to the console with indentation reflecting nesting depth.
///
/// The expression to visualize.
/// Current indentation prefix.
/// Whether this is the root expression.
public static void DebugPrintExpressionTree(SysExpression expression, string indent = "", bool isRoot = true)
{
if (!_debugEnabled || expression == null)
return;
var nodeType = expression.NodeType.ToString();
var expressionType = expression.Type.Name;
Console.WriteLine($"[ExprTree] {indent}{(isRoot ? "▶ " : "├─")} {nodeType} ({expressionType})");
// Increase indent for child nodes
var childIndent = indent + (isRoot ? " " : "│ ");
// Process child expressions depending on the type
switch (expression)
{
case MethodCallExpression methodCall:
Console.WriteLine($"[ExprTree] {childIndent}├─ Method: {methodCall.Method.Name}");
Console.WriteLine($"[ExprTree] {childIndent}├─ Object:");
if (methodCall.Object != null)
DebugPrintExpressionTree(methodCall.Object, childIndent + "│ ", false);
if (methodCall.Arguments.Count > 0)
{
Console.WriteLine($"[ExprTree] {childIndent}├─ Arguments ({methodCall.Arguments.Count}):");
for (int i = 0; i < methodCall.Arguments.Count; i++)
{
Console.WriteLine($"[ExprTree] {childIndent}│ ├─ Arg[{i}]:");
DebugPrintExpressionTree(methodCall.Arguments[i], childIndent + "│ │ ", false);
}
}
break;
case BinaryExpression binary:
Console.WriteLine($"[ExprTree] {childIndent}├─ Left:");
DebugPrintExpressionTree(binary.Left, childIndent + "│ ", false);
Console.WriteLine($"[ExprTree] {childIndent}├─ Right:");
DebugPrintExpressionTree(binary.Right, childIndent + "│ ", false);
break;
case UnaryExpression unary:
Console.WriteLine($"[ExprTree] {childIndent}├─ Operand:");
DebugPrintExpressionTree(unary.Operand, childIndent + "│ ", false);
break;
case System.Linq.Expressions.ConstantExpression constant:
var value = constant.Value?.ToString() ?? "null";
Console.WriteLine($"[ExprTree] {childIndent}├─ Value: {value}");
break;
case NewExpression newExpr:
Console.WriteLine($"[ExprTree] {childIndent}├─ Constructor: {newExpr.Constructor.DeclaringType.Name}");
if (newExpr.Arguments.Count > 0)
{
Console.WriteLine($"[ExprTree] {childIndent}├─ Arguments ({newExpr.Arguments.Count}):");
for (int i = 0; i < newExpr.Arguments.Count; i++)
{
Console.WriteLine($"[ExprTree] {childIndent}│ ├─ Arg[{i}]:");
DebugPrintExpressionTree(newExpr.Arguments[i], childIndent + "│ │ ", false);
}
}
break;
case LambdaExpression lambda:
Console.WriteLine($"[ExprTree] {childIndent}├─ Parameters ({lambda.Parameters.Count}):");
for (int i = 0; i < lambda.Parameters.Count; i++)
{
var param = lambda.Parameters[i];
Console.WriteLine($"[ExprTree] {childIndent}│ ├─ Param[{i}]: {param.Name} ({param.Type.Name})");
}
Console.WriteLine($"[ExprTree] {childIndent}├─ Body:");
DebugPrintExpressionTree(lambda.Body, childIndent + "│ ", false);
break;
case MemberExpression member:
Console.WriteLine($"[ExprTree] {childIndent}├─ Member: {member.Member.Name}");
Console.WriteLine($"[ExprTree] {childIndent}├─ Expression:");
DebugPrintExpressionTree(member.Expression, childIndent + "│ ", false);
break;
case BlockExpression block:
Console.WriteLine($"[ExprTree] {childIndent}├─ Variables ({block.Variables.Count}):");
for (int i = 0; i < block.Variables.Count; i++)
{
var variable = block.Variables[i];
Console.WriteLine($"[ExprTree] {childIndent}│ ├─ Var[{i}]: {variable.Name} ({variable.Type.Name})");
}
Console.WriteLine($"[ExprTree] {childIndent}├─ Expressions ({block.Expressions.Count}):");
for (int i = 0; i < block.Expressions.Count; i++)
{
Console.WriteLine($"[ExprTree] {childIndent}│ ├─ Expr[{i}]:");
DebugPrintExpressionTree(block.Expressions[i], childIndent + "│ │ ", false);
}
break;
case ConditionalExpression conditional:
Console.WriteLine($"[ExprTree] {childIndent}├─ Test:");
DebugPrintExpressionTree(conditional.Test, childIndent + "│ ", false);
Console.WriteLine($"[ExprTree] {childIndent}├─ IfTrue:");
DebugPrintExpressionTree(conditional.IfTrue, childIndent + "│ ", false);
Console.WriteLine($"[ExprTree] {childIndent}├─ IfFalse:");
DebugPrintExpressionTree(conditional.IfFalse, childIndent + "│ ", false);
break;
}
}
#endregion
#region Public methods for obtaining compiled delegates
///
/// Gets a compiled delegate for processing a template string.
///
/// The template string containing ${...} placeholders.
/// Optional context identifier for cache isolation. When provided, the cache key is scoped to this context.
/// A compiled function that resolves the template against an .
public static Func GetCompiledTemplate(string template, string? contextId = null)
{
ArgumentException.ThrowIfNullOrEmpty(template, nameof(template));
var cacheKey = BuildCacheKey(contextId, template);
DebugLog($"Requesting compiled template: '{template}' (key: '{cacheKey}')");
if (_templateCache.TryGetValue(cacheKey, out var cached))
{
System.Threading.Interlocked.Increment(ref _templateHits);
DebugLog($" Template found in cache: '{cacheKey}'");
return cached;
}
System.Threading.Interlocked.Increment(ref _templateMisses);
DebugLog($" Compiling new template: '{template}'");
var compiled = _templateCache.GetOrAdd(cacheKey, _ => CompileTemplateString(template));
DebugLog($" Template compiled and added to cache: '{cacheKey}'");
return compiled;
}
///
/// Gets a compiled delegate for resolving properties.
///
/// The property expression string.
/// Optional context identifier for cache isolation.
/// A compiled function that resolves a property value from a source object and expression.
public static Func