Public repository: timo / feel

Reader

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

feel / crates / feel-wasm / smoke.mjs · 11.1 KB · at 93b43c1c833b · raw

1
// Smoke test for the WASM build.
2
//
3
// Build first:
4
//   wasm-pack build crates/feel-wasm --target nodejs
5
// Then run:
6
//   node crates/feel-wasm/smoke.mjs
7
//
8
// Expected output (one line per case):
9
//   1 + 1 => 2
10
//   5 in [1..10] => true
11
//   if 1 < 2 then 10 else 20 => 10
12
//   for i in [1,2,3] return i + 1 => [2,3,4]
13
//   "apple" < "banana" => true
14
//   {a: 1, b: a + 1} => {"a":1,"b":2}
15
//   person.age (ctx {"person":{"age":42}}) => 42
16
17
import { evaluate, evaluate_strict, compile } from "./pkg/feel_wasm.js";
18
19
// [expression, context-object, expected-value]. The context is a native JS
20
// object and the result is a native JS value (no JSON strings). These mirror the
21
// feel-core and feel-pg tests, demonstrating "same core, same result" across all
22
// three targets.
23
const cases = [
24
  ["1 + 1", {}, 2],
25
  ["5 in [1..10]", {}, true],
26
  ["if 1 < 2 then 10 else 20", {}, 10],
27
  ["for i in [1,2,3] return i + 1", {}, [2, 3, 4]],
28
  ['"apple" < "banana"', {}, true],
29
  // Context literal -> JS object, and path access into a nested input context.
30
  ["{a: 1, b: a + 1}", {}, { a: 1, b: 2 }],
31
  ["person.age", { person: { age: 42 } }, 42],
32
  // Regex builtins run on the host JS RegExp engine (ADR-16).
33
  ['matches("foobar", "^fo*b")', {}, true],
34
  ['replace("banana", "a", "o")', {}, "bonono"],
35
  ['split("a;b;c;;", ";")', {}, ["a", "b", "c", "", ""]],
36
];
37
38
const eq = (a, b) => JSON.stringify(a) === JSON.stringify(b);
39
40
let ok = true;
41
for (const [expr, ctx, expected] of cases) {
42
  const got = evaluate(expr, ctx);
43
  console.log(`${expr} => ${JSON.stringify(got)}`);
44
  if (!eq(got, expected)) {
45
    console.error(`FAIL: expected ${JSON.stringify(expected)}, got ${JSON.stringify(got)}`);
46
    ok = false;
47
  }
48
}
49
50
// Temporal (ADR-18): date-family results come back as native JS `Date` objects,
51
// durations as ISO-8601 strings, and `Date` objects are accepted in the context.
52
const dateResult = evaluate("date(2017, 8, 3)", {});
53
console.log(`date(2017, 8, 3) => ${dateResult instanceof Date ? dateResult.toISOString() : JSON.stringify(dateResult)}`);
54
if (!(dateResult instanceof Date) || !dateResult.toISOString().startsWith("2017-08-03")) {
55
  console.error("FAIL: date(...) should be a Date object");
56
  ok = false;
57
}
58
const durResult = evaluate('duration("P1Y2M")', {});
59
console.log(`duration("P1Y2M") => ${JSON.stringify(durResult)}`);
60
if (durResult !== "P1Y2M") {
61
  console.error("FAIL: duration should be an ISO-8601 string");
62
  ok = false;
63
}
64
const yearFromDate = evaluate("d.year", { d: new Date("2017-08-03T00:00:00Z") });
65
console.log(`d.year (ctx { d: Date }) => ${JSON.stringify(yearFromDate)}`);
66
if (yearFromDate !== 2017) {
67
  console.error("FAIL: a Date object should be accepted in the context");
68
  ok = false;
69
}
70
71
// Lazy host-object access (ADR-21): an object in the context is wrapped and its
72
// members resolve on demand via `Reflect.get`, which *fires JS accessor getters*.
73
const getterObj = {
74
  get name() {
75
    return "Ada";
76
  },
77
};
78
const getterResult = evaluate("o.name", { o: getterObj });
79
console.log(`o.name (getter) => ${JSON.stringify(getterResult)}`);
80
if (getterResult !== "Ada") {
81
  console.error("FAIL: a JS getter should fire on path access");
82
  ok = false;
83
}
84
// Lazy navigation through nested getters (the ORM lazy-load shape).
85
const orderObj = {
86
  get customer() {
87
    return {
88
      get address() {
89
        return { city: "Paris" };
90
      },
91
    };
92
  },
93
};
94
const nested = evaluate("o.customer.address.city", { o: orderObj });
95
console.log(`o.customer.address.city => ${JSON.stringify(nested)}`);
96
if (nested !== "Paris") {
97
  console.error("FAIL: nested getter navigation");
98
  ok = false;
99
}
100
// Output pass-through: a host object that reaches the result is the *same* object.
101
const origObj = { city: "Berlin" };
102
const passed = evaluate("o", { o: origObj });
103
console.log(`o passthrough identity => ${passed === origObj}`);
104
if (passed !== origObj) {
105
  console.error("FAIL: a Foreign result should pass the original object through");
106
  ok = false;
107
}
108
// A cyclic object needs no guard in lazy mode: a finite path terminates.
109
const cyc = { a: 1 };
110
cyc.self = cyc;
111
const cycResult = evaluate("x.self.self.a", { x: cyc });
112
console.log(`x.self.self.a (cyclic) => ${JSON.stringify(cycResult)}`);
113
if (cycResult !== 1) {
114
  console.error("FAIL: a finite path over a cyclic object should terminate");
115
  ok = false;
116
}
117
118
// Descendant `e ... name` (DMN 10.3.2.7): recursively collect every value bound to
119
// `name` in `e` and all nested contexts. Unlike the lazy `.`, it is an *unbounded*
120
// traversal, so a cyclic object would loop forever without the WeakMap-based
121
// identity (JS exposes no cheap object address, so object identity is derived via a
122
// WeakMap<object, number>).
123
const descendantCases = [
124
  ["{a: {b: {b: 1}}} ... b", {}, [{ b: 1 }, 1]],
125
  ["[{x:1},{x:2}] ... x", {}, [1, 2]],
126
  ["{a:1} ... z", {}, []],
127
  ["o ... name", { o: { customer: { name: "Ada" } } }, ["Ada"]],
128
];
129
for (const [expr, ctx, expected] of descendantCases) {
130
  const got = evaluate(expr, ctx);
131
  console.log(`${expr} => ${JSON.stringify(got)}`);
132
  if (!eq(got, expected)) {
133
    console.error(`FAIL: ${expr} expected ${JSON.stringify(expected)}, got ${JSON.stringify(got)}`);
134
    ok = false;
135
  }
136
}
137
// The descendant traversal over a *cyclic* object must terminate: the back-edge into
138
// the same object (same WeakMap id) is cut after the first re-entry. `cyc2.next`
139
// points back to `cyc2`, so `value` is collected twice before the cycle is broken.
140
const cyc2 = { value: 42 };
141
cyc2.next = cyc2;
142
const cycDesc = evaluate("c ... value", { c: cyc2 });
143
console.log(`c ... value (cyclic) => ${JSON.stringify(cycDesc)}`);
144
if (!eq(cycDesc, [42, 42])) {
145
  console.error(`FAIL: descendant over a cyclic object should terminate with [42,42], got ${JSON.stringify(cycDesc)}`);
146
  ok = false;
147
}
148
149
// Boundary policy (ADR-14): a type error is a lenient `null`, but `evaluate_strict`
150
// surfaces it as a thrown exception instead of letting it pass silently as `null`.
151
const threw = (fn) => {
152
  try {
153
    fn();
154
    return false;
155
  } catch {
156
    return true;
157
  }
158
};
159
160
const strictCases = [
161
  ["1 + true", {}, null, true], // lenient: null; strict: throws
162
  ["null", {}, null, false], // a genuine value-null is fine even in strict
163
];
164
for (const [expr, ctx, expectedLenient, expectStrictThrow] of strictCases) {
165
  const lenient = evaluate(expr, ctx);
166
  const strictThrew = threw(() => evaluate_strict(expr, ctx));
167
  console.log(`${expr} => lenient ${JSON.stringify(lenient)} | strict throws: ${strictThrew}`);
168
  if (!eq(lenient, expectedLenient) || strictThrew !== expectStrictThrow) {
169
    console.error(`FAIL: ${expr} lenient/strict mismatch`);
170
    ok = false;
171
  }
172
}
173
// Compiled path: parse once, evaluate against many contexts (the parse-once /
174
// evaluate-many API). `free()` is the optional explicit-cleanup escape hatch;
175
// otherwise wasm-bindgen's FinalizationRegistry reclaims it on GC.
176
const prog = compile("a + 1");
177
const compiledCases = [
178
  [{ a: 1 }, 2],
179
  [{ a: 41 }, 42],
180
];
181
for (const [ctx, expected] of compiledCases) {
182
  const got = prog.evaluate(ctx);
183
  console.log(`compiled "a + 1" (ctx ${JSON.stringify(ctx)}) => ${JSON.stringify(got)}`);
184
  if (!eq(got, expected)) {
185
    console.error(`FAIL: expected ${JSON.stringify(expected)}, got ${JSON.stringify(got)}`);
186
    ok = false;
187
  }
188
}
189
prog.free();
190
191
// Special-character names (§10.3.1.6, ADR-47): the context is the scope. `a-b`
192
// is the in-scope NAME when the object binds it, subtraction otherwise; `a - b`
193
// is the same candidate (spaces are not part of the name); `(a)-(b)` is the
194
// escape hatch; a hyphen name works as a path base. The compiled class is
195
// probe-free (a compiled program pins no scope): `a-b` stays arithmetic there.
196
const nameCases = [
197
  ["a-b", { "a-b": 5 }, 5],
198
  ["a - b", { "a-b": 5 }, 5],
199
  ["a-b", { a: 7, b: 3 }, 4],
200
  ["(a)-(b)", { a: 7, b: 3, "a-b": 100 }, 4],
201
  ["x-y.hour", { "x-y": { hour: 3 } }, 3],
202
  // A member word never fuses against the root scope: `x.y-z` is (x.y) - z.
203
  ["x.y-z", { x: { y: 10 }, z: 3, "y-z": 1 }, 7],
204
];
205
for (const [expr, ctx, expected] of nameCases) {
206
  const got = evaluate(expr, ctx);
207
  console.log(`${expr} (special-char name) => ${JSON.stringify(got)}`);
208
  if (!eq(got, expected)) {
209
    console.error(`FAIL: expected ${JSON.stringify(expected)}, got ${JSON.stringify(got)}`);
210
    ok = false;
211
  }
212
}
213
{
214
  // The ambient `functions` registry is part of the parse-time scope: a
215
  // hyphen-named host function is callable.
216
  const got = evaluate("my-fn(2)", {}, { "my-fn": (x) => x * 10 });
217
  if (!eq(got, 20)) {
218
    console.error(`FAIL: my-fn(2) via registry expected 20, got ${JSON.stringify(got)}`);
219
    ok = false;
220
  }
221
}
222
{
223
  const prog2 = compile("a-b");
224
  const compiledNameCases = [
225
    [{ "a-b": 5 }, null], // probe-free: subtraction of unbound names, not the key
226
    [{ a: 7, b: 3 }, 4],
227
  ];
228
  for (const [ctx, expected] of compiledNameCases) {
229
    const got = prog2.evaluate(ctx);
230
    if (!eq(got, expected)) {
231
      console.error(`FAIL: compiled "a-b" expected ${JSON.stringify(expected)}, got ${JSON.stringify(got)}`);
232
      ok = false;
233
    }
234
  }
235
  prog2.free();
236
}
237
238
// Host callables (ADR-23): a JS function in the context is a FEEL function the
239
// expression can invoke. Positional FEEL args -> positional JS args; named FEEL
240
// args -> a single trailing options object (JS has no keyword arguments).
241
const hostFnCases = [
242
  // positional
243
  ["f(2, 3)", { f: (a, b) => a + b }, 5],
244
  // named -> options object {a, b}
245
  ["f(b: 3, a: 2)", { f: (o) => o.a - o.b }, -1],
246
  // mixed positional + named -> (positional…, {named})
247
  ["f(2, b: 3)", { f: (a, o) => a - o.b }, -1],
248
  // a host default applies (feel-core does no arity check for host callables)
249
  ["f(2)", { f: (a, b = 10) => a + b }, 12],
250
  // a host object argument round-trips by identity into the function
251
  ["grab(o)", { grab: (o) => o.total, o: { total: 99 } }, 99],
252
  // a function-valued binding shadows a built-in of the same name
253
  ["count(2, 3)", { count: (a, b) => a * b }, 6],
254
];
255
for (const [expr, ctx, expected] of hostFnCases) {
256
  const got = evaluate(expr, ctx);
257
  console.log(`${expr} (host fn) => ${JSON.stringify(got)}`);
258
  if (!eq(got, expected)) {
259
    console.error(`FAIL: expected ${JSON.stringify(expected)}, got ${JSON.stringify(got)}`);
260
    ok = false;
261
  }
262
}
263
264
// The ambient function registry (third argument): functions live apart from data.
265
const regResult = evaluate("add(x, 3)", { x: 2 }, { add: (a, b) => a + b });
266
console.log(`add(x, 3) (registry) => ${JSON.stringify(regResult)}`);
267
if (regResult !== 5) {
268
  console.error("FAIL: ambient function registry");
269
  ok = false;
270
}
271
272
// A thrown exception inside a host callable is a lenient null (error-null).
273
const threwResult = evaluate("boom(1)", {
274
  boom: () => {
275
    throw new Error("nope");
276
  },
277
});
278
console.log(`boom(1) (throws) => ${JSON.stringify(threwResult)}`);
279
if (threwResult !== null) {
280
  console.error("FAIL: a host exception should be a lenient null");
281
  ok = false;
282
}
283
284
// A host callable that reaches the result passes back as the same function.
285
const idFn = (a) => a;
286
const idResult = evaluate("f", { f: idFn });
287
console.log(`f passthrough identity => ${idResult === idFn}`);
288
if (idResult !== idFn) {
289
  console.error("FAIL: a returned host function should pass through by identity");
290
  ok = false;
291
}
292
293
if (!ok) process.exit(1);
294
console.error("smoke test passed");