Public repository: timo / feel

Reader

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

feel / crates / feel-lua / src / lib.rs · 20.0 KB · at 93b43c1c833b · raw

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