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
100fn slot_ref<'a, D: Data<'a>>(slots: &[Option<Val<'a, D>>], i: u16) -> Result<Val<'a, D>, Error> {
102 slots
103 .get(usize::from(i))
104 .copied()
105 .flatten()
106 .ok_or_else(|| runtime("槽位越界或未初始化"))
107}
108
109fn slot_set<'a, D: Data<'a>>(
111 slots: &mut [Option<Val<'a, D>>],
112 i: u16,
113 v: Val<'a, D>,
114) -> Result<(), Error> {
115 match slots.get_mut(usize::from(i)) {
116 Some(slot) => {
117 *slot = Some(v);
118 Ok(())
119 }
120 None => Err(runtime("槽位越界")),
121 }
122}
123
124fn val_of<'a, D: Data<'a>>(d: D) -> Val<'a, D> {
125 match d.kind() {
126 Kind::Null => Val::Null,
127 Kind::Bool => Val::Bool(d.as_bool().unwrap_or(false)),
128 Kind::Number => Val::Num(d.as_f64().unwrap_or(f64::NAN)),
129 Kind::String => Val::Str(d.as_str().unwrap_or("")),
130 Kind::Array => Val::Arr(d),
131 Kind::Object => Val::Obj(d),
132 }
133}
134
135fn const_to_val<'a, D: Data<'a>>(c: &'a ConstVal) -> Val<'a, D> {
136 match c {
137 ConstVal::Undefined => Val::Undefined,
138 ConstVal::Null => Val::Null,
139 ConstVal::Bool(b) => Val::Bool(*b),
140 ConstVal::Num(n) => Val::Num(*n),
141 ConstVal::Str(s) => Val::Str(s),
142 }
143}
144
145fn to_js_string<'a, D: Data<'a>>(v: &Val<'a, D>) -> Option<Cow<'a, str>> {
147 match v {
148 Val::Str(s) => Some(Cow::Borrowed(*s)),
149 Val::Num(n) => Some(Cow::Owned(format_num(*n))),
150 Val::Bool(b) => Some(Cow::Borrowed(if *b { "true" } else { "false" })),
151 Val::Null => Some(Cow::Borrowed("null")),
152 Val::Undefined | Val::ShortCircuit => Some(Cow::Borrowed("undefined")),
153 Val::Arr(_) | Val::Obj(_) => None,
154 Val::EmptyObj => None,
155 }
156}
157
158fn eval_node<'a, D: Data<'a>>(
159 n: &'a Node,
160 cx: &Cx<'a, D>,
161 slots: &mut [Option<Val<'a, D>>],
162) -> Result<Val<'a, D>, Error> {
163 match n {
164 Node::Const(c) => Ok(const_to_val(c)),
165 Node::Item => Ok(val_of(cx.row)),
166 Node::Group(inner) => Ok(norm(eval_node(inner, cx, slots)?)),
168 Node::Params => Ok(match cx.params {
170 Some(p) => val_of(p),
171 None => Val::EmptyObj,
172 }),
173 Node::Local(i) => slot_ref(slots, *i),
174 Node::Path { base, segs } => resolve(*base, segs, cx, slots),
175 Node::Member {
176 base,
177 name,
178 optional,
179 } => {
180 let v = eval_node(base, cx, slots)?;
181 if matches!(v, Val::ShortCircuit) {
182 return Ok(Val::ShortCircuit);
183 }
184 lookup(v, name, *optional)
185 }
186 Node::Length { base, optional } => {
187 let v = eval_node(base, cx, slots)?;
188 if matches!(v, Val::ShortCircuit) {
189 return Ok(Val::ShortCircuit);
190 }
191 match v {
192 Val::Str(s) => Ok(Val::Num(semantics::utf16_len(s) as f64)),
193 Val::Arr(d) => Ok(Val::Num(d.len() as f64)),
194 Val::Obj(d) => Ok(d.get("length").map_or(Val::Undefined, val_of)),
196 Val::EmptyObj => Ok(Val::Undefined),
197 Val::Undefined | Val::Null if *optional => Ok(Val::ShortCircuit),
198 Val::Undefined | Val::Null => Err(runtime("读取 null/undefined 的 `.length`")),
199 Val::Num(_) | Val::Bool(_) => Ok(Val::Undefined),
201 Val::ShortCircuit => Ok(Val::ShortCircuit),
202 }
203 }
204 Node::Index {
205 base,
206 index,
207 optional,
208 } => {
209 let b = eval_node(base, cx, slots)?;
210 if matches!(b, Val::ShortCircuit) {
211 return Ok(Val::ShortCircuit);
212 }
213 let i = eval_node(index, cx, slots)?;
214 index_into(b, norm(i), *optional)
215 }
216 Node::Call {
217 base,
218 method,
219 optional,
220 arg,
221 } => {
222 let b = eval_node(base, cx, slots)?;
223 if matches!(b, Val::ShortCircuit) {
224 return Ok(Val::ShortCircuit);
225 }
226 let a = eval_node(arg, cx, slots)?;
227 call_method(b, *method, *optional, norm(a))
228 }
229 Node::ConstIncludes { set, hay } => {
230 let v = norm(eval_node(hay, cx, slots)?);
231 let probe = match v {
232 Val::Str(s) => Probe::Str(s),
233 Val::Num(n) => Probe::Num(n),
234 _ => Probe::Other,
235 };
236 Ok(Val::Bool(set.contains(probe)))
237 }
238 Node::Some {
239 base,
240 slot,
241 body,
242 optional,
243 } => {
244 let b = eval_node(base, cx, slots)?;
245 match b {
246 Val::ShortCircuit => Ok(Val::ShortCircuit),
247 Val::Arr(d) => {
248 for i in 0..d.len() {
249 let Some(el) = d.at(i) else { continue };
250 slot_set(slots, *slot, val_of(el))?;
251 if semantics::truthy(&norm(eval_node(body, cx, slots)?)) {
252 return Ok(Val::Bool(true));
253 }
254 }
255 Ok(Val::Bool(false))
256 }
257 Val::Undefined | Val::Null if *optional => Ok(Val::ShortCircuit),
258 Val::Undefined | Val::Null => Err(runtime("`.some` 的调用基座是 null/undefined")),
259 _ => Err(type_err("`.some` 只能用于数组")),
260 }
261 }
262 Node::ParseInt(inner) => {
263 let v = norm(eval_node(inner, cx, slots)?);
264 let n = match v {
265 Val::Str(s) => semantics::parse_int(s),
266 Val::Num(n) if n.is_finite() => {
269 let text = format_num(n);
270 semantics::parse_int(&text)
271 }
272 _ => f64::NAN,
274 };
275 Ok(Val::Num(n))
276 }
277 Node::IsArray(inner) => {
278 let v = norm(eval_node(inner, cx, slots)?);
279 Ok(Val::Bool(matches!(v, Val::Arr(_))))
280 }
281 Node::Not(inner) => {
282 let v = norm(eval_node(inner, cx, slots)?);
283 Ok(Val::Bool(!semantics::truthy(&v)))
284 }
285 Node::And(l, r) => {
286 let lv = norm(eval_node(l, cx, slots)?);
287 if semantics::truthy(&lv) {
288 Ok(norm(eval_node(r, cx, slots)?))
290 } else {
291 Ok(lv)
292 }
293 }
294 Node::Or(l, r) => {
295 let lv = norm(eval_node(l, cx, slots)?);
296 if semantics::truthy(&lv) {
297 Ok(lv)
298 } else {
299 Ok(norm(eval_node(r, cx, slots)?))
300 }
301 }
302 Node::Nullish(l, r) => {
306 let lv = norm(eval_node(l, cx, slots)?);
307 match lv {
308 Val::Null | Val::Undefined => Ok(norm(eval_node(r, cx, slots)?)),
309 other => Ok(other),
310 }
311 }
312 Node::StrictEq(l, r) => {
313 let lv = norm(eval_node(l, cx, slots)?);
314 let rv = norm(eval_node(r, cx, slots)?);
315 if needs_identity(&lv) && needs_identity(&rv) {
319 return Err(Error::new(
320 ErrorKind::Unsupported,
321 "对象/数组之间的 `===`/`!==` 需要引用身份,契约外".to_string(),
322 ));
323 }
324 Ok(Val::Bool(semantics::strict_eq(&lv, &rv)))
325 }
326 Node::LooseEq(l, r) => {
327 let lv = norm(eval_node(l, cx, slots)?);
328 let rv = norm(eval_node(r, cx, slots)?);
329 if (needs_to_primitive(&lv) || needs_to_primitive(&rv))
334 && !matches!(lv, Val::Null | Val::Undefined)
335 && !matches!(rv, Val::Null | Val::Undefined)
336 {
337 return Err(Error::new(
338 ErrorKind::Unsupported,
339 "数组/对象参与 `==`/`!=` 需要 ToPrimitive,契约外".to_string(),
340 ));
341 }
342 Ok(Val::Bool(semantics::loose_eq(&lv, &rv)))
343 }
344 Node::Rel { op, lhs, rhs } => {
345 let lv = norm(eval_node(lhs, cx, slots)?);
346 let rv = norm(eval_node(rhs, cx, slots)?);
347 if needs_to_primitive(&lv) || needs_to_primitive(&rv) {
348 return Err(Error::new(
349 ErrorKind::Unsupported,
350 "数组/对象参与关系比较需要 ToPrimitive,契约外".to_string(),
351 ));
352 }
353 let ord = semantics::compare(&lv, &rv);
354 let out = match (ord, op) {
355 (Some(o), RelOp::Lt) => o.is_lt(),
356 (Some(o), RelOp::Le) => o.is_le(),
357 (Some(o), RelOp::Gt) => o.is_gt(),
358 (Some(o), RelOp::Ge) => o.is_ge(),
359 (None, _) => false,
360 };
361 Ok(Val::Bool(out))
362 }
363 Node::DateNew(arg) => {
365 let ms = match arg {
366 None => date::now_ms(),
367 Some(a) => match norm(eval_node(a, cx, slots)?) {
368 Val::Num(n) => date::clip(n),
369 Val::Str(s) => date::parse(s),
370 Val::Null => 0.0,
372 Val::Bool(b) => {
373 if b {
374 1.0
375 } else {
376 0.0
377 }
378 }
379 Val::Undefined => f64::NAN,
381 Val::Arr(_) | Val::Obj(_) | Val::EmptyObj => {
382 return Err(Error::new(
383 ErrorKind::Unsupported,
384 "`new Date(...)` 的数组/对象参数需要 ToPrimitive,契约外".to_string(),
385 ));
386 }
387 Val::ShortCircuit => f64::NAN,
389 },
390 };
391 Ok(Val::Num(ms))
392 }
393 Node::DateNow => Ok(Val::Num(date::now_ms())),
394 Node::GetTime(inner) => {
395 let v = eval_node(inner, cx, slots)?;
396 match v {
397 Val::Num(n) => Ok(Val::Num(n)),
399 Val::ShortCircuit => Ok(Val::ShortCircuit),
400 other => Err(type_err(&format!(
401 "`.getTime()` 的基座不是 Date(得到 {other:?})"
402 ))),
403 }
404 }
405 Node::MathFloor(inner) => {
406 let v = norm(eval_node(inner, cx, slots)?);
407 let n = semantics::to_number(&v)
408 .ok_or_else(|| type_err("`Math.floor` 的参数需要 ToNumber(数组/对象契约外)"))?;
409 Ok(Val::Num(n.floor()))
410 }
411 Node::Arith { op, lhs, rhs } => {
412 let lv = norm(eval_node(lhs, cx, slots)?);
413 let rv = norm(eval_node(rhs, cx, slots)?);
414 let a = semantics::to_number(&lv)
415 .ok_or_else(|| type_err("算术左值需要 ToNumber(数组/对象契约外)"))?;
416 let b = semantics::to_number(&rv)
417 .ok_or_else(|| type_err("算术右值需要 ToNumber(数组/对象契约外)"))?;
418 Ok(Val::Num(match op {
420 ArithOp::Sub => a - b,
421 ArithOp::Mul => a * b,
422 ArithOp::Div => a / b,
423 }))
424 }
425 Node::Set { .. } => Err(runtime("绑定语句不能出现在表达式位置")),
426 }
427}
428
429fn resolve<'a, D: Data<'a>>(
430 base: PathBase,
431 segs: &'a [PathSeg],
432 cx: &Cx<'a, D>,
433 slots: &mut [Option<Val<'a, D>>],
434) -> Result<Val<'a, D>, Error> {
435 let mut v = match base {
436 PathBase::Item => val_of(cx.row),
437 PathBase::Params => match cx.params {
438 Some(p) => val_of(p),
439 None => Val::EmptyObj,
440 },
441 PathBase::Local(i) => slot_ref(slots, i)?,
442 };
443 for seg in segs {
444 if matches!(v, Val::ShortCircuit) {
447 return Ok(Val::ShortCircuit);
448 }
449 if matches!(v, Val::Undefined | Val::Null) {
450 if seg.optional {
451 return Ok(Val::ShortCircuit);
452 }
453 return Err(runtime(&format!(
454 "读取 `{}` 时基座是 null/undefined(JS 会抛 TypeError)",
455 seg.name
456 )));
457 }
458 v = match v {
459 Val::Obj(d) => d.get(&seg.name).map_or(Val::Undefined, val_of),
460 Val::Arr(_) | Val::EmptyObj => Val::Undefined,
462 _ => Val::Undefined,
464 };
465 }
466 Ok(v)
467}
468
469fn lookup<'a, D: Data<'a>>(v: Val<'a, D>, name: &str, optional: bool) -> Result<Val<'a, D>, Error> {
471 match v {
472 Val::Obj(d) => Ok(d.get(name).map_or(Val::Undefined, val_of)),
473 Val::ShortCircuit => Ok(Val::ShortCircuit),
474 Val::Undefined | Val::Null => {
475 if optional {
476 Ok(Val::ShortCircuit)
477 } else {
478 Err(runtime(&format!(
479 "读取 `{name}` 时基座是 null/undefined(JS 会抛 TypeError)"
480 )))
481 }
482 }
483 Val::Str(_) | Val::Num(_) | Val::Bool(_) => Ok(Val::Undefined),
485 Val::Arr(_) | Val::EmptyObj => Ok(Val::Undefined),
486 }
487}
488
489fn index_into<'a, D: Data<'a>>(
490 base: Val<'a, D>,
491 index: Val<'a, D>,
492 optional: bool,
493) -> Result<Val<'a, D>, Error> {
494 match (base, index) {
495 (Val::ShortCircuit, _) => Ok(Val::ShortCircuit),
496 (Val::Arr(d), Val::Num(n)) => {
497 if !(0.0..(d.len() as f64)).contains(&n) || n.fract() != 0.0 {
502 return Ok(Val::Undefined);
503 }
504 Ok(d.at(n as usize).map_or(Val::Undefined, val_of))
505 }
506 (Val::Obj(d), Val::Num(n)) => {
508 let key = format_num(n);
509 Ok(d.get(&key).map_or(Val::Undefined, val_of))
510 }
511 (Val::Obj(d), Val::Str(s)) => Ok(d.get(s).map_or(Val::Undefined, val_of)),
512 (Val::Arr(d), Val::Str(s)) => {
514 if s == "length" {
515 return Ok(Val::Num(d.len() as f64));
516 }
517 match canonical_index(s) {
521 Some(k) if k < d.len() => Ok(d.at(k).map_or(Val::Undefined, val_of)),
522 _ => Ok(Val::Undefined),
523 }
524 }
525 (Val::Str(s), Val::Str(idx)) => match canonical_index(idx) {
527 Some(k) => match utf16_char_at(s, k) {
528 Utf16At::Char(c) => Ok(Val::Str(c)),
529 Utf16At::None => Ok(Val::Undefined),
530 Utf16At::Surrogate => Err(Error::new(
531 ErrorKind::Unsupported,
532 "非 BMP 字符的 UTF-16 中间码元是孤立代理,无法用 Rust str 表示",
533 )),
534 },
535 None => Ok(Val::Undefined),
536 },
537 (Val::Str(s), Val::Num(n)) => {
538 if n < 0.0 || n.fract() != 0.0 {
539 return Ok(Val::Undefined);
540 }
541 match utf16_char_at(s, n as usize) {
542 Utf16At::Char(c) => Ok(Val::Str(c)),
543 Utf16At::None => Ok(Val::Undefined),
544 Utf16At::Surrogate => Err(Error::new(
546 ErrorKind::Unsupported,
547 "非 BMP 字符的 UTF-16 中间码元是孤立代理,无法用 Rust str 表示",
548 )),
549 }
550 }
551 (Val::Undefined | Val::Null, _) if optional => Ok(Val::ShortCircuit),
552 (Val::Undefined | Val::Null, _) => Err(runtime("对 null/undefined 取下标")),
553 (Val::Arr(_), _) => Err(type_err("数组下标必须是整数")),
554 (Val::EmptyObj, _) => Ok(Val::Undefined),
555 _ => Ok(Val::Undefined),
556 }
557}
558
559fn canonical_index(s: &str) -> Option<usize> {
562 let b = s.as_bytes();
563 if b.is_empty() || !b[0].is_ascii_digit() {
564 return None;
565 }
566 if b.len() > 1 && b[0] == b'0' {
567 return None;
568 }
569 s.parse::<usize>().ok()
570}
571
572enum Utf16At<'a> {
573 Char(&'a str),
575 Surrogate,
577 None,
579}
580
581fn utf16_char_at(s: &str, idx: usize) -> Utf16At<'_> {
582 let mut pos = 0usize;
583 for (byte, ch) in s.char_indices() {
584 let units = ch.len_utf16();
585 if pos == idx {
586 return if units == 1 {
590 match s.get(byte..byte + ch.len_utf8()) {
591 Some(c) => Utf16At::Char(c),
592 None => Utf16At::None,
593 }
594 } else {
595 Utf16At::Surrogate
596 };
597 }
598 if units == 2 && pos < idx && idx < pos + units {
599 return Utf16At::Surrogate;
600 }
601 pos += units;
602 }
603 Utf16At::None
604}
605
606fn call_method<'a, D: Data<'a>>(
607 base: Val<'a, D>,
608 method: Method,
609 optional: bool,
610 arg: Val<'a, D>,
611) -> Result<Val<'a, D>, Error> {
612 if matches!(base, Val::ShortCircuit) {
613 return Ok(Val::ShortCircuit);
614 }
615 if matches!(base, Val::Undefined | Val::Null) && optional {
616 return Ok(Val::ShortCircuit);
617 }
618 match base {
619 Val::Str(s) => {
620 let Some(needle) = to_js_string(&arg) else {
621 return Err(type_err("字符串方法的参数不能是数组/对象"));
622 };
623 match method {
624 Method::Includes => Ok(Val::Bool(s.contains(needle.as_ref()))),
625 Method::IndexOf => Ok(Val::Num(match s.find(needle.as_ref()) {
626 Some(byte) => semantics::utf16_len(&s[..byte]) as f64,
627 None => -1.0,
628 })),
629 Method::StartsWith => Ok(Val::Bool(s.starts_with(needle.as_ref()))),
630 Method::EndsWith => Ok(Val::Bool(s.ends_with(needle.as_ref()))),
631 Method::Some => Err(type_err("`.some` 只能用于数组")),
632 Method::GetTime => Err(runtime("`.getTime()` 走独立节点")),
633 }
634 }
635 Val::Arr(d) => match method {
636 Method::Includes | Method::IndexOf if needs_identity(&arg) => Err(Error::new(
637 ErrorKind::Unsupported,
638 "数组方法的引用参数需要身份比较,契约外".to_string(),
639 )),
640 Method::Includes => {
641 for i in 0..d.len() {
642 let Some(el) = d.at(i) else { continue };
643 if semantics::same_value_zero(&val_of(el), &arg) {
644 return Ok(Val::Bool(true));
645 }
646 }
647 Ok(Val::Bool(false))
648 }
649 Method::IndexOf => {
650 for i in 0..d.len() {
651 let Some(el) = d.at(i) else { continue };
652 if semantics::strict_eq(&val_of(el), &arg) {
653 return Ok(Val::Num(i as f64));
654 }
655 }
656 Ok(Val::Num(-1.0))
657 }
658 Method::StartsWith => Err(type_err("`.startsWith` 只能用于字符串")),
659 Method::EndsWith => Err(type_err("`.endsWith` 只能用于字符串")),
660 Method::Some => Err(type_err("`.some` 走独立节点")),
661 Method::GetTime => Err(runtime("`.getTime()` 走独立节点")),
662 },
663 Val::Undefined | Val::Null => Err(runtime("对 null/undefined 调用方法")),
664 _ => Err(type_err("基座不是数组或字符串")),
665 }
666}