js2rust-predicate 0.1.7

Compile side-effect-free JavaScript predicates into a zero-allocation Rust evaluator
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
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
//! 求值:按节点树走一遍,零分配、无虚表。
//!
//! 约束:所有字符串都借用自数据或编译产物(`'a` 同时覆盖两者),
//! 唯一可能分配的是 `Num` 参与字符串方法时的格式化(语料里不存在)。

use std::borrow::Cow;
use std::marker::PhantomData;

use crate::ast::Method;
use crate::compile::{ArithOp, ConstVal, Node, PathBase, PathSeg, Program, RelOp, format_num};
use crate::date;
use crate::error::{Error, ErrorKind};
use crate::semantics;
use crate::set::Probe;
use crate::value::{Data, Kind, Val};

/// 与解析器的槽位上限保持一致。
const MAX_SLOTS: usize = 16;

struct Cx<'a, D: Data<'a>> {
    row: D,
    params: Option<D>,
    _l: PhantomData<&'a ()>,
}

impl Program {
    /// 对一行数据求值。
    ///
    /// `row` 是 `item`,`params` 是 `params`(未传时为 `undefined`)。
    /// 两者必须是同一个类型——调用方用一个覆盖两种数据来源的枚举适配器即可。
    ///
    /// 返回 `Err` 时是否 fail-closed 由调用方决定。
    pub fn eval<'a, D: Data<'a>>(&'a self, row: D, params: Option<D>) -> Result<bool, Error> {
        // 编译期已知槽位数;固定数组必须容得下,否则是解析器/编译器漂移
        debug_assert!(usize::from(self.slots) <= MAX_SLOTS, "槽位数超出上限");
        let mut slots: [Option<Val<'a, D>>; MAX_SLOTS] = [None; MAX_SLOTS];
        let cx = Cx {
            row,
            params,
            _l: PhantomData,
        };
        for step in self.steps.iter() {
            match step {
                Node::Set { slot, value } => {
                    // 短路哨兵只在**同一条链**内透传;一旦绑定到变量就成了普通
                    // undefined,后续 `x.length` 在 JS 里是 TypeError 而不是短路。
                    let v = norm(eval_node(value, &cx, &mut slots)?);
                    slot_set(&mut slots, *slot, v)?;
                }
                _ => {
                    return Err(Error::new(ErrorKind::Runtime, "非绑定步骤"));
                }
            }
        }
        let out = norm(eval_node(&self.result, &cx, &mut slots)?);
        // 与生产端对齐:rquickjs 把完成值按 `bool` 严格转换,非布尔值是**错误**而非
        // truthiness(`undefined?.includes(x)`、裸 `parseInt(...)` 都属此类)。
        match out {
            Val::Bool(b) => Ok(b),
            other => Err(runtime(&format!(
                "filter 表达式结果不是布尔(完成值 {:?},生产端会抛转换错误)",
                other
            ))),
        }
    }
}

fn runtime(msg: &str) -> Error {
    Error::new(ErrorKind::Runtime, msg.to_string())
}

/// 类型不匹配(JS 里会得到 `undefined` 或抛 TypeError 的形态,这里显式报错)。
fn type_err(msg: &str) -> Error {
    Error::new(ErrorKind::Type, msg.to_string())
}

/// 是否需要 JS ToPrimitive 才能比较(数组/对象)。严格比较不走这里——
/// `===` 对引用身份恒 false 是既有契约,与 ToPrimitive 无关。
fn needs_to_primitive<'a, D: Data<'a>>(v: &Val<'a, D>) -> bool {
    matches!(v, Val::Arr(_) | Val::Obj(_) | Val::EmptyObj)
}

/// 值是否为 JS 引用类型。`Data` 是零分配游标,没有对象身份信息,
/// 因此两个引用之间的 `===` / `.includes` / `.indexOf` 无法判定(同一引用
/// 在 JS 为 true,不同引用为 false)。调用方必须显式报 `Unsupported`,
/// 不能静默按 false 处理。
fn needs_identity<'a, D: Data<'a>>(v: &Val<'a, D>) -> bool {
    matches!(v, Val::Arr(_) | Val::Obj(_) | Val::EmptyObj)
}

/// 把可选链短路哨兵归一成 `undefined`:只应在**消费值**的地方调用
/// (比较、真值判断、方法参数、最终结果),链式节点之间必须原样透传。
fn norm<'a, D: Data<'a>>(v: Val<'a, D>) -> Val<'a, D> {
    match v {
        Val::ShortCircuit => Val::Undefined,
        other => other,
    }
}

/// 标准原型上的方法和属性名。
///
/// 数据模型只保存自有字段;但 JS 里 `"abc".includes` / `[].map` / `({}).toString`
/// 取到的是函数。游标没有函数值,若静默返回 `undefined`,漏写 `()` 会静默改变
/// 谓词结果。这里列出常见原型成员,访问时显式 `Unsupported`;未知字段仍按
/// JS 的缺失属性返回 `undefined`。
const OBJECT_PROTO: &[&str] = &[
    "constructor",
    "hasOwnProperty",
    "isPrototypeOf",
    "propertyIsEnumerable",
    "toLocaleString",
    "toString",
    "valueOf",
    "__proto__",
    "__defineGetter__",
    "__defineSetter__",
    "__lookupGetter__",
    "__lookupSetter__",
];

const ARRAY_PROTO: &[&str] = &[
    "at",
    "concat",
    "constructor",
    "copyWithin",
    "entries",
    "every",
    "fill",
    "filter",
    "find",
    "findIndex",
    "findLast",
    "findLastIndex",
    "flat",
    "flatMap",
    "forEach",
    "includes",
    "indexOf",
    "join",
    "keys",
    "lastIndexOf",
    "map",
    "pop",
    "push",
    "reduce",
    "reduceRight",
    "reverse",
    "shift",
    "slice",
    "some",
    "sort",
    "splice",
    "toLocaleString",
    "toString",
    "unshift",
    "values",
];

const STRING_PROTO: &[&str] = &[
    "anchor",
    "at",
    "big",
    "blink",
    "bold",
    "charAt",
    "charCodeAt",
    "codePointAt",
    "concat",
    "constructor",
    "endsWith",
    "fixed",
    "fontcolor",
    "fontsize",
    "includes",
    "indexOf",
    "isWellFormed",
    "italics",
    "lastIndexOf",
    "link",
    "localeCompare",
    "match",
    "matchAll",
    "normalize",
    "padEnd",
    "padStart",
    "repeat",
    "replace",
    "replaceAll",
    "search",
    "slice",
    "small",
    "split",
    "startsWith",
    "strike",
    "sub",
    "substr",
    "substring",
    "sup",
    "toLocaleLowerCase",
    "toLocaleUpperCase",
    "toLowerCase",
    "toString",
    "toUpperCase",
    "toWellFormed",
    "trim",
    "trimEnd",
    "trimStart",
    "valueOf",
];

const NUMBER_PROTO: &[&str] = &[
    "constructor",
    "toExponential",
    "toFixed",
    "toLocaleString",
    "toPrecision",
    "toString",
    "valueOf",
];

const BOOLEAN_PROTO: &[&str] = &["constructor", "toString", "valueOf"];

const DATE_PROTO: &[&str] = &[
    "constructor",
    "getDate",
    "getDay",
    "getFullYear",
    "getHours",
    "getMilliseconds",
    "getMinutes",
    "getMonth",
    "getSeconds",
    "getTime",
    "getTimezoneOffset",
    "getUTCDate",
    "getUTCDay",
    "getUTCFullYear",
    "getUTCHours",
    "getUTCMilliseconds",
    "getUTCMinutes",
    "getUTCMonth",
    "getUTCSeconds",
    "getYear",
    "setDate",
    "setFullYear",
    "setHours",
    "setMilliseconds",
    "setMinutes",
    "setMonth",
    "setSeconds",
    "setTime",
    "setUTCDate",
    "setUTCFullYear",
    "setUTCHours",
    "setUTCMilliseconds",
    "setUTCMinutes",
    "setUTCMonth",
    "setUTCSeconds",
    "setYear",
    "toDateString",
    "toISOString",
    "toJSON",
    "toLocaleDateString",
    "toLocaleString",
    "toLocaleTimeString",
    "toString",
    "toTimeString",
    "toUTCString",
    "valueOf",
];

fn is_prototype_member<'a, D: Data<'a>>(v: &Val<'a, D>, name: &str) -> bool {
    match v {
        Val::Str(_) => STRING_PROTO.contains(&name),
        Val::Num(_) => NUMBER_PROTO.contains(&name),
        Val::Bool(_) => BOOLEAN_PROTO.contains(&name),
        Val::Arr(_) => ARRAY_PROTO.contains(&name),
        Val::Obj(_) | Val::EmptyObj => OBJECT_PROTO.contains(&name),
        Val::Date(_) => DATE_PROTO.contains(&name),
        Val::Undefined | Val::Null | Val::ShortCircuit => false,
    }
}

fn prototype_error(name: &str) -> Error {
    Error::new(
        ErrorKind::Unsupported,
        format!("属性 `{name}` 是内置原型方法/属性,本 crate 没有函数值,契约外"),
    )
}

/// 读槽位:越界或未初始化都回错误,绝不用下标 panic。
fn slot_ref<'a, D: Data<'a>>(slots: &[Option<Val<'a, D>>], i: u16) -> Result<Val<'a, D>, Error> {
    slots
        .get(usize::from(i))
        .copied()
        .flatten()
        .ok_or_else(|| runtime("槽位越界或未初始化"))
}

/// 写槽位。
fn slot_set<'a, D: Data<'a>>(
    slots: &mut [Option<Val<'a, D>>],
    i: u16,
    v: Val<'a, D>,
) -> Result<(), Error> {
    match slots.get_mut(usize::from(i)) {
        Some(slot) => {
            *slot = Some(v);
            Ok(())
        }
        None => Err(runtime("槽位越界")),
    }
}

fn val_of<'a, D: Data<'a>>(d: D) -> Val<'a, D> {
    match d.kind() {
        Kind::Null => Val::Null,
        Kind::Bool => Val::Bool(d.as_bool().unwrap_or(false)),
        Kind::Number => Val::Num(d.as_f64().unwrap_or(f64::NAN)),
        Kind::String => Val::Str(d.as_str().unwrap_or("")),
        Kind::Array => Val::Arr(d),
        Kind::Object => Val::Obj(d),
    }
}

fn const_to_val<'a, D: Data<'a>>(c: &'a ConstVal) -> Val<'a, D> {
    match c {
        ConstVal::Undefined => Val::Undefined,
        ConstVal::Null => Val::Null,
        ConstVal::Bool(b) => Val::Bool(*b),
        ConstVal::Num(n) => Val::Num(*n),
        ConstVal::Str(s) => Val::Str(s),
    }
}

/// JS 字符串化,只在字符串方法/常量数组比较时用到。
fn to_js_string<'a, D: Data<'a>>(v: &Val<'a, D>) -> Option<Cow<'a, str>> {
    match v {
        Val::Str(s) => Some(Cow::Borrowed(*s)),
        Val::Num(n) => Some(Cow::Owned(format_num(*n))),
        Val::Bool(b) => Some(Cow::Borrowed(if *b { "true" } else { "false" })),
        Val::Null => Some(Cow::Borrowed("null")),
        Val::Undefined | Val::ShortCircuit => Some(Cow::Borrowed("undefined")),
        // Date 的默认 ToPrimitive 是 Date.prototype.toString(含时区/本地化),
        // 不能降成毫秒数字;字符串方法/模板遇到 Date 一律 fail-closed。
        Val::Date(_) => None,
        Val::Arr(_) | Val::Obj(_) => None,
        Val::EmptyObj => None,
    }
}

/// JS `Array.prototype.toString` 的扁平近似:逗号 join 原始元素。
///
/// `parseInt` 会先把参数转字符串,而 `[1]` 在 JS 里是 `"1"`。数组里一旦出现
/// 引用元素(嵌套数组/对象),完整 ToString 需要递归与对象身份,超出契约,
/// 这里显式 `Unsupported`,不能静默退回 NaN。
fn array_to_js_string<'a, D: Data<'a>>(d: D) -> Result<String, Error> {
    let mut out = String::new();
    for i in 0..d.len() {
        if i > 0 {
            out.push(',');
        }
        let Some(el) = d.at(i) else { continue };
        match val_of(el) {
            Val::Null | Val::Undefined => {}
            Val::Str(s) => out.push_str(s),
            Val::Num(n) => out.push_str(&format_num(n)),
            Val::Bool(b) => out.push_str(if b { "true" } else { "false" }),
            Val::Date(_) | Val::Arr(_) | Val::Obj(_) | Val::EmptyObj | Val::ShortCircuit => {
                return Err(Error::new(
                    ErrorKind::Unsupported,
                    "`parseInt` 的数组参数含引用元素,需要完整 ToString,契约外",
                ));
            }
        }
    }
    Ok(out)
}

fn eval_node<'a, D: Data<'a>>(
    n: &'a Node,
    cx: &Cx<'a, D>,
    slots: &mut [Option<Val<'a, D>>],
) -> Result<Val<'a, D>, Error> {
    match n {
        Node::Const(c) => Ok(const_to_val(c)),
        Node::Item => Ok(val_of(cx.row)),
        // 括号打断可选链:`(item?.a)` 的值是普通 undefined,外层的 `.length` 会抛错
        Node::Group(inner) => Ok(norm(eval_node(inner, cx, slots)?)),
        // `params` 缺省时生产端是 `JSON.parse("{}")`,即空对象;不是 undefined
        Node::Params => Ok(match cx.params {
            Some(p) => val_of(p),
            None => Val::EmptyObj,
        }),
        Node::Local(i) => slot_ref(slots, *i),
        Node::Path { base, segs } => resolve(*base, segs, cx, slots),
        Node::Member {
            base,
            name,
            optional,
        } => {
            let v = eval_node(base, cx, slots)?;
            if matches!(v, Val::ShortCircuit) {
                return Ok(Val::ShortCircuit);
            }
            lookup(v, name, *optional)
        }
        Node::Length { base, optional } => {
            let v = eval_node(base, cx, slots)?;
            if matches!(v, Val::ShortCircuit) {
                return Ok(Val::ShortCircuit);
            }
            match v {
                Val::Str(s) => Ok(Val::Num(semantics::utf16_len(s) as f64)),
                Val::Arr(d) => Ok(Val::Num(d.len() as f64)),
                // 对象可能有自有 `length` 字段;先按属性读,缺失才是 undefined
                Val::Obj(d) => Ok(d.get("length").map_or(Val::Undefined, val_of)),
                Val::EmptyObj => Ok(Val::Undefined),
                Val::Undefined | Val::Null if *optional => Ok(Val::ShortCircuit),
                Val::Undefined | Val::Null => Err(runtime("读取 null/undefined 的 `.length`")),
                // 数字、布尔、Date 装箱后没有自有 `length`,取到的是 undefined(不是抛错)
                Val::Num(_) | Val::Bool(_) | Val::Date(_) => Ok(Val::Undefined),
                Val::ShortCircuit => Ok(Val::ShortCircuit),
            }
        }
        Node::Index {
            base,
            index,
            optional,
        } => {
            let b = eval_node(base, cx, slots)?;
            if matches!(b, Val::ShortCircuit) {
                return Ok(Val::ShortCircuit);
            }
            // JS 的 `a?.[i]` 在 a 为 nullish 时整链短路,`i` 根本不会求值。
            // 必须在求值下标之前判空,否则下标里的 TypeError 会泄漏出来。
            if *optional && matches!(b, Val::Undefined | Val::Null) {
                return Ok(Val::ShortCircuit);
            }
            let i = eval_node(index, cx, slots)?;
            index_into(b, norm(i), *optional)
        }
        Node::Call {
            base,
            method,
            optional,
            arg,
        } => {
            let b = eval_node(base, cx, slots)?;
            if matches!(b, Val::ShortCircuit) {
                return Ok(Val::ShortCircuit);
            }
            // 同上:`a?.includes(f())` 在 a 为 nullish 时不会求值 f()。
            if *optional && matches!(b, Val::Undefined | Val::Null) {
                return Ok(Val::ShortCircuit);
            }
            let a = eval_node(arg, cx, slots)?;
            call_method(b, *method, *optional, norm(a))
        }
        Node::ConstIncludes { set, hay } => {
            let v = norm(eval_node(hay, cx, slots)?);
            let probe = match v {
                Val::Str(s) => Probe::Str(s),
                Val::Num(n) => Probe::Num(n),
                _ => Probe::Other,
            };
            Ok(Val::Bool(set.contains(probe)))
        }
        Node::Some {
            base,
            slot,
            body,
            optional,
        } => {
            let b = eval_node(base, cx, slots)?;
            match b {
                Val::ShortCircuit => Ok(Val::ShortCircuit),
                Val::Arr(d) => {
                    for i in 0..d.len() {
                        let Some(el) = d.at(i) else { continue };
                        slot_set(slots, *slot, val_of(el))?;
                        if semantics::truthy(&norm(eval_node(body, cx, slots)?)) {
                            return Ok(Val::Bool(true));
                        }
                    }
                    Ok(Val::Bool(false))
                }
                Val::Undefined | Val::Null if *optional => Ok(Val::ShortCircuit),
                Val::Undefined | Val::Null => Err(runtime("`.some` 的调用基座是 null/undefined")),
                _ => Err(type_err("`.some` 只能用于数组")),
            }
        }
        Node::ParseInt(inner) => {
            let v = norm(eval_node(inner, cx, slots)?);
            let n = match v {
                Val::Str(s) => semantics::parse_int(s),
                // JS 先字符串化再取数字前缀:`parseInt(1.9)` → 1,
                // `parseInt(1e21)` → 1(`String(1e21)` 是 "1e+21"),`parseInt(Infinity)` → NaN
                Val::Num(n) if n.is_finite() => {
                    let text = format_num(n);
                    semantics::parse_int(&text)
                }
                // `parseInt(new Date(0))` 先转成 Date 字符串(以星期名开头)→ NaN
                Val::Date(_) => f64::NAN,
                // JS 的 Array#toString 是逗号 join;只支持原始元素,引用元素 fail-closed
                Val::Arr(d) => semantics::parse_int(&array_to_js_string(d)?),
                // JS `parseInt(true)` 先转字符串 "true" 再取数字前缀,得到 NaN
                _ => f64::NAN,
            };
            Ok(Val::Num(n))
        }
        Node::IsArray(inner) => {
            let v = norm(eval_node(inner, cx, slots)?);
            Ok(Val::Bool(matches!(v, Val::Arr(_))))
        }
        Node::Not(inner) => {
            let v = norm(eval_node(inner, cx, slots)?);
            Ok(Val::Bool(!semantics::truthy(&v)))
        }
        Node::And(l, r) => {
            let lv = norm(eval_node(l, cx, slots)?);
            if semantics::truthy(&lv) {
                // 逻辑运算跨过了链的边界:右值即使是短路线,结果也是普通值。
                Ok(norm(eval_node(r, cx, slots)?))
            } else {
                Ok(lv)
            }
        }
        Node::Or(l, r) => {
            let lv = norm(eval_node(l, cx, slots)?);
            if semantics::truthy(&lv) {
                Ok(lv)
            } else {
                Ok(norm(eval_node(r, cx, slots)?))
            }
        }
        // `??` 只看 null/undefined,不看 falsy:`0 ?? 1` → 0、`'' ?? 'x'` → ''。
        // 可选链短路的哨兵先归一成 undefined,所以 `item?.a ?? b` 在 item 缺失时取 b,
        // 与 JS 把 `(item?.a)` 当 undefined 再合并一致。
        Node::Nullish(l, r) => {
            let lv = norm(eval_node(l, cx, slots)?);
            match lv {
                Val::Null | Val::Undefined => Ok(norm(eval_node(r, cx, slots)?)),
                other => Ok(other),
            }
        }
        Node::StrictEq(l, r) => {
            let lv = norm(eval_node(l, cx, slots)?);
            let rv = norm(eval_node(r, cx, slots)?);
            // 引用之间要做身份比较(`item.o === item.o` 在 JS 为 true),
            // 而 Data 游标没有身份信息;静默按 false 会改写语义。
            // 一边是引用、一边是原始值则类型必不同,恒 false,无需拒绝。
            // Date 同理:编译期只能拒绝 AST 上的 DateNew,局部变量绕过后
            // 两个日期引用是否相同无法判定,必须 fail-closed。
            if matches!((&lv, &rv), (Val::Date(_), Val::Date(_))) {
                return Err(Error::new(
                    ErrorKind::Unsupported,
                    "Date 之间的 `===`/`!==` 需要引用身份,契约外".to_string(),
                ));
            }
            if needs_identity(&lv) && needs_identity(&rv) {
                return Err(Error::new(
                    ErrorKind::Unsupported,
                    "对象/数组之间的 `===`/`!==` 需要引用身份,契约外".to_string(),
                ));
            }
            Ok(Val::Bool(semantics::strict_eq(&lv, &rv)))
        }
        Node::LooseEq(l, r) => {
            let lv = norm(eval_node(l, cx, slots)?);
            let rv = norm(eval_node(r, cx, slots)?);
            // Date 的默认 ToPrimitive 走 Date.prototype.toString(字符串 hint),
            // 不是数值:`new Date(0) == 0` 在 JS 为 false。Date 与数字/布尔可安全
            // 判 false;与字符串/Date/数组/对象比较需要真实 Date 字符串或引用身份,
            // 无法在本 crate 中表达,显式 fail-closed。
            if matches!(lv, Val::Date(_)) || matches!(rv, Val::Date(_)) {
                let other = if matches!(lv, Val::Date(_)) { &rv } else { &lv };
                return match other {
                    Val::Null | Val::Undefined => Ok(Val::Bool(false)),
                    Val::Num(_) | Val::Bool(_) => Ok(Val::Bool(false)),
                    _ => Err(Error::new(
                        ErrorKind::Unsupported,
                        "Date 参与 `==`/`!=` 需要 ToPrimitive 或引用身份,契约外".to_string(),
                    )),
                };
            }
            // 数组/对象参与 `==` 要走 ToPrimitive(数组 join、对象 "[object Object]")。
            // 本 crate 的 Val::Str 只能借用,无法承载 join 出的字符串;静默按 false
            // 处理会错判(`[] == false` 在 JS 为 true),显式报 Unsupported。
            // 与 null/undefined 比较恒 false,无需 ToPrimitive,保持原行为。
            if (needs_to_primitive(&lv) || needs_to_primitive(&rv))
                && !matches!(lv, Val::Null | Val::Undefined)
                && !matches!(rv, Val::Null | Val::Undefined)
            {
                return Err(Error::new(
                    ErrorKind::Unsupported,
                    "数组/对象参与 `==`/`!=` 需要 ToPrimitive,契约外".to_string(),
                ));
            }
            Ok(Val::Bool(semantics::loose_eq(&lv, &rv)))
        }
        Node::Rel { op, lhs, rhs } => {
            let lv = norm(eval_node(lhs, cx, slots)?);
            let rv = norm(eval_node(rhs, cx, slots)?);
            if needs_to_primitive(&lv) || needs_to_primitive(&rv) {
                return Err(Error::new(
                    ErrorKind::Unsupported,
                    "数组/对象参与关系比较需要 ToPrimitive,契约外".to_string(),
                ));
            }
            let ord = semantics::compare(&lv, &rv);
            let out = match (ord, op) {
                (Some(o), RelOp::Lt) => o.is_lt(),
                (Some(o), RelOp::Le) => o.is_le(),
                (Some(o), RelOp::Gt) => o.is_gt(),
                (Some(o), RelOp::Ge) => o.is_ge(),
                (None, _) => false,
            };
            Ok(Val::Bool(out))
        }
        // `new Date()` 取真实时钟;参数按 JS 的 ToPrimitive 语义折算成时刻。
        Node::DateNew(arg) => {
            let ms = match arg {
                None => date::now_ms(),
                Some(a) => match norm(eval_node(a, cx, slots)?) {
                    Val::Num(n) => date::clip(n),
                    // `new Date(dateObject)` 按 ES 规范直接复制其 time value
                    Val::Date(n) => date::clip(n),
                    Val::Str(s) => date::parse(s),
                    // `new Date(null)` 是 epoch 0,`new Date(true)` 是 1
                    Val::Null => 0.0,
                    Val::Bool(b) => {
                        if b {
                            1.0
                        } else {
                            0.0
                        }
                    }
                    // `new Date(undefined)` 是 Invalid Date
                    Val::Undefined => f64::NAN,
                    // 数组走 ToPrimitive(join 再当字符串解析):quickjs 实测
                    // `new Date([])` → NaN、`new Date([1])` → 2001-01-01。
                    // 引用元素的数组需要完整 ToString → Unsupported(同 parseInt)。
                    Val::Arr(d) => date::parse(&array_to_js_string(d)?),
                    // 普通对象 ToPrimitive 是 "[object Object]" → 不可解析 → NaN
                    // (quickjs 实测 `new Date({})` 为 NaN)。
                    Val::Obj(_) | Val::EmptyObj => f64::NAN,
                    // 短路哨兵已在上面归一成 undefined
                    Val::ShortCircuit => f64::NAN,
                },
            };
            Ok(Val::Date(ms))
        }
        Node::DateNow => Ok(Val::Num(date::now_ms())),
        Node::GetTime { base, optional } => {
            let v = eval_node(base, cx, slots)?;
            if matches!(v, Val::ShortCircuit) {
                return Ok(Val::ShortCircuit);
            }
            if *optional && matches!(v, Val::Undefined | Val::Null) {
                return Ok(Val::ShortCircuit);
            }
            match v {
                // `.getTime()` 只接受真正的 Date 值;`Date.now()` 是数字,
                // 在 JS 里调用 `.getTime()` 会抛 TypeError,不能静默返回时间戳。
                Val::Date(n) => Ok(Val::Num(n)),
                other => Err(type_err(&format!(
                    "`.getTime()` 的基座不是 Date(得到 {other:?})"
                ))),
            }
        }
        Node::MathFloor(inner) => {
            let v = norm(eval_node(inner, cx, slots)?);
            let n = semantics::to_number(&v)
                .ok_or_else(|| type_err("`Math.floor` 的参数需要 ToNumber(数组/对象契约外)"))?;
            Ok(Val::Num(n.floor()))
        }
        Node::Arith { op, lhs, rhs } => {
            let lv = norm(eval_node(lhs, cx, slots)?);
            let rv = norm(eval_node(rhs, cx, slots)?);
            let a = semantics::to_number(&lv)
                .ok_or_else(|| type_err("算术左值需要 ToNumber(数组/对象契约外)"))?;
            let b = semantics::to_number(&rv)
                .ok_or_else(|| type_err("算术右值需要 ToNumber(数组/对象契约外)"))?;
            // f64 的 `/` 与 JS 一致:`x/0` → ±Infinity,`0/0` → NaN
            Ok(Val::Num(match op {
                ArithOp::Sub => a - b,
                ArithOp::Mul => a * b,
                ArithOp::Div => a / b,
            }))
        }
        Node::Set { .. } => Err(runtime("绑定语句不能出现在表达式位置")),
    }
}

fn resolve<'a, D: Data<'a>>(
    base: PathBase,
    segs: &'a [PathSeg],
    cx: &Cx<'a, D>,
    slots: &mut [Option<Val<'a, D>>],
) -> Result<Val<'a, D>, Error> {
    let mut v = match base {
        PathBase::Item => val_of(cx.row),
        PathBase::Params => match cx.params {
            Some(p) => val_of(p),
            None => Val::EmptyObj,
        },
        PathBase::Local(i) => slot_ref(slots, i)?,
    };
    for seg in segs {
        // `?.` 一旦在任一段短路,整条链后续所有访问都不再发生(JS optional chain 语义),
        // 用哨兵一路透传到链尾;键缺失则只产生 undefined,让后续段按 JS 规则抛错。
        if matches!(v, Val::ShortCircuit) {
            return Ok(Val::ShortCircuit);
        }
        if matches!(v, Val::Undefined | Val::Null) {
            if seg.optional {
                return Ok(Val::ShortCircuit);
            }
            return Err(runtime(&format!(
                "读取 `{}` 时基座是 null/undefined(JS 会抛 TypeError)",
                seg.name
            )));
        }
        // 对象先查自有字段;没有自有字段时,内置原型成员要 fail-closed
        // (`item.o.toString` 在 JS 里是函数,不是 undefined)。
        v = match &v {
            Val::Obj(d) => match d.get(&seg.name) {
                Some(x) => val_of(x),
                None if is_prototype_member(&v, &seg.name) => {
                    return Err(prototype_error(&seg.name));
                }
                None => Val::Undefined,
            },
            _ if is_prototype_member(&v, &seg.name) => {
                return Err(prototype_error(&seg.name));
            }
            // 数组/空对象/原始类型上的未知属性在 JS 里是 undefined
            _ => Val::Undefined,
        };
    }
    Ok(v)
}

/// 单段成员访问,`?.` 使基座为空时整链短路(返回哨兵)。
fn lookup<'a, D: Data<'a>>(v: Val<'a, D>, name: &str, optional: bool) -> Result<Val<'a, D>, Error> {
    match v {
        Val::Obj(d) => match d.get(name) {
            Some(x) => Ok(val_of(x)),
            None if is_prototype_member(&Val::Obj(d), name) => Err(prototype_error(name)),
            None => Ok(Val::Undefined),
        },
        Val::ShortCircuit => Ok(Val::ShortCircuit),
        Val::Undefined | Val::Null => {
            if optional {
                Ok(Val::ShortCircuit)
            } else {
                Err(runtime(&format!(
                    "读取 `{name}` 时基座是 null/undefined(JS 会抛 TypeError)"
                )))
            }
        }
        // 原始类型/数组/Date/空对象:内置原型成员显式失败,未知属性才是 undefined
        other if is_prototype_member(&other, name) => Err(prototype_error(name)),
        _ => Ok(Val::Undefined),
    }
}

fn object_property<'a, D: Data<'a>>(d: D, key: &str) -> Result<Val<'a, D>, Error> {
    match d.get(key) {
        Some(x) => Ok(val_of(x)),
        None if OBJECT_PROTO.contains(&key) => Err(prototype_error(key)),
        None => Ok(Val::Undefined),
    }
}

fn index_into<'a, D: Data<'a>>(
    base: Val<'a, D>,
    index: Val<'a, D>,
    optional: bool,
) -> Result<Val<'a, D>, Error> {
    match (base, index) {
        (Val::ShortCircuit, _) => Ok(Val::ShortCircuit),
        (Val::Arr(d), Val::Num(n)) => {
            // `n as usize` 在 n ≥ 2^64 时会饱和成 usize::MAX。把它交给外部
            // `Data::at` 实现会在用 `vec[i]` 的适配器上直接 panic;即使契约
            // 要求越界返回 None,也不该把明显越界的下标传出去。先按数组
            // 长度裁剪,越界即 undefined(JS 语义本就如此)。
            if !(0.0..(d.len() as f64)).contains(&n) || n.fract() != 0.0 {
                return Ok(Val::Undefined);
            }
            Ok(d.at(n as usize).map_or(Val::Undefined, val_of))
        }
        // JS ToPropertyKey:数字键先按 String(n) 转字符串,再查对象属性
        (Val::Obj(d), Val::Num(n)) => {
            let key = format_num(n);
            Ok(d.get(&key).map_or(Val::Undefined, val_of))
        }
        (Val::Obj(d), Val::Str(s)) => object_property(d, s),
        (Val::Obj(d), Val::Bool(b)) => object_property(d, if b { "true" } else { "false" }),
        (Val::Obj(d), Val::Null) => object_property(d, "null"),
        (Val::Obj(d), Val::Undefined) => object_property(d, "undefined"),
        (Val::Obj(_), Val::Date(_) | Val::Arr(_) | Val::Obj(_) | Val::EmptyObj) => Err(Error::new(
            ErrorKind::Unsupported,
            "对象下标是引用类型,需要 ToPropertyKey,契约外".to_string(),
        )),
        // 数组上的字符串键:`"length"` 是元属性,规范数字串是下标,其余是普通属性
        (Val::Arr(d), Val::Str(s)) => {
            if s == "length" {
                return Ok(Val::Num(d.len() as f64));
            }
            // 与数字下标分支同样要按 `d.len()` 裁剪:`canonical_index` 接受
            // `"18446744073709551615"`(= usize::MAX),裸传给外部 `Data::at`
            // 会在用 `vec[i]` 的适配器上 panic。
            match canonical_index(s) {
                Some(k) if k < d.len() => Ok(d.at(k).map_or(Val::Undefined, val_of)),
                _ if ARRAY_PROTO.contains(&s) => Err(prototype_error(s)),
                _ => Ok(Val::Undefined),
            }
        }
        // 数组上的 bool/null/undefined/Date 键不是数组下标,数据数组没有自有属性
        (Val::Arr(_), Val::Bool(_) | Val::Null | Val::Undefined | Val::Date(_)) => {
            Ok(Val::Undefined)
        }
        (Val::Arr(_), Val::Arr(_) | Val::Obj(_) | Val::EmptyObj) => Err(Error::new(
            ErrorKind::Unsupported,
            "数组下标是引用类型,需要 ToPropertyKey,契约外".to_string(),
        )),
        // 字符串下标同样走 ToPropertyKey:规范数字串按 UTF-16 码元取字符
        (Val::Str(s), Val::Str(idx)) => {
            if idx == "length" {
                return Ok(Val::Num(semantics::utf16_len(s) as f64));
            }
            match canonical_index(idx) {
                Some(k) => match utf16_char_at(s, k) {
                    Utf16At::Char(c) => Ok(Val::Str(c)),
                    Utf16At::None => Ok(Val::Undefined),
                    Utf16At::Surrogate => Err(Error::new(
                        ErrorKind::Unsupported,
                        "非 BMP 字符的 UTF-16 中间码元是孤立代理,无法用 Rust str 表示",
                    )),
                },
                _ if STRING_PROTO.contains(&idx) => Err(prototype_error(idx)),
                None => Ok(Val::Undefined),
            }
        }
        (Val::Str(s), Val::Num(n)) => {
            if n < 0.0 || n.fract() != 0.0 {
                return Ok(Val::Undefined);
            }
            match utf16_char_at(s, n as usize) {
                Utf16At::Char(c) => Ok(Val::Str(c)),
                Utf16At::None => Ok(Val::Undefined),
                // JS 会返回孤立代理码元 "\ud800" 一类字符串,Rust 的 str 无法表示
                Utf16At::Surrogate => Err(Error::new(
                    ErrorKind::Unsupported,
                    "非 BMP 字符的 UTF-16 中间码元是孤立代理,无法用 Rust str 表示",
                )),
            }
        }
        (Val::Str(_), Val::Bool(_) | Val::Null | Val::Undefined | Val::Date(_)) => {
            Ok(Val::Undefined)
        }
        (Val::Str(_), Val::Arr(_) | Val::Obj(_) | Val::EmptyObj) => Err(Error::new(
            ErrorKind::Unsupported,
            "字符串下标是引用类型,需要 ToPropertyKey,契约外".to_string(),
        )),
        // Date 是对象:已知原型成员(如 getTime)是函数,未知属性是 undefined
        (Val::Date(_), Val::Str(s)) => {
            if DATE_PROTO.contains(&s) {
                Err(prototype_error(s))
            } else {
                Ok(Val::Undefined)
            }
        }
        (Val::Date(_), Val::Bool(_) | Val::Null | Val::Undefined | Val::Num(_) | Val::Date(_)) => {
            Ok(Val::Undefined)
        }
        (Val::Date(_), Val::Arr(_) | Val::Obj(_) | Val::EmptyObj) => Err(Error::new(
            ErrorKind::Unsupported,
            "Date 下标是引用类型,需要 ToPropertyKey,契约外".to_string(),
        )),
        (Val::Undefined | Val::Null, _) if optional => Ok(Val::ShortCircuit),
        (Val::Undefined | Val::Null, _) => Err(runtime("对 null/undefined 取下标")),
        (Val::Num(_), Val::Str(s)) => {
            if NUMBER_PROTO.contains(&s) {
                Err(prototype_error(s))
            } else {
                Ok(Val::Undefined)
            }
        }
        (Val::Bool(_), Val::Str(s)) => {
            if BOOLEAN_PROTO.contains(&s) {
                Err(prototype_error(s))
            } else {
                Ok(Val::Undefined)
            }
        }
        (Val::EmptyObj, Val::Str(s)) => {
            if OBJECT_PROTO.contains(&s) {
                Err(prototype_error(s))
            } else {
                Ok(Val::Undefined)
            }
        }
        (Val::Num(_) | Val::Bool(_) | Val::EmptyObj, _) => Ok(Val::Undefined),
        (Val::Arr(_), _) => Err(type_err("数组下标必须是整数")),
        (Val::Str(_), _) => Ok(Val::Undefined),
        _ => Ok(Val::Undefined),
    }
}

/// 数组的规范数字键:`"0"`/`"12"` 是下标,`"01"`/`"+1"`/`"-1"`/`"a"` 不是
/// (后者在数组上只是普通属性,取到 undefined)。
fn canonical_index(s: &str) -> Option<usize> {
    let b = s.as_bytes();
    if b.is_empty() || !b[0].is_ascii_digit() {
        return None;
    }
    if b.len() > 1 && b[0] == b'0' {
        return None;
    }
    s.parse::<usize>().ok()
}

enum Utf16At<'a> {
    /// 完整字符的借用切片。
    Char(&'a str),
    /// 落在代理对中间:JS 返回孤立代理,Rust `str` 无法表达。
    Surrogate,
    /// 越界。
    None,
}

fn utf16_char_at(s: &str, idx: usize) -> Utf16At<'_> {
    let mut pos = 0usize;
    for (byte, ch) in s.char_indices() {
        let units = ch.len_utf16();
        if pos == idx {
            // 非 BMP 字符的起始码元是孤立高代理:JS `"😀"[0]` / `"a😀b"[1]`
            // 返回 `"\ud83d"`,不等于完整字符。Rust str 表达不了单独代理,
            // 与落在代理对中间的低代理一样按契约外拒绝,不能静默返回整字符。
            return if units == 1 {
                match s.get(byte..byte + ch.len_utf8()) {
                    Some(c) => Utf16At::Char(c),
                    None => Utf16At::None,
                }
            } else {
                Utf16At::Surrogate
            };
        }
        if units == 2 && pos < idx && idx < pos + units {
            return Utf16At::Surrogate;
        }
        pos += units;
    }
    Utf16At::None
}

fn call_method<'a, D: Data<'a>>(
    base: Val<'a, D>,
    method: Method,
    optional: bool,
    arg: Val<'a, D>,
) -> Result<Val<'a, D>, Error> {
    if matches!(base, Val::ShortCircuit) {
        return Ok(Val::ShortCircuit);
    }
    if matches!(base, Val::Undefined | Val::Null) && optional {
        return Ok(Val::ShortCircuit);
    }
    match base {
        Val::Str(s) => {
            let Some(needle) = to_js_string(&arg) else {
                return Err(type_err("字符串方法的参数不能是数组/对象"));
            };
            match method {
                Method::Includes => Ok(Val::Bool(s.contains(needle.as_ref()))),
                Method::IndexOf => Ok(Val::Num(match s.find(needle.as_ref()) {
                    Some(byte) => semantics::utf16_len(&s[..byte]) as f64,
                    None => -1.0,
                })),
                Method::StartsWith => Ok(Val::Bool(s.starts_with(needle.as_ref()))),
                Method::EndsWith => Ok(Val::Bool(s.ends_with(needle.as_ref()))),
                Method::Some => Err(type_err("`.some` 只能用于数组")),
                Method::GetTime => Err(runtime("`.getTime()` 走独立节点")),
            }
        }
        Val::Arr(d) => match method {
            Method::Includes | Method::IndexOf if needs_identity(&arg) => Err(Error::new(
                ErrorKind::Unsupported,
                "数组方法的引用参数需要身份比较,契约外".to_string(),
            )),
            Method::Includes => {
                for i in 0..d.len() {
                    let Some(el) = d.at(i) else { continue };
                    if semantics::same_value_zero(&val_of(el), &arg) {
                        return Ok(Val::Bool(true));
                    }
                }
                Ok(Val::Bool(false))
            }
            Method::IndexOf => {
                for i in 0..d.len() {
                    let Some(el) = d.at(i) else { continue };
                    if semantics::strict_eq(&val_of(el), &arg) {
                        return Ok(Val::Num(i as f64));
                    }
                }
                Ok(Val::Num(-1.0))
            }
            Method::StartsWith => Err(type_err("`.startsWith` 只能用于字符串")),
            Method::EndsWith => Err(type_err("`.endsWith` 只能用于字符串")),
            Method::Some => Err(type_err("`.some` 走独立节点")),
            Method::GetTime => Err(runtime("`.getTime()` 走独立节点")),
        },
        Val::Undefined | Val::Null => Err(runtime("对 null/undefined 调用方法")),
        _ => Err(type_err("基座不是数组或字符串")),
    }
}