tabnas-expr 0.5.12

Pratt expression-operator plugin for the tabnas parsing engine, over the jsonic base grammar
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
521
522
523
// Cross-runtime conformance, driven by the shared `test/spec/*.tsv`
// fixtures at the repository root (see ../../test/AGENTS.md).
//
// The fixture loader, the escape codec and the row loop all come from
// tabnas_support, whose TypeScript half `ts/test/spec.test.ts` and Go half
// `go/expr_test.go` run the SAME files, so the three implementations
// cannot drift without one of them going red, and neither can the
// loaders.
//
// What varies per case is the CONFIGURED PARSER, which cannot live in a
// fixture column: several files need operators defined in the plugin's
// options. So each test builds its own, exactly as the TypeScript and Go
// runners do, and every fixture is named by the test that supplies it.

mod common;

use serde_json::json;
use tabnas::{Tabnas, Value as EngineValue};
use tabnas_expr::{ExprOptions, OpDef, PrevalDef};
use tabnas_support::{Runner, Value};

use common::{parse_simplified, parser_default, parser_for, parser_with, spec_dir, to_failure};

/// Run one fixture file with the parser the test built for it.
fn run_spec(name: &str, parser: Tabnas) {
    let path = spec_dir().join(name);
    assert!(path.is_file(), "missing shared fixture {}", path.display());
    Runner::new(move |input| {
        parse_simplified(&parser, input)
            .map(Value::from)
            .map_err(to_failure)
    })
    .file(&path);
}

// --- default operator table ------------------------------------------------

#[test]
fn spec_happy() {
    run_spec("happy.tsv", parser_default());
}

#[test]
fn spec_binary() {
    run_spec("binary.tsv", parser_default());
}

#[test]
fn spec_dangling_operator() {
    run_spec("dangling-operator.tsv", parser_default());
}

#[test]
fn spec_arithmetic_mixed() {
    run_spec("arithmetic-mixed.tsv", parser_default());
}

#[test]
fn spec_prefix_infix_mixed() {
    run_spec("prefix-infix-mixed.tsv", parser_default());
}

#[test]
fn spec_paren_deep_nest() {
    run_spec("paren-deep-nest.tsv", parser_default());
}

#[test]
fn spec_structure_arith() {
    run_spec("structure-arith.tsv", parser_default());
}

#[test]
fn spec_structure() {
    run_spec("structure.tsv", parser_default());
}

#[test]
fn spec_unary_prefix_basic() {
    run_spec("unary-prefix-basic.tsv", parser_default());
}

#[test]
fn spec_paren_basic() {
    run_spec("paren-basic.tsv", parser_default());
}

#[test]
fn spec_implicit_list_top_basic() {
    run_spec("implicit-list-top-basic.tsv", parser_default());
}

#[test]
fn spec_json_base() {
    run_spec("json-base.tsv", parser_default());
}

#[test]
fn spec_jsonic_base() {
    run_spec("jsonic-base.tsv", parser_default());
}

#[test]
fn spec_implicit_list_top_paren() {
    run_spec("implicit-list-top-paren.tsv", parser_default());
}

#[test]
fn spec_paren_implicit_list() {
    run_spec("paren-implicit-list.tsv", parser_default());
}

#[test]
fn spec_paren_implicit_map() {
    run_spec("paren-implicit-map.tsv", parser_default());
}

#[test]
fn spec_map_implicit_list_paren() {
    run_spec("map-implicit-list-paren.tsv", parser_default());
}

#[test]
fn spec_paren_list_implicit_structure_comma() {
    run_spec("paren-list-implicit-structure-comma.tsv", parser_default());
}

#[test]
fn spec_paren_list_implicit_structure_space() {
    run_spec("paren-list-implicit-structure-space.tsv", parser_default());
}

#[test]
fn spec_paren_map_implicit_structure_comma() {
    run_spec("paren-map-implicit-structure-comma.tsv", parser_default());
}

#[test]
fn spec_paren_map_implicit_structure_space() {
    run_spec("paren-map-implicit-structure-space.tsv", parser_default());
}

#[test]
fn spec_infix_in_paren_map() {
    run_spec("infix-in-paren-map.tsv", parser_default());
}

// --- per-file operator tables ----------------------------------------------

/// The `!` and `?` suffix pair several unary fixtures register.
fn suffix_ops() -> serde_json::Value {
    json!({
        "op": {
            "factorial": { "suffix": true, "left": 6000000, "src": "!" },
            "question": { "suffix": true, "left": 3500000, "src": "?" },
        }
    })
}

#[test]
fn spec_binding_power_zero() {
    run_spec(
        "binding-power-zero.tsv",
        parser_for(json!({
            "op": {
                // `zero` declares both powers as 0, which the canonical
                // reads as unset; `below` sits on a negative tier, the only
                // place a genuine zero would differ from the fallback.
                "zero": { "infix": true, "left": 0, "right": 0, "src": "~" },
                "below": { "infix": true, "left": -2000000, "right": -1900000, "src": "@" },
            }
        })),
    );
}

#[test]
fn spec_unary_prefix_edge() {
    run_spec(
        "unary-prefix-edge.tsv",
        parser_for(json!({
            "op": {
                "at": { "prefix": true, "right": 5000000, "src": "@" },
                "tight": { "infix": true, "left": 7000000, "right": 7100000, "src": "~" },
            }
        })),
    );
}

#[test]
fn spec_unary_suffix_basic() {
    run_spec("unary-suffix-basic.tsv", parser_for(suffix_ops()));
}

#[test]
fn spec_unary_suffix_arith() {
    run_spec("unary-suffix-arith.tsv", parser_for(suffix_ops()));
}

#[test]
fn spec_unary_suffix_structure() {
    run_spec("unary-suffix-structure.tsv", parser_for(suffix_ops()));
}

#[test]
fn spec_unary_suffix_prefix() {
    run_spec("unary-suffix-prefix.tsv", parser_for(suffix_ops()));
}

#[test]
fn spec_unary_suffix_paren() {
    run_spec("unary-suffix-paren.tsv", parser_for(suffix_ops()));
}

#[test]
fn spec_unary_suffix_edge() {
    run_spec(
        "unary-suffix-edge.tsv",
        parser_for(json!({
            "op": {
                "factorial": { "suffix": true, "left": 6000000, "src": "!" },
                "question": { "suffix": true, "left": 3500000, "src": "?" },
                "tight": { "infix": true, "left": 7000000, "right": 7100000, "src": "~" },
            }
        })),
    );
}

/// The suffix and ternary pair the basic ternary fixtures register.
fn ternary_ops() -> serde_json::Value {
    json!({
        "op": {
            "factorial": { "suffix": true, "src": "!", "left": 6000000 },
            "ternary": { "ternary": true, "src": ["?", ":"] },
        }
    })
}

#[test]
fn spec_ternary_basic() {
    run_spec("ternary-basic.tsv", parser_for(ternary_ops()));
}

#[test]
fn spec_ternary_implicit_list() {
    run_spec("ternary-implicit-list.tsv", parser_for(ternary_ops()));
}

#[test]
fn spec_ternary_many_2() {
    run_spec(
        "ternary-many-2.tsv",
        parser_for(json!({
            "op": {
                "foo": { "ternary": true, "src": ["?", ":"] },
                "bar": { "ternary": true, "src": ["QQ", "CC"] },
            }
        })),
    );
}

#[test]
fn spec_ternary_many_3() {
    run_spec(
        "ternary-many-3.tsv",
        parser_for(json!({
            "op": {
                "foo": { "ternary": true, "src": ["?", ":"] },
                "bar": { "ternary": true, "src": ["QQ", "CC"] },
                "zed": { "ternary": true, "src": ["%%", "@@"] },
            }
        })),
    );
}

#[test]
fn spec_ternary_paren_preval() {
    run_spec(
        "ternary-paren-preval.tsv",
        parser_for(json!({
            "op": {
                "ternary": { "ternary": true, "src": ["?", ":"] },
                "plain": {
                    "paren": true, "osrc": "(", "csrc": ")",
                    "preval": { "active": true },
                },
            }
        })),
    );
}

#[test]
fn spec_paren_preval_chain() {
    run_spec(
        "paren-preval-chain.tsv",
        parser_for(json!({
            "op": {
                "index": {
                    "paren": true, "osrc": "[", "csrc": "]",
                    "preval": { "required": true },
                },
                "call": {
                    "paren": true, "osrc": "(", "csrc": ")",
                    "preval": { "active": true },
                },
                "plain": null,
            }
        })),
    );
}

#[test]
fn spec_add_infix() {
    run_spec(
        "add-infix.tsv",
        parser_for(json!({
            "op": {
                "foo": { "infix": true, "left": 3500000, "right": 3600000, "src": "foo" },
            }
        })),
    );
}

#[test]
fn spec_add_paren() {
    run_spec(
        "add-paren.tsv",
        parser_for(json!({
            "op": { "angle": { "paren": true, "osrc": "<", "csrc": ">" } }
        })),
    );
}

#[test]
fn spec_paren_preval_basic() {
    run_spec(
        "paren-preval-basic.tsv",
        parser_for(json!({
            "op": {
                "angle": {
                    "osrc": "<", "csrc": ">", "paren": true,
                    "preval": { "active": true },
                },
            }
        })),
    );
}

#[test]
fn spec_paren_preval_overload() {
    run_spec(
        "paren-preval-overload.tsv",
        parser_for(json!({
            "op": {
                "factorial": { "suffix": true, "left": 6000000, "src": "!" },
                "square": {
                    "osrc": "[", "csrc": "]", "paren": true,
                    "preval": { "required": true },
                },
                "brace": {
                    "osrc": "{", "csrc": "}", "paren": true,
                    "preval": { "required": true },
                },
            }
        })),
    );
}

#[test]
fn spec_paren_preval_implicit() {
    run_spec(
        "paren-preval-implicit.tsv",
        parser_for(json!({ "op": { "plain": { "preval": true } } })),
    );
}

// --- the evaluate option ---------------------------------------------------

fn number_at(terms: &[EngineValue], index: usize) -> f64 {
    match terms.get(index) {
        Some(EngineValue::Number(number)) => *number,
        _ => 0.0,
    }
}

fn factorial(n: f64) -> f64 {
    if n <= 1.0 {
        return 1.0;
    }
    let mut out = 1.0;
    let mut step = 2.0;
    while step <= n {
        out *= step;
        step += 1.0;
    }
    out
}

/// The math expression grammar the TypeScript and Go runners build for
/// `evaluate-math.tsv`: the full pipeline of parse, S-expression, evaluate
/// and result, including preval function parens `min(x,y)` / `max(x,y)`.
#[test]
fn spec_evaluate_math() {
    let options = ExprOptions::new()
        .with_op("addition", OpDef::infix("+", 140, 150))
        .with_op("subtraction", OpDef::infix("-", 140, 150))
        .with_op("multiplication", OpDef::infix("*", 160, 170))
        .with_op("division", OpDef::infix("/", 160, 170))
        .with_op("negative", OpDef::prefix("-", 200))
        .with_op("positive", OpDef::prefix("+", 200))
        .with_op("factorial", OpDef::suffix("!", 300))
        .with_op(
            "func",
            OpDef::paren("(", ")").with_preval(PrevalDef {
                active: true,
                required: false,
                allow: None,
            }),
        )
        .with_evaluate(|_site, op, terms| {
            let left = number_at(terms, 0);
            let right = number_at(terms, 1);
            match op.name.as_str() {
                "addition-infix" => EngineValue::Number(left + right),
                "subtraction-infix" => EngineValue::Number(left - right),
                "multiplication-infix" => EngineValue::Number(left * right),
                "division-infix" => {
                    EngineValue::Number(if 0.0 == right { 0.0 } else { left / right })
                }
                "negative-prefix" => EngineValue::Number(-left),
                "positive-prefix" => EngineValue::Number(left),
                "factorial-suffix" => EngineValue::Number(factorial(left)),
                "func-paren" => {
                    let EngineValue::String(name) =
                        terms.first().unwrap_or(&EngineValue::Undefined)
                    else {
                        // Plain parens with no preval: the inner value.
                        return terms.first().cloned().unwrap_or(EngineValue::Undefined);
                    };
                    // A preval function call: the arguments follow the
                    // name, and an implicit list arrives as one array.
                    let rest = &terms[1..];
                    let args: Vec<EngineValue> = match rest {
                        [EngineValue::Array(members)] => members.to_vec(),
                        other => other.to_vec(),
                    };
                    // Variadic, as the TypeScript side's `Math.min(...args)`
                    // is: fixed at two arguments, a three-argument row would
                    // agree with TypeScript only when the third happens not
                    // to be the extremum.
                    match name.as_str() {
                        "min" | "max" => {
                            let mut best = number_at(&args, 0);
                            for index in 1..args.len() {
                                let candidate = number_at(&args, index);
                                if ("min" == name) == (candidate < best) && candidate != best {
                                    best = candidate;
                                }
                            }
                            EngineValue::Number(best)
                        }
                        _ => EngineValue::Number(number_at(&args, 0)),
                    }
                }
                "plain-paren" => EngineValue::Number(left),
                _ => EngineValue::Number(left),
            }
        });
    run_spec("evaluate-math.tsv", parser_with(options));
}

// --- the coverage itself ---------------------------------------------------

/// Every shared fixture on disk is run by a test in this file.
///
/// Fixture coverage was a prose claim before this: `../AGENTS.md` said all
/// three runtimes run `test/spec/*.tsv`, and nothing failed when one of
/// them did not. A fixture only some runtimes run proves nothing, and the
/// runtime that quietly skips one is the runtime that has drifted.
///
/// The check reads this source file rather than a hand-kept list, because
/// a hand-kept list is the same claim one indirection further away: a
/// fixture could be added to it without a `run_spec` call and the gate
/// would still be green. A fixture name is "run" when it appears as a
/// string literal here, which is exactly how `run_spec` is handed one.
#[test]
fn every_shared_fixture_is_run() {
    let source = std::fs::read_to_string(
        common::repo_root()
            .join("rs")
            .join("tests")
            .join("parity_test.rs"),
    )
    .expect("this test file is readable");

    let mut fixtures: Vec<String> = std::fs::read_dir(spec_dir())
        .expect("the shared fixture directory is readable")
        .map(|entry| entry.expect("a readable directory entry").file_name())
        .map(|name| name.to_string_lossy().into_owned())
        .filter(|name| name.ends_with(".tsv"))
        .collect();
    fixtures.sort();

    assert!(
        !fixtures.is_empty(),
        "no fixtures in {}; the coverage gate would pass over nothing",
        spec_dir().display()
    );

    let missing: Vec<&String> = fixtures
        .iter()
        .filter(|name| !source.contains(&format!("\"{name}\"")))
        .collect();

    assert!(
        missing.is_empty(),
        "no Rust runner for {} of {} shared fixtures: {:?}. \
         Add a `run_spec` test with the operator table the file assumes, \
         matching the TypeScript and Go runners.",
        missing.len(),
        fixtures.len(),
        missing
    );
}