Skip to main content

js2rust_predicate/
eval.rs

1//! 求值:按节点树走一遍,零分配、无虚表。
2//!
3//! 约束:所有字符串都借用自数据或编译产物(`'a` 同时覆盖两者),
4//! 唯一可能分配的是 `Num` 参与字符串方法时的格式化(语料里不存在)。
5
6use std::borrow::Cow;
7use std::marker::PhantomData;
8
9use crate::ast::Method;
10use crate::compile::{ArithOp, ConstVal, Node, PathBase, PathSeg, Program, RelOp, format_num};
11use crate::date;
12use crate::error::{Error, ErrorKind};
13use crate::semantics;
14use crate::set::Probe;
15use crate::value::{Data, Kind, Val};
16
17/// 与解析器的槽位上限保持一致。
18const MAX_SLOTS: usize = 16;
19
20struct Cx<'a, D: Data<'a>> {
21    row: D,
22    params: Option<D>,
23    _l: PhantomData<&'a ()>,
24}
25
26impl Program {
27    /// 对一行数据求值。
28    ///
29    /// `row` 是 `item`,`params` 是 `params`(未传时为 `undefined`)。
30    /// 两者必须是同一个类型——调用方用一个覆盖两种数据来源的枚举适配器即可。
31    ///
32    /// 返回 `Err` 时是否 fail-closed 由调用方决定。
33    pub fn eval<'a, D: Data<'a>>(&'a self, row: D, params: Option<D>) -> Result<bool, Error> {
34        // 编译期已知槽位数;固定数组必须容得下,否则是解析器/编译器漂移
35        debug_assert!(usize::from(self.slots) <= MAX_SLOTS, "槽位数超出上限");
36        let mut slots: [Option<Val<'a, D>>; MAX_SLOTS] = [None; MAX_SLOTS];
37        let cx = Cx {
38            row,
39            params,
40            _l: PhantomData,
41        };
42        for step in self.steps.iter() {
43            match step {
44                Node::Set { slot, value } => {
45                    // 短路哨兵只在**同一条链**内透传;一旦绑定到变量就成了普通
46                    // undefined,后续 `x.length` 在 JS 里是 TypeError 而不是短路。
47                    let v = norm(eval_node(value, &cx, &mut slots)?);
48                    slot_set(&mut slots, *slot, v)?;
49                }
50                _ => {
51                    return Err(Error::new(ErrorKind::Runtime, "非绑定步骤"));
52                }
53            }
54        }
55        let out = norm(eval_node(&self.result, &cx, &mut slots)?);
56        // 与生产端对齐:rquickjs 把完成值按 `bool` 严格转换,非布尔值是**错误**而非
57        // truthiness(`undefined?.includes(x)`、裸 `parseInt(...)` 都属此类)。
58        match out {
59            Val::Bool(b) => Ok(b),
60            other => Err(runtime(&format!(
61                "filter 表达式结果不是布尔(完成值 {:?},生产端会抛转换错误)",
62                other
63            ))),
64        }
65    }
66}
67
68fn runtime(msg: &str) -> Error {
69    Error::new(ErrorKind::Runtime, msg.to_string())
70}
71
72/// 类型不匹配(JS 里会得到 `undefined` 或抛 TypeError 的形态,这里显式报错)。
73fn type_err(msg: &str) -> Error {
74    Error::new(ErrorKind::Type, msg.to_string())
75}
76
77/// 是否需要 JS ToPrimitive 才能比较(数组/对象)。严格比较不走这里——
78/// `===` 对引用身份恒 false 是既有契约,与 ToPrimitive 无关。
79fn needs_to_primitive<'a, D: Data<'a>>(v: &Val<'a, D>) -> bool {
80    matches!(v, Val::Arr(_) | Val::Obj(_) | Val::EmptyObj)
81}
82
83/// 值是否为 JS 引用类型。`Data` 是零分配游标,没有对象身份信息,
84/// 因此两个引用之间的 `===` / `.includes` / `.indexOf` 无法判定(同一引用
85/// 在 JS 为 true,不同引用为 false)。调用方必须显式报 `Unsupported`,
86/// 不能静默按 false 处理。
87fn needs_identity<'a, D: Data<'a>>(v: &Val<'a, D>) -> bool {
88    matches!(v, Val::Arr(_) | Val::Obj(_) | Val::EmptyObj)
89}
90
91/// 把可选链短路哨兵归一成 `undefined`:只应在**消费值**的地方调用
92/// (比较、真值判断、方法参数、最终结果),链式节点之间必须原样透传。
93fn norm<'a, D: Data<'a>>(v: Val<'a, D>) -> Val<'a, D> {
94    match v {
95        Val::ShortCircuit => Val::Undefined,
96        other => other,
97    }
98}
99
100/// 标准原型上的方法和属性名。
101///
102/// 数据模型只保存自有字段;但 JS 里 `"abc".includes` / `[].map` / `({}).toString`
103/// 取到的是函数。游标没有函数值,若静默返回 `undefined`,漏写 `()` 会静默改变
104/// 谓词结果。这里列出常见原型成员,访问时显式 `Unsupported`;未知字段仍按
105/// JS 的缺失属性返回 `undefined`。
106const OBJECT_PROTO: &[&str] = &[
107    "constructor",
108    "hasOwnProperty",
109    "isPrototypeOf",
110    "propertyIsEnumerable",
111    "toLocaleString",
112    "toString",
113    "valueOf",
114    "__proto__",
115    "__defineGetter__",
116    "__defineSetter__",
117    "__lookupGetter__",
118    "__lookupSetter__",
119];
120
121const ARRAY_PROTO: &[&str] = &[
122    "at",
123    "concat",
124    "constructor",
125    "copyWithin",
126    "entries",
127    "every",
128    "fill",
129    "filter",
130    "find",
131    "findIndex",
132    "findLast",
133    "findLastIndex",
134    "flat",
135    "flatMap",
136    "forEach",
137    "includes",
138    "indexOf",
139    "join",
140    "keys",
141    "lastIndexOf",
142    "map",
143    "pop",
144    "push",
145    "reduce",
146    "reduceRight",
147    "reverse",
148    "shift",
149    "slice",
150    "some",
151    "sort",
152    "splice",
153    "toLocaleString",
154    "toString",
155    "unshift",
156    "values",
157];
158
159const STRING_PROTO: &[&str] = &[
160    "anchor",
161    "at",
162    "big",
163    "blink",
164    "bold",
165    "charAt",
166    "charCodeAt",
167    "codePointAt",
168    "concat",
169    "constructor",
170    "endsWith",
171    "fixed",
172    "fontcolor",
173    "fontsize",
174    "includes",
175    "indexOf",
176    "isWellFormed",
177    "italics",
178    "lastIndexOf",
179    "link",
180    "localeCompare",
181    "match",
182    "matchAll",
183    "normalize",
184    "padEnd",
185    "padStart",
186    "repeat",
187    "replace",
188    "replaceAll",
189    "search",
190    "slice",
191    "small",
192    "split",
193    "startsWith",
194    "strike",
195    "sub",
196    "substr",
197    "substring",
198    "sup",
199    "toLocaleLowerCase",
200    "toLocaleUpperCase",
201    "toLowerCase",
202    "toString",
203    "toUpperCase",
204    "toWellFormed",
205    "trim",
206    "trimEnd",
207    "trimStart",
208    "valueOf",
209];
210
211const NUMBER_PROTO: &[&str] = &[
212    "constructor",
213    "toExponential",
214    "toFixed",
215    "toLocaleString",
216    "toPrecision",
217    "toString",
218    "valueOf",
219];
220
221const BOOLEAN_PROTO: &[&str] = &["constructor", "toString", "valueOf"];
222
223const DATE_PROTO: &[&str] = &[
224    "constructor",
225    "getDate",
226    "getDay",
227    "getFullYear",
228    "getHours",
229    "getMilliseconds",
230    "getMinutes",
231    "getMonth",
232    "getSeconds",
233    "getTime",
234    "getTimezoneOffset",
235    "getUTCDate",
236    "getUTCDay",
237    "getUTCFullYear",
238    "getUTCHours",
239    "getUTCMilliseconds",
240    "getUTCMinutes",
241    "getUTCMonth",
242    "getUTCSeconds",
243    "getYear",
244    "setDate",
245    "setFullYear",
246    "setHours",
247    "setMilliseconds",
248    "setMinutes",
249    "setMonth",
250    "setSeconds",
251    "setTime",
252    "setUTCDate",
253    "setUTCFullYear",
254    "setUTCHours",
255    "setUTCMilliseconds",
256    "setUTCMinutes",
257    "setUTCMonth",
258    "setUTCSeconds",
259    "setYear",
260    "toDateString",
261    "toISOString",
262    "toJSON",
263    "toLocaleDateString",
264    "toLocaleString",
265    "toLocaleTimeString",
266    "toString",
267    "toTimeString",
268    "toUTCString",
269    "valueOf",
270];
271
272fn is_prototype_member<'a, D: Data<'a>>(v: &Val<'a, D>, name: &str) -> bool {
273    match v {
274        Val::Str(_) => STRING_PROTO.contains(&name),
275        Val::Num(_) => NUMBER_PROTO.contains(&name),
276        Val::Bool(_) => BOOLEAN_PROTO.contains(&name),
277        Val::Arr(_) => ARRAY_PROTO.contains(&name),
278        Val::Obj(_) | Val::EmptyObj => OBJECT_PROTO.contains(&name),
279        Val::Date(_) => DATE_PROTO.contains(&name),
280        Val::Undefined | Val::Null | Val::ShortCircuit => false,
281    }
282}
283
284fn prototype_error(name: &str) -> Error {
285    Error::new(
286        ErrorKind::Unsupported,
287        format!("属性 `{name}` 是内置原型方法/属性,本 crate 没有函数值,契约外"),
288    )
289}
290
291/// 读槽位:越界或未初始化都回错误,绝不用下标 panic。
292fn slot_ref<'a, D: Data<'a>>(slots: &[Option<Val<'a, D>>], i: u16) -> Result<Val<'a, D>, Error> {
293    slots
294        .get(usize::from(i))
295        .copied()
296        .flatten()
297        .ok_or_else(|| runtime("槽位越界或未初始化"))
298}
299
300/// 写槽位。
301fn slot_set<'a, D: Data<'a>>(
302    slots: &mut [Option<Val<'a, D>>],
303    i: u16,
304    v: Val<'a, D>,
305) -> Result<(), Error> {
306    match slots.get_mut(usize::from(i)) {
307        Some(slot) => {
308            *slot = Some(v);
309            Ok(())
310        }
311        None => Err(runtime("槽位越界")),
312    }
313}
314
315fn val_of<'a, D: Data<'a>>(d: D) -> Val<'a, D> {
316    match d.kind() {
317        Kind::Null => Val::Null,
318        Kind::Bool => Val::Bool(d.as_bool().unwrap_or(false)),
319        Kind::Number => Val::Num(d.as_f64().unwrap_or(f64::NAN)),
320        Kind::String => Val::Str(d.as_str().unwrap_or("")),
321        Kind::Array => Val::Arr(d),
322        Kind::Object => Val::Obj(d),
323    }
324}
325
326fn const_to_val<'a, D: Data<'a>>(c: &'a ConstVal) -> Val<'a, D> {
327    match c {
328        ConstVal::Undefined => Val::Undefined,
329        ConstVal::Null => Val::Null,
330        ConstVal::Bool(b) => Val::Bool(*b),
331        ConstVal::Num(n) => Val::Num(*n),
332        ConstVal::Str(s) => Val::Str(s),
333    }
334}
335
336/// JS 字符串化,只在字符串方法/常量数组比较时用到。
337fn to_js_string<'a, D: Data<'a>>(v: &Val<'a, D>) -> Option<Cow<'a, str>> {
338    match v {
339        Val::Str(s) => Some(Cow::Borrowed(*s)),
340        Val::Num(n) => Some(Cow::Owned(format_num(*n))),
341        Val::Bool(b) => Some(Cow::Borrowed(if *b { "true" } else { "false" })),
342        Val::Null => Some(Cow::Borrowed("null")),
343        Val::Undefined | Val::ShortCircuit => Some(Cow::Borrowed("undefined")),
344        // Date 的默认 ToPrimitive 是 Date.prototype.toString(含时区/本地化),
345        // 不能降成毫秒数字;字符串方法/模板遇到 Date 一律 fail-closed。
346        Val::Date(_) => None,
347        Val::Arr(_) | Val::Obj(_) => None,
348        Val::EmptyObj => None,
349    }
350}
351
352/// JS `Array.prototype.toString` 的扁平近似:逗号 join 原始元素。
353///
354/// `parseInt` 会先把参数转字符串,而 `[1]` 在 JS 里是 `"1"`。数组里一旦出现
355/// 引用元素(嵌套数组/对象),完整 ToString 需要递归与对象身份,超出契约,
356/// 这里显式 `Unsupported`,不能静默退回 NaN。
357fn array_to_js_string<'a, D: Data<'a>>(d: D) -> Result<String, Error> {
358    let mut out = String::new();
359    for i in 0..d.len() {
360        if i > 0 {
361            out.push(',');
362        }
363        let Some(el) = d.at(i) else { continue };
364        match val_of(el) {
365            Val::Null | Val::Undefined => {}
366            Val::Str(s) => out.push_str(s),
367            Val::Num(n) => out.push_str(&format_num(n)),
368            Val::Bool(b) => out.push_str(if b { "true" } else { "false" }),
369            Val::Date(_) | Val::Arr(_) | Val::Obj(_) | Val::EmptyObj | Val::ShortCircuit => {
370                return Err(Error::new(
371                    ErrorKind::Unsupported,
372                    "`parseInt` 的数组参数含引用元素,需要完整 ToString,契约外",
373                ));
374            }
375        }
376    }
377    Ok(out)
378}
379
380fn eval_node<'a, D: Data<'a>>(
381    n: &'a Node,
382    cx: &Cx<'a, D>,
383    slots: &mut [Option<Val<'a, D>>],
384) -> Result<Val<'a, D>, Error> {
385    match n {
386        Node::Const(c) => Ok(const_to_val(c)),
387        Node::Item => Ok(val_of(cx.row)),
388        // 括号打断可选链:`(item?.a)` 的值是普通 undefined,外层的 `.length` 会抛错
389        Node::Group(inner) => Ok(norm(eval_node(inner, cx, slots)?)),
390        // `params` 缺省时生产端是 `JSON.parse("{}")`,即空对象;不是 undefined
391        Node::Params => Ok(match cx.params {
392            Some(p) => val_of(p),
393            None => Val::EmptyObj,
394        }),
395        Node::Local(i) => slot_ref(slots, *i),
396        Node::Path { base, segs } => resolve(*base, segs, cx, slots),
397        Node::Member {
398            base,
399            name,
400            optional,
401        } => {
402            let v = eval_node(base, cx, slots)?;
403            if matches!(v, Val::ShortCircuit) {
404                return Ok(Val::ShortCircuit);
405            }
406            lookup(v, name, *optional)
407        }
408        Node::Length { base, optional } => {
409            let v = eval_node(base, cx, slots)?;
410            if matches!(v, Val::ShortCircuit) {
411                return Ok(Val::ShortCircuit);
412            }
413            match v {
414                Val::Str(s) => Ok(Val::Num(semantics::utf16_len(s) as f64)),
415                Val::Arr(d) => Ok(Val::Num(d.len() as f64)),
416                // 对象可能有自有 `length` 字段;先按属性读,缺失才是 undefined
417                Val::Obj(d) => Ok(d.get("length").map_or(Val::Undefined, val_of)),
418                Val::EmptyObj => Ok(Val::Undefined),
419                Val::Undefined | Val::Null if *optional => Ok(Val::ShortCircuit),
420                Val::Undefined | Val::Null => Err(runtime("读取 null/undefined 的 `.length`")),
421                // 数字、布尔、Date 装箱后没有自有 `length`,取到的是 undefined(不是抛错)
422                Val::Num(_) | Val::Bool(_) | Val::Date(_) => Ok(Val::Undefined),
423                Val::ShortCircuit => Ok(Val::ShortCircuit),
424            }
425        }
426        Node::Index {
427            base,
428            index,
429            optional,
430        } => {
431            let b = eval_node(base, cx, slots)?;
432            if matches!(b, Val::ShortCircuit) {
433                return Ok(Val::ShortCircuit);
434            }
435            // JS 的 `a?.[i]` 在 a 为 nullish 时整链短路,`i` 根本不会求值。
436            // 必须在求值下标之前判空,否则下标里的 TypeError 会泄漏出来。
437            if *optional && matches!(b, Val::Undefined | Val::Null) {
438                return Ok(Val::ShortCircuit);
439            }
440            let i = eval_node(index, cx, slots)?;
441            index_into(b, norm(i), *optional)
442        }
443        Node::Call {
444            base,
445            method,
446            optional,
447            arg,
448        } => {
449            let b = eval_node(base, cx, slots)?;
450            if matches!(b, Val::ShortCircuit) {
451                return Ok(Val::ShortCircuit);
452            }
453            // 同上:`a?.includes(f())` 在 a 为 nullish 时不会求值 f()。
454            if *optional && matches!(b, Val::Undefined | Val::Null) {
455                return Ok(Val::ShortCircuit);
456            }
457            let a = eval_node(arg, cx, slots)?;
458            call_method(b, *method, *optional, norm(a))
459        }
460        Node::ConstIncludes { set, hay } => {
461            let v = norm(eval_node(hay, cx, slots)?);
462            let probe = match v {
463                Val::Str(s) => Probe::Str(s),
464                Val::Num(n) => Probe::Num(n),
465                _ => Probe::Other,
466            };
467            Ok(Val::Bool(set.contains(probe)))
468        }
469        Node::Some {
470            base,
471            slot,
472            body,
473            optional,
474        } => {
475            let b = eval_node(base, cx, slots)?;
476            match b {
477                Val::ShortCircuit => Ok(Val::ShortCircuit),
478                Val::Arr(d) => {
479                    for i in 0..d.len() {
480                        let Some(el) = d.at(i) else { continue };
481                        slot_set(slots, *slot, val_of(el))?;
482                        if semantics::truthy(&norm(eval_node(body, cx, slots)?)) {
483                            return Ok(Val::Bool(true));
484                        }
485                    }
486                    Ok(Val::Bool(false))
487                }
488                Val::Undefined | Val::Null if *optional => Ok(Val::ShortCircuit),
489                Val::Undefined | Val::Null => Err(runtime("`.some` 的调用基座是 null/undefined")),
490                _ => Err(type_err("`.some` 只能用于数组")),
491            }
492        }
493        Node::ParseInt(inner) => {
494            let v = norm(eval_node(inner, cx, slots)?);
495            let n = match v {
496                Val::Str(s) => semantics::parse_int(s),
497                // JS 先字符串化再取数字前缀:`parseInt(1.9)` → 1,
498                // `parseInt(1e21)` → 1(`String(1e21)` 是 "1e+21"),`parseInt(Infinity)` → NaN
499                Val::Num(n) if n.is_finite() => {
500                    let text = format_num(n);
501                    semantics::parse_int(&text)
502                }
503                // `parseInt(new Date(0))` 先转成 Date 字符串(以星期名开头)→ NaN
504                Val::Date(_) => f64::NAN,
505                // JS 的 Array#toString 是逗号 join;只支持原始元素,引用元素 fail-closed
506                Val::Arr(d) => semantics::parse_int(&array_to_js_string(d)?),
507                // JS `parseInt(true)` 先转字符串 "true" 再取数字前缀,得到 NaN
508                _ => f64::NAN,
509            };
510            Ok(Val::Num(n))
511        }
512        Node::IsArray(inner) => {
513            let v = norm(eval_node(inner, cx, slots)?);
514            Ok(Val::Bool(matches!(v, Val::Arr(_))))
515        }
516        Node::Not(inner) => {
517            let v = norm(eval_node(inner, cx, slots)?);
518            Ok(Val::Bool(!semantics::truthy(&v)))
519        }
520        Node::And(l, r) => {
521            let lv = norm(eval_node(l, cx, slots)?);
522            if semantics::truthy(&lv) {
523                // 逻辑运算跨过了链的边界:右值即使是短路线,结果也是普通值。
524                Ok(norm(eval_node(r, cx, slots)?))
525            } else {
526                Ok(lv)
527            }
528        }
529        Node::Or(l, r) => {
530            let lv = norm(eval_node(l, cx, slots)?);
531            if semantics::truthy(&lv) {
532                Ok(lv)
533            } else {
534                Ok(norm(eval_node(r, cx, slots)?))
535            }
536        }
537        // `??` 只看 null/undefined,不看 falsy:`0 ?? 1` → 0、`'' ?? 'x'` → ''。
538        // 可选链短路的哨兵先归一成 undefined,所以 `item?.a ?? b` 在 item 缺失时取 b,
539        // 与 JS 把 `(item?.a)` 当 undefined 再合并一致。
540        Node::Nullish(l, r) => {
541            let lv = norm(eval_node(l, cx, slots)?);
542            match lv {
543                Val::Null | Val::Undefined => Ok(norm(eval_node(r, cx, slots)?)),
544                other => Ok(other),
545            }
546        }
547        Node::StrictEq(l, r) => {
548            let lv = norm(eval_node(l, cx, slots)?);
549            let rv = norm(eval_node(r, cx, slots)?);
550            // 引用之间要做身份比较(`item.o === item.o` 在 JS 为 true),
551            // 而 Data 游标没有身份信息;静默按 false 会改写语义。
552            // 一边是引用、一边是原始值则类型必不同,恒 false,无需拒绝。
553            // Date 同理:编译期只能拒绝 AST 上的 DateNew,局部变量绕过后
554            // 两个日期引用是否相同无法判定,必须 fail-closed。
555            if matches!((&lv, &rv), (Val::Date(_), Val::Date(_))) {
556                return Err(Error::new(
557                    ErrorKind::Unsupported,
558                    "Date 之间的 `===`/`!==` 需要引用身份,契约外".to_string(),
559                ));
560            }
561            if needs_identity(&lv) && needs_identity(&rv) {
562                return Err(Error::new(
563                    ErrorKind::Unsupported,
564                    "对象/数组之间的 `===`/`!==` 需要引用身份,契约外".to_string(),
565                ));
566            }
567            Ok(Val::Bool(semantics::strict_eq(&lv, &rv)))
568        }
569        Node::LooseEq(l, r) => {
570            let lv = norm(eval_node(l, cx, slots)?);
571            let rv = norm(eval_node(r, cx, slots)?);
572            // Date 的默认 ToPrimitive 走 Date.prototype.toString(字符串 hint),
573            // 不是数值:`new Date(0) == 0` 在 JS 为 false。Date 与数字/布尔可安全
574            // 判 false;与字符串/Date/数组/对象比较需要真实 Date 字符串或引用身份,
575            // 无法在本 crate 中表达,显式 fail-closed。
576            if matches!(lv, Val::Date(_)) || matches!(rv, Val::Date(_)) {
577                let other = if matches!(lv, Val::Date(_)) { &rv } else { &lv };
578                return match other {
579                    Val::Null | Val::Undefined => Ok(Val::Bool(false)),
580                    Val::Num(_) | Val::Bool(_) => Ok(Val::Bool(false)),
581                    _ => Err(Error::new(
582                        ErrorKind::Unsupported,
583                        "Date 参与 `==`/`!=` 需要 ToPrimitive 或引用身份,契约外".to_string(),
584                    )),
585                };
586            }
587            // 数组/对象参与 `==` 要走 ToPrimitive(数组 join、对象 "[object Object]")。
588            // 本 crate 的 Val::Str 只能借用,无法承载 join 出的字符串;静默按 false
589            // 处理会错判(`[] == false` 在 JS 为 true),显式报 Unsupported。
590            // 与 null/undefined 比较恒 false,无需 ToPrimitive,保持原行为。
591            if (needs_to_primitive(&lv) || needs_to_primitive(&rv))
592                && !matches!(lv, Val::Null | Val::Undefined)
593                && !matches!(rv, Val::Null | Val::Undefined)
594            {
595                return Err(Error::new(
596                    ErrorKind::Unsupported,
597                    "数组/对象参与 `==`/`!=` 需要 ToPrimitive,契约外".to_string(),
598                ));
599            }
600            Ok(Val::Bool(semantics::loose_eq(&lv, &rv)))
601        }
602        Node::Rel { op, lhs, rhs } => {
603            let lv = norm(eval_node(lhs, cx, slots)?);
604            let rv = norm(eval_node(rhs, cx, slots)?);
605            if needs_to_primitive(&lv) || needs_to_primitive(&rv) {
606                return Err(Error::new(
607                    ErrorKind::Unsupported,
608                    "数组/对象参与关系比较需要 ToPrimitive,契约外".to_string(),
609                ));
610            }
611            let ord = semantics::compare(&lv, &rv);
612            let out = match (ord, op) {
613                (Some(o), RelOp::Lt) => o.is_lt(),
614                (Some(o), RelOp::Le) => o.is_le(),
615                (Some(o), RelOp::Gt) => o.is_gt(),
616                (Some(o), RelOp::Ge) => o.is_ge(),
617                (None, _) => false,
618            };
619            Ok(Val::Bool(out))
620        }
621        // `new Date()` 取真实时钟;参数按 JS 的 ToPrimitive 语义折算成时刻。
622        Node::DateNew(arg) => {
623            let ms = match arg {
624                None => date::now_ms(),
625                Some(a) => match norm(eval_node(a, cx, slots)?) {
626                    Val::Num(n) => date::clip(n),
627                    // `new Date(dateObject)` 按 ES 规范直接复制其 time value
628                    Val::Date(n) => date::clip(n),
629                    Val::Str(s) => date::parse(s),
630                    // `new Date(null)` 是 epoch 0,`new Date(true)` 是 1
631                    Val::Null => 0.0,
632                    Val::Bool(b) => {
633                        if b {
634                            1.0
635                        } else {
636                            0.0
637                        }
638                    }
639                    // `new Date(undefined)` 是 Invalid Date
640                    Val::Undefined => f64::NAN,
641                    Val::Arr(_) | Val::Obj(_) | Val::EmptyObj => {
642                        return Err(Error::new(
643                            ErrorKind::Unsupported,
644                            "`new Date(...)` 的数组/对象参数需要 ToPrimitive,契约外".to_string(),
645                        ));
646                    }
647                    // 短路哨兵已在上面归一成 undefined
648                    Val::ShortCircuit => f64::NAN,
649                },
650            };
651            Ok(Val::Date(ms))
652        }
653        Node::DateNow => Ok(Val::Num(date::now_ms())),
654        Node::GetTime { base, optional } => {
655            let v = eval_node(base, cx, slots)?;
656            if matches!(v, Val::ShortCircuit) {
657                return Ok(Val::ShortCircuit);
658            }
659            if *optional && matches!(v, Val::Undefined | Val::Null) {
660                return Ok(Val::ShortCircuit);
661            }
662            match v {
663                // `.getTime()` 只接受真正的 Date 值;`Date.now()` 是数字,
664                // 在 JS 里调用 `.getTime()` 会抛 TypeError,不能静默返回时间戳。
665                Val::Date(n) => Ok(Val::Num(n)),
666                other => Err(type_err(&format!(
667                    "`.getTime()` 的基座不是 Date(得到 {other:?})"
668                ))),
669            }
670        }
671        Node::MathFloor(inner) => {
672            let v = norm(eval_node(inner, cx, slots)?);
673            let n = semantics::to_number(&v)
674                .ok_or_else(|| type_err("`Math.floor` 的参数需要 ToNumber(数组/对象契约外)"))?;
675            Ok(Val::Num(n.floor()))
676        }
677        Node::Arith { op, lhs, rhs } => {
678            let lv = norm(eval_node(lhs, cx, slots)?);
679            let rv = norm(eval_node(rhs, cx, slots)?);
680            let a = semantics::to_number(&lv)
681                .ok_or_else(|| type_err("算术左值需要 ToNumber(数组/对象契约外)"))?;
682            let b = semantics::to_number(&rv)
683                .ok_or_else(|| type_err("算术右值需要 ToNumber(数组/对象契约外)"))?;
684            // f64 的 `/` 与 JS 一致:`x/0` → ±Infinity,`0/0` → NaN
685            Ok(Val::Num(match op {
686                ArithOp::Sub => a - b,
687                ArithOp::Mul => a * b,
688                ArithOp::Div => a / b,
689            }))
690        }
691        Node::Set { .. } => Err(runtime("绑定语句不能出现在表达式位置")),
692    }
693}
694
695fn resolve<'a, D: Data<'a>>(
696    base: PathBase,
697    segs: &'a [PathSeg],
698    cx: &Cx<'a, D>,
699    slots: &mut [Option<Val<'a, D>>],
700) -> Result<Val<'a, D>, Error> {
701    let mut v = match base {
702        PathBase::Item => val_of(cx.row),
703        PathBase::Params => match cx.params {
704            Some(p) => val_of(p),
705            None => Val::EmptyObj,
706        },
707        PathBase::Local(i) => slot_ref(slots, i)?,
708    };
709    for seg in segs {
710        // `?.` 一旦在任一段短路,整条链后续所有访问都不再发生(JS optional chain 语义),
711        // 用哨兵一路透传到链尾;键缺失则只产生 undefined,让后续段按 JS 规则抛错。
712        if matches!(v, Val::ShortCircuit) {
713            return Ok(Val::ShortCircuit);
714        }
715        if matches!(v, Val::Undefined | Val::Null) {
716            if seg.optional {
717                return Ok(Val::ShortCircuit);
718            }
719            return Err(runtime(&format!(
720                "读取 `{}` 时基座是 null/undefined(JS 会抛 TypeError)",
721                seg.name
722            )));
723        }
724        // 对象先查自有字段;没有自有字段时,内置原型成员要 fail-closed
725        // (`item.o.toString` 在 JS 里是函数,不是 undefined)。
726        v = match &v {
727            Val::Obj(d) => match d.get(&seg.name) {
728                Some(x) => val_of(x),
729                None if is_prototype_member(&v, &seg.name) => {
730                    return Err(prototype_error(&seg.name));
731                }
732                None => Val::Undefined,
733            },
734            _ if is_prototype_member(&v, &seg.name) => {
735                return Err(prototype_error(&seg.name));
736            }
737            // 数组/空对象/原始类型上的未知属性在 JS 里是 undefined
738            _ => Val::Undefined,
739        };
740    }
741    Ok(v)
742}
743
744/// 单段成员访问,`?.` 使基座为空时整链短路(返回哨兵)。
745fn lookup<'a, D: Data<'a>>(v: Val<'a, D>, name: &str, optional: bool) -> Result<Val<'a, D>, Error> {
746    match v {
747        Val::Obj(d) => match d.get(name) {
748            Some(x) => Ok(val_of(x)),
749            None if is_prototype_member(&Val::Obj(d), name) => Err(prototype_error(name)),
750            None => Ok(Val::Undefined),
751        },
752        Val::ShortCircuit => Ok(Val::ShortCircuit),
753        Val::Undefined | Val::Null => {
754            if optional {
755                Ok(Val::ShortCircuit)
756            } else {
757                Err(runtime(&format!(
758                    "读取 `{name}` 时基座是 null/undefined(JS 会抛 TypeError)"
759                )))
760            }
761        }
762        // 原始类型/数组/Date/空对象:内置原型成员显式失败,未知属性才是 undefined
763        other if is_prototype_member(&other, name) => Err(prototype_error(name)),
764        _ => Ok(Val::Undefined),
765    }
766}
767
768fn object_property<'a, D: Data<'a>>(d: D, key: &str) -> Result<Val<'a, D>, Error> {
769    match d.get(key) {
770        Some(x) => Ok(val_of(x)),
771        None if OBJECT_PROTO.contains(&key) => Err(prototype_error(key)),
772        None => Ok(Val::Undefined),
773    }
774}
775
776fn index_into<'a, D: Data<'a>>(
777    base: Val<'a, D>,
778    index: Val<'a, D>,
779    optional: bool,
780) -> Result<Val<'a, D>, Error> {
781    match (base, index) {
782        (Val::ShortCircuit, _) => Ok(Val::ShortCircuit),
783        (Val::Arr(d), Val::Num(n)) => {
784            // `n as usize` 在 n ≥ 2^64 时会饱和成 usize::MAX。把它交给外部
785            // `Data::at` 实现会在用 `vec[i]` 的适配器上直接 panic;即使契约
786            // 要求越界返回 None,也不该把明显越界的下标传出去。先按数组
787            // 长度裁剪,越界即 undefined(JS 语义本就如此)。
788            if !(0.0..(d.len() as f64)).contains(&n) || n.fract() != 0.0 {
789                return Ok(Val::Undefined);
790            }
791            Ok(d.at(n as usize).map_or(Val::Undefined, val_of))
792        }
793        // JS ToPropertyKey:数字键先按 String(n) 转字符串,再查对象属性
794        (Val::Obj(d), Val::Num(n)) => {
795            let key = format_num(n);
796            Ok(d.get(&key).map_or(Val::Undefined, val_of))
797        }
798        (Val::Obj(d), Val::Str(s)) => object_property(d, s),
799        (Val::Obj(d), Val::Bool(b)) => object_property(d, if b { "true" } else { "false" }),
800        (Val::Obj(d), Val::Null) => object_property(d, "null"),
801        (Val::Obj(d), Val::Undefined) => object_property(d, "undefined"),
802        (Val::Obj(_), Val::Date(_) | Val::Arr(_) | Val::Obj(_) | Val::EmptyObj) => Err(Error::new(
803            ErrorKind::Unsupported,
804            "对象下标是引用类型,需要 ToPropertyKey,契约外".to_string(),
805        )),
806        // 数组上的字符串键:`"length"` 是元属性,规范数字串是下标,其余是普通属性
807        (Val::Arr(d), Val::Str(s)) => {
808            if s == "length" {
809                return Ok(Val::Num(d.len() as f64));
810            }
811            // 与数字下标分支同样要按 `d.len()` 裁剪:`canonical_index` 接受
812            // `"18446744073709551615"`(= usize::MAX),裸传给外部 `Data::at`
813            // 会在用 `vec[i]` 的适配器上 panic。
814            match canonical_index(s) {
815                Some(k) if k < d.len() => Ok(d.at(k).map_or(Val::Undefined, val_of)),
816                _ if ARRAY_PROTO.contains(&s) => Err(prototype_error(s)),
817                _ => Ok(Val::Undefined),
818            }
819        }
820        // 数组上的 bool/null/undefined/Date 键不是数组下标,数据数组没有自有属性
821        (Val::Arr(_), Val::Bool(_) | Val::Null | Val::Undefined | Val::Date(_)) => {
822            Ok(Val::Undefined)
823        }
824        (Val::Arr(_), Val::Arr(_) | Val::Obj(_) | Val::EmptyObj) => Err(Error::new(
825            ErrorKind::Unsupported,
826            "数组下标是引用类型,需要 ToPropertyKey,契约外".to_string(),
827        )),
828        // 字符串下标同样走 ToPropertyKey:规范数字串按 UTF-16 码元取字符
829        (Val::Str(s), Val::Str(idx)) => {
830            if idx == "length" {
831                return Ok(Val::Num(semantics::utf16_len(s) as f64));
832            }
833            match canonical_index(idx) {
834                Some(k) => match utf16_char_at(s, k) {
835                    Utf16At::Char(c) => Ok(Val::Str(c)),
836                    Utf16At::None => Ok(Val::Undefined),
837                    Utf16At::Surrogate => Err(Error::new(
838                        ErrorKind::Unsupported,
839                        "非 BMP 字符的 UTF-16 中间码元是孤立代理,无法用 Rust str 表示",
840                    )),
841                },
842                _ if STRING_PROTO.contains(&idx) => Err(prototype_error(idx)),
843                None => Ok(Val::Undefined),
844            }
845        }
846        (Val::Str(s), Val::Num(n)) => {
847            if n < 0.0 || n.fract() != 0.0 {
848                return Ok(Val::Undefined);
849            }
850            match utf16_char_at(s, n as usize) {
851                Utf16At::Char(c) => Ok(Val::Str(c)),
852                Utf16At::None => Ok(Val::Undefined),
853                // JS 会返回孤立代理码元 "\ud800" 一类字符串,Rust 的 str 无法表示
854                Utf16At::Surrogate => Err(Error::new(
855                    ErrorKind::Unsupported,
856                    "非 BMP 字符的 UTF-16 中间码元是孤立代理,无法用 Rust str 表示",
857                )),
858            }
859        }
860        (Val::Str(_), Val::Bool(_) | Val::Null | Val::Undefined | Val::Date(_)) => {
861            Ok(Val::Undefined)
862        }
863        (Val::Str(_), Val::Arr(_) | Val::Obj(_) | Val::EmptyObj) => Err(Error::new(
864            ErrorKind::Unsupported,
865            "字符串下标是引用类型,需要 ToPropertyKey,契约外".to_string(),
866        )),
867        // Date 是对象:已知原型成员(如 getTime)是函数,未知属性是 undefined
868        (Val::Date(_), Val::Str(s)) => {
869            if DATE_PROTO.contains(&s) {
870                Err(prototype_error(s))
871            } else {
872                Ok(Val::Undefined)
873            }
874        }
875        (Val::Date(_), Val::Bool(_) | Val::Null | Val::Undefined | Val::Num(_) | Val::Date(_)) => {
876            Ok(Val::Undefined)
877        }
878        (Val::Date(_), Val::Arr(_) | Val::Obj(_) | Val::EmptyObj) => Err(Error::new(
879            ErrorKind::Unsupported,
880            "Date 下标是引用类型,需要 ToPropertyKey,契约外".to_string(),
881        )),
882        (Val::Undefined | Val::Null, _) if optional => Ok(Val::ShortCircuit),
883        (Val::Undefined | Val::Null, _) => Err(runtime("对 null/undefined 取下标")),
884        (Val::Num(_), Val::Str(s)) => {
885            if NUMBER_PROTO.contains(&s) {
886                Err(prototype_error(s))
887            } else {
888                Ok(Val::Undefined)
889            }
890        }
891        (Val::Bool(_), Val::Str(s)) => {
892            if BOOLEAN_PROTO.contains(&s) {
893                Err(prototype_error(s))
894            } else {
895                Ok(Val::Undefined)
896            }
897        }
898        (Val::EmptyObj, Val::Str(s)) => {
899            if OBJECT_PROTO.contains(&s) {
900                Err(prototype_error(s))
901            } else {
902                Ok(Val::Undefined)
903            }
904        }
905        (Val::Num(_) | Val::Bool(_) | Val::EmptyObj, _) => Ok(Val::Undefined),
906        (Val::Arr(_), _) => Err(type_err("数组下标必须是整数")),
907        (Val::Str(_), _) => Ok(Val::Undefined),
908        _ => Ok(Val::Undefined),
909    }
910}
911
912/// 数组的规范数字键:`"0"`/`"12"` 是下标,`"01"`/`"+1"`/`"-1"`/`"a"` 不是
913/// (后者在数组上只是普通属性,取到 undefined)。
914fn canonical_index(s: &str) -> Option<usize> {
915    let b = s.as_bytes();
916    if b.is_empty() || !b[0].is_ascii_digit() {
917        return None;
918    }
919    if b.len() > 1 && b[0] == b'0' {
920        return None;
921    }
922    s.parse::<usize>().ok()
923}
924
925enum Utf16At<'a> {
926    /// 完整字符的借用切片。
927    Char(&'a str),
928    /// 落在代理对中间:JS 返回孤立代理,Rust `str` 无法表达。
929    Surrogate,
930    /// 越界。
931    None,
932}
933
934fn utf16_char_at(s: &str, idx: usize) -> Utf16At<'_> {
935    let mut pos = 0usize;
936    for (byte, ch) in s.char_indices() {
937        let units = ch.len_utf16();
938        if pos == idx {
939            // 非 BMP 字符的起始码元是孤立高代理:JS `"😀"[0]` / `"a😀b"[1]`
940            // 返回 `"\ud83d"`,不等于完整字符。Rust str 表达不了单独代理,
941            // 与落在代理对中间的低代理一样按契约外拒绝,不能静默返回整字符。
942            return if units == 1 {
943                match s.get(byte..byte + ch.len_utf8()) {
944                    Some(c) => Utf16At::Char(c),
945                    None => Utf16At::None,
946                }
947            } else {
948                Utf16At::Surrogate
949            };
950        }
951        if units == 2 && pos < idx && idx < pos + units {
952            return Utf16At::Surrogate;
953        }
954        pos += units;
955    }
956    Utf16At::None
957}
958
959fn call_method<'a, D: Data<'a>>(
960    base: Val<'a, D>,
961    method: Method,
962    optional: bool,
963    arg: Val<'a, D>,
964) -> Result<Val<'a, D>, Error> {
965    if matches!(base, Val::ShortCircuit) {
966        return Ok(Val::ShortCircuit);
967    }
968    if matches!(base, Val::Undefined | Val::Null) && optional {
969        return Ok(Val::ShortCircuit);
970    }
971    match base {
972        Val::Str(s) => {
973            let Some(needle) = to_js_string(&arg) else {
974                return Err(type_err("字符串方法的参数不能是数组/对象"));
975            };
976            match method {
977                Method::Includes => Ok(Val::Bool(s.contains(needle.as_ref()))),
978                Method::IndexOf => Ok(Val::Num(match s.find(needle.as_ref()) {
979                    Some(byte) => semantics::utf16_len(&s[..byte]) as f64,
980                    None => -1.0,
981                })),
982                Method::StartsWith => Ok(Val::Bool(s.starts_with(needle.as_ref()))),
983                Method::EndsWith => Ok(Val::Bool(s.ends_with(needle.as_ref()))),
984                Method::Some => Err(type_err("`.some` 只能用于数组")),
985                Method::GetTime => Err(runtime("`.getTime()` 走独立节点")),
986            }
987        }
988        Val::Arr(d) => match method {
989            Method::Includes | Method::IndexOf if needs_identity(&arg) => Err(Error::new(
990                ErrorKind::Unsupported,
991                "数组方法的引用参数需要身份比较,契约外".to_string(),
992            )),
993            Method::Includes => {
994                for i in 0..d.len() {
995                    let Some(el) = d.at(i) else { continue };
996                    if semantics::same_value_zero(&val_of(el), &arg) {
997                        return Ok(Val::Bool(true));
998                    }
999                }
1000                Ok(Val::Bool(false))
1001            }
1002            Method::IndexOf => {
1003                for i in 0..d.len() {
1004                    let Some(el) = d.at(i) else { continue };
1005                    if semantics::strict_eq(&val_of(el), &arg) {
1006                        return Ok(Val::Num(i as f64));
1007                    }
1008                }
1009                Ok(Val::Num(-1.0))
1010            }
1011            Method::StartsWith => Err(type_err("`.startsWith` 只能用于字符串")),
1012            Method::EndsWith => Err(type_err("`.endsWith` 只能用于字符串")),
1013            Method::Some => Err(type_err("`.some` 走独立节点")),
1014            Method::GetTime => Err(runtime("`.getTime()` 走独立节点")),
1015        },
1016        Val::Undefined | Val::Null => Err(runtime("对 null/undefined 调用方法")),
1017        _ => Err(type_err("基座不是数组或字符串")),
1018    }
1019}