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::StrictEq(l, r) => {
294 let lv = norm(eval_node(l, cx, slots)?);
295 let rv = norm(eval_node(r, cx, slots)?);
296 Ok(Val::Bool(semantics::strict_eq(&lv, &rv)))
297 }
298 Node::LooseEq(l, r) => {
299 let lv = norm(eval_node(l, cx, slots)?);
300 let rv = norm(eval_node(r, cx, slots)?);
301 if (needs_to_primitive(&lv) || needs_to_primitive(&rv))
306 && !matches!(lv, Val::Null | Val::Undefined)
307 && !matches!(rv, Val::Null | Val::Undefined)
308 {
309 return Err(Error::new(
310 ErrorKind::Unsupported,
311 "数组/对象参与 `==`/`!=` 需要 ToPrimitive,契约外".to_string(),
312 ));
313 }
314 Ok(Val::Bool(semantics::loose_eq(&lv, &rv)))
315 }
316 Node::Rel { op, lhs, rhs } => {
317 let lv = norm(eval_node(lhs, cx, slots)?);
318 let rv = norm(eval_node(rhs, cx, slots)?);
319 if needs_to_primitive(&lv) || needs_to_primitive(&rv) {
320 return Err(Error::new(
321 ErrorKind::Unsupported,
322 "数组/对象参与关系比较需要 ToPrimitive,契约外".to_string(),
323 ));
324 }
325 let ord = semantics::compare(&lv, &rv);
326 let out = match (ord, op) {
327 (Some(o), RelOp::Lt) => o.is_lt(),
328 (Some(o), RelOp::Le) => o.is_le(),
329 (Some(o), RelOp::Gt) => o.is_gt(),
330 (Some(o), RelOp::Ge) => o.is_ge(),
331 (None, _) => false,
332 };
333 Ok(Val::Bool(out))
334 }
335 Node::Set { .. } => Err(runtime("绑定语句不能出现在表达式位置")),
336 }
337}
338
339fn resolve<'a, D: Data<'a>>(
340 base: PathBase,
341 segs: &'a [PathSeg],
342 cx: &Cx<'a, D>,
343 slots: &mut [Option<Val<'a, D>>],
344) -> Result<Val<'a, D>, Error> {
345 let mut v = match base {
346 PathBase::Item => val_of(cx.row),
347 PathBase::Params => match cx.params {
348 Some(p) => val_of(p),
349 None => Val::EmptyObj,
350 },
351 PathBase::Local(i) => slot_ref(slots, i)?,
352 };
353 for seg in segs {
354 if matches!(v, Val::ShortCircuit) {
357 return Ok(Val::ShortCircuit);
358 }
359 if matches!(v, Val::Undefined | Val::Null) {
360 if seg.optional {
361 return Ok(Val::ShortCircuit);
362 }
363 return Err(runtime(&format!(
364 "读取 `{}` 时基座是 null/undefined(JS 会抛 TypeError)",
365 seg.name
366 )));
367 }
368 v = match v {
369 Val::Obj(d) => d.get(&seg.name).map_or(Val::Undefined, val_of),
370 Val::Arr(_) | Val::EmptyObj => Val::Undefined,
372 _ => Val::Undefined,
374 };
375 }
376 Ok(v)
377}
378
379fn lookup<'a, D: Data<'a>>(v: Val<'a, D>, name: &str, optional: bool) -> Result<Val<'a, D>, Error> {
381 match v {
382 Val::Obj(d) => Ok(d.get(name).map_or(Val::Undefined, val_of)),
383 Val::ShortCircuit => Ok(Val::ShortCircuit),
384 Val::Undefined | Val::Null => {
385 if optional {
386 Ok(Val::ShortCircuit)
387 } else {
388 Err(runtime(&format!(
389 "读取 `{name}` 时基座是 null/undefined(JS 会抛 TypeError)"
390 )))
391 }
392 }
393 Val::Str(_) | Val::Num(_) | Val::Bool(_) => Ok(Val::Undefined),
395 Val::Arr(_) | Val::EmptyObj => Ok(Val::Undefined),
396 }
397}
398
399fn index_into<'a, D: Data<'a>>(
400 base: Val<'a, D>,
401 index: Val<'a, D>,
402 optional: bool,
403) -> Result<Val<'a, D>, Error> {
404 match (base, index) {
405 (Val::ShortCircuit, _) => Ok(Val::ShortCircuit),
406 (Val::Arr(d), Val::Num(n)) => {
407 if n < 0.0 || n.fract() != 0.0 {
408 return Ok(Val::Undefined);
409 }
410 Ok(d.at(n as usize).map_or(Val::Undefined, val_of))
411 }
412 (Val::Obj(d), Val::Num(n)) => {
414 let key = format_num(n);
415 Ok(d.get(&key).map_or(Val::Undefined, val_of))
416 }
417 (Val::Obj(d), Val::Str(s)) => Ok(d.get(s).map_or(Val::Undefined, val_of)),
418 (Val::Arr(d), Val::Str(s)) => {
420 if s == "length" {
421 return Ok(Val::Num(d.len() as f64));
422 }
423 match canonical_index(s) {
424 Some(k) => Ok(d.at(k).map_or(Val::Undefined, val_of)),
425 None => Ok(Val::Undefined),
426 }
427 }
428 (Val::Str(s), Val::Str(idx)) => match canonical_index(idx) {
430 Some(k) => match utf16_char_at(s, k) {
431 Utf16At::Char(c) => Ok(Val::Str(c)),
432 Utf16At::None => Ok(Val::Undefined),
433 Utf16At::Surrogate => Err(Error::new(
434 ErrorKind::Unsupported,
435 "非 BMP 字符的 UTF-16 中间码元是孤立代理,无法用 Rust str 表示",
436 )),
437 },
438 None => Ok(Val::Undefined),
439 },
440 (Val::Str(s), Val::Num(n)) => {
441 if n < 0.0 || n.fract() != 0.0 {
442 return Ok(Val::Undefined);
443 }
444 match utf16_char_at(s, n as usize) {
445 Utf16At::Char(c) => Ok(Val::Str(c)),
446 Utf16At::None => Ok(Val::Undefined),
447 Utf16At::Surrogate => Err(Error::new(
449 ErrorKind::Unsupported,
450 "非 BMP 字符的 UTF-16 中间码元是孤立代理,无法用 Rust str 表示",
451 )),
452 }
453 }
454 (Val::Undefined | Val::Null, _) if optional => Ok(Val::ShortCircuit),
455 (Val::Undefined | Val::Null, _) => Err(runtime("对 null/undefined 取下标")),
456 (Val::Arr(_), _) => Err(type_err("数组下标必须是整数")),
457 (Val::EmptyObj, _) => Ok(Val::Undefined),
458 _ => Ok(Val::Undefined),
459 }
460}
461
462fn canonical_index(s: &str) -> Option<usize> {
465 let b = s.as_bytes();
466 if b.is_empty() || !b[0].is_ascii_digit() {
467 return None;
468 }
469 if b.len() > 1 && b[0] == b'0' {
470 return None;
471 }
472 s.parse::<usize>().ok()
473}
474
475enum Utf16At<'a> {
476 Char(&'a str),
478 Surrogate,
480 None,
482}
483
484fn utf16_char_at(s: &str, idx: usize) -> Utf16At<'_> {
485 let mut pos = 0usize;
486 for (byte, ch) in s.char_indices() {
487 if pos == idx {
488 let end = byte + ch.len_utf8();
489 return match s.get(byte..end) {
490 Some(c) => Utf16At::Char(c),
491 None => Utf16At::None,
492 };
493 }
494 let units = ch.len_utf16();
495 if units == 2 && pos < idx && idx < pos + units {
496 return Utf16At::Surrogate;
497 }
498 pos += units;
499 }
500 Utf16At::None
501}
502
503fn call_method<'a, D: Data<'a>>(
504 base: Val<'a, D>,
505 method: Method,
506 optional: bool,
507 arg: Val<'a, D>,
508) -> Result<Val<'a, D>, Error> {
509 if matches!(base, Val::ShortCircuit) {
510 return Ok(Val::ShortCircuit);
511 }
512 if matches!(base, Val::Undefined | Val::Null) && optional {
513 return Ok(Val::ShortCircuit);
514 }
515 match base {
516 Val::Str(s) => {
517 let Some(needle) = to_js_string(&arg) else {
518 return Err(type_err("字符串方法的参数不能是数组/对象"));
519 };
520 match method {
521 Method::Includes => Ok(Val::Bool(s.contains(needle.as_ref()))),
522 Method::IndexOf => Ok(Val::Num(match s.find(needle.as_ref()) {
523 Some(byte) => semantics::utf16_len(&s[..byte]) as f64,
524 None => -1.0,
525 })),
526 Method::Some => Err(type_err("`.some` 只能用于数组")),
527 }
528 }
529 Val::Arr(d) => match method {
530 Method::Includes => {
531 for i in 0..d.len() {
532 let Some(el) = d.at(i) else { continue };
533 if semantics::same_value_zero(&val_of(el), &arg) {
534 return Ok(Val::Bool(true));
535 }
536 }
537 Ok(Val::Bool(false))
538 }
539 Method::IndexOf => {
540 for i in 0..d.len() {
541 let Some(el) = d.at(i) else { continue };
542 if semantics::strict_eq(&val_of(el), &arg) {
543 return Ok(Val::Num(i as f64));
544 }
545 }
546 Ok(Val::Num(-1.0))
547 }
548 Method::Some => Err(type_err("`.some` 走独立节点")),
549 },
550 Val::Undefined | Val::Null => Err(runtime("对 null/undefined 调用方法")),
551 _ => Err(type_err("基座不是数组或字符串")),
552 }
553}