Public repository: timo / feel

Reader

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

feat(core): named arguments for built-in functions (ADR-23, spec §10.3.2.13.5)

public

feat(core): named arguments for built-in functions (ADR-23, spec §10.3.2.13.5)

The FEEL spec allows named arguments for built-ins too, not only for
user-defined functions. Add a per-built-in formal-parameter-name table
(builtin_param_names, names taken verbatim from the spec §10.3.4 tables) and
implement the reorder_named seam left as a stub by the previous commit: it
slots positional and named arguments into the built-in's positional order,
binds unsupplied params to null, and returns None (→ error-null / registry
fallback) for an unknown parameter name, a doubly-supplied parameter, too many
positional args, or a name with no table (the purely variadic aggregates
min/max/sum/… which the spec gives no single named-parameter form).

So substring(string: "foobar", start position: 3) now equals substring("foobar", 3).

Tests: named built-in calls across string/list/numeric/context categories,
order independence, optional-arg omission, unknown-name and variadic-name
rejection.

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

modified crates/feel-core/src/builtins.rs +150 −7

@@ -155,15 +155,158 @@
155155
     })
156156
 }
157157
 
158
+/// Formal parameter names, in positional order, for each named-callable built-in
159
+/// (FEEL spec §10.3.4 tables). The names are taken verbatim from the spec so that
160
+/// `substring(string: "foobar", start position: 3)` matches exactly.
161
+///
162
+/// Purely variadic / dual-form aggregates (`min`, `max`, `sum`, `mean`, `product`,
163
+/// `median`, `stddev`, `mode`, `all`, `any`) and varargs list builders (`append`,
164
+/// `concatenate`, `union`) are **not** in this table: the spec gives them no single
165
+/// named-parameter form, and a named call to them should be an error-null.
166
+///
167
+/// `context put` has two overloads (`key: string` vs `keys: list`); both share the
168
+/// same three-element positional signature, so a single row covers both.
169
+fn builtin_param_names(name: &str) -> Option<&'static [&'static str]> {
170
+    // Spec §10.3.4.1 — conversion functions
171
+    // `number(from)` and `number(from, grouping separator, decimal separator)`
172
+    // share the same positional order; named callers must supply matching names.
173
+    // `date and time(from)` and `date and time(date, time)` are overloaded; the
174
+    // 3-slot table covers both (the 1-arg `from` form uses slot 0 only).
175
+    Some(match name {
176
+        // --- conversion (spec §10.3.4.1) ---
177
+        "string" => &["from"],
178
+        "number" => &["from", "grouping separator", "decimal separator"],
179
+        "duration" => &["from"],
180
+        "years and months duration" => &["from", "to"],
181
+
182
+        // --- temporal constructors (spec §10.3.4.1) ---
183
+        // `date` has three overloads; the 3-slot table handles all of them
184
+        // (single-arg `from` uses slot 0, three-arg form fills all three).
185
+        "date" => &["year", "month", "day"],
186
+        // `time` has a 4-arg component form; the `from` single-arg form uses slot 0.
187
+        "time" => &["hour", "minute", "second", "offset"],
188
+        // `date and time` has a 2-arg `(date, time)` form and a 1-arg `from` form.
189
+        "date and time" => &["date", "time"],
190
+
191
+        // --- temporal component functions (spec §10.3.4.8) ---
192
+        "day of week" => &["date"],
193
+        "month of year" => &["date"],
194
+        "day of year" => &["date"],
195
+        "week of year" => &["date"],
196
+
197
+        // --- string functions (spec §10.3.4.3) ---
198
+        "substring" => &["string", "start position", "length"],
199
+        "string length" => &["string"],
200
+        "upper case" => &["string"],
201
+        "lower case" => &["string"],
202
+        "substring before" => &["string", "match"],
203
+        "substring after" => &["string", "match"],
204
+        "contains" => &["string", "match"],
205
+        "starts with" => &["string", "match"],
206
+        "ends with" => &["string", "match"],
207
+        "replace" => &["input", "pattern", "replacement", "flags"],
208
+        "matches" => &["input", "pattern", "flags"],
209
+        // `split` is named `string, delimiter` in spec Table 75.
210
+        "split" => &["string", "delimiter"],
211
+        "string join" => &["list", "delimiter"],
212
+
213
+        // --- list functions (spec §10.3.4.4) ---
214
+        "list contains" => &["list", "element"],
215
+        "count" => &["list"],
216
+        "sublist" => &["list", "start position", "length"],
217
+        "remove" => &["list", "position"],
218
+        "reverse" => &["list"],
219
+        "flatten" => &["list"],
220
+        "index of" => &["list", "match"],
221
+        "distinct values" => &["list"],
222
+        "insert before" => &["list", "position", "newItem"],
223
+        "list replace" => &["list", "position", "newItem"],
224
+
225
+        // --- context functions (spec §10.3.4.10) ---
226
+        "get value" => &["m", "key"],
227
+        "get entries" => &["m"],
228
+        "context" => &["entries"],
229
+        // Both `context put(context, key, value)` and `context put(context, keys, value)`
230
+        // share the same positional slots; the `key`/`keys` distinction is resolved by
231
+        // the underlying impl, not here.
232
+        "context put" => &["context", "key", "value"],
233
+        "context merge" => &["contexts"],
234
+
235
+        // --- numeric functions (spec §10.3.4.5) ---
236
+        "decimal" => &["n", "scale"],
237
+        "floor" => &["n", "scale"],
238
+        "ceiling" => &["n", "scale"],
239
+        "round up" => &["n", "scale"],
240
+        "round down" => &["n", "scale"],
241
+        "round half up" => &["n", "scale"],
242
+        "round half down" => &["n", "scale"],
243
+        "abs" => &["n"],
244
+        "modulo" => &["dividend", "divisor"],
245
+        "sqrt" => &["number"],
246
+        "exp" => &["number"],
247
+        "log" => &["number"],
248
+        "even" => &["number"],
249
+        "odd" => &["number"],
250
+
251
+        // Any other name has no named-parameter table entry.
252
+        _ => return None,
253
+    })
254
+}
255
+
158256
 /// Reorder a built-in call's positional + named arguments into the built-in's
159257
 /// positional parameter order (FEEL spec §10.3.2.13.5 allows named arguments for
160
-/// built-ins too). This needs a per-built-in parameter-name table, which is the
161
-/// **Sonnet-Teilaufgabe** in the implementation plan; until that lands, no built-in
162
-/// advertises named parameters, so a named call is unresolvable here and yields
163
-/// `None` — the caller then tries the host function registry. DO NOT inline away:
164
-/// this is the documented seam the table plugs into.
165
-fn reorder_named(_name: &str, _args: crate::function::Args) -> Option<Vec<Value>> {
166
-    None
258
+/// built-ins too). Uses [`builtin_param_names`] to look up the formal parameter
259
+/// table, then slots each named argument at its declared index, filling any
260
+/// unsupplied trailing optional parameters with [`Value::Null`].
261
+///
262
+/// Returns `None` when:
263
+/// - `name` has no parameter-name table (variadic or unknown built-in), or
264
+/// - a named argument refers to an unknown parameter name, or
265
+/// - a parameter is supplied both positionally and by name.
266
+///
267
+/// `None` propagates as an error-null at the call site (the caller tries the host
268
+/// function registry next; an unrecognised name still falls through correctly).
269
+fn reorder_named(name: &str, args: crate::function::Args) -> Option<Vec<Value>> {
270
+    let params = builtin_param_names(name)?;
271
+
272
+    let crate::function::Args { positional, named } = args;
273
+
274
+    // More positional arguments than the table has slots -> error-null.
275
+    if positional.len() > params.len() {
276
+        return None;
277
+    }
278
+
279
+    // Start with a slot vector: fill positional slots left to right, leave the
280
+    // rest as `None` (not yet supplied).
281
+    let mut slots: Vec<Option<Value>> = positional.into_iter().map(Some).collect();
282
+    slots.resize(params.len(), None);
283
+
284
+    // Place each named argument at its declared index.
285
+    for (arg_name, value) in named {
286
+        let idx = params.iter().position(|&p| p == arg_name)?; // unknown name -> None
287
+        if slots[idx].is_some() {
288
+            return None; // double-supplied (positional + named) -> error-null
289
+        }
290
+        slots[idx] = Some(value);
291
+    }
292
+
293
+    // Determine the effective length: trim trailing None slots that were never
294
+    // supplied (the built-in's own arity logic handles optional trailing params).
295
+    let last_supplied = slots.iter().rposition(|s| s.is_some());
296
+    let take = match last_supplied {
297
+        Some(i) => i + 1,
298
+        None => 0,
299
+    };
300
+
301
+    // Convert to Vec<Value>, substituting Value::Null for any gap that is still
302
+    // unsupplied but lies before the last-supplied slot.
303
+    let out = slots
304
+        .into_iter()
305
+        .take(take)
306
+        .map(|s| s.unwrap_or(Value::Null))
307
+        .collect();
308
+
309
+    Some(out)
167310
 }
168311
 
169312
 /// A nullary builtin: produce the value when called with no arguments, else an

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

@@ -1082,6 +1082,110 @@
10821082
         // Non-regex builtins are unaffected.
10831083
         assert_eq!(raw("sum([1, 2, 3])"), num(6.0));
10841084
     }
1085
+
1086
+    /// Named-argument built-in calls (FEEL spec §10.3.2.13.5).
1087
+    ///
1088
+    /// Each test cites the TCK fixture or spec table section that motivates it.
1089
+    #[test]
1090
+    fn named_args_builtin_functions() {
1091
+        let s = |v: &str| Value::String(v.to_string());
1092
+
1093
+        // spec §10.3.4.3 Table 75: `substring(string, start position, length?)`
1094
+        // Named call must equal the positional call (TCK 0008-feel-builtins / substring).
1095
+        assert_eq!(
1096
+            ev(r#"substring(string: "foobar", start position: 3)"#),
1097
+            s("obar")
1098
+        );
1099
+        assert_eq!(
1100
+            ev(r#"substring("foobar", 3)"#),
1101
+            s("obar")
1102
+        );
1103
+
1104
+        // spec §10.3.4.3: named arguments are order-independent.
1105
+        assert_eq!(
1106
+            ev(r#"substring(start position: 3, string: "foobar")"#),
1107
+            s("obar")
1108
+        );
1109
+
1110
+        // spec §10.3.4.3: omitting the optional `length` named arg still works.
1111
+        assert_eq!(
1112
+            ev(r#"substring(string: "foobar", start position: 3)"#),
1113
+            ev(r#"substring("foobar", 3)"#)
1114
+        );
1115
+
1116
+        // spec §10.3.4.3: supplying the optional `length` by name.
1117
+        assert_eq!(
1118
+            ev(r#"substring(string: "foobar", start position: 3, length: 3)"#),
1119
+            s("oba")
1120
+        );
1121
+
1122
+        // spec §10.3.4.3: `contains(string, match)`.
1123
+        assert_eq!(
1124
+            ev(r#"contains(string: "foobar", match: "oob")"#),
1125
+            b(true)
1126
+        );
1127
+
1128
+        // spec §10.3.4.3: `string length(string)`.
1129
+        assert_eq!(ev(r#"string length(string: "abc")"#), num(3.0));
1130
+
1131
+        // spec §10.3.4.3: `upper case(string)` / `lower case(string)`.
1132
+        assert_eq!(ev(r#"upper case(string: "aBc")"#), s("ABC"));
1133
+        assert_eq!(ev(r#"lower case(string: "aBc4")"#), s("abc4"));
1134
+
1135
+        // spec §10.3.4.3: `starts with(string, match)`.
1136
+        assert_eq!(ev(r#"starts with(string: "foobar", match: "foo")"#), b(true));
1137
+
1138
+        // spec §10.3.4.3: `ends with(string, match)`.
1139
+        assert_eq!(ev(r#"ends with(string: "foobar", match: "bar")"#), b(true));
1140
+
1141
+        // spec §10.3.4.3: `substring before(string, match)` / `substring after(string, match)`.
1142
+        assert_eq!(
1143
+            ev(r#"substring before(string: "foobar", match: "bar")"#),
1144
+            s("foo")
1145
+        );
1146
+        assert_eq!(
1147
+            ev(r#"substring after(string: "foobar", match: "ob")"#),
1148
+            s("ar")
1149
+        );
1150
+
1151
+        // spec §10.3.4.4: `list contains(list, element)`.
1152
+        assert_eq!(ev("list contains(list: [1,2,3], element: 2)"), b(true));
1153
+
1154
+        // spec §10.3.4.4: `count(list)`.
1155
+        assert_eq!(ev("count(list: [1,2,3])"), num(3.0));
1156
+
1157
+        // spec §10.3.4.4: `sublist(list, start position, length?)`.
1158
+        assert_eq!(
1159
+            ev("sublist(list: [4,5,6], start position: 1, length: 2)"),
1160
+            list(vec![num(4.0), num(5.0)])
1161
+        );
1162
+
1163
+        // spec §10.3.4.5: `decimal(n, scale)`.
1164
+        assert_eq!(ev("decimal(n: 1.5, scale: 0)"), num(2.0));
1165
+
1166
+        // spec §10.3.4.5: `abs(n)`.
1167
+        assert_eq!(ev("abs(n: -10)"), num(10.0));
1168
+
1169
+        // spec §10.3.4.5: `modulo(dividend, divisor)`.
1170
+        assert_eq!(ev("modulo(dividend: 12, divisor: 5)"), num(2.0));
1171
+
1172
+        // spec §10.3.4.10: `get value(m, key)`.
1173
+        assert_eq!(ev(r#"get value(m: {a: 1}, key: "a")"#), num(1.0));
1174
+
1175
+        // spec §10.3.4.1: `string(from)`.
1176
+        assert_eq!(ev("string(from: 1.1)"), s("1.1"));
1177
+
1178
+        // Unknown parameter name -> error-null (spec §10.3.2.13.5: no match -> null).
1179
+        // ev() uses into_lenient(), so error-null collapses to Value::Null.
1180
+        assert_eq!(
1181
+            ev(r#"substring(string: "foobar", start: 3)"#),
1182
+            Value::Null
1183
+        );
1184
+
1185
+        // A variadic-only built-in called with named args -> null (no table entry).
1186
+        // `sum` accepts either a list or N scalars; it has no named-parameter form.
1187
+        assert_eq!(ev("sum(n: 1)"), Value::Null);
1188
+    }
10851189
 }
10861190
 
10871191
 /// Tests for the lazy [`Value::Foreign`] seam (ADR-21). feel-core never constructs