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 · 22.1 KB · at da382279c66c · raw

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