feat(core,pg,wasm): add compile/CompiledExpr for parse-once evaluation
public
feat(core,pg,wasm): add compile/CompiledExpr for parse-once evaluation - feel-core: compile(expr) -> CompiledExpr with evaluate(&ctx); evaluate() now routes through it (additive, no API break) - feel-pg: cache the parsed AST per call site via pgrx::pg_func_extra (fn_extra in fn_mcxt), keyed on the expression text — parse-once per query - feel-wasm: compile() + CompiledExpr class (evaluate/evaluate_strict); shared run() boundary helper; FinalizationRegistry auto-cleanup + optional free() - smoke.mjs + README: document the compiled path Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
| Changeset | 73ce8b92b17e57e99babb93e3cb643cdd9a9b46d |
|---|---|
| Author (claimed) | Timo Stolz <timo.stolz@gmail.com>, |
| Parents | ef495d189b55 |
| Children | |
| Pushlog | by timo via ssh |
modified README.md +7 −1
| @@ -171,13 +171,19 @@ | ||
| 171 | 171 | arose from a type/domain error. |
| 172 | 172 | |
| 173 | 173 | ```js |
| 174 | -import { evaluate, evaluate_strict } from "./pkg/feel_wasm.js"; | |
| 174 | +import { evaluate, evaluate_strict, compile } from "./pkg/feel_wasm.js"; | |
| 175 | 175 | |
| 176 | 176 | evaluate("1 + 1", {}); // => 2 |
| 177 | 177 | evaluate("person.age", { person: { age: 42 } }); // => 42 |
| 178 | 178 | evaluate("{a: 1, b: a + 1}", {}); // => { a: 1, b: 2 } |
| 179 | 179 | evaluate("1 + true", {}); // => null (lenient) |
| 180 | 180 | evaluate_strict("1 + true", {}); // throws (strict) |
| 181 | + | |
| 182 | +// Parse once, evaluate many times (e.g. one expression over many rows): | |
| 183 | +const prog = compile("a + 1"); | |
| 184 | +prog.evaluate({ a: 1 }); // => 2 | |
| 185 | +prog.evaluate({ a: 41 }); // => 42 | |
| 186 | +prog.free(); // optional; else GC reclaims it | |
| 181 | 187 | ``` |
| 182 | 188 | |
| 183 | 189 | Compile-only check without wasm-pack: |
modified crates/feel-core/src/lib.rs +65 −4
| @@ -62,17 +62,51 @@ | ||
| 62 | 62 | } |
| 63 | 63 | } |
| 64 | 64 | |
| 65 | +/// A parsed FEEL expression, ready to be evaluated repeatedly. | |
| 66 | +/// | |
| 67 | +/// Parsing is the per-call cost that does not depend on the context, so callers | |
| 68 | +/// that evaluate the same expression against many contexts (e.g. one decision | |
| 69 | +/// over many rows) should [`compile`] once and reuse the result. The wrapped AST | |
| 70 | +/// is fully owning, so a `CompiledExpr` carries no borrow of the source string. | |
| 71 | +/// | |
| 72 | +/// ``` | |
| 73 | +/// use feel_core::{compile, Context, Value}; | |
| 74 | +/// let prog = compile("a + 1").unwrap(); | |
| 75 | +/// let mut ctx = Context::empty(); | |
| 76 | +/// ctx.insert("a", Value::Number(1.0)); | |
| 77 | +/// assert_eq!(prog.evaluate(&ctx).unwrap(), Value::Number(2.0)); | |
| 78 | +/// ``` | |
| 79 | +#[derive(Debug, Clone)] | |
| 80 | +pub struct CompiledExpr(ast::Expr); | |
| 81 | + | |
| 82 | +impl CompiledExpr { | |
| 83 | + /// Evaluate this already-parsed expression against a context. | |
| 84 | + pub fn evaluate(&self, context: &Context) -> Result<Value, FeelError> { | |
| 85 | + eval::eval(&self.0, context) | |
| 86 | + } | |
| 87 | +} | |
| 88 | + | |
| 89 | +/// Parse a FEEL expression into a reusable [`CompiledExpr`] without evaluating it. | |
| 90 | +/// | |
| 91 | +/// Returns [`FeelError::Parse`] if the expression is syntactically invalid. | |
| 92 | +pub fn compile(expr: &str) -> Result<CompiledExpr, FeelError> { | |
| 93 | + feel::ExprParser::new() | |
| 94 | + .parse(expr) | |
| 95 | + .map(CompiledExpr) | |
| 96 | + .map_err(|e| FeelError::Parse(e.to_string())) | |
| 97 | +} | |
| 98 | + | |
| 65 | 99 | /// Parse and evaluate a FEEL expression against a context. |
| 100 | +/// | |
| 101 | +/// Convenience for `compile(expr)?.evaluate(context)`; prefer [`compile`] when | |
| 102 | +/// evaluating the same expression more than once. | |
| 66 | 103 | /// |
| 67 | 104 | /// ``` |
| 68 | 105 | /// use feel_core::{evaluate, Context, Value}; |
| 69 | 106 | /// assert_eq!(evaluate("1 + 1", &Context::empty()).unwrap(), Value::Number(2.0)); |
| 70 | 107 | /// ``` |
| 71 | 108 | pub fn evaluate(expr: &str, context: &Context) -> Result<Value, FeelError> { |
| 72 | - let ast = feel::ExprParser::new() | |
| 73 | - .parse(expr) | |
| 74 | - .map_err(|e| FeelError::Parse(e.to_string()))?; | |
| 75 | - eval::eval(&ast, context) | |
| 109 | + compile(expr)?.evaluate(context) | |
| 76 | 110 | } |
| 77 | 111 | |
| 78 | 112 | #[cfg(test)] |
| @@ -97,6 +131,33 @@ | ||
| 97 | 131 | } |
| 98 | 132 | fn list(items: Vec<Value>) -> Value { |
| 99 | 133 | Value::List(items) |
| 134 | + } | |
| 135 | + | |
| 136 | + #[test] | |
| 137 | + fn compile_matches_evaluate() { | |
| 138 | + // The compiled path and the one-shot path must agree. | |
| 139 | + for src in ["1 + 1", "5 in [1..10]", "if 1 < 2 then 10 else 20"] { | |
| 140 | + let one_shot = evaluate(src, &Context::empty()).unwrap(); | |
| 141 | + let compiled = compile(src).unwrap().evaluate(&Context::empty()).unwrap(); | |
| 142 | + assert_eq!(one_shot, compiled, "mismatch for `{src}`"); | |
| 143 | + } | |
| 144 | + } | |
| 145 | + | |
| 146 | + #[test] | |
| 147 | + fn compiled_expr_reused_across_contexts() { | |
| 148 | + // One parse, evaluated against two different contexts. | |
| 149 | + let prog = compile("a + 1").unwrap(); | |
| 150 | + let mut c1 = Context::empty(); | |
| 151 | + c1.insert("a", num(1.0)); | |
| 152 | + let mut c2 = Context::empty(); | |
| 153 | + c2.insert("a", num(41.0)); | |
| 154 | + assert_eq!(prog.evaluate(&c1).unwrap().into_lenient(), num(2.0)); | |
| 155 | + assert_eq!(prog.evaluate(&c2).unwrap().into_lenient(), num(42.0)); | |
| 156 | + } | |
| 157 | + | |
| 158 | + #[test] | |
| 159 | + fn compile_reports_parse_error() { | |
| 160 | + assert!(matches!(compile("1 +"), Err(FeelError::Parse(_)))); | |
| 100 | 161 | } |
| 101 | 162 | |
| 102 | 163 | #[test] |
modified crates/feel-pg/src/lib.rs +44 −4
| @@ -10,9 +10,9 @@ | ||
| 10 | 10 | //! project's boundary-mapping decision. |
| 11 | 11 | |
| 12 | 12 | use pgrx::prelude::*; |
| 13 | -use pgrx::JsonB; | |
| 14 | - | |
| 15 | -use feel_core::{evaluate, Context, Value}; | |
| 13 | +use pgrx::{pg_func_extra, JsonB, PgBox}; | |
| 14 | + | |
| 15 | +use feel_core::{compile, CompiledExpr, Context, Value}; | |
| 16 | 16 | |
| 17 | 17 | ::pgrx::pg_module_magic!(); |
| 18 | 18 | |
| @@ -23,15 +23,42 @@ | ||
| 23 | 23 | /// jsonb `null`. Pass `strict => true` to instead raise an ERROR when the result |
| 24 | 24 | /// is, or contains, such an error-null, so the error does not pass silently |
| 25 | 25 | /// (ADR-14). |
| 26 | +/// | |
| 27 | +/// The parsed expression is cached in the call site's `fn_extra` slot (allocated | |
| 28 | +/// in `flinfo->fn_mcxt`, which lives for the whole query — never the per-row | |
| 29 | +/// context), keyed on the expression text. So when `expr` is a query constant — | |
| 30 | +/// the usual case, e.g. one decision over many rows — it is parsed once per query | |
| 31 | +/// and only re-parsed if the text actually changes. No global/session cache. | |
| 26 | 32 | #[pg_extern] |
| 27 | 33 | fn feel_eval( |
| 28 | 34 | expr: &str, |
| 29 | 35 | context: default!(JsonB, "'{}'::jsonb"), |
| 30 | 36 | strict: default!(bool, "false"), |
| 37 | + fcinfo: pg_sys::FunctionCallInfo, | |
| 31 | 38 | ) -> JsonB { |
| 39 | + // SAFETY: `fcinfo` is the genuine call info injected by the pgrx wrapper; | |
| 40 | + // `pg_func_extra` allocates the cache in `fn_mcxt` and registers a drop | |
| 41 | + // callback, so the owned `CompiledExpr` is freed on context teardown. | |
| 42 | + let mut cache: PgBox<Option<(String, CompiledExpr)>> = | |
| 43 | + unsafe { pg_func_extra(fcinfo, || None) }; | |
| 44 | + let stale = match &*cache { | |
| 45 | + Some((cached, _)) => cached != expr, | |
| 46 | + None => true, | |
| 47 | + }; | |
| 48 | + if stale { | |
| 49 | + match compile(expr) { | |
| 50 | + Ok(compiled) => *cache = Some((expr.to_owned(), compiled)), | |
| 51 | + Err(e) => error!("feel_eval failed: {e}"), | |
| 52 | + } | |
| 53 | + } | |
| 54 | + let compiled = match &*cache { | |
| 55 | + Some((_, compiled)) => compiled, | |
| 56 | + None => unreachable!("cache populated above"), | |
| 57 | + }; | |
| 58 | + | |
| 32 | 59 | let ctx = context_from_json(&context.0) |
| 33 | 60 | .unwrap_or_else(|e| error!("invalid feel context: {e}")); |
| 34 | - match evaluate(expr, &ctx) { | |
| 61 | + match compiled.evaluate(&ctx) { | |
| 35 | 62 | Ok(value) if strict && value.contains_error() => { |
| 36 | 63 | error!("feel_eval: result is null from a type or domain error (strict mode)") |
| 37 | 64 | } |
| @@ -168,6 +195,19 @@ | ||
| 168 | 195 | } |
| 169 | 196 | |
| 170 | 197 | #[pg_test] |
| 198 | + fn same_expression_over_many_contexts() { | |
| 199 | + // One constant expression evaluated against many per-row jsonb contexts: | |
| 200 | + // exercises the fn_extra parse-once reuse path; each row must still be | |
| 201 | + // correct. `a + 1` over a generated series of contexts. | |
| 202 | + let matched = Spi::get_one::<bool>( | |
| 203 | + r#"SELECT bool_and(feel_eval('a + 1', jsonb_build_object('a', g)) = to_jsonb(g + 1)) | |
| 204 | + FROM generate_series(1, 100) AS g"#, | |
| 205 | + ) | |
| 206 | + .expect("SPI query failed"); | |
| 207 | + assert_eq!(matched, Some(true)); | |
| 208 | + } | |
| 209 | + | |
| 210 | + #[pg_test] | |
| 171 | 211 | fn path_access_reads_nested_context() { |
| 172 | 212 | // A nested jsonb object is bound as a FEEL context; `p.age` reads it. |
| 173 | 213 | let matched = Spi::get_one::<bool>( |
modified crates/feel-wasm/smoke.mjs +19 −1
| @@ -14,7 +14,7 @@ | ||
| 14 | 14 | // {a: 1, b: a + 1} => {"a":1,"b":2} |
| 15 | 15 | // person.age (ctx {"person":{"age":42}}) => 42 |
| 16 | 16 | |
| 17 | -import { evaluate, evaluate_strict } from "./pkg/feel_wasm.js"; | |
| 17 | +import { evaluate, evaluate_strict, compile } from "./pkg/feel_wasm.js"; | |
| 18 | 18 | |
| 19 | 19 | // [expression, context-object, expected-value]. The context is a native JS |
| 20 | 20 | // object and the result is a native JS value (no JSON strings). These mirror the |
| @@ -67,5 +67,23 @@ | ||
| 67 | 67 | ok = false; |
| 68 | 68 | } |
| 69 | 69 | } |
| 70 | +// Compiled path: parse once, evaluate against many contexts (the parse-once / | |
| 71 | +// evaluate-many API). `free()` is the optional explicit-cleanup escape hatch; | |
| 72 | +// otherwise wasm-bindgen's FinalizationRegistry reclaims it on GC. | |
| 73 | +const prog = compile("a + 1"); | |
| 74 | +const compiledCases = [ | |
| 75 | + [{ a: 1 }, 2], | |
| 76 | + [{ a: 41 }, 42], | |
| 77 | +]; | |
| 78 | +for (const [ctx, expected] of compiledCases) { | |
| 79 | + const got = prog.evaluate(ctx); | |
| 80 | + console.log(`compiled "a + 1" (ctx ${JSON.stringify(ctx)}) => ${JSON.stringify(got)}`); | |
| 81 | + if (!eq(got, expected)) { | |
| 82 | + console.error(`FAIL: expected ${JSON.stringify(expected)}, got ${JSON.stringify(got)}`); | |
| 83 | + ok = false; | |
| 84 | + } | |
| 85 | +} | |
| 86 | +prog.free(); | |
| 87 | + | |
| 70 | 88 | if (!ok) process.exit(1); |
| 71 | 89 | console.error("smoke test passed"); |
modified crates/feel-wasm/src/lib.rs +62 −17
| @@ -1,12 +1,15 @@ | ||
| 1 | 1 | //! WASM wrapper for `feel-core`, built with wasm-bindgen. |
| 2 | 2 | //! |
| 3 | -//! Exposes `evaluate(expr, context) -> JsValue`, taking the context as a native | |
| 4 | -//! JS object and returning the result as a native JS value. The boundary mapping | |
| 5 | -//! lives here (not in `feel-core`), per the project's boundary-mapping decision: | |
| 6 | -//! `JsValue` is bridged to `serde_json::Value` with `serde-wasm-bindgen`, then to | |
| 7 | -//! `feel-core`'s [`Value`] by the existing recursive helpers. | |
| 3 | +//! Exposes the one-shot `evaluate(expr, context) -> JsValue` plus a | |
| 4 | +//! `compile(expr) -> CompiledExpr` class for parse-once / evaluate-many: parsing | |
| 5 | +//! is the per-call cost that does not depend on the context, so callers that | |
| 6 | +//! evaluate the same expression against many contexts should compile once and | |
| 7 | +//! reuse. The context is a native JS object and the result a native JS value. The | |
| 8 | +//! boundary mapping lives here (not in `feel-core`), per the project's | |
| 9 | +//! boundary-mapping decision: `JsValue` is bridged to `serde_json::Value` with | |
| 10 | +//! `serde-wasm-bindgen`, then to `feel-core`'s [`Value`] by the helpers below. | |
| 8 | 11 | |
| 9 | -use feel_core::{evaluate as core_evaluate, Context, Value}; | |
| 12 | +use feel_core::{compile as core_compile, CompiledExpr as CoreCompiled, Context, Value}; | |
| 10 | 13 | use serde::Serialize; |
| 11 | 14 | use wasm_bindgen::prelude::*; |
| 12 | 15 | |
| @@ -19,8 +22,7 @@ | ||
| 19 | 22 | /// surface such errors as a thrown exception instead. |
| 20 | 23 | #[wasm_bindgen] |
| 21 | 24 | pub fn evaluate(expr: &str, context: JsValue) -> Result<JsValue, JsError> { |
| 22 | - let value = eval_value(expr, context).map_err(|m| JsError::new(&m))?; | |
| 23 | - to_js(&value_to_json(&value)) | |
| 25 | + run(&compile_core(expr)?, context, false) | |
| 24 | 26 | } |
| 25 | 27 | |
| 26 | 28 | /// Evaluate a FEEL expression (strict boundary policy): if the result is, or |
| @@ -29,20 +31,63 @@ | ||
| 29 | 31 | /// returned as `null`. |
| 30 | 32 | #[wasm_bindgen] |
| 31 | 33 | pub fn evaluate_strict(expr: &str, context: JsValue) -> Result<JsValue, JsError> { |
| 32 | - let value = eval_value(expr, context).map_err(|m| JsError::new(&m))?; | |
| 33 | - if value.contains_error() { | |
| 34 | + run(&compile_core(expr)?, context, true) | |
| 35 | +} | |
| 36 | + | |
| 37 | +/// A parsed FEEL expression, reusable across many evaluations. | |
| 38 | +/// | |
| 39 | +/// Build one with [`compile`], then call [`CompiledExpr::evaluate`] repeatedly — | |
| 40 | +/// parsing happens once, each call only maps the context across the boundary. | |
| 41 | +/// wasm-bindgen exposes a `free()` method and registers instances with a | |
| 42 | +/// `FinalizationRegistry`, so the WASM-side memory is reclaimed on GC; calling | |
| 43 | +/// `free()` explicitly is an optional escape hatch, not required. | |
| 44 | +#[wasm_bindgen] | |
| 45 | +pub struct CompiledExpr { | |
| 46 | + inner: CoreCompiled, | |
| 47 | +} | |
| 48 | + | |
| 49 | +/// Parse a FEEL expression into a reusable [`CompiledExpr`] (throws on a parse | |
| 50 | +/// error). Does not evaluate. | |
| 51 | +#[wasm_bindgen] | |
| 52 | +pub fn compile(expr: &str) -> Result<CompiledExpr, JsError> { | |
| 53 | + Ok(CompiledExpr { | |
| 54 | + inner: compile_core(expr)?, | |
| 55 | + }) | |
| 56 | +} | |
| 57 | + | |
| 58 | +#[wasm_bindgen] | |
| 59 | +impl CompiledExpr { | |
| 60 | + /// Evaluate this compiled expression against a context (lenient policy). | |
| 61 | + pub fn evaluate(&self, context: JsValue) -> Result<JsValue, JsError> { | |
| 62 | + run(&self.inner, context, false) | |
| 63 | + } | |
| 64 | + | |
| 65 | + /// Evaluate this compiled expression against a context (strict policy; see | |
| 66 | + /// the free `evaluate_strict`). | |
| 67 | + pub fn evaluate_strict(&self, context: JsValue) -> Result<JsValue, JsError> { | |
| 68 | + run(&self.inner, context, true) | |
| 69 | + } | |
| 70 | +} | |
| 71 | + | |
| 72 | +fn compile_core(expr: &str) -> Result<CoreCompiled, JsError> { | |
| 73 | + core_compile(expr).map_err(|e| JsError::new(&e.to_string())) | |
| 74 | +} | |
| 75 | + | |
| 76 | +/// Shared per-call boundary: map the JS context in, evaluate the compiled | |
| 77 | +/// program, optionally surface error-nulls strictly, map the result back out. | |
| 78 | +fn run(compiled: &CoreCompiled, context: JsValue, strict: bool) -> Result<JsValue, JsError> { | |
| 79 | + let parsed: serde_json::Value = serde_wasm_bindgen::from_value(context) | |
| 80 | + .map_err(|e| JsError::new(&format!("invalid context: {e}")))?; | |
| 81 | + let ctx = context_from_json(&parsed).map_err(|m| JsError::new(&m))?; | |
| 82 | + let value = compiled | |
| 83 | + .evaluate(&ctx) | |
| 84 | + .map_err(|e| JsError::new(&e.to_string()))?; | |
| 85 | + if strict && value.contains_error() { | |
| 34 | 86 | return Err(JsError::new( |
| 35 | 87 | "evaluation produced a null from a type or domain error", |
| 36 | 88 | )); |
| 37 | 89 | } |
| 38 | 90 | to_js(&value_to_json(&value)) |
| 39 | -} | |
| 40 | - | |
| 41 | -fn eval_value(expr: &str, context: JsValue) -> Result<Value, String> { | |
| 42 | - let parsed: serde_json::Value = | |
| 43 | - serde_wasm_bindgen::from_value(context).map_err(|e| format!("invalid context: {e}"))?; | |
| 44 | - let ctx = context_from_json(&parsed)?; | |
| 45 | - core_evaluate(expr, &ctx).map_err(|e| e.to_string()) | |
| 46 | 91 | } |
| 47 | 92 | |
| 48 | 93 | /// Serialize a JSON value to a native `JsValue`. The `json_compatible` serializer |