Public repository: timo / feel

Reader

An interpreter of FEEL, written in Rust, with integrations for PostgreSQL, WASM, Lua, and Python.

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>
Changeset73ce8b92b17e57e99babb93e3cb643cdd9a9b46d
Author (claimed)Timo Stolz <timo.stolz@gmail.com>,
Parentsef495d189b55
Children
Pushlog
by timo via ssh

modified README.md +7 −1

@@ -171,13 +171,19 @@
171171
 arose from a type/domain error.
172172
 
173173
 ```js
174
-import { evaluate, evaluate_strict } from "./pkg/feel_wasm.js";
174
+import { evaluate, evaluate_strict, compile } from "./pkg/feel_wasm.js";
175175
 
176176
 evaluate("1 + 1", {});                         // => 2
177177
 evaluate("person.age", { person: { age: 42 } }); // => 42
178178
 evaluate("{a: 1, b: a + 1}", {});              // => { a: 1, b: 2 }
179179
 evaluate("1 + true", {});                      // => null  (lenient)
180180
 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
181187
 ```
182188
 
183189
 Compile-only check without wasm-pack:

modified crates/feel-core/src/lib.rs +65 −4

@@ -62,17 +62,51 @@
6262
     }
6363
 }
6464
 
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
+
6599
 /// 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.
66103
 ///
67104
 /// ```
68105
 /// use feel_core::{evaluate, Context, Value};
69106
 /// assert_eq!(evaluate("1 + 1", &Context::empty()).unwrap(), Value::Number(2.0));
70107
 /// ```
71108
 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)
76110
 }
77111
 
78112
 #[cfg(test)]
@@ -97,6 +131,33 @@
97131
     }
98132
     fn list(items: Vec<Value>) -> Value {
99133
         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(_))));
100161
     }
101162
 
102163
     #[test]

modified crates/feel-pg/src/lib.rs +44 −4

@@ -10,9 +10,9 @@
1010
 //! project's boundary-mapping decision.
1111
 
1212
 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};
1616
 
1717
 ::pgrx::pg_module_magic!();
1818
 
@@ -23,15 +23,42 @@
2323
 /// jsonb `null`. Pass `strict => true` to instead raise an ERROR when the result
2424
 /// is, or contains, such an error-null, so the error does not pass silently
2525
 /// (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.
2632
 #[pg_extern]
2733
 fn feel_eval(
2834
     expr: &str,
2935
     context: default!(JsonB, "'{}'::jsonb"),
3036
     strict: default!(bool, "false"),
37
+    fcinfo: pg_sys::FunctionCallInfo,
3138
 ) -> 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
+
3259
     let ctx = context_from_json(&context.0)
3360
         .unwrap_or_else(|e| error!("invalid feel context: {e}"));
34
-    match evaluate(expr, &ctx) {
61
+    match compiled.evaluate(&ctx) {
3562
         Ok(value) if strict && value.contains_error() => {
3663
             error!("feel_eval: result is null from a type or domain error (strict mode)")
3764
         }
@@ -168,6 +195,19 @@
168195
     }
169196
 
170197
     #[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]
171211
     fn path_access_reads_nested_context() {
172212
         // A nested jsonb object is bound as a FEEL context; `p.age` reads it.
173213
         let matched = Spi::get_one::<bool>(

modified crates/feel-wasm/smoke.mjs +19 −1

@@ -14,7 +14,7 @@
1414
 //   {a: 1, b: a + 1} => {"a":1,"b":2}
1515
 //   person.age (ctx {"person":{"age":42}}) => 42
1616
 
17
-import { evaluate, evaluate_strict } from "./pkg/feel_wasm.js";
17
+import { evaluate, evaluate_strict, compile } from "./pkg/feel_wasm.js";
1818
 
1919
 // [expression, context-object, expected-value]. The context is a native JS
2020
 // object and the result is a native JS value (no JSON strings). These mirror the
@@ -67,5 +67,23 @@
6767
     ok = false;
6868
   }
6969
 }
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
+
7088
 if (!ok) process.exit(1);
7189
 console.error("smoke test passed");

modified crates/feel-wasm/src/lib.rs +62 −17

@@ -1,12 +1,15 @@
11
 //! WASM wrapper for `feel-core`, built with wasm-bindgen.
22
 //!
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.
811
 
9
-use feel_core::{evaluate as core_evaluate, Context, Value};
12
+use feel_core::{compile as core_compile, CompiledExpr as CoreCompiled, Context, Value};
1013
 use serde::Serialize;
1114
 use wasm_bindgen::prelude::*;
1215
 
@@ -19,8 +22,7 @@
1922
 /// surface such errors as a thrown exception instead.
2023
 #[wasm_bindgen]
2124
 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)
2426
 }
2527
 
2628
 /// Evaluate a FEEL expression (strict boundary policy): if the result is, or
@@ -29,20 +31,63 @@
2931
 /// returned as `null`.
3032
 #[wasm_bindgen]
3133
 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() {
3486
         return Err(JsError::new(
3587
             "evaluation produced a null from a type or domain error",
3688
         ));
3789
     }
3890
     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())
4691
 }
4792
 
4893
 /// Serialize a JSON value to a native `JsValue`. The `json_compatible` serializer