rulesxp 0.3.1

Multi-language rules expression evaluator supporting JSONLogic and Scheme with strict typing
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
/*
 This module defines the core Abstract Syntax Tree (AST) types and helper functions
 for representing values in the interpreter. The main enum, [`Value`], covers
 all Scheme data types, including numbers, symbols, strings, booleans, lists, built-in
 and user-defined functions, and precompiled operations. Ergonomic helper functions
 such as [`val`], [`sym`], and [`nil`] are provided for convenient AST construction
 in both code and tests. The module also implements conversion traits for common Rust
 types, making it easy to build Values from Rust literals, arrays, slices, and
 vectors. Equality and display logic are customized to match Scheme semantics, including
 round-trip compatibility for precompiled operations.
*/

use crate::Error;
use crate::builtinops::BuiltinOp;
use crate::evaluator::intooperation::OperationFn;

/// Type alias for number values in interpreter
pub(crate) type NumberType = i64;

/// Allowed non-alphanumeric characters in Scheme symbol names
/// Most represent mathematical symbols or predicates ("?"), "$" supported for JavaScript identifiers
#[cfg(any(feature = "scheme", feature = "jsonlogic"))]
pub(crate) const SYMBOL_SPECIAL_CHARS: &str = "+-*/<>=!?_$";

/// Check if a string is a valid symbol name
/// Valid: non-empty, no leading digit, no "-digit" prefix, alphanumeric + SYMBOL_SPECIAL_CHARS
/// Note: This function is tested as part of the parser tests in parser.rs
#[cfg(any(feature = "scheme", feature = "jsonlogic"))]
pub(crate) fn is_valid_symbol(name: &str) -> bool {
    let mut chars = name.chars();

    match chars.next() {
        None => false, // name is empty
        Some(first_char) => {
            if first_char.is_ascii_digit() {
                return false;
            }

            if first_char == '-'
                && let Some(second_char) = chars.next()
                && second_char.is_ascii_digit()
            {
                return false;
            }

            // Check all characters are valid
            // The first character is checked here again, but it's a cheap operation.
            name.chars()
                .all(|c| c.is_alphanumeric() || SYMBOL_SPECIAL_CHARS.contains(c))
        }
    }
}

/// Core AST type in interpreter
///
/// Note: PrecompiledOps (optimized s-expressions) don't equality-compare to dynamically
/// generated unoptimized s-expressions. However, since no expression can *return* a
/// PrecompiledOp (they're consumed during evaluation), this is not a concern for user code.
///
/// To build an AST, use the ergonomic helper functions:
/// - `val(42)` for values, `sym("name")` for symbols, `nil()` for empty lists
/// - `val([1, 2, 3])` for homogeneous lists
/// - `val(vec![sym("op"), val(42)])` for mixed lists
#[derive(Clone)]
pub enum Value {
    /// Numbers (integers only)
    Number(NumberType),
    /// Symbols (identifiers)
    Symbol(String),
    /// String literals
    String(String),
    /// Boolean values
    Bool(bool),
    /// Lists (including proper and improper lists, empty list represents nil)
    List(Vec<Value>),
    /// Pre-compiled operations with their arguments (optimized during parsing)
    PrecompiledOp {
        op: &'static BuiltinOp,
        op_id: String,
        args: Vec<Value>,
    },
    /// Built-in functions (used when called through Symbol, not pre-optimized due to dynamism)
    /// Uses id string for equality comparison instead of function pointer
    BuiltinFunction {
        id: String,
        // Stored as an Arc to allow dynamic wrapping of typed Rust functions/closures.
        // Trait object enables registering strongly typed functions (e.g. fn(i64, i64)->i64)
        // that are automatically converted to the canonical evaluator signature.
        func: std::sync::Arc<OperationFn>,
    },
    /// User-defined functions (params, body, closure env)
    Function {
        params: Vec<String>,
        body: Box<Value>,
        env: crate::evaluator::Environment,
    },
    /// Unspecified values (e.g., return value of define)
    /// These values never equal themselves or any other value
    Unspecified,
}

impl std::fmt::Debug for Value {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Value::Number(n) => write!(f, "Number({n})"),
            Value::Symbol(s) => write!(f, "Symbol({s})"),
            Value::String(s) => write!(f, "String(\"{s}\")"),
            Value::Bool(b) => write!(f, "Bool({b})"),
            Value::List(list) => {
                write!(f, "List(")?;
                for (i, v) in list.iter().enumerate() {
                    if i > 0 {
                        write!(f, ", ")?;
                    }
                    write!(f, "{v:?}")?;
                }
                write!(f, ")")
            }
            Value::PrecompiledOp { op_id, args, .. } => {
                write!(f, "PrecompiledOp({op_id}, args=[")?;
                for (i, a) in args.iter().enumerate() {
                    if i > 0 {
                        write!(f, ", ")?;
                    }
                    write!(f, "{a:?}")?;
                }
                write!(f, "])")
            }
            Value::BuiltinFunction { id, .. } => write!(f, "BuiltinFunction({id})"),
            Value::Function { params, body, .. } => {
                write!(f, "Function(params={params:?}, body={body:?})")
            }
            Value::Unspecified => write!(f, "Unspecified"),
        }
    }
}

// From trait implementations for Value - enables .into() conversion
impl From<&str> for Value {
    fn from(s: &str) -> Self {
        Value::String(s.to_owned())
    }
}

impl From<String> for Value {
    fn from(s: String) -> Self {
        Value::String(s)
    }
}

impl From<bool> for Value {
    fn from(b: bool) -> Self {
        Value::Bool(b)
    }
}

macro_rules! impl_from_integer {
    ($int_type:ty) => {
        impl From<$int_type> for Value {
            fn from(n: $int_type) -> Self {
                Value::Number(n as i64)
            }
        }
    };
}

// Generate From implementations for all integer types
impl_from_integer!(i8);
impl_from_integer!(i16);
impl_from_integer!(i32);
impl_from_integer!(NumberType); // Special case - no casting
impl_from_integer!(u8);
impl_from_integer!(u16);
impl_from_integer!(u32);

impl<T: Into<Value>> From<Vec<T>> for Value {
    fn from(v: Vec<T>) -> Self {
        Value::List(v.into_iter().map(|x| x.into()).collect())
    }
}

impl<T: Into<Value>, const N: usize> From<[T; N]> for Value {
    fn from(arr: [T; N]) -> Self {
        Value::List(arr.into_iter().map(|x| x.into()).collect())
    }
}

impl<T: Into<Value> + Clone> From<&[T]> for Value {
    fn from(slice: &[T]) -> Self {
        Value::List(slice.iter().cloned().map(|x| x.into()).collect())
    }
}

// Fallible conversions from `Value` back into primitive Rust types.

impl std::convert::TryInto<NumberType> for Value {
    type Error = Error;

    fn try_into(self) -> Result<NumberType, Error> {
        if let Value::Number(n) = self {
            Ok(n)
        } else {
            Err(Error::TypeError("expected number".into()))
        }
    }
}

impl std::convert::TryInto<bool> for Value {
    type Error = Error;

    fn try_into(self) -> Result<bool, Error> {
        if let Value::Bool(b) = self {
            Ok(b)
        } else {
            Err(Error::TypeError("expected boolean".into()))
        }
    }
}

///   Helper function for creating symbols - works great in mixed lists!
///   Accepts both &str and String via Into<&str>
#[cfg_attr(not(test), expect(dead_code))]
pub(crate) fn sym<S: AsRef<str>>(name: S) -> Value {
    Value::Symbol(name.as_ref().to_owned())
}

/// Helper function for creating Values - works great in mixed lists!
/// Accepts any type that can be converted to Value
#[cfg_attr(not(test), expect(dead_code))]
pub(crate) fn val<T: Into<Value>>(value: T) -> Value {
    value.into()
}

/// Helper function for creating empty lists (nil) - follows Lisp/Scheme conventions
/// In Lisp, nil represents the empty list
#[cfg_attr(not(test), expect(dead_code))]
pub(crate) fn nil() -> Value {
    Value::List(vec![])
}

impl std::fmt::Display for Value {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Value::Number(n) => write!(f, "{n}"),
            Value::Symbol(s) => write!(f, "{s}"),
            Value::String(s) => {
                write!(f, "\"")?;
                for ch in s.chars() {
                    match ch {
                        '"' => write!(f, "\\\"")?,
                        '\\' => write!(f, "\\\\")?,
                        '\n' => write!(f, "\\n")?,
                        '\t' => write!(f, "\\t")?,
                        '\r' => write!(f, "\\r")?,
                        c => write!(f, "{c}")?,
                    }
                }
                write!(f, "\"")
            }
            Value::Bool(b) => write!(f, "{}", if *b { "#t" } else { "#f" }),
            Value::List(elements) => {
                write!(f, "(")?;
                for (i, elem) in elements.iter().enumerate() {
                    if i > 0 {
                        write!(f, " ")?;
                    }
                    write!(f, "{elem}")?;
                }
                write!(f, ")")
            }
            Value::BuiltinFunction { id, .. } => write!(f, "#<builtin-function:{id}>"),
            Value::PrecompiledOp { .. } => {
                // Display PrecompiledOp as parseable list form for round-trip compatibility
                write!(f, "{}", self.to_uncompiled_form())
            }
            Value::Function { .. } => write!(f, "#<function>"),
            Value::Unspecified => write!(f, "#<unspecified>"),
        }
    }
}

impl Value {
    /// Convert PrecompiledOp back to List form for display purposes
    pub(crate) fn to_uncompiled_form(&self) -> Value {
        match self {
            Value::PrecompiledOp { op, args, .. } => {
                let mut elements = vec![Value::Symbol(op.scheme_id.to_owned())];
                for arg in args {
                    elements.push(arg.to_uncompiled_form()); // Recursively convert nested PrecompiledOps
                }
                Value::List(elements)
            }
            Value::List(elements) => {
                // Recursively convert nested elements
                Value::List(
                    elements
                        .iter()
                        .map(|elem| elem.to_uncompiled_form())
                        .collect(),
                )
            }
            other => other.clone(), // Leave other types unchanged
        }
    }

    /// Check if a value represents nil (empty list)
    pub(crate) fn is_nil(&self) -> bool {
        matches!(self, Value::List(list) if list.is_empty())
    }
}

impl PartialEq for Value {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (Value::Number(a), Value::Number(b)) => a == b,
            (Value::Symbol(a), Value::Symbol(b)) => a == b,
            (Value::String(a), Value::String(b)) => a == b,
            (Value::Bool(a), Value::Bool(b)) => a == b,
            (Value::List(a), Value::List(b)) => a == b,
            (
                Value::PrecompiledOp {
                    op_id: id1,
                    args: args1,
                    ..
                },
                Value::PrecompiledOp {
                    op_id: id2,
                    args: args2,
                    ..
                },
            ) => {
                // Compare PrecompiledOps by id string, not function pointer
                id1 == id2 && args1 == args2
            }
            (Value::BuiltinFunction { id: id1, .. }, Value::BuiltinFunction { id: id2, .. }) => {
                // Compare BuiltinFunctions by id string, not function pointer
                id1 == id2
            }
            (
                Value::Function {
                    params: p1,
                    body: b1,
                    env: e1,
                },
                Value::Function {
                    params: p2,
                    body: b2,
                    env: e2,
                },
            ) => p1 == p2 && b1 == b2 && e1 == e2,
            (Value::Unspecified, _) | (_, Value::Unspecified) => false, // Unspecified never equals anything
            _ => false, // Different variants are never equal
        }
    }
}

#[cfg(test)]
mod helper_function_tests {
    use super::*;

    #[test]
    fn test_helper_functions_data_driven() {
        // Test cases as (Value, Value) tuples: (helper_result, expected_value)
        let test_cases = vec![
            // Basic numbers
            (val(42), Value::Number(42)),
            (val(-17), Value::Number(-17)),
            (val(-0), Value::Number(0)),
            // Different integer types from macro
            (val(4294967295u32), Value::Number(4294967295)),
            (val(2147483647i32), Value::Number(2147483647)),
            (val(255u8), Value::Number(255)),
            (val(-128i8), Value::Number(-128)),
            (val(65535u16), Value::Number(65535)),
            (val(-32768i16), Value::Number(-32768)),
            (val(NumberType::MAX), Value::Number(NumberType::MAX)),
            (val(NumberType::MIN), Value::Number(NumberType::MIN)),
            // Basic booleans
            (val(true), Value::Bool(true)),
            (val("hello"), Value::String("hello".to_owned())),
            (val(""), Value::String(String::new())),
            // Sym, from both &str and String
            (sym("foo-bar?"), Value::Symbol("foo-bar?".to_owned())),
            (sym("-"), Value::Symbol("-".to_owned())),
            (sym(String::from("test")), Value::Symbol("test".to_owned())),
            // Empty list (nil)
            (nil(), Value::List(vec![])),
            // Lists from arrays and vecs of primitives
            (
                val([1, 2, 3]),
                Value::List(vec![Value::Number(1), Value::Number(2), Value::Number(3)]),
            ),
            (
                val(["hello", "world"]),
                Value::List(vec![
                    Value::String("hello".to_owned()),
                    Value::String("world".to_owned()),
                ]),
            ),
            (
                val([true, false, true]),
                Value::List(vec![
                    Value::Bool(true),
                    Value::Bool(false),
                    Value::Bool(true),
                ]),
            ),
            // Mixed type lists using helper functions
            (
                val(vec![sym("operation"), val(42), val("result"), val(true)]),
                Value::List(vec![
                    Value::Symbol("operation".to_owned()),
                    Value::Number(42),
                    Value::String("result".to_owned()),
                    Value::Bool(true),
                ]),
            ),
            // From<&[T]> slice conversion
            (
                Value::from(&[1i64, 2, 3][..]),
                Value::List(vec![Value::Number(1), Value::Number(2), Value::Number(3)]),
            ),
        ];

        run_helper_function_tests(test_cases);
    }

    /// Helper function to run data-driven tests for helper functions
    fn run_helper_function_tests(test_cases: Vec<(Value, Value)>) {
        for (i, (actual, expected)) in test_cases.iter().enumerate() {
            assert!(
                !(actual != expected),
                "Test case {} failed:\n  Expected: {:?}\n  Got: {:?}",
                i + 1,
                expected,
                actual
            );
        }
    }

    #[test]
    fn test_unspecified_values() {
        // Unspecified never equals anything, including itself
        let unspec = Value::Unspecified;
        assert_ne!(unspec, unspec);
        assert_ne!(unspec, Value::Unspecified);
        assert_ne!(unspec, val(42));
    }

    #[test]
    #[cfg(feature = "scheme")]
    fn test_debug_display_and_equality() {
        use crate::evaluator::{create_global_env, eval};
        use crate::scheme::parse_scheme;

        let mut env = create_global_env();
        eval(&parse_scheme("(define f +)").unwrap(), &mut env).unwrap();
        let builtin_fn = eval(&parse_scheme("f").unwrap(), &mut env).unwrap();
        let func = eval(&parse_scheme("(lambda (x) (+ x 1))").unwrap(), &mut env).unwrap();
        let precompiled = parse_scheme("(+ 1 2)").unwrap();

        let list_val = val([1, 2, 3]);

        // Debug: (value, expected_substring)
        let debug_cases: Vec<(&Value, &str)> = vec![
            (&list_val, "List("),
            (&precompiled, "PrecompiledOp"),
            (&builtin_fn, "BuiltinFunction"),
            (&func, "Function"),
            (&Value::Unspecified, "Unspecified"),
        ];
        for (value, expected) in &debug_cases {
            assert!(
                format!("{value:?}").contains(expected),
                "Debug of {value:?} should contain '{expected}'"
            );
        }

        // Display: (value, expected_substring)
        let display_cases: Vec<(&Value, &str)> = vec![
            (&builtin_fn, "#<builtin-function:"),
            (&func, "#<function>"),
            (&Value::Unspecified, "#<unspecified>"),
        ];
        for (value, expected) in &display_cases {
            assert!(
                format!("{value}").contains(expected),
                "Display of {value} should contain '{expected}'"
            );
        }

        // PartialEq: one test per uncovered match arm
        let mut env2 = create_global_env();
        eval(&parse_scheme("(define f2 +)").unwrap(), &mut env2).unwrap();
        assert!(builtin_fn == eval(&parse_scheme("f2").unwrap(), &mut env2).unwrap());

        let func_b = eval(&parse_scheme("(lambda (x) (+ x 1))").unwrap(), &mut env).unwrap();
        assert!(func == func_b);

        assert!(precompiled == parse_scheme("(+ 1 2)").unwrap());

        assert!(builtin_fn != func); // cross-variant catch-all arm

        // Error Display: (error, expected_substring)
        let error_cases: Vec<(crate::Error, &str)> = vec![
            (
                crate::Error::arity_error_with_expr(2, 3, "x".into()),
                "Arity error",
            ),
            (crate::Error::ParseError("x".into()), "Parse error"),
            (crate::Error::arity_error(2, 3), "Arity error"),
        ];
        for (error, expected) in &error_cases {
            assert!(
                format!("{error}").contains(expected),
                "Error '{error}' should contain '{expected}'"
            );
        }
    }
}