1use 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
17const 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 pub fn eval<'a, D: Data<'a>>(&'a self, row: D, params: Option<D>) -> Result<bool, Error> {
34 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 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 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
72fn type_err(msg: &str) -> Error {
74 Error::new(ErrorKind::Type, msg.to_string())
75}
76
77fn needs_to_primitive<'a, D: Data<'a>>(v: &Val<'a, D>) -> bool {
80 matches!(v, Val::Arr(_) | Val::Obj(_) | Val::EmptyObj)
81}
82
83fn needs_identity<'a, D: Data<'a>>(v: &Val<'a, D>) -> bool {
88 matches!(v, Val::Arr(_) | Val::Obj(_) | Val::EmptyObj)
89}
90
91fn 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
100const 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
291fn 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
300fn 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
336fn 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 Val::Date(_) => None,
347 Val::Arr(_) | Val::Obj(_) => None,
348 Val::EmptyObj => None,
349 }
350}
351
352fn 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 Node::Group(inner) => Ok(norm(eval_node(inner, cx, slots)?)),
390 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 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 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 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 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 Val::Num(n) if n.is_finite() => {
500 let text = format_num(n);
501 semantics::parse_int(&text)
502 }
503 Val::Date(_) => f64::NAN,
505 Val::Arr(d) => semantics::parse_int(&array_to_js_string(d)?),
507 _ => 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 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 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 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 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 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 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 Val::Date(n) => date::clip(n),
629 Val::Str(s) => date::parse(s),
630 Val::Null => 0.0,
632 Val::Bool(b) => {
633 if b {
634 1.0
635 } else {
636 0.0
637 }
638 }
639 Val::Undefined => f64::NAN,
641 Val::Arr(d) => date::parse(&array_to_js_string(d)?),
645 Val::Obj(_) | Val::EmptyObj => f64::NAN,
648 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 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 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 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 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 _ => Val::Undefined,
740 };
741 }
742 Ok(v)
743}
744
745fn 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 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 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 (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 (Val::Arr(d), Val::Str(s)) => {
809 if s == "length" {
810 return Ok(Val::Num(d.len() as f64));
811 }
812 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 (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 (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 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 (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
913fn 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 Char(&'a str),
929 Surrogate,
931 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 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}