1use 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
16const 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 pub fn eval<'a, D: Data<'a>>(&'a self, row: D, params: Option<D>) -> Result<bool, Error> {
33 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 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 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
71fn type_err(msg: &str) -> Error {
73 Error::new(ErrorKind::Type, msg.to_string())
74}
75
76fn needs_to_primitive<'a, D: Data<'a>>(v: &Val<'a, D>) -> bool {
79 matches!(v, Val::Arr(_) | Val::Obj(_) | Val::EmptyObj)
80}
81
82fn 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
91fn 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
100fn 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
136fn 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 Node::Group(inner) => Ok(norm(eval_node(inner, cx, slots)?)),
159 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 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 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 Val::Num(n) if n.is_finite() => {
260 let text = format_num(n);
261 semantics::parse_int(&text)
262 }
263 _ => 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 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 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 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 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 Val::Arr(_) | Val::EmptyObj => Val::Undefined,
382 _ => Val::Undefined,
384 };
385 }
386 Ok(v)
387}
388
389fn 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 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 if n < 0.0 || n.fract() != 0.0 {
418 return Ok(Val::Undefined);
419 }
420 Ok(d.at(n as usize).map_or(Val::Undefined, val_of))
421 }
422 (Val::Obj(d), Val::Num(n)) => {
424 let key = format_num(n);
425 Ok(d.get(&key).map_or(Val::Undefined, val_of))
426 }
427 (Val::Obj(d), Val::Str(s)) => Ok(d.get(s).map_or(Val::Undefined, val_of)),
428 (Val::Arr(d), Val::Str(s)) => {
430 if s == "length" {
431 return Ok(Val::Num(d.len() as f64));
432 }
433 match canonical_index(s) {
434 Some(k) => Ok(d.at(k).map_or(Val::Undefined, val_of)),
435 None => Ok(Val::Undefined),
436 }
437 }
438 (Val::Str(s), Val::Str(idx)) => match canonical_index(idx) {
440 Some(k) => match utf16_char_at(s, k) {
441 Utf16At::Char(c) => Ok(Val::Str(c)),
442 Utf16At::None => Ok(Val::Undefined),
443 Utf16At::Surrogate => Err(Error::new(
444 ErrorKind::Unsupported,
445 "非 BMP 字符的 UTF-16 中间码元是孤立代理,无法用 Rust str 表示",
446 )),
447 },
448 None => Ok(Val::Undefined),
449 },
450 (Val::Str(s), Val::Num(n)) => {
451 if n < 0.0 || n.fract() != 0.0 {
452 return Ok(Val::Undefined);
453 }
454 match utf16_char_at(s, n as usize) {
455 Utf16At::Char(c) => Ok(Val::Str(c)),
456 Utf16At::None => Ok(Val::Undefined),
457 Utf16At::Surrogate => Err(Error::new(
459 ErrorKind::Unsupported,
460 "非 BMP 字符的 UTF-16 中间码元是孤立代理,无法用 Rust str 表示",
461 )),
462 }
463 }
464 (Val::Undefined | Val::Null, _) if optional => Ok(Val::ShortCircuit),
465 (Val::Undefined | Val::Null, _) => Err(runtime("对 null/undefined 取下标")),
466 (Val::Arr(_), _) => Err(type_err("数组下标必须是整数")),
467 (Val::EmptyObj, _) => Ok(Val::Undefined),
468 _ => Ok(Val::Undefined),
469 }
470}
471
472fn canonical_index(s: &str) -> Option<usize> {
475 let b = s.as_bytes();
476 if b.is_empty() || !b[0].is_ascii_digit() {
477 return None;
478 }
479 if b.len() > 1 && b[0] == b'0' {
480 return None;
481 }
482 s.parse::<usize>().ok()
483}
484
485enum Utf16At<'a> {
486 Char(&'a str),
488 Surrogate,
490 None,
492}
493
494fn utf16_char_at(s: &str, idx: usize) -> Utf16At<'_> {
495 let mut pos = 0usize;
496 for (byte, ch) in s.char_indices() {
497 if pos == idx {
498 let end = byte + ch.len_utf8();
499 return match s.get(byte..end) {
500 Some(c) => Utf16At::Char(c),
501 None => Utf16At::None,
502 };
503 }
504 let units = ch.len_utf16();
505 if units == 2 && pos < idx && idx < pos + units {
506 return Utf16At::Surrogate;
507 }
508 pos += units;
509 }
510 Utf16At::None
511}
512
513fn call_method<'a, D: Data<'a>>(
514 base: Val<'a, D>,
515 method: Method,
516 optional: bool,
517 arg: Val<'a, D>,
518) -> Result<Val<'a, D>, Error> {
519 if matches!(base, Val::ShortCircuit) {
520 return Ok(Val::ShortCircuit);
521 }
522 if matches!(base, Val::Undefined | Val::Null) && optional {
523 return Ok(Val::ShortCircuit);
524 }
525 match base {
526 Val::Str(s) => {
527 let Some(needle) = to_js_string(&arg) else {
528 return Err(type_err("字符串方法的参数不能是数组/对象"));
529 };
530 match method {
531 Method::Includes => Ok(Val::Bool(s.contains(needle.as_ref()))),
532 Method::IndexOf => Ok(Val::Num(match s.find(needle.as_ref()) {
533 Some(byte) => semantics::utf16_len(&s[..byte]) as f64,
534 None => -1.0,
535 })),
536 Method::Some => Err(type_err("`.some` 只能用于数组")),
537 }
538 }
539 Val::Arr(d) => match method {
540 Method::Includes => {
541 for i in 0..d.len() {
542 let Some(el) = d.at(i) else { continue };
543 if semantics::same_value_zero(&val_of(el), &arg) {
544 return Ok(Val::Bool(true));
545 }
546 }
547 Ok(Val::Bool(false))
548 }
549 Method::IndexOf => {
550 for i in 0..d.len() {
551 let Some(el) = d.at(i) else { continue };
552 if semantics::strict_eq(&val_of(el), &arg) {
553 return Ok(Val::Num(i as f64));
554 }
555 }
556 Ok(Val::Num(-1.0))
557 }
558 Method::Some => Err(type_err("`.some` 走独立节点")),
559 },
560 Val::Undefined | Val::Null => Err(runtime("对 null/undefined 调用方法")),
561 _ => Err(type_err("基座不是数组或字符串")),
562 }
563}