Public repository: timo / feel

Reader

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

feat(core): add non-temporal multi-word builtin functions

public

feat(core): add non-temporal multi-word builtin functions

Now that the lexer joins multi-word names (ADR-17), wire up the dispatch arms
and implementations for the non-temporal multi-word builtins:

- string: string length, upper case, lower case, substring before,
  substring after, starts with, ends with, string join
- list:   list contains, index of, distinct values, insert before,
  list replace (positional form; the matching-function form needs function
  values and stays deferred per ADR-15)
- context: get value, get entries (over the existing Value::Context)

Semantics match the DMN-TCK level-3 fixtures (string join skips null items and
treats a scalar as a one-element list; substring before/after split at the first
match; get value returns null for an absent or present-null entry; list replace
truncates a fractional position). Error policy is unchanged (ADR-14): wrong
arity/type/domain and the still-unimplemented temporal phrases are error-nulls.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Changeset8c9458293de350d04ae0ce4dc0e94ab760dde518
Author (claimed)Timo Stolz <timo.stolz@gmail.com>,
Parentsc1abc8bcec97
Children
Pushlog
by timo via ssh

modified crates/feel-core/src/builtins.rs +238 −2

@@ -1,5 +1,8 @@
1
-//! Built-in functions — the single-word, non-temporal slice (DECISIONS.md
2
-//! ADR-15).
1
+//! Built-in functions — the non-temporal slice (DECISIONS.md ADR-15/ADR-17).
2
+//!
3
+//! Single-word (`abs`, `count`) and multi-word (`string length`, `list
4
+//! contains`, `get value`) names alike; the lexer hands a space-normalised name
5
+//! string here, so dispatch is a plain match either way (ADR-17).
36
 //!
47
 //! Dispatch is by name + arity. Error policy follows ADR-14: a type/arity/domain
58
 //! error (or an unknown function) is an *error-null* (`Value::Error`), while a
@@ -18,6 +21,7 @@
1821
 //! match/replace/split itself live in the provider.
1922
 
2023
 use std::cmp::Ordering;
24
+use std::collections::BTreeMap;
2125
 
2226
 use crate::eval::{as_number, feel_order};
2327
 use crate::regex_provider::{match_value, FeelRegex};
@@ -50,6 +54,14 @@
5054
         "replace" => replace_fn(args, regex),
5155
         "split" => split_fn(args, regex),
5256
         "matches" => matches_fn(args, regex),
57
+        "string length" => string_length_fn(args),
58
+        "upper case" => case_fn(args, true),
59
+        "lower case" => case_fn(args, false),
60
+        "substring before" => substring_before_after_fn(args, true),
61
+        "substring after" => substring_before_after_fn(args, false),
62
+        "starts with" => starts_ends_with_fn(args, true),
63
+        "ends with" => starts_ends_with_fn(args, false),
64
+        "string join" => string_join_fn(args),
5365
 
5466
         // --- list ---
5567
         "count" => count_fn(args),
@@ -70,6 +82,15 @@
7082
         "reverse" => reverse_fn(args),
7183
         "flatten" => flatten_fn(args),
7284
         "sublist" => sublist_fn(args),
85
+        "list contains" => list_contains_fn(args),
86
+        "index of" => index_of_fn(args),
87
+        "distinct values" => distinct_values_fn(args),
88
+        "insert before" => insert_before_fn(args),
89
+        "list replace" => list_replace_fn(args),
90
+
91
+        // --- context ---
92
+        "get value" => get_value_fn(args),
93
+        "get entries" => get_entries_fn(args),
7394
 
7495
         // --- numeric ---
7596
         "decimal" => decimal_fn(args),
@@ -293,6 +314,92 @@
293314
     }
294315
 }
295316
 
317
+fn string_length_fn(args: Vec<Value>) -> Value {
318
+    match args.as_slice() {
319
+        // FEEL string length counts code points, not UTF-8 bytes.
320
+        [Value::String(s)] => Value::Number(s.chars().count() as f64),
321
+        [Value::Null] => Value::Null,
322
+        _ => Value::Error,
323
+    }
324
+}
325
+
326
+fn case_fn(args: Vec<Value>, upper: bool) -> Value {
327
+    match args.as_slice() {
328
+        [Value::String(s)] => {
329
+            Value::String(if upper { s.to_uppercase() } else { s.to_lowercase() })
330
+        }
331
+        [Value::Null] => Value::Null,
332
+        _ => Value::Error,
333
+    }
334
+}
335
+
336
+fn starts_ends_with_fn(args: Vec<Value>, starts: bool) -> Value {
337
+    match args.as_slice() {
338
+        [Value::String(s), Value::String(m)] => Value::Boolean(if starts {
339
+            s.starts_with(m.as_str())
340
+        } else {
341
+            s.ends_with(m.as_str())
342
+        }),
343
+        [Value::Null, _] | [_, Value::Null] => Value::Null,
344
+        _ => Value::Error,
345
+    }
346
+}
347
+
348
+/// `substring before`/`substring after`: split `string` at the **first**
349
+/// occurrence of `match`. Not found (for a non-empty match) is `""`. An empty
350
+/// match sits at position 0, so `before` is `""` and `after` is the whole string.
351
+fn substring_before_after_fn(args: Vec<Value>, before: bool) -> Value {
352
+    match args.as_slice() {
353
+        [Value::String(s), Value::String(m)] => {
354
+            // A byte offset from `find` is always a valid char boundary because it
355
+            // is the start of an actual substring match.
356
+            let part = match s.find(m.as_str()) {
357
+                Some(p) if before => &s[..p],
358
+                Some(p) => &s[p + m.len()..],
359
+                None => "",
360
+            };
361
+            Value::String(part.to_string())
362
+        }
363
+        [Value::Null, _] | [_, Value::Null] => Value::Null,
364
+        _ => Value::Error,
365
+    }
366
+}
367
+
368
+/// `string join(list[, delimiter])`: concatenate the string items of `list`,
369
+/// joined by `delimiter` (absent/null → no separator). Null items are skipped; a
370
+/// non-string, non-null item is a type error. A scalar string argument is treated
371
+/// as a one-element list. Other arities (0, 3, …) and non-list/-string arguments
372
+/// are errors (per DMN-TCK 1140).
373
+fn string_join_fn(args: Vec<Value>) -> Value {
374
+    let (list_v, delim) = match args.as_slice() {
375
+        [l] => (l, String::new()),
376
+        [l, d] => {
377
+            let d = match d {
378
+                Value::String(s) => s.clone(),
379
+                Value::Null => String::new(),
380
+                _ => return Value::Error,
381
+            };
382
+            (l, d)
383
+        }
384
+        _ => return Value::Error,
385
+    };
386
+    let items = match list_v {
387
+        Value::List(items) => items.clone(),
388
+        Value::String(s) => vec![Value::String(s.clone())],
389
+        Value::Null => return Value::Null,
390
+        _ => return Value::Error,
391
+    };
392
+    let mut parts: Vec<String> = Vec::new();
393
+    for it in &items {
394
+        match it {
395
+            Value::String(s) => parts.push(s.clone()),
396
+            Value::Null => {} // null entries are skipped
397
+            _ => return Value::Error,
398
+        }
399
+    }
400
+    Value::String(parts.join(&delim))
401
+}
402
+
296403
 // --------------------------------------------------------------------------- //
297404
 // String (regex) — dialect-dependent; the actual engine is the host's (ADR-16).
298405
 // These functions only sort out the FEEL argument shapes and hand pattern +
@@ -688,6 +795,135 @@
688795
     Value::List(items[from0 as usize..(from0 + take) as usize].to_vec())
689796
 }
690797
 
798
+fn list_contains_fn(args: Vec<Value>) -> Value {
799
+    match args.as_slice() {
800
+        [Value::List(items), e] => Value::Boolean(items.iter().any(|x| x == e)),
801
+        [Value::Null, _] => Value::Null,
802
+        _ => Value::Error,
803
+    }
804
+}
805
+
806
+/// `index of(list, match)`: the 1-based positions where an element equals `match`
807
+/// (FEEL equality), as a list (empty if none).
808
+fn index_of_fn(args: Vec<Value>) -> Value {
809
+    match args.as_slice() {
810
+        [Value::List(items), m] => Value::List(
811
+            items
812
+                .iter()
813
+                .enumerate()
814
+                .filter(|(_, x)| *x == m)
815
+                .map(|(i, _)| Value::Number((i + 1) as f64))
816
+                .collect(),
817
+        ),
818
+        [Value::Null, _] => Value::Null,
819
+        _ => Value::Error,
820
+    }
821
+}
822
+
823
+/// `distinct values(list)`: drop duplicates (FEEL equality), keeping first order.
824
+fn distinct_values_fn(args: Vec<Value>) -> Value {
825
+    match args.as_slice() {
826
+        [Value::List(items)] => {
827
+            let mut out: Vec<Value> = Vec::new();
828
+            for it in items {
829
+                if !out.iter().any(|x| x == it) {
830
+                    out.push(it.clone());
831
+                }
832
+            }
833
+            Value::List(out)
834
+        }
835
+        [Value::Null] => Value::Null,
836
+        _ => Value::Error,
837
+    }
838
+}
839
+
840
+/// `insert before(list, position, newItem)`: insert `newItem` so it ends up at
841
+/// `position` (1-based, negative from the end). The position must address an
842
+/// existing element; out of range is an error.
843
+fn insert_before_fn(args: Vec<Value>) -> Value {
844
+    match args.as_slice() {
845
+        [Value::List(items), pos_v, new_item] => {
846
+            let pos = match num_arg(pos_v) {
847
+                NumArg::Num(p) => p.trunc() as i64,
848
+                NumArg::Null => return Value::Null,
849
+                NumArg::Err => return Value::Error,
850
+            };
851
+            let n = items.len() as i64;
852
+            match resolve_index(pos, n) {
853
+                Some(idx) if idx < n => {
854
+                    let mut out = items.clone();
855
+                    out.insert(idx as usize, new_item.clone());
856
+                    Value::List(out)
857
+                }
858
+                _ => Value::Error,
859
+            }
860
+        }
861
+        [Value::Null, _, _] => Value::Null,
862
+        _ => Value::Error,
863
+    }
864
+}
865
+
866
+/// `list replace(list, position, newItem)` — the positional form only; the
867
+/// matching-function form needs function values and stays deferred (ADR-15). A
868
+/// scalar `list` is treated as a one-element list (per DMN-TCK 1155).
869
+fn list_replace_fn(args: Vec<Value>) -> Value {
870
+    let [list_v, pos_v, new_item] = args.as_slice() else {
871
+        return Value::Error;
872
+    };
873
+    let mut items = match list_v {
874
+        Value::List(items) => items.clone(),
875
+        Value::Null => return Value::Null,
876
+        other => vec![other.clone()],
877
+    };
878
+    let pos = match num_arg(pos_v) {
879
+        NumArg::Num(p) => p.trunc() as i64,
880
+        NumArg::Null => return Value::Null,
881
+        NumArg::Err => return Value::Error,
882
+    };
883
+    let n = items.len() as i64;
884
+    match resolve_index(pos, n) {
885
+        Some(idx) if idx < n => {
886
+            items[idx as usize] = new_item.clone();
887
+            Value::List(items)
888
+        }
889
+        _ => Value::Error,
890
+    }
891
+}
892
+
893
+// --------------------------------------------------------------------------- //
894
+// Context
895
+// --------------------------------------------------------------------------- //
896
+
897
+/// `get value(context, key)`: the value bound to `key`, or `null` if absent
898
+/// (including a present `null` value). A non-context or non-string key is an
899
+/// error (per DMN-TCK 0080).
900
+fn get_value_fn(args: Vec<Value>) -> Value {
901
+    match args.as_slice() {
902
+        [Value::Context(map), Value::String(key)] => map.get(key).cloned().unwrap_or(Value::Null),
903
+        [Value::Null, _] | [Value::Context(_), Value::Null] => Value::Null,
904
+        _ => Value::Error,
905
+    }
906
+}
907
+
908
+/// `get entries(context)`: a list of `{key, value}` contexts, one per entry, in
909
+/// key order (per DMN-TCK 0081).
910
+fn get_entries_fn(args: Vec<Value>) -> Value {
911
+    match args.as_slice() {
912
+        [Value::Context(map)] => Value::List(
913
+            map.iter()
914
+                .map(|(k, v)| {
915
+                    let mut entry = BTreeMap::new();
916
+                    entry.insert("key".to_string(), Value::String(k.clone()));
917
+                    entry.insert("value".to_string(), v.clone());
918
+                    Value::Context(entry)
919
+                })
920
+                .collect(),
921
+        ),
922
+        [Value::Null] => Value::Null,
923
+        _ => Value::Error,
924
+    }
925
+}
926
+
691927
 // --------------------------------------------------------------------------- //
692928
 // Numeric
693929
 // --------------------------------------------------------------------------- //

modified crates/feel-core/src/lib.rs +79 −0

@@ -595,6 +595,85 @@
595595
         assert_eq!(ev("now()"), Value::Null); // temporal, not yet implemented
596596
     }
597597
 
598
+    #[test]
599
+    fn multi_word_builtin_functions() {
600
+        use std::collections::BTreeMap;
601
+        let s = |v: &str| Value::String(v.to_string());
602
+        let ctx_val = |pairs: &[(&str, Value)]| {
603
+            Value::Context(
604
+                pairs
605
+                    .iter()
606
+                    .map(|(k, v)| (k.to_string(), v.clone()))
607
+                    .collect::<BTreeMap<_, _>>(),
608
+            )
609
+        };
610
+
611
+        // --- string (multi-word) --- (spec §10.3.4.1)
612
+        assert_eq!(ev(r#"string length("abc")"#), num(3.0));
613
+        assert_eq!(ev(r#"string length("aaaaa dddd ")"#), num(11.0)); // trailing space counts
614
+        assert_eq!(ev(r#"upper case("aBc")"#), s("ABC"));
615
+        assert_eq!(ev(r#"lower case("aBc4")"#), s("abc4"));
616
+        assert_eq!(ev(r#"substring before("foobar", "bar")"#), s("foo"));
617
+        assert_eq!(ev(r#"substring before("abc", "a")"#), s("")); // match at start
618
+        assert_eq!(ev(r#"substring before("foobar", "x")"#), s("")); // not found
619
+        assert_eq!(ev(r#"substring after("foobar", "ob")"#), s("ar"));
620
+        assert_eq!(ev(r#"substring after("abc", "")"#), s("abc")); // empty match
621
+        assert_eq!(ev(r#"starts with("foobar", "foo")"#), b(true));
622
+        assert_eq!(ev(r#"starts with("foobar", "x")"#), b(false));
623
+        assert_eq!(ev(r#"ends with("foobar", "bar")"#), b(true));
624
+        assert_eq!(ev(r#"string join(["a","b","c"])"#), s("abc"));
625
+        assert_eq!(ev(r#"string join(["a","b","c"], " and ")"#), s("a and b and c"));
626
+        assert_eq!(ev(r#"string join(["a","b","c"], null)"#), s("abc")); // null delim = ""
627
+        assert_eq!(ev(r#"string join(["a",null,"c"], "X")"#), s("aXc")); // null items skipped
628
+        assert_eq!(ev("string join([])"), s("")); // empty list -> empty string
629
+        assert_eq!(ev(r#"string join("a", "X")"#), s("a")); // scalar -> one-element list
630
+        assert_eq!(ev("string join()"), Value::Null); // wrong arity -> null
631
+        assert_eq!(ev(r#"string join([1,2,3], "X")"#), Value::Null); // non-string items -> null
632
+
633
+        // --- list (multi-word) --- (spec §10.3.4.4)
634
+        assert_eq!(ev("list contains([1,2,3], 2)"), b(true));
635
+        assert_eq!(ev("list contains([1,2,3], 9)"), b(false));
636
+        assert_eq!(ev("list contains([[1,2],[3]], [3])"), b(true)); // structural element
637
+        assert_eq!(ev("index of([1,2,3,2], 2)"), list(vec![num(2.0), num(4.0)]));
638
+        assert_eq!(ev("index of([1,2,3], 9)"), list(vec![]));
639
+        assert_eq!(
640
+            ev("distinct values([1,2,3,2,1])"),
641
+            list(vec![num(1.0), num(2.0), num(3.0)])
642
+        );
643
+        assert_eq!(
644
+            ev("insert before([1,2,3], 1, 4)"),
645
+            list(vec![num(4.0), num(1.0), num(2.0), num(3.0)])
646
+        );
647
+        assert_eq!(
648
+            ev("insert before([1,2,3], 3, 4)"),
649
+            list(vec![num(1.0), num(2.0), num(4.0), num(3.0)])
650
+        );
651
+        assert_eq!(ev("list replace([1,2,3], 2, 4)"), list(vec![num(1.0), num(4.0), num(3.0)]));
652
+        assert_eq!(ev("list replace([1,2,3], -1, 4)"), list(vec![num(1.0), num(2.0), num(4.0)]));
653
+        assert_eq!(ev("list replace([1,2,3], 0, 4)"), Value::Null); // position 0 invalid
654
+        assert_eq!(
655
+            ev("list replace([1,2,3], 2.5, 4)"), // position truncates toward zero
656
+            list(vec![num(1.0), num(4.0), num(3.0)])
657
+        );
658
+
659
+        // --- context (multi-word) --- (spec §10.3.4.6)
660
+        assert_eq!(ev(r#"get value({a: "foo"}, "a")"#), s("foo"));
661
+        assert_eq!(ev(r#"get value({a: "foo"}, "z")"#), Value::Null); // absent key
662
+        assert_eq!(ev(r#"get value({a: null}, "a")"#), Value::Null); // present null value
663
+        assert_eq!(ev(r#"get value("foo", "a")"#), Value::Null); // not a context -> null
664
+        assert_eq!(
665
+            ev(r#"get entries({a: "foo", b: "bar"})"#),
666
+            list(vec![
667
+                ctx_val(&[("key", s("a")), ("value", s("foo"))]),
668
+                ctx_val(&[("key", s("b")), ("value", s("bar"))]),
669
+            ])
670
+        );
671
+        assert_eq!(ev("get entries({})"), list(vec![]));
672
+
673
+        // --- keyword-phrase temporal builtin: parses, still error-null (lenient) ---
674
+        assert_eq!(ev(r#"date and time("2018-12-08")"#), Value::Null);
675
+    }
676
+
598677
     // The regex builtins are dialect-dependent (ADR-16): under the default
599678
     // `rust-regex` provider they keep the Rust-dialect results recorded in
600679
     // ADR-15; under `--no-default-features` (no provider) they evaluate to null.