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::{ConstVal, Node, PathBase, PathSeg, Program, RelOp, format_num};
11use crate::error::{Error, ErrorKind};
12use crate::semantics;
13use crate::set::Probe;
14use crate::value::{Data, Kind, Val};
15
16/// 与解析器的槽位上限保持一致。
17const MAX_SLOTS: usize = 16;
18
19struct Cx<'a, D: Data<'a>> {
20    row: D,
21    params: Option<D>,
22    _l: PhantomData<&'a ()>,
23}
24
25impl Program {
26    /// 对一行数据求值。
27    ///
28    /// `row` 是 `item`,`params` 是 `params`(未传时为 `undefined`)。
29    /// 两者必须是同一个类型——调用方用一个覆盖两种数据来源的枚举适配器即可。
30    ///
31    /// 返回 `Err` 时是否 fail-closed 由调用方决定。
32    pub fn eval<'a, D: Data<'a>>(&'a self, row: D, params: Option<D>) -> Result<bool, Error> {
33        // 编译期已知槽位数;固定数组必须容得下,否则是解析器/编译器漂移
34        debug_assert!(usize::from(self.slots) <= MAX_SLOTS, "槽位数超出上限");
35        let mut slots: [Option<Val<'a, D>>; MAX_SLOTS] = [None; MAX_SLOTS];
36        let cx = Cx {
37            row,
38            params,
39            _l: PhantomData,
40        };
41        for step in self.steps.iter() {
42            match step {
43                Node::Set { slot, value } => {
44                    // 短路哨兵只在**同一条链**内透传;一旦绑定到变量就成了普通
45                    // undefined,后续 `x.length` 在 JS 里是 TypeError 而不是短路。
46                    let v = norm(eval_node(value, &cx, &mut slots)?);
47                    slot_set(&mut slots, *slot, v)?;
48                }
49                _ => {
50                    return Err(Error::new(ErrorKind::Runtime, "非绑定步骤"));
51                }
52            }
53        }
54        let out = norm(eval_node(&self.result, &cx, &mut slots)?);
55        // 与生产端对齐:rquickjs 把完成值按 `bool` 严格转换,非布尔值是**错误**而非
56        // truthiness(`undefined?.includes(x)`、裸 `parseInt(...)` 都属此类)。
57        match out {
58            Val::Bool(b) => Ok(b),
59            other => Err(runtime(&format!(
60                "filter 表达式结果不是布尔(完成值 {:?},生产端会抛转换错误)",
61                other
62            ))),
63        }
64    }
65}
66
67fn runtime(msg: &str) -> Error {
68    Error::new(ErrorKind::Runtime, msg.to_string())
69}
70
71/// 类型不匹配(JS 里会得到 `undefined` 或抛 TypeError 的形态,这里显式报错)。
72fn type_err(msg: &str) -> Error {
73    Error::new(ErrorKind::Type, msg.to_string())
74}
75
76/// 是否需要 JS ToPrimitive 才能比较(数组/对象)。严格比较不走这里——
77/// `===` 对引用身份恒 false 是既有契约,与 ToPrimitive 无关。
78fn needs_to_primitive<'a, D: Data<'a>>(v: &Val<'a, D>) -> bool {
79    matches!(v, Val::Arr(_) | Val::Obj(_) | Val::EmptyObj)
80}
81
82/// 把可选链短路哨兵归一成 `undefined`:只应在**消费值**的地方调用
83/// (比较、真值判断、方法参数、最终结果),链式节点之间必须原样透传。
84fn norm<'a, D: Data<'a>>(v: Val<'a, D>) -> Val<'a, D> {
85    match v {
86        Val::ShortCircuit => Val::Undefined,
87        other => other,
88    }
89}
90
91/// 读槽位:越界或未初始化都回错误,绝不用下标 panic。
92fn slot_ref<'a, D: Data<'a>>(slots: &[Option<Val<'a, D>>], i: u16) -> Result<Val<'a, D>, Error> {
93    slots
94        .get(usize::from(i))
95        .copied()
96        .flatten()
97        .ok_or_else(|| runtime("槽位越界或未初始化"))
98}
99
100/// 写槽位。
101fn slot_set<'a, D: Data<'a>>(
102    slots: &mut [Option<Val<'a, D>>],
103    i: u16,
104    v: Val<'a, D>,
105) -> Result<(), Error> {
106    match slots.get_mut(usize::from(i)) {
107        Some(slot) => {
108            *slot = Some(v);
109            Ok(())
110        }
111        None => Err(runtime("槽位越界")),
112    }
113}
114
115fn val_of<'a, D: Data<'a>>(d: D) -> Val<'a, D> {
116    match d.kind() {
117        Kind::Null => Val::Null,
118        Kind::Bool => Val::Bool(d.as_bool().unwrap_or(false)),
119        Kind::Number => Val::Num(d.as_f64().unwrap_or(f64::NAN)),
120        Kind::String => Val::Str(d.as_str().unwrap_or("")),
121        Kind::Array => Val::Arr(d),
122        Kind::Object => Val::Obj(d),
123    }
124}
125
126fn const_to_val<'a, D: Data<'a>>(c: &'a ConstVal) -> Val<'a, D> {
127    match c {
128        ConstVal::Undefined => Val::Undefined,
129        ConstVal::Null => Val::Null,
130        ConstVal::Bool(b) => Val::Bool(*b),
131        ConstVal::Num(n) => Val::Num(*n),
132        ConstVal::Str(s) => Val::Str(s),
133    }
134}
135
136/// JS 字符串化,只在字符串方法/常量数组比较时用到。
137fn to_js_string<'a, D: Data<'a>>(v: &Val<'a, D>) -> Option<Cow<'a, str>> {
138    match v {
139        Val::Str(s) => Some(Cow::Borrowed(*s)),
140        Val::Num(n) => Some(Cow::Owned(format_num(*n))),
141        Val::Bool(b) => Some(Cow::Borrowed(if *b { "true" } else { "false" })),
142        Val::Null => Some(Cow::Borrowed("null")),
143        Val::Undefined | Val::ShortCircuit => Some(Cow::Borrowed("undefined")),
144        Val::Arr(_) | Val::Obj(_) => None,
145        Val::EmptyObj => None,
146    }
147}
148
149fn eval_node<'a, D: Data<'a>>(
150    n: &'a Node,
151    cx: &Cx<'a, D>,
152    slots: &mut [Option<Val<'a, D>>],
153) -> Result<Val<'a, D>, Error> {
154    match n {
155        Node::Const(c) => Ok(const_to_val(c)),
156        Node::Item => Ok(val_of(cx.row)),
157        // 括号打断可选链:`(item?.a)` 的值是普通 undefined,外层的 `.length` 会抛错
158        Node::Group(inner) => Ok(norm(eval_node(inner, cx, slots)?)),
159        // `params` 缺省时生产端是 `JSON.parse("{}")`,即空对象;不是 undefined
160        Node::Params => Ok(match cx.params {
161            Some(p) => val_of(p),
162            None => Val::EmptyObj,
163        }),
164        Node::Local(i) => slot_ref(slots, *i),
165        Node::Path { base, segs } => resolve(*base, segs, cx, slots),
166        Node::Member {
167            base,
168            name,
169            optional,
170        } => {
171            let v = eval_node(base, cx, slots)?;
172            if matches!(v, Val::ShortCircuit) {
173                return Ok(Val::ShortCircuit);
174            }
175            lookup(v, name, *optional)
176        }
177        Node::Length { base, optional } => {
178            let v = eval_node(base, cx, slots)?;
179            if matches!(v, Val::ShortCircuit) {
180                return Ok(Val::ShortCircuit);
181            }
182            match v {
183                Val::Str(s) => Ok(Val::Num(semantics::utf16_len(s) as f64)),
184                Val::Arr(d) => Ok(Val::Num(d.len() as f64)),
185                // 对象可能有自有 `length` 字段;先按属性读,缺失才是 undefined
186                Val::Obj(d) => Ok(d.get("length").map_or(Val::Undefined, val_of)),
187                Val::EmptyObj => Ok(Val::Undefined),
188                Val::Undefined | Val::Null if *optional => Ok(Val::ShortCircuit),
189                Val::Undefined | Val::Null => Err(runtime("读取 null/undefined 的 `.length`")),
190                // 数字、布尔装箱后没有自有 `length`,取到的是 undefined(不是抛错)
191                Val::Num(_) | Val::Bool(_) => Ok(Val::Undefined),
192                Val::ShortCircuit => Ok(Val::ShortCircuit),
193            }
194        }
195        Node::Index {
196            base,
197            index,
198            optional,
199        } => {
200            let b = eval_node(base, cx, slots)?;
201            if matches!(b, Val::ShortCircuit) {
202                return Ok(Val::ShortCircuit);
203            }
204            let i = eval_node(index, cx, slots)?;
205            index_into(b, norm(i), *optional)
206        }
207        Node::Call {
208            base,
209            method,
210            optional,
211            arg,
212        } => {
213            let b = eval_node(base, cx, slots)?;
214            if matches!(b, Val::ShortCircuit) {
215                return Ok(Val::ShortCircuit);
216            }
217            let a = eval_node(arg, cx, slots)?;
218            call_method(b, *method, *optional, norm(a))
219        }
220        Node::ConstIncludes { set, hay } => {
221            let v = norm(eval_node(hay, cx, slots)?);
222            let probe = match v {
223                Val::Str(s) => Probe::Str(s),
224                Val::Num(n) => Probe::Num(n),
225                _ => Probe::Other,
226            };
227            Ok(Val::Bool(set.contains(probe)))
228        }
229        Node::Some {
230            base,
231            slot,
232            body,
233            optional,
234        } => {
235            let b = eval_node(base, cx, slots)?;
236            match b {
237                Val::ShortCircuit => Ok(Val::ShortCircuit),
238                Val::Arr(d) => {
239                    for i in 0..d.len() {
240                        let Some(el) = d.at(i) else { continue };
241                        slot_set(slots, *slot, val_of(el))?;
242                        if semantics::truthy(&norm(eval_node(body, cx, slots)?)) {
243                            return Ok(Val::Bool(true));
244                        }
245                    }
246                    Ok(Val::Bool(false))
247                }
248                Val::Undefined | Val::Null if *optional => Ok(Val::ShortCircuit),
249                Val::Undefined | Val::Null => Err(runtime("`.some` 的调用基座是 null/undefined")),
250                _ => Err(type_err("`.some` 只能用于数组")),
251            }
252        }
253        Node::ParseInt(inner) => {
254            let v = norm(eval_node(inner, cx, slots)?);
255            let n = match v {
256                Val::Str(s) => semantics::parse_int(s),
257                // JS 先字符串化再取数字前缀:`parseInt(1.9)` → 1,
258                // `parseInt(1e21)` → 1(`String(1e21)` 是 "1e+21"),`parseInt(Infinity)` → NaN
259                Val::Num(n) if n.is_finite() => {
260                    let text = format_num(n);
261                    semantics::parse_int(&text)
262                }
263                // JS `parseInt(true)` 先转字符串 "true" 再取数字前缀,得到 NaN
264                _ => f64::NAN,
265            };
266            Ok(Val::Num(n))
267        }
268        Node::IsArray(inner) => {
269            let v = norm(eval_node(inner, cx, slots)?);
270            Ok(Val::Bool(matches!(v, Val::Arr(_))))
271        }
272        Node::Not(inner) => {
273            let v = norm(eval_node(inner, cx, slots)?);
274            Ok(Val::Bool(!semantics::truthy(&v)))
275        }
276        Node::And(l, r) => {
277            let lv = norm(eval_node(l, cx, slots)?);
278            if semantics::truthy(&lv) {
279                // 逻辑运算跨过了链的边界:右值即使是短路线,结果也是普通值。
280                Ok(norm(eval_node(r, cx, slots)?))
281            } else {
282                Ok(lv)
283            }
284        }
285        Node::Or(l, r) => {
286            let lv = norm(eval_node(l, cx, slots)?);
287            if semantics::truthy(&lv) {
288                Ok(lv)
289            } else {
290                Ok(norm(eval_node(r, cx, slots)?))
291            }
292        }
293        // `??` 只看 null/undefined,不看 falsy:`0 ?? 1` → 0、`'' ?? 'x'` → ''。
294        // 可选链短路的哨兵先归一成 undefined,所以 `item?.a ?? b` 在 item 缺失时取 b,
295        // 与 JS 把 `(item?.a)` 当 undefined 再合并一致。
296        Node::Nullish(l, r) => {
297            let lv = norm(eval_node(l, cx, slots)?);
298            match lv {
299                Val::Null | Val::Undefined => Ok(norm(eval_node(r, cx, slots)?)),
300                other => Ok(other),
301            }
302        }
303        Node::StrictEq(l, r) => {
304            let lv = norm(eval_node(l, cx, slots)?);
305            let rv = norm(eval_node(r, cx, slots)?);
306            Ok(Val::Bool(semantics::strict_eq(&lv, &rv)))
307        }
308        Node::LooseEq(l, r) => {
309            let lv = norm(eval_node(l, cx, slots)?);
310            let rv = norm(eval_node(r, cx, slots)?);
311            // 数组/对象参与 `==` 要走 ToPrimitive(数组 join、对象 "[object Object]")。
312            // 本 crate 的 Val::Str 只能借用,无法承载 join 出的字符串;静默按 false
313            // 处理会错判(`[] == false` 在 JS 为 true),显式报 Unsupported。
314            // 与 null/undefined 比较恒 false,无需 ToPrimitive,保持原行为。
315            if (needs_to_primitive(&lv) || needs_to_primitive(&rv))
316                && !matches!(lv, Val::Null | Val::Undefined)
317                && !matches!(rv, Val::Null | Val::Undefined)
318            {
319                return Err(Error::new(
320                    ErrorKind::Unsupported,
321                    "数组/对象参与 `==`/`!=` 需要 ToPrimitive,契约外".to_string(),
322                ));
323            }
324            Ok(Val::Bool(semantics::loose_eq(&lv, &rv)))
325        }
326        Node::Rel { op, lhs, rhs } => {
327            let lv = norm(eval_node(lhs, cx, slots)?);
328            let rv = norm(eval_node(rhs, cx, slots)?);
329            if needs_to_primitive(&lv) || needs_to_primitive(&rv) {
330                return Err(Error::new(
331                    ErrorKind::Unsupported,
332                    "数组/对象参与关系比较需要 ToPrimitive,契约外".to_string(),
333                ));
334            }
335            let ord = semantics::compare(&lv, &rv);
336            let out = match (ord, op) {
337                (Some(o), RelOp::Lt) => o.is_lt(),
338                (Some(o), RelOp::Le) => o.is_le(),
339                (Some(o), RelOp::Gt) => o.is_gt(),
340                (Some(o), RelOp::Ge) => o.is_ge(),
341                (None, _) => false,
342            };
343            Ok(Val::Bool(out))
344        }
345        Node::Set { .. } => Err(runtime("绑定语句不能出现在表达式位置")),
346    }
347}
348
349fn resolve<'a, D: Data<'a>>(
350    base: PathBase,
351    segs: &'a [PathSeg],
352    cx: &Cx<'a, D>,
353    slots: &mut [Option<Val<'a, D>>],
354) -> Result<Val<'a, D>, Error> {
355    let mut v = match base {
356        PathBase::Item => val_of(cx.row),
357        PathBase::Params => match cx.params {
358            Some(p) => val_of(p),
359            None => Val::EmptyObj,
360        },
361        PathBase::Local(i) => slot_ref(slots, i)?,
362    };
363    for seg in segs {
364        // `?.` 一旦在任一段短路,整条链后续所有访问都不再发生(JS optional chain 语义),
365        // 用哨兵一路透传到链尾;键缺失则只产生 undefined,让后续段按 JS 规则抛错。
366        if matches!(v, Val::ShortCircuit) {
367            return Ok(Val::ShortCircuit);
368        }
369        if matches!(v, Val::Undefined | Val::Null) {
370            if seg.optional {
371                return Ok(Val::ShortCircuit);
372            }
373            return Err(runtime(&format!(
374                "读取 `{}` 时基座是 null/undefined(JS 会抛 TypeError)",
375                seg.name
376            )));
377        }
378        v = match v {
379            Val::Obj(d) => d.get(&seg.name).map_or(Val::Undefined, val_of),
380            // 数组/空对象上的具名属性在 JS 里是 undefined(`.length` 另有节点)
381            Val::Arr(_) | Val::EmptyObj => Val::Undefined,
382            // 原始类型装箱后没有业务属性(短路哨兵已在上面拦截)
383            _ => Val::Undefined,
384        };
385    }
386    Ok(v)
387}
388
389/// 单段成员访问,`?.` 使基座为空时整链短路(返回哨兵)。
390fn lookup<'a, D: Data<'a>>(v: Val<'a, D>, name: &str, optional: bool) -> Result<Val<'a, D>, Error> {
391    match v {
392        Val::Obj(d) => Ok(d.get(name).map_or(Val::Undefined, val_of)),
393        Val::ShortCircuit => Ok(Val::ShortCircuit),
394        Val::Undefined | Val::Null => {
395            if optional {
396                Ok(Val::ShortCircuit)
397            } else {
398                Err(runtime(&format!(
399                    "读取 `{name}` 时基座是 null/undefined(JS 会抛 TypeError)"
400                )))
401            }
402        }
403        // 原始类型被 JS 装箱后没有业务属性,一律 undefined
404        Val::Str(_) | Val::Num(_) | Val::Bool(_) => Ok(Val::Undefined),
405        Val::Arr(_) | Val::EmptyObj => Ok(Val::Undefined),
406    }
407}
408
409fn index_into<'a, D: Data<'a>>(
410    base: Val<'a, D>,
411    index: Val<'a, D>,
412    optional: bool,
413) -> Result<Val<'a, D>, Error> {
414    match (base, index) {
415        (Val::ShortCircuit, _) => Ok(Val::ShortCircuit),
416        (Val::Arr(d), Val::Num(n)) => {
417            // `n as usize` 在 n ≥ 2^64 时会饱和成 usize::MAX。把它交给外部
418            // `Data::at` 实现会在用 `vec[i]` 的适配器上直接 panic;即使契约
419            // 要求越界返回 None,也不该把明显越界的下标传出去。先按数组
420            // 长度裁剪,越界即 undefined(JS 语义本就如此)。
421            if !(0.0..(d.len() as f64)).contains(&n) || n.fract() != 0.0 {
422                return Ok(Val::Undefined);
423            }
424            Ok(d.at(n as usize).map_or(Val::Undefined, val_of))
425        }
426        // JS ToPropertyKey:数字键先按 String(n) 转字符串,再查对象属性
427        (Val::Obj(d), Val::Num(n)) => {
428            let key = format_num(n);
429            Ok(d.get(&key).map_or(Val::Undefined, val_of))
430        }
431        (Val::Obj(d), Val::Str(s)) => Ok(d.get(s).map_or(Val::Undefined, val_of)),
432        // 数组上的字符串键:`"length"` 是元属性,规范数字串是下标,其余是普通属性(undefined)
433        (Val::Arr(d), Val::Str(s)) => {
434            if s == "length" {
435                return Ok(Val::Num(d.len() as f64));
436            }
437            match canonical_index(s) {
438                Some(k) => Ok(d.at(k).map_or(Val::Undefined, val_of)),
439                None => Ok(Val::Undefined),
440            }
441        }
442        // 字符串下标同样走 ToPropertyKey:规范数字串按 UTF-16 码元取字符
443        (Val::Str(s), Val::Str(idx)) => match canonical_index(idx) {
444            Some(k) => match utf16_char_at(s, k) {
445                Utf16At::Char(c) => Ok(Val::Str(c)),
446                Utf16At::None => Ok(Val::Undefined),
447                Utf16At::Surrogate => Err(Error::new(
448                    ErrorKind::Unsupported,
449                    "非 BMP 字符的 UTF-16 中间码元是孤立代理,无法用 Rust str 表示",
450                )),
451            },
452            None => Ok(Val::Undefined),
453        },
454        (Val::Str(s), Val::Num(n)) => {
455            if n < 0.0 || n.fract() != 0.0 {
456                return Ok(Val::Undefined);
457            }
458            match utf16_char_at(s, n as usize) {
459                Utf16At::Char(c) => Ok(Val::Str(c)),
460                Utf16At::None => Ok(Val::Undefined),
461                // JS 会返回孤立代理码元 "\ud800" 一类字符串,Rust 的 str 无法表示
462                Utf16At::Surrogate => Err(Error::new(
463                    ErrorKind::Unsupported,
464                    "非 BMP 字符的 UTF-16 中间码元是孤立代理,无法用 Rust str 表示",
465                )),
466            }
467        }
468        (Val::Undefined | Val::Null, _) if optional => Ok(Val::ShortCircuit),
469        (Val::Undefined | Val::Null, _) => Err(runtime("对 null/undefined 取下标")),
470        (Val::Arr(_), _) => Err(type_err("数组下标必须是整数")),
471        (Val::EmptyObj, _) => Ok(Val::Undefined),
472        _ => Ok(Val::Undefined),
473    }
474}
475
476/// 数组的规范数字键:`"0"`/`"12"` 是下标,`"01"`/`"+1"`/`"-1"`/`"a"` 不是
477/// (后者在数组上只是普通属性,取到 undefined)。
478fn canonical_index(s: &str) -> Option<usize> {
479    let b = s.as_bytes();
480    if b.is_empty() || !b[0].is_ascii_digit() {
481        return None;
482    }
483    if b.len() > 1 && b[0] == b'0' {
484        return None;
485    }
486    s.parse::<usize>().ok()
487}
488
489enum Utf16At<'a> {
490    /// 完整字符的借用切片。
491    Char(&'a str),
492    /// 落在代理对中间:JS 返回孤立代理,Rust `str` 无法表达。
493    Surrogate,
494    /// 越界。
495    None,
496}
497
498fn utf16_char_at(s: &str, idx: usize) -> Utf16At<'_> {
499    let mut pos = 0usize;
500    for (byte, ch) in s.char_indices() {
501        if pos == idx {
502            let end = byte + ch.len_utf8();
503            return match s.get(byte..end) {
504                Some(c) => Utf16At::Char(c),
505                None => Utf16At::None,
506            };
507        }
508        let units = ch.len_utf16();
509        if units == 2 && pos < idx && idx < pos + units {
510            return Utf16At::Surrogate;
511        }
512        pos += units;
513    }
514    Utf16At::None
515}
516
517fn call_method<'a, D: Data<'a>>(
518    base: Val<'a, D>,
519    method: Method,
520    optional: bool,
521    arg: Val<'a, D>,
522) -> Result<Val<'a, D>, Error> {
523    if matches!(base, Val::ShortCircuit) {
524        return Ok(Val::ShortCircuit);
525    }
526    if matches!(base, Val::Undefined | Val::Null) && optional {
527        return Ok(Val::ShortCircuit);
528    }
529    match base {
530        Val::Str(s) => {
531            let Some(needle) = to_js_string(&arg) else {
532                return Err(type_err("字符串方法的参数不能是数组/对象"));
533            };
534            match method {
535                Method::Includes => Ok(Val::Bool(s.contains(needle.as_ref()))),
536                Method::IndexOf => Ok(Val::Num(match s.find(needle.as_ref()) {
537                    Some(byte) => semantics::utf16_len(&s[..byte]) as f64,
538                    None => -1.0,
539                })),
540                Method::StartsWith => Ok(Val::Bool(s.starts_with(needle.as_ref()))),
541                Method::EndsWith => Ok(Val::Bool(s.ends_with(needle.as_ref()))),
542                Method::Some => Err(type_err("`.some` 只能用于数组")),
543            }
544        }
545        Val::Arr(d) => match method {
546            Method::Includes => {
547                for i in 0..d.len() {
548                    let Some(el) = d.at(i) else { continue };
549                    if semantics::same_value_zero(&val_of(el), &arg) {
550                        return Ok(Val::Bool(true));
551                    }
552                }
553                Ok(Val::Bool(false))
554            }
555            Method::IndexOf => {
556                for i in 0..d.len() {
557                    let Some(el) = d.at(i) else { continue };
558                    if semantics::strict_eq(&val_of(el), &arg) {
559                        return Ok(Val::Num(i as f64));
560                    }
561                }
562                Ok(Val::Num(-1.0))
563            }
564            Method::StartsWith => Err(type_err("`.startsWith` 只能用于字符串")),
565            Method::EndsWith => Err(type_err("`.endsWith` 只能用于字符串")),
566            Method::Some => Err(type_err("`.some` 走独立节点")),
567        },
568        Val::Undefined | Val::Null => Err(runtime("对 null/undefined 调用方法")),
569        _ => Err(type_err("基座不是数组或字符串")),
570    }
571}