Public repository: timo / feel

Reader

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

Outline: 30 definitions
1
//! Lua wrapper for `feel-core`, built with mlua (ADR-22).
2
//!
3
//! Exposes a Lua module — `local feel = require("feel")` — with the one-shot
4
//! `feel.evaluate(expr, context, functions)` plus `feel.compile(expr)` for
5
//! parse-once / evaluate-many: parsing is the per-call cost that does not depend on
6
//! the context, so callers evaluating the same expression against many contexts
7
//! should compile once and reuse. The context and the result are native Lua values;
8
//! the boundary mapping lives here (not in `feel-core`), per the cardinal rule
9
//! (ADR-1).
10
//!
11
//! Like feel-wasm (JS), Lua has **no keyword arguments** and is **single-threaded**,
12
//! so this wrapper is the close analogue of feel-wasm:
13
//!
14
//! * Context input is **lazy** (ADR-21/RD-9): a table is wrapped behind feel-core's
15
//!   `ForeignObject` seam, so `order.customer.address` resolves one segment at a
16
//!   time via `table[key]` (firing any `__index` metamethod) instead of the whole
17
//!   graph being walked up front. Scalars convert eagerly; a `Foreign`/`Function`
18
//!   that reaches the result passes the original Lua value back untouched (identity).
19
//! * Host callables (ADR-23): a Lua function passed in becomes a FEEL function the
20
//!   engine can invoke. Lua has no kwargs, so FEEL named arguments become a single
21
//!   trailing options table `{name = value}` (the feel-wasm convention). A failed
22
//!   call (a raised Lua error / longjmp, caught by mlua at the boundary) maps to an
23
//!   **error-null** (`Value::Error`, ADR-14) — distinct from a value-null, which is
24
//!   what a failed *member access* or a regular `return nil` yields.
25
//! * Regex is the bundled `RustRegex` dialect (RD-7 — no Lua-pattern provider), and
26
//!   temporal values cross the boundary as ISO-8601 strings (RD-8).
27
//!
28
//! Because a (finite) expression can only navigate a finite path, and output passes
29
//! through rather than re-walking, cyclic tables need no cycle guard.
30
31
use std::any::Any;
32
use std::collections::BTreeMap;
33
use std::sync::Arc;
34
35
use feel_core::{
36
    compile as core_compile, Args, CompiledExpr as CoreCompiled, Context, EvalEnv, Foreign,
37
    ForeignFunction, ForeignObject, Func, FunctionRegistry, Value,
38
};
39
use mlua::{Lua, Table, Value as LuaValue, Variadic};
40
41
/// Re-export mlua so the integration tests (and Rust embedders) use the exact same
42
/// build of the library — no second Lua linked.
43
pub use mlua;
44
45
// --------------------------------------------------------------------------- //
46
// Public module surface
47
// --------------------------------------------------------------------------- //
48
49
/// Build the `feel` module table into an existing Lua state.
50
///
51
/// This is the entry the loadable module (`luaopen_feel`) calls, and the one the
52
/// Rust integration tests call directly against an embedded VM. It registers
53
/// `evaluate`, `evaluate_strict` and `compile` on a fresh table and returns it.
54
pub fn build_module(lua: &Lua) -> mlua::Result<Table> {
55
    let exports = lua.create_table()?;
56
    exports.set(
57
        "evaluate",
58
        lua.create_function(
59
            |lua, (expr, context, functions): (String, LuaValue, LuaValue)| {
60
                run(lua, &compile_core(&expr)?, context, functions, false)
61
            },
62
        )?,
63
    )?;
64
    exports.set(
65
        "evaluate_strict",
66
        lua.create_function(
67
            |lua, (expr, context, functions): (String, LuaValue, LuaValue)| {
68
                run(lua, &compile_core(&expr)?, context, functions, true)
69
            },
70
        )?,
71
    )?;
72
    exports.set(
73
        "compile",
74
        lua.create_function(|_, expr: String| compile_expr(&expr))?,
75
    )?;
76
    Ok(exports)
77
}
78
79
/// The loadable-module entry point: `require("feel")` calls `luaopen_feel`, which
80
/// returns the module table. Only built in `module` mode (links the host's Lua);
81
/// the default (vendored) build embeds Lua for `Lua::new()` and the tests.
82
#[cfg(feature = "module")]
83
#[mlua::lua_module]
84
fn feel(lua: &Lua) -> mlua::Result<Table> {
85
    build_module(lua)
86
}
87
88
/// A parsed FEEL expression, reusable across many evaluations (the `feel.compile`
89
/// result). Exposed to Lua as userdata with `:evaluate` / `:evaluate_strict`.
90
struct CompiledExpr {
91
    inner: CoreCompiled,
92
}
93
94
impl mlua::UserData for CompiledExpr {
95
    fn add_methods<M: mlua::UserDataMethods<Self>>(methods: &mut M) {
96
        methods.add_method(
97
            "evaluate",
98
            |lua, this, (context, functions): (LuaValue, LuaValue)| {
99
                run(lua, &this.inner, context, functions, false)
100
            },
101
        );
102
        methods.add_method(
103
            "evaluate_strict",
104
            |lua, this, (context, functions): (LuaValue, LuaValue)| {
105
                run(lua, &this.inner, context, functions, true)
106
            },
107
        );
108
    }
109
}
110
111
/// Parse into the core's reusable form, mapping a parse error to a Lua error.
112
fn compile_core(expr: &str) -> mlua::Result<CoreCompiled> {
113
    core_compile(expr).map_err(|e| mlua::Error::RuntimeError(e.to_string()))
114
}
115
116
/// Parse into the `feel.compile` userdata wrapper.
117
fn compile_expr(expr: &str) -> mlua::Result<CompiledExpr> {
118
    Ok(CompiledExpr {
119
        inner: compile_core(expr)?,
120
    })
121
}
122
123
/// Shared per-call boundary: map the Lua context in, evaluate against the bundled
124
/// regex provider and the system clock, optionally surface error-nulls strictly,
125
/// map the result back out.
126
fn run(
127
    lua: &Lua,
128
    compiled: &CoreCompiled,
129
    context: LuaValue,
130
    functions: LuaValue,
131
    strict: bool,
132
) -> mlua::Result<LuaValue> {
133
    let ctx = context_from_lua(&context)?;
134
    // Ambient host functions (ADR-23): a Lua table of `name -> function`, consulted
135
    // after context bindings and built-ins. A non-table (e.g. `nil`) -> no registry.
136
    let registry = LuaFunctionRegistry {
137
        funcs: table_or_none(&functions),
138
    };
139
    let env = EvalEnv::with_functions(&REGEX, now_zoned(), &registry);
140
    let value = compiled
141
        .evaluate_with_env(&ctx, &env)
142
        .map_err(|e| mlua::Error::RuntimeError(e.to_string()))?;
143
    if strict && value.contains_error() {
144
        return Err(mlua::Error::RuntimeError(
145
            "evaluation produced a null from a type or domain error".to_string(),
146
        ));
147
    }
148
    value_to_lua(lua, &value)
149
}
150
151
/// The bundled Rust regex engine (RD-7): feel-lua keeps the XPath/`RustRegex`
152
/// dialect, so `matches`/`replace`/`split` are byte-identical to feel-core/TCK.
153
static REGEX: feel_core::RustRegex = feel_core::RustRegex;
154
155
/// The evaluation instant for `now()`/`today()`: the system clock as a fixed-offset
156
/// UTC `Zoned`, so `now()` serialises as `…+00:00` (mirrors feel-py).
157
fn now_zoned() -> jiff::Zoned {
158
    let utc = jiff::tz::TimeZone::fixed(jiff::tz::Offset::UTC);
159
    jiff::Timestamp::now().to_zoned(utc)
160
}
161
162
fn table_or_none(value: &LuaValue) -> Option<Table> {
163
    match value {
164
        LuaValue::Table(t) => Some(t.clone()),
165
        _ => None,
166
    }
167
}
168
169
// --------------------------------------------------------------------------- //
170
// Context mapping (Lua -> feel-core Context/Value)
171
// --------------------------------------------------------------------------- //
172
173
/// Build a [`Context`] from the top-level Lua value. `nil` is the empty context; a
174
/// (non-sequence) table maps to a context of its string-keyed pairs; anything else
175
/// (a scalar, or a sequence table) is an error.
176
fn context_from_lua(value: &LuaValue) -> mlua::Result<Context> {
177
    match value {
178
        LuaValue::Nil => Ok(Context::new()),
179
        LuaValue::Table(t) => match lua_force(t) {
180
            Value::Context(map) => {
181
                let mut ctx = Context::new();
182
                for (k, v) in map {
183
                    ctx.insert(k, v);
184
                }
185
                Ok(ctx)
186
            }
187
            _ => Err(mlua::Error::RuntimeError(
188
                "context must be a table of name=value pairs, not a sequence".to_string(),
189
            )),
190
        },
191
        _ => Err(mlua::Error::RuntimeError(
192
            "context must be a table or nil".to_string(),
193
        )),
194
    }
195
}
196
197
/// Convert a single Lua value to a [`Value`] **shallowly** (ADR-21): scalars
198
/// eagerly; a function to a FEEL function value (ADR-23); a table to a lazy
199
/// `Value::Foreign` (the list-vs-context decision is deferred to [`lua_force`]).
200
/// Nothing is walked beyond this one level, so cyclic tables are harmless here.
201
fn shallow_convert_lua(value: &LuaValue) -> Value {
202
    match value {
203
        LuaValue::Nil => Value::Null,
204
        LuaValue::Boolean(b) => Value::Boolean(*b),
205
        LuaValue::Integer(i) => Value::Number(*i as f64),
206
        LuaValue::Number(n) => Value::Number(*n),
207
        LuaValue::String(s) => Value::String(s.to_string_lossy()),
208
        // A Lua function becomes a FEEL function value the host can invoke (ADR-23).
209
        LuaValue::Function(f) => Func::Foreign(Arc::new(LuaForeignFn { func: f.clone() })).into_value(),
210
        // Any table is wrapped lazily; members resolve on access.
211
        LuaValue::Table(t) => Value::Foreign(Foreign(Arc::new(LuaForeign { table: t.clone() }))),
212
        // threads / userdata / light-userdata / errors have no FEEL representation.
213
        _ => Value::Null,
214
    }
215
}
216
217
/// Resolve one member of a Lua table by name — the FEEL dot (ADR-21) — via
218
/// `table[key]`, which fires an `__index` metamethod. An absent member (`nil`) or a
219
/// raised metamethod is a **value-null**. The returned value is shallow.
220
fn lua_get_member(table: &Table, key: &str) -> Value {
221
    match table.get::<LuaValue>(key) {
222
        Ok(v) => shallow_convert_lua(&v),
223
        Err(_) => Value::Null,
224
    }
225
}
226
227
/// Materialise a Lua table *one level* into a concrete [`Value`] (ADR-21): a
228
/// sequence (`#t >= 1`) to a `Value::List` of `t[1..=#t]`; any other table to a
229
/// `Value::Context` of its string-keyed pairs (non-string keys and a mixed table's
230
/// hash part are dropped — the documented simplification). Members are
231
/// shallow-converted, so nested tables stay lazy.
232
fn lua_force(table: &Table) -> Value {
233
    let len = table.raw_len();
234
    if len > 0 {
235
        let mut items = Vec::with_capacity(len);
236
        for i in 1..=len {
237
            let v = table.get::<LuaValue>(i as i64).unwrap_or(LuaValue::Nil);
238
            items.push(shallow_convert_lua(&v));
239
        }
240
        return Value::List(items);
241
    }
242
    let mut map = BTreeMap::new();
243
    for pair in table.pairs::<LuaValue, LuaValue>() {
244
        if let Ok((LuaValue::String(k), v)) = pair {
245
            map.insert(k.to_string_lossy(), shallow_convert_lua(&v));
246
        }
247
    }
248
    Value::Context(map)
249
}
250
251
/// A lazily-resolved Lua table behind feel-core's [`ForeignObject`] seam. The owned
252
/// `Table` (mlua >= 0.10, no `'lua` lifetime) is `'static`, so it fits the
253
/// `Arc<dyn ForeignObject + 'static>` seam directly (ADR-22). Lua is single-threaded,
254
/// so the handle is used as-is (no token).
255
#[derive(Debug)]
256
struct LuaForeign {
257
    table: Table,
258
}
259
260
impl ForeignObject for LuaForeign {
261
    fn get(&self, key: &str) -> Value {
262
        lua_get_member(&self.table, key)
263
    }
264
265
    fn force(&self) -> Value {
266
        lua_force(&self.table)
267
    }
268
269
    fn as_any(&self) -> &dyn Any {
270
        self
271
    }
272
273
    /// Lua table identity for cycle detection in unbounded traversals (the
274
    /// descendant `...` operator). feel-lua mints a fresh `Arc<LuaForeign>` per wrap
275
    /// (`shallow_convert_lua` re-runs on every `force`/`get`), so the Rust allocation
276
    /// address is *not* stable; the underlying Lua table's pointer (stable across
277
    /// `Table::clone`, = the table's identity) is. `Table::to_pointer` exposes it.
278
    fn identity(&self) -> usize {
279
        self.table.to_pointer() as usize
280
    }
281
}
282
283
// --------------------------------------------------------------------------- //
284
// Host callables (ADR-23): a Lua function invoked from FEEL
285
// --------------------------------------------------------------------------- //
286
287
/// A Lua function behind feel-core's [`ForeignFunction`] seam. `func` is the
288
/// original `Function`, kept whole for identity pass-through on output.
289
#[derive(Debug)]
290
struct LuaForeignFn {
291
    func: mlua::Function,
292
}
293
294
impl ForeignFunction for LuaForeignFn {
295
    fn call(&self, args: Args) -> Value {
296
        // A raised Lua error / longjmp is caught by mlua and surfaced as `Err`,
297
        // which we map to an error-null (ADR-14/ADR-22) — never a silent value-null.
298
        lua_call(&self.func, args).unwrap_or(Value::Error)
299
    }
300
301
    fn as_any(&self) -> &dyn Any {
302
        self
303
    }
304
}
305
306
/// One marshalled FEEL argument, converted to a Lua value lazily via mlua's
307
/// [`IntoLua`](mlua::IntoLua). Converting on demand means the `&Lua` is the one
308
/// `Function::call` already holds — `ForeignFunction::call` is handed no state.
309
enum LuaArg<'a> {
310
    Pos(&'a Value),
311
    /// FEEL named arguments collapsed into a single trailing options table
312
    /// `{name = value}` — Lua has no kwargs, so this is the feel-wasm convention.
313
    NamedTable(&'a [(String, Value)]),
314
}
315
316
impl mlua::IntoLua for LuaArg<'_> {
317
    fn into_lua(self, lua: &Lua) -> mlua::Result<LuaValue> {
318
        match self {
319
            LuaArg::Pos(v) => value_to_lua(lua, v),
320
            LuaArg::NamedTable(named) => {
321
                let t = lua.create_table()?;
322
                for (k, v) in named {
323
                    t.set(k.as_str(), value_to_lua(lua, v)?)?;
324
                }
325
                Ok(LuaValue::Table(t))
326
            }
327
        }
328
    }
329
}
330
331
/// Invoke a Lua function with FEEL arguments (ADR-23): positional FEEL args become
332
/// positional Lua args; if any named args are present, a single trailing options
333
/// table `{name = value}` is appended. The return value is shallow-converted.
334
fn lua_call(func: &mlua::Function, args: Args) -> mlua::Result<Value> {
335
    let mut items: Vec<LuaArg> = args.positional.iter().map(LuaArg::Pos).collect();
336
    if !args.named.is_empty() {
337
        items.push(LuaArg::NamedTable(args.named.as_slice()));
338
    }
339
    let ret: LuaValue = func.call(Variadic::from_iter(items))?;
340
    Ok(shallow_convert_lua(&ret))
341
}
342
343
/// A host function registry backed by a Lua table `name -> function` (the third
344
/// `functions` argument; ADR-23). The ambient-function path, beside binding a
345
/// function directly in the context.
346
#[derive(Debug)]
347
struct LuaFunctionRegistry {
348
    funcs: Option<Table>,
349
}
350
351
impl FunctionRegistry for LuaFunctionRegistry {
352
    fn get(&self, name: &str) -> Option<Arc<dyn ForeignFunction>> {
353
        let funcs = self.funcs.as_ref()?;
354
        match funcs.get::<LuaValue>(name) {
355
            Ok(LuaValue::Function(f)) => Some(Arc::new(LuaForeignFn { func: f })),
356
            _ => None,
357
        }
358
    }
359
}
360
361
// --------------------------------------------------------------------------- //
362
// Result mapping (feel-core Value -> native Lua)
363
// --------------------------------------------------------------------------- //
364
365
/// Map a `feel-core` [`Value`] to a native Lua value. Integral numbers become Lua
366
/// integers (so `1 + 1` is `2`, not `2.0`); temporal values become ISO-8601 strings
367
/// (RD-8); error/value nulls become `nil`; a `Foreign`/`Function` that reached the
368
/// result is handed back **by identity** (the original table/function, untouched).
369
fn value_to_lua(lua: &Lua, value: &Value) -> mlua::Result<LuaValue> {
370
    Ok(match value {
371
        Value::Number(n) => number_to_lua(*n),
372
        Value::Boolean(b) => LuaValue::Boolean(*b),
373
        Value::String(s) => LuaValue::String(lua.create_string(s)?),
374
        Value::Null | Value::Error => LuaValue::Nil,
375
        Value::List(items) => {
376
            let t = lua.create_table()?;
377
            for (i, item) in items.iter().enumerate() {
378
                t.set(i as i64 + 1, value_to_lua(lua, item)?)?;
379
            }
380
            LuaValue::Table(t)
381
        }
382
        Value::Context(map) => {
383
            let t = lua.create_table()?;
384
            for (k, v) in map {
385
                t.set(k.as_str(), value_to_lua(lua, v)?)?;
386
            }
387
            LuaValue::Table(t)
388
        }
389
        // A range has no native Lua type; hand it back as a table carrying DMN's
390
        // four range properties (§10.3.4.6), so `r["start included"]` reads naturally.
391
        Value::Range(r) => {
392
            // An unbounded endpoint (`[1..)`/`(..10]`; ADR-31) maps to host `null` and
393
            // is never `included` (`±∞` is no member), regardless of the bracket.
394
            let t = lua.create_table()?;
395
            t.set("start", value_to_lua(lua, r.start.as_ref().unwrap_or(&Value::Null))?)?;
396
            t.set("end", value_to_lua(lua, r.end.as_ref().unwrap_or(&Value::Null))?)?;
397
            t.set("start included", r.start.is_some() && !r.start_open)?;
398
            t.set("end included", r.end.is_some() && !r.end_open)?;
399
            LuaValue::Table(t)
400
        }
401
        Value::Date(_)
402
        | Value::Time(_)
403
        | Value::DateTime(_)
404
        | Value::YearsMonthsDuration(_)
405
        | Value::DaysTimeDuration(_) => {
406
            let iso = feel_core::temporal::to_iso(value).unwrap_or_default();
407
            LuaValue::String(lua.create_string(&iso)?)
408
        }
409
        // Identity pass-through (ADR-21): a lazy host value that reached the result
410
        // is handed back as the *original* table, untouched. The downcast cannot
411
        // miss (`LuaForeign` is the only impl); fall back to forcing if it ever does.
412
        Value::Foreign(f) => match f.0.as_any().downcast_ref::<LuaForeign>() {
413
            Some(lf) => LuaValue::Table(lf.table.clone()),
414
            None => value_to_lua(lua, &f.0.force())?,
415
        },
416
        // A function value (ADR-23): a host callable is handed back as the original
417
        // Lua function (identity); a native FEEL closure has no Lua representation
418
        // and crosses out as `nil`.
419
        Value::Function(f) => match &**f {
420
            Func::Foreign(host_fn) => match host_fn.as_any().downcast_ref::<LuaForeignFn>() {
421
                Some(lf) => LuaValue::Function(lf.func.clone()),
422
                None => LuaValue::Nil,
423
            },
424
            Func::Closure(_) | Func::Builtin(_) => LuaValue::Nil,
425
        },
426
        // An opaque comparison-test value `(< 10)` (ADR-32) has no native Lua type;
427
        // like a native FEEL closure it crosses out as `nil`.
428
        Value::UnaryTestVal(_) => LuaValue::Nil,
429
    })
430
}
431
432
/// Map a FEEL number to a Lua value: an integral value in the exact-integer range
433
/// becomes a Lua integer, otherwise a Lua float (so `1 + 1` is `2`, not `2.0`).
434
fn number_to_lua(n: f64) -> LuaValue {
435
    if n.is_finite() && n.fract() == 0.0 && n.abs() < 9.007_199_254_740_992e15 {
436
        LuaValue::Integer(n as mlua::Integer)
437
    } else {
438
        LuaValue::Number(n)
439
    }
440
}