Path: redb-route/redb.Route/Expressions/ExpressionResolver.Template.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.Template.cs ---- using System; using System.Collections.Generic; using System.Text; using System.Text.RegularExpressions; using redb.Route.Abstractions; namespace redb.Route.Expressions; /// /// The template engine: the one pipeline that gives a ${...} placeholder its meaning. /// Until 2026-08-28 two independent engines interpreted placeholders — one under /// , another under ResolveTypedOrTemplate — with /// complementary holes: the first understood unspaced comparisons and dashed header names but not /// arithmetic, the second the reverse. Both now route through , /// so a placeholder means the same thing wherever it is written. /// public static partial class ExpressionResolver { /// /// Compiles the inner text of a single ${...} placeholder into a typed evaluator. /// /// The rules, in order: jpath(...) and xpath(...) keep their own syntax (the /// expression tokenizer does not read $ or / paths); body and /// contentType are direct accessors; a header. or property. prefix /// resolves by the literal-name-first rule below; anything else is a full expression compiled /// by the AST engine — arithmetic, comparisons, functions, ternary and index access included. /// /// /// Literal-name-first: header.Content-Type is the header of that exact name when it /// exists; header.user.Age is the member path behind the user header; /// header.a+1, matching neither, is the expression. The name check happens per /// exchange, which is what makes a dash usable in a name at all — no grammar can tell a /// dashed name from a subtraction, but the message can. /// /// /// The text between ${ and }. /// An evaluator returning the CLR-typed value of the placeholder. /// Thrown when the text is not a resolvable placeholder. internal static Func CompilePlaceholder(string placeholder) { ArgumentException.ThrowIfNullOrWhiteSpace(placeholder); var text = placeholder.Trim(); // ${expr:F4}: a format suffix, format(expr, 'F4') with the invariant culture (findings register row 34 point 4). if (TrySplitFormatSuffix(text, out var formatted, out var suffix)) { var value = CompilePlaceholder(formatted); return exchange => Ast_Format(value(exchange), suffix, null); } // ${jsonpath:$.a.b} and ${xpath://a}: Apache Camel's spellings of jpath('...') and xpath('...') (row 34 point 2). // The path is the rest of the placeholder as written; only a whole placeholder, where its end is known. foreach (var (prefix, apply) in PathSpellings) if (text.StartsWith(prefix, StringComparison.Ordinal)) { var path = text[prefix.Length..].Trim(); if (path.Length == 0) throw new ExpressionCompilationException($"${{{text}}} names no path: write ${{{prefix}$.a.b}} or ${{{prefix}//a}}."); return exchange => apply(exchange, path); } // ${file:name}: the file language over the file headers (row 34 point 3). if (text.StartsWith("file:", StringComparison.Ordinal)) return FileKey(text); if (text.StartsWith("file:", StringComparison.OrdinalIgnoreCase)) throw new ExpressionCompilationException( $"${{{text}}}: file keys are lowercase: ${{file:{text["file:".Length..].Trim().ToLowerInvariant()}}}."); // A namespaced call (bean:svc.Check(...)) is the AST's, deterministically: no shortcut below knows it. if (ContainsNamespacedCall(text)) return GetCompiledValueExpressionWithAst(text); var jpath = JPathFunctionRegex.Match(text); if (jpath.Success && jpath.Value.Trim() == text && !HasSecondArgument(jpath.Groups[1].Value)) { var path = Unquote(jpath.Groups[1].Value.Trim()); return exchange => ApplyJPath(exchange, path); } var xpath = XPathFunctionRegex.Match(text); if (xpath.Success && xpath.Value.Trim() == text && !HasSecondArgument(xpath.Groups[1].Value)) { var path = Unquote(xpath.Groups[1].Value.Trim()); return exchange => ApplyXPath(exchange, path); } if (text == "body") return exchange => exchange.In.getBody(); if (text == "contentType") return exchange => exchange.In.ContentType; if (text.StartsWith(HEADER_PREFIX, StringComparison.Ordinal) && text.Length > HEADER_PREFIX.Length) return CompileAccessorPlaceholder(text, text[HEADER_PREFIX.Length..], isHeader: true); if (text.StartsWith(PROPERTY_PREFIX, StringComparison.Ordinal) && text.Length > PROPERTY_PREFIX.Length) return CompileAccessorPlaceholder(text, text[PROPERTY_PREFIX.Length..], isHeader: false); return GetCompiledValueExpressionWithAst(text); } /// /// Tells a one-argument xpath(path) from a two-argument xpath(path, source). /// /// /// The shortcut above exists because a bare path is not something the expression tokenizer can /// read — $.store.book and /order/id are not tokens. A second argument is, /// though, and it has to be evaluated against the exchange, so the placeholder belongs to the /// AST engine instead. Commas inside quotes and inside brackets are part of the path /// ($..book[0,1], /a[@x='1,2']) and do not count. /// private static bool HasSecondArgument(string arguments) { var depth = 0; var quote = '\0'; foreach (var c in arguments) { if (quote != '\0') { if (c == quote) quote = '\0'; continue; } switch (c) { case '\'' or '"': quote = c; break; case '(' or '[' or '{': depth++; break; case ')' or ']' or '}': depth--; break; case ',' when depth == 0: return true; } } return false; } /// /// The literal-name-first evaluator for a header. or property. placeholder: /// the exact name wins, then the smart nested path, then the whole text as an expression. /// The expression leg is compiled eagerly so a placeholder that can be nothing at all still /// fails at build time rather than rendering as emptiness forever. /// private static Func CompileAccessorPlaceholder(string full, string tail, bool isHeader) { // A tail that cannot compile as an expression still works as a pure name lookup when it is one word (a dashed // name is a subtraction of unknowns and compiles anyway). A tail with whitespace is an expression, and one that // does not compile (header.b == 3 garbage) is the error, at build time (findings register row 32). Func? expression; try { expression = GetCompiledValueExpressionWithAst(full); } catch (Exception) when (!tail.Any(char.IsWhiteSpace)) { expression = null; } var nested = tail.Contains('.'); return exchange => { if (isHeader) { if (exchange.In.Headers.ContainsKey(tail)) return exchange.In.getHeader(tail); if (nested) { var value = ResolveHeaderSmart(exchange, tail); if (value is not null) return value; } } else { if (exchange.Properties.ContainsKey(tail)) return exchange.getProperty(tail); if (nested) { var value = ResolvePropertySmart(exchange, tail); if (value is not null) return value; } } return expression?.Invoke(exchange); }; } /// /// Compiles a full template — literal text with ${...} holes — into a string /// producer. Each hole goes through ; the text between holes /// is emitted verbatim, whatever operators it happens to contain. /// private static Func CompileTemplateString(string template) { var holes = TemplateScanner.Holes(template); var segments = new List>(holes.Count * 2 + 1); var position = 0; foreach (var hole in holes) { if (hole.Start > position) { var literal = Unescape(template[position..hole.Start]); segments.Add(_ => literal); } var compiled = CompilePlaceholder(hole.InnerOf(template)); segments.Add(exchange => TemplateText(compiled(exchange))); position = hole.Start + hole.Length; } if (position < template.Length) { var tail = Unescape(template[position..]); segments.Add(_ => tail); } return exchange => { var text = new StringBuilder(); foreach (var segment in segments) text.Append(segment(exchange)); return text.ToString(); }; } /// /// The text between holes with each escape \${ written as the literal ${ it stands for. Outside a /// hole a \${ is always an escape: the scanner never opens a hole there. /// private static string Unescape(string literal) => literal.Contains("\\${", StringComparison.Ordinal) ? literal.Replace("\\${", "${", StringComparison.Ordinal) : literal; /// /// Reports whether the whole string is exactly one ${...} placeholder, in which case /// its value keeps the CLR type instead of being rendered to text. /// /// The template string. /// The inner text when the string is a single placeholder. /// true when the string is one placeholder with nothing around it. internal static bool TryGetSinglePlaceholder(string template, out string placeholder) { if (template.Length > 3 && template.StartsWith("${", StringComparison.Ordinal) && TemplateScanner.Scan(template) is { Unclosed.Count: 0, Holes: [var only] } && only.Length == template.Length) { placeholder = only.InnerOf(template); return true; } placeholder = string.Empty; return false; } /// /// Gets a cached typed evaluator for the inner text of a single placeholder. /// internal static Func GetCompiledPlaceholder(string placeholder, string? contextId = null) { var cacheKey = BuildCacheKey(contextId, "placeholder:" + placeholder); return _valueExpressionCache.GetOrAdd(cacheKey, _ => CompilePlaceholder(placeholder)); } /// /// ${file:key}, Apache Camel's file language (row 34 point 3) over the redbFile.* headers the file /// consumers set, through ; an unknown key is an error listing the keys. /// private static Func FileKey(string text) { var key = text["file:".Length..]; if (!FileLanguage.TryGetFact(key, StringComparison.Ordinal, out var fact)) throw new ExpressionCompilationException($"${{{text}}}: {FileLanguage.UnknownKeyMessage(key)}"); return exchange => FileLanguage.Value(fact, new FileHeaderFacts(exchange.In.Headers)); } /// The Camel path spellings of a whole placeholder and the readers they stand for. private static readonly (string Prefix, Func Apply)[] PathSpellings = [ ("jsonpath:", ApplyJPath), ("xpath:", ApplyXPath), ]; /// /// A placeholder expr:FORMAT whose last colon at the top level (outside quotes, parentheses and brackets, with /// no ? of a ternary before it) is followed by a standard .NET format: one letter and up to two digits /// (F4, N2, D8). The left side must name a value with a dot or a call (total.CostUsd, /// round(x)), so a namespace written against its name (env:X, file:name) is never a format. /// internal static bool TrySplitFormatSuffix(string text, out string expression, out string format) { expression = format = string.Empty; var depth = 0; var quote = '\0'; var colon = -1; for (var i = 0; i < text.Length; i++) { var ch = text[i]; if (quote != '\0') { if (ch == '\\' && i + 1 < text.Length) i++; else if (ch == quote) quote = '\0'; continue; } switch (ch) { case '\'' or '"': quote = ch; break; case '(' or '[': depth++; break; case ')' or ']': if (depth > 0) depth--; break; case '?' when depth == 0: return false; // a ternary's colon, or ?? case ':' when depth == 0: colon = i; break; } } if (colon <= 0) return false; var left = text[..colon].Trim(); var right = text[(colon + 1)..].Trim(); if (!FormatSuffixRegex.IsMatch(right) || left.Length == 0 || BareWordRegex.IsMatch(left)) return false; expression = left; format = right; return true; } private static readonly Regex FormatSuffixRegex = new(@"^[A-Za-z][0-9]{0,2}$", RegexOptions.Compiled); private static readonly Regex BareWordRegex = new(@"^[A-Za-z_][A-Za-z0-9_]*$", RegexOptions.Compiled); private static string Unquote(string text) => text.Length >= 2 && ((text.StartsWith('\'') && text.EndsWith('\'')) || (text.StartsWith('"') && text.EndsWith('"'))) ? text[1..^1] : text; }