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