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                    // 数组走 ToPrimitive(join 再当字符串解析):quickjs 实测
642                    // `new Date([])` → NaN、`new Date([1])` → 2001-01-01。
643                    // 引用元素的数组需要完整 ToString → Unsupported(同 parseInt)。
644                    Val::Arr(d) => date::parse(&array_to_js_string(d)?),
645                    // 普通对象 ToPrimitive 是 "[object Object]" → 不可解析 → NaN
646                    // (quickjs 实测 `new Date({})` 为 NaN)。
647                    Val::Obj(_) | Val::EmptyObj => f64::NAN,
648                    // 短路哨兵已在上面归一成 undefined
649                    Val::ShortCircuit => f64::NAN,
650                },
651            };
652            Ok(Val::Date(ms))
653        }
654        Node::DateNow => Ok(Val::Num(date::now_ms())),
655        Node::GetTime { base, optional } => {
656            let v = eval_node(base, cx, slots)?;
657            if matches!(v, Val::ShortCircuit) {
658                return Ok(Val::ShortCircuit);
659            }
660            if *optional && matches!(v, Val::Undefined | Val::Null) {
661                return Ok(Val::ShortCircuit);
662            }
663            match v {
664                // `.getTime()` 只接受真正的 Date 值;`Date.now()` 是数字,
665                // 在 JS 里调用 `.getTime()` 会抛 TypeError,不能静默返回时间戳。
666                Val::Date(n) => Ok(Val::Num(n)),
667                other => Err(type_err(&format!(
668                    "`.getTime()` 的基座不是 Date(得到 {other:?})"
669                ))),
670            }
671        }
672        Node::MathFloor(inner) => {
673            let v = norm(eval_node(inner, cx, slots)?);
674            let n = semantics::to_number(&v)
675                .ok_or_else(|| type_err("`Math.floor` 的参数需要 ToNumber(数组/对象契约外)"))?;
676            Ok(Val::Num(n.floor()))
677        }
678        Node::Arith { op, lhs, rhs } => {
679            let lv = norm(eval_node(lhs, cx, slots)?);
680            let rv = norm(eval_node(rhs, cx, slots)?);
681            let a = semantics::to_number(&lv)
682                .ok_or_else(|| type_err("算术左值需要 ToNumber(数组/对象契约外)"))?;
683            let b = semantics::to_number(&rv)
684                .ok_or_else(|| type_err("算术右值需要 ToNumber(数组/对象契约外)"))?;
685            // f64 的 `/` 与 JS 一致:`x/0` → ±Infinity,`0/0` → NaN
686            Ok(Val::Num(match op {
687                ArithOp::Sub => a - b,
688                ArithOp::Mul => a * b,
689                ArithOp::Div => a / b,
690            }))
691        }
692        Node::Set { .. } => Err(runtime("绑定语句不能出现在表达式位置")),
693    }
694}
695
696fn resolve<'a, D: Data<'a>>(
697    base: PathBase,
698    segs: &'a [PathSeg],
699    cx: &Cx<'a, D>,
700    slots: &mut [Option<Val<'a, D>>],
701) -> Result<Val<'a, D>, Error> {
702    let mut v = match base {
703        PathBase::Item => val_of(cx.row),
704        PathBase::Params => match cx.params {
705            Some(p) => val_of(p),
706            None => Val::EmptyObj,
707        },
708        PathBase::Local(i) => slot_ref(slots, i)?,
709    };
710    for seg in segs {
711        // `?.` 一旦在任一段短路,整条链后续所有访问都不再发生(JS optional chain 语义),
712        // 用哨兵一路透传到链尾;键缺失则只产生 undefined,让后续段按 JS 规则抛错。
713        if matches!(v, Val::ShortCircuit) {
714            return Ok(Val::ShortCircuit);
715        }
716        if matches!(v, Val::Undefined | Val::Null) {
717            if seg.optional {
718                return Ok(Val::ShortCircuit);
719            }
720            return Err(runtime(&format!(
721                "读取 `{}` 时基座是 null/undefined(JS 会抛 TypeError)",
722                seg.name
723            )));
724        }
725        // 对象先查自有字段;没有自有字段时,内置原型成员要 fail-closed
726        // (`item.o.toString` 在 JS 里是函数,不是 undefined)。
727        v = match &v {
728            Val::Obj(d) => match d.get(&seg.name) {
729                Some(x) => val_of(x),
730                None if is_prototype_member(&v, &seg.name) => {
731                    return Err(prototype_error(&seg.name));
732                }
733                None => Val::Undefined,
734            },
735            _ if is_prototype_member(&v, &seg.name) => {
736                return Err(prototype_error(&seg.name));
737            }
738            // 数组/空对象/原始类型上的未知属性在 JS 里是 undefined
739            _ => Val::Undefined,
740        };
741    }
742    Ok(v)
743}
744
745/// 单段成员访问,`?.` 使基座为空时整链短路(返回哨兵)。
746fn lookup<'a, D: Data<'a>>(v: Val<'a, D>, name: &str, optional: bool) -> Result<Val<'a, D>, Error> {
747    match v {
748        Val::Obj(d) => match d.get(name) {
749            Some(x) => Ok(val_of(x)),
750            None if is_prototype_member(&Val::Obj(d), name) => Err(prototype_error(name)),
751            None => Ok(Val::Undefined),
752        },
753        Val::ShortCircuit => Ok(Val::ShortCircuit),
754        Val::Undefined | Val::Null => {
755            if optional {
756                Ok(Val::ShortCircuit)
757            } else {
758                Err(runtime(&format!(
759                    "读取 `{name}` 时基座是 null/undefined(JS 会抛 TypeError)"
760                )))
761            }
762        }
763        // 原始类型/数组/Date/空对象:内置原型成员显式失败,未知属性才是 undefined
764        other if is_prototype_member(&other, name) => Err(prototype_error(name)),
765        _ => Ok(Val::Undefined),
766    }
767}
768
769fn object_property<'a, D: Data<'a>>(d: D, key: &str) -> Result<Val<'a, D>, Error> {
770    match d.get(key) {
771        Some(x) => Ok(val_of(x)),
772        None if OBJECT_PROTO.contains(&key) => Err(prototype_error(key)),
773        None => Ok(Val::Undefined),
774    }
775}
776
777fn index_into<'a, D: Data<'a>>(
778    base: Val<'a, D>,
779    index: Val<'a, D>,
780    optional: bool,
781) -> Result<Val<'a, D>, Error> {
782    match (base, index) {
783        (Val::ShortCircuit, _) => Ok(Val::ShortCircuit),
784        (Val::Arr(d), Val::Num(n)) => {
785            // `n as usize` 在 n ≥ 2^64 时会饱和成 usize::MAX。把它交给外部
786            // `Data::at` 实现会在用 `vec[i]` 的适配器上直接 panic;即使契约
787            // 要求越界返回 None,也不该把明显越界的下标传出去。先按数组
788            // 长度裁剪,越界即 undefined(JS 语义本就如此)。
789            if !(0.0..(d.len() as f64)).contains(&n) || n.fract() != 0.0 {
790                return Ok(Val::Undefined);
791            }
792            Ok(d.at(n as usize).map_or(Val::Undefined, val_of))
793        }
794        // JS ToPropertyKey:数字键先按 String(n) 转字符串,再查对象属性
795        (Val::Obj(d), Val::Num(n)) => {
796            let key = format_num(n);
797            Ok(d.get(&key).map_or(Val::Undefined, val_of))
798        }
799        (Val::Obj(d), Val::Str(s)) => object_property(d, s),
800        (Val::Obj(d), Val::Bool(b)) => object_property(d, if b { "true" } else { "false" }),
801        (Val::Obj(d), Val::Null) => object_property(d, "null"),
802        (Val::Obj(d), Val::Undefined) => object_property(d, "undefined"),
803        (Val::Obj(_), Val::Date(_) | Val::Arr(_) | Val::Obj(_) | Val::EmptyObj) => Err(Error::new(
804            ErrorKind::Unsupported,
805            "对象下标是引用类型,需要 ToPropertyKey,契约外".to_string(),
806        )),
807        // 数组上的字符串键:`"length"` 是元属性,规范数字串是下标,其余是普通属性
808        (Val::Arr(d), Val::Str(s)) => {
809            if s == "length" {
810                return Ok(Val::Num(d.len() as f64));
811            }
812            // 与数字下标分支同样要按 `d.len()` 裁剪:`canonical_index` 接受
813            // `"18446744073709551615"`(= usize::MAX),裸传给外部 `Data::at`
814            // 会在用 `vec[i]` 的适配器上 panic。
815            match canonical_index(s) {
816                Some(k) if k < d.len() => Ok(d.at(k).map_or(Val::Undefined, val_of)),
817                _ if ARRAY_PROTO.contains(&s) => Err(prototype_error(s)),
818                _ => Ok(Val::Undefined),
819            }
820        }
821        // 数组上的 bool/null/undefined/Date 键不是数组下标,数据数组没有自有属性
822        (Val::Arr(_), Val::Bool(_) | Val::Null | Val::Undefined | Val::Date(_)) => {
823            Ok(Val::Undefined)
824        }
825        (Val::Arr(_), Val::Arr(_) | Val::Obj(_) | Val::EmptyObj) => Err(Error::new(
826            ErrorKind::Unsupported,
827            "数组下标是引用类型,需要 ToPropertyKey,契约外".to_string(),
828        )),
829        // 字符串下标同样走 ToPropertyKey:规范数字串按 UTF-16 码元取字符
830        (Val::Str(s), Val::Str(idx)) => {
831            if idx == "length" {
832                return Ok(Val::Num(semantics::utf16_len(s) as f64));
833            }
834            match canonical_index(idx) {
835                Some(k) => match utf16_char_at(s, k) {
836                    Utf16At::Char(c) => Ok(Val::Str(c)),
837                    Utf16At::None => Ok(Val::Undefined),
838                    Utf16At::Surrogate => Err(Error::new(
839                        ErrorKind::Unsupported,
840                        "非 BMP 字符的 UTF-16 中间码元是孤立代理,无法用 Rust str 表示",
841                    )),
842                },
843                _ if STRING_PROTO.contains(&idx) => Err(prototype_error(idx)),
844                None => Ok(Val::Undefined),
845            }
846        }
847        (Val::Str(s), Val::Num(n)) => {
848            if n < 0.0 || n.fract() != 0.0 {
849                return Ok(Val::Undefined);
850            }
851            match utf16_char_at(s, n as usize) {
852                Utf16At::Char(c) => Ok(Val::Str(c)),
853                Utf16At::None => Ok(Val::Undefined),
854                // JS 会返回孤立代理码元 "\ud800" 一类字符串,Rust 的 str 无法表示
855                Utf16At::Surrogate => Err(Error::new(
856                    ErrorKind::Unsupported,
857                    "非 BMP 字符的 UTF-16 中间码元是孤立代理,无法用 Rust str 表示",
858                )),
859            }
860        }
861        (Val::Str(_), Val::Bool(_) | Val::Null | Val::Undefined | Val::Date(_)) => {
862            Ok(Val::Undefined)
863        }
864        (Val::Str(_), Val::Arr(_) | Val::Obj(_) | Val::EmptyObj) => Err(Error::new(
865            ErrorKind::Unsupported,
866            "字符串下标是引用类型,需要 ToPropertyKey,契约外".to_string(),
867        )),
868        // Date 是对象:已知原型成员(如 getTime)是函数,未知属性是 undefined
869        (Val::Date(_), Val::Str(s)) => {
870            if DATE_PROTO.contains(&s) {
871                Err(prototype_error(s))
872            } else {
873                Ok(Val::Undefined)
874            }
875        }
876        (Val::Date(_), Val::Bool(_) | Val::Null | Val::Undefined | Val::Num(_) | Val::Date(_)) => {
877            Ok(Val::Undefined)
878        }
879        (Val::Date(_), Val::Arr(_) | Val::Obj(_) | Val::EmptyObj) => Err(Error::new(
880            ErrorKind::Unsupported,
881            "Date 下标是引用类型,需要 ToPropertyKey,契约外".to_string(),
882        )),
883        (Val::Undefined | Val::Null, _) if optional => Ok(Val::ShortCircuit),
884        (Val::Undefined | Val::Null, _) => Err(runtime("对 null/undefined 取下标")),
885        (Val::Num(_), Val::Str(s)) => {
886            if NUMBER_PROTO.contains(&s) {
887                Err(prototype_error(s))
888            } else {
889                Ok(Val::Undefined)
890            }
891        }
892        (Val::Bool(_), Val::Str(s)) => {
893            if BOOLEAN_PROTO.contains(&s) {
894                Err(prototype_error(s))
895            } else {
896                Ok(Val::Undefined)
897            }
898        }
899        (Val::EmptyObj, Val::Str(s)) => {
900            if OBJECT_PROTO.contains(&s) {
901                Err(prototype_error(s))
902            } else {
903                Ok(Val::Undefined)
904            }
905        }
906        (Val::Num(_) | Val::Bool(_) | Val::EmptyObj, _) => Ok(Val::Undefined),
907        (Val::Arr(_), _) => Err(type_err("数组下标必须是整数")),
908        (Val::Str(_), _) => Ok(Val::Undefined),
909        _ => Ok(Val::Undefined),
910    }
911}
912
913/// 数组的规范数字键:`"0"`/`"12"` 是下标,`"01"`/`"+1"`/`"-1"`/`"a"` 不是
914/// (后者在数组上只是普通属性,取到 undefined)。
915fn canonical_index(s: &str) -> Option<usize> {
916    let b = s.as_bytes();
917    if b.is_empty() || !b[0].is_ascii_digit() {
918        return None;
919    }
920    if b.len() > 1 && b[0] == b'0' {
921        return None;
922    }
923    s.parse::<usize>().ok()
924}
925
926enum Utf16At<'a> {
927    /// 完整字符的借用切片。
928    Char(&'a str),
929    /// 落在代理对中间:JS 返回孤立代理,Rust `str` 无法表达。
930    Surrogate,
931    /// 越界。
932    None,
933}
934
935fn utf16_char_at(s: &str, idx: usize) -> Utf16At<'_> {
936    let mut pos = 0usize;
937    for (byte, ch) in s.char_indices() {
938        let units = ch.len_utf16();
939        if pos == idx {
940            // 非 BMP 字符的起始码元是孤立高代理:JS `"😀"[0]` / `"a😀b"[1]`
941            // 返回 `"\ud83d"`,不等于完整字符。Rust str 表达不了单独代理,
942            // 与落在代理对中间的低代理一样按契约外拒绝,不能静默返回整字符。
943            return if units == 1 {
944                match s.get(byte..byte + ch.len_utf8()) {
945                    Some(c) => Utf16At::Char(c),
946                    None => Utf16At::None,
947                }
948            } else {
949                Utf16At::Surrogate
950            };
951        }
952        if units == 2 && pos < idx && idx < pos + units {
953            return Utf16At::Surrogate;
954        }
955        pos += units;
956    }
957    Utf16At::None
958}
959
960fn call_method<'a, D: Data<'a>>(
961    base: Val<'a, D>,
962    method: Method,
963    optional: bool,
964    arg: Val<'a, D>,
965) -> Result<Val<'a, D>, Error> {
966    if matches!(base, Val::ShortCircuit) {
967        return Ok(Val::ShortCircuit);
968    }
969    if matches!(base, Val::Undefined | Val::Null) && optional {
970        return Ok(Val::ShortCircuit);
971    }
972    match base {
973        Val::Str(s) => {
974            let Some(needle) = to_js_string(&arg) else {
975                return Err(type_err("字符串方法的参数不能是数组/对象"));
976            };
977            match method {
978                Method::Includes => Ok(Val::Bool(s.contains(needle.as_ref()))),
979                Method::IndexOf => Ok(Val::Num(match s.find(needle.as_ref()) {
980                    Some(byte) => semantics::utf16_len(&s[..byte]) as f64,
981                    None => -1.0,
982                })),
983                Method::StartsWith => Ok(Val::Bool(s.starts_with(needle.as_ref()))),
984                Method::EndsWith => Ok(Val::Bool(s.ends_with(needle.as_ref()))),
985                Method::Some => Err(type_err("`.some` 只能用于数组")),
986                Method::GetTime => Err(runtime("`.getTime()` 走独立节点")),
987            }
988        }
989        Val::Arr(d) => match method {
990            Method::Includes | Method::IndexOf if needs_identity(&arg) => Err(Error::new(
991                ErrorKind::Unsupported,
992                "数组方法的引用参数需要身份比较,契约外".to_string(),
993            )),
994            Method::Includes => {
995                for i in 0..d.len() {
996                    let Some(el) = d.at(i) else { continue };
997                    if semantics::same_value_zero(&val_of(el), &arg) {
998                        return Ok(Val::Bool(true));
999                    }
1000                }
1001                Ok(Val::Bool(false))
1002            }
1003            Method::IndexOf => {
1004                for i in 0..d.len() {
1005                    let Some(el) = d.at(i) else { continue };
1006                    if semantics::strict_eq(&val_of(el), &arg) {
1007                        return Ok(Val::Num(i as f64));
1008                    }
1009                }
1010                Ok(Val::Num(-1.0))
1011            }
1012            Method::StartsWith => Err(type_err("`.startsWith` 只能用于字符串")),
1013            Method::EndsWith => Err(type_err("`.endsWith` 只能用于字符串")),
1014            Method::Some => Err(type_err("`.some` 走独立节点")),
1015            Method::GetTime => Err(runtime("`.getTime()` 走独立节点")),
1016        },
1017        Val::Undefined | Val::Null => Err(runtime("对 null/undefined 调用方法")),
1018        _ => Err(type_err("基座不是数组或字符串")),
1019    }
1020}