1use crate::ast::{BinOp, Binding, Expr, Global, Method, Program as Ast};
13use crate::error::{Error, ErrorKind};
14use crate::parser;
15use crate::set::ConstSet;
16
17#[derive(Clone, Debug)]
19pub(crate) enum ConstVal {
20 Undefined,
22 Null,
24 Bool(bool),
26 Num(f64),
28 Str(Box<str>),
30}
31
32#[derive(Clone, Copy, Debug)]
34pub(crate) enum PathBase {
35 Item,
37 Params,
39 Local(u16),
41}
42
43#[derive(Clone, Debug)]
45pub(crate) struct PathSeg {
46 pub name: Box<str>,
48 pub optional: bool,
50}
51
52#[derive(Clone, Copy, Debug)]
54pub(crate) enum ArithOp {
55 Sub,
57 Mul,
59 Div,
61}
62
63#[derive(Clone, Copy, Debug)]
65pub(crate) enum RelOp {
66 Lt,
68 Le,
70 Gt,
72 Ge,
74}
75
76#[derive(Debug)]
78pub(crate) enum Node {
79 Const(ConstVal),
81 Item,
83 Params,
85 Local(u16),
87 Path {
89 base: PathBase,
90 segs: Box<[PathSeg]>,
91 },
92 Member {
94 base: Box<Node>,
95 name: Box<str>,
96 optional: bool,
97 },
98 Length { base: Box<Node>, optional: bool },
100 Index {
102 base: Box<Node>,
103 index: Box<Node>,
104 optional: bool,
105 },
106 Call {
108 base: Box<Node>,
109 method: Method,
110 optional: bool,
111 arg: Box<Node>,
112 },
113 ConstIncludes { set: ConstSet, hay: Box<Node> },
115 Some {
117 base: Box<Node>,
118 slot: u16,
119 body: Box<Node>,
120 optional: bool,
121 },
122 ParseInt(Box<Node>),
124 IsArray(Box<Node>),
126 Group(Box<Node>),
128 Not(Box<Node>),
130 And(Box<Node>, Box<Node>),
132 Or(Box<Node>, Box<Node>),
134 Nullish(Box<Node>, Box<Node>),
136 StrictEq(Box<Node>, Box<Node>),
138 LooseEq(Box<Node>, Box<Node>),
140 DateNew(Option<Box<Node>>),
142 DateNow,
144 GetTime { base: Box<Node>, optional: bool },
146 MathFloor(Box<Node>),
148 Arith {
150 op: ArithOp,
151 lhs: Box<Node>,
152 rhs: Box<Node>,
153 },
154 Rel {
156 op: RelOp,
157 lhs: Box<Node>,
158 rhs: Box<Node>,
159 },
160 Set { slot: u16, value: Box<Node> },
162}
163
164#[derive(Debug)]
166pub struct Program {
167 pub(crate) steps: Box<[Node]>,
168 pub(crate) result: Node,
169 pub(crate) slots: u16,
170}
171
172pub fn compile(src: &str) -> Result<Program, Error> {
174 let ast = parser::parse(src)?;
175 compile_ast(&ast)
176}
177
178fn compile_ast(ast: &Ast) -> Result<Program, Error> {
179 let mut steps = Vec::with_capacity(ast.bindings.len());
180 for Binding { slot, value } in &ast.bindings {
181 let node = build(value)?;
182 steps.push(Node::Set {
183 slot: *slot,
184 value: Box::new(node),
185 });
186 }
187 let result = build(&ast.result)?;
188 Ok(Program {
189 steps: steps.into_boxed_slice(),
190 result,
191 slots: ast.slots,
192 })
193}
194
195fn build(e: &Expr) -> Result<Node, Error> {
196 Ok(match e {
197 Expr::Undefined => Node::Const(ConstVal::Undefined),
198 Expr::Null => Node::Const(ConstVal::Null),
199 Expr::Bool(b) => Node::Const(ConstVal::Bool(*b)),
200 Expr::Num(n) => Node::Const(ConstVal::Num(*n)),
201 Expr::Str(s) => Node::Const(ConstVal::Str(s.as_str().into())),
202 Expr::Item => Node::Item,
203 Expr::Params => Node::Params,
204 Expr::Local(i) => Node::Local(*i),
205 Expr::Array(items) => {
206 if items.is_empty() {
208 return Err(unsupported("空数组字面量只能用于 `.includes`"));
209 }
210 return Err(unsupported("数组字面量只能作为 `.includes` 的接收者"));
211 }
212 Expr::Member {
213 base,
214 name,
215 optional,
216 } => {
217 if &**name == "length" {
218 Node::Length {
219 base: Box::new(build(base)?),
220 optional: *optional,
221 }
222 } else {
223 match path_of(e) {
224 Some((root, segs)) => Node::Path {
225 base: root,
226 segs: segs.into_boxed_slice(),
227 },
228 None => Node::Member {
229 base: Box::new(build(base)?),
230 name: name.clone(),
231 optional: *optional,
232 },
233 }
234 }
235 }
236 Expr::Index {
237 base,
238 index,
239 optional,
240 } => Node::Index {
241 base: Box::new(build(base)?),
242 index: Box::new(build(index)?),
243 optional: *optional,
244 },
245 Expr::Call {
246 base,
247 method,
248 optional,
249 args,
250 } => {
251 if matches!(method, Method::GetTime) {
256 if !args.is_empty() {
257 return Err(unsupported("`.getTime()` 不接受参数"));
258 }
259 return Ok(Node::GetTime {
260 base: Box::new(build(base)?),
261 optional: *optional,
262 });
263 }
264 let arg = args.first().ok_or_else(|| unsupported("方法缺少参数"))?;
265 if matches!(method, Method::Includes) {
267 if let Expr::Array(items) = &**base {
268 return Ok(Node::ConstIncludes {
269 set: const_set(items)?,
270 hay: Box::new(build(arg)?),
271 });
272 }
273 }
274 match method {
275 Method::Some => {
276 let Expr::Arrow { slot, body } = arg else {
277 return Err(unsupported("`.some` 只支持 `x => expr`"));
278 };
279 Node::Some {
280 base: Box::new(build(base)?),
281 slot: *slot,
282 body: Box::new(build(body)?),
283 optional: *optional,
284 }
285 }
286 Method::GetTime => return Err(unsupported("`.getTime()` 不接受参数")),
288 Method::Includes | Method::IndexOf | Method::StartsWith | Method::EndsWith => {
289 Node::Call {
290 base: Box::new(build(base)?),
291 method: *method,
292 optional: *optional,
293 arg: Box::new(build(arg)?),
294 }
295 }
296 }
297 }
298 Expr::GlobalCall { global, args } => {
299 let arg = args.first().ok_or_else(|| unsupported("调用缺少参数"))?;
300 let inner = build(arg)?;
301 match global {
302 Global::ParseInt => Node::ParseInt(Box::new(inner)),
303 Global::IsArray => Node::IsArray(Box::new(inner)),
304 }
305 }
306 Expr::Group(inner) => Node::Group(Box::new(build(inner)?)),
307 Expr::Not(inner) => {
308 let node = build(inner)?;
309 match node {
310 Node::Const(c) => Node::Const(ConstVal::Bool(!const_truthy(&c))),
311 other => Node::Not(Box::new(other)),
312 }
313 }
314 Expr::Binary { op, lhs, rhs } => {
315 if matches!(op, BinOp::Eq3 | BinOp::Ne3) && (is_date_expr(lhs) || is_date_expr(rhs)) {
319 return Err(unsupported(
320 "Date 之间的 `===`/`!==` 在 JS 里是引用比较(恒 false),请改用 `>=`/`<` 或 `.getTime()`",
321 ));
322 }
323 let l = build(lhs)?;
324 if let Node::Const(c) = &l {
327 let short = match op {
328 BinOp::And => !const_truthy(c),
329 BinOp::Or => const_truthy(c),
330 BinOp::Nullish => !const_nullish(c),
333 _ => false,
334 };
335 if short {
336 return Ok(Node::Const(c.clone()));
337 }
338 }
339 let r = build(rhs)?;
340 match op {
341 BinOp::Sub | BinOp::Mul | BinOp::Div => Node::Arith {
342 op: match op {
343 BinOp::Sub => ArithOp::Sub,
344 BinOp::Mul => ArithOp::Mul,
345 _ => ArithOp::Div,
346 },
347 lhs: Box::new(l),
348 rhs: Box::new(r),
349 },
350 BinOp::And => match (&l, &r) {
351 (Node::Const(c), _) if !const_truthy(c) => Node::Const(c.clone()),
352 (Node::Const(_), _) => r,
353 _ => Node::And(Box::new(l), Box::new(r)),
354 },
355 BinOp::Or => match (&l, &r) {
356 (Node::Const(c), _) if const_truthy(c) => Node::Const(c.clone()),
357 (Node::Const(_), _) => r,
358 _ => Node::Or(Box::new(l), Box::new(r)),
359 },
360 BinOp::Nullish => match (&l, &r) {
361 (Node::Const(c), _) if const_nullish(c) => r,
362 (Node::Const(c), _) => Node::Const(c.clone()),
363 _ => Node::Nullish(Box::new(l), Box::new(r)),
364 },
365 BinOp::Eq3 => match (&l, &r) {
366 (Node::Const(a), Node::Const(b)) => {
367 Node::Const(ConstVal::Bool(const_strict_eq(a, b)))
368 }
369 _ => Node::StrictEq(Box::new(l), Box::new(r)),
370 },
371 BinOp::Ne3 => match (&l, &r) {
372 (Node::Const(a), Node::Const(b)) => {
373 Node::Const(ConstVal::Bool(!const_strict_eq(a, b)))
374 }
375 _ => Node::Not(Box::new(Node::StrictEq(Box::new(l), Box::new(r)))),
376 },
377 BinOp::Eq2 => Node::LooseEq(Box::new(l), Box::new(r)),
378 BinOp::Ne2 => Node::Not(Box::new(Node::LooseEq(Box::new(l), Box::new(r)))),
379 BinOp::Lt => Node::Rel {
380 op: RelOp::Lt,
381 lhs: Box::new(l),
382 rhs: Box::new(r),
383 },
384 BinOp::Le => Node::Rel {
385 op: RelOp::Le,
386 lhs: Box::new(l),
387 rhs: Box::new(r),
388 },
389 BinOp::Gt => Node::Rel {
390 op: RelOp::Gt,
391 lhs: Box::new(l),
392 rhs: Box::new(r),
393 },
394 BinOp::Ge => Node::Rel {
395 op: RelOp::Ge,
396 lhs: Box::new(l),
397 rhs: Box::new(r),
398 },
399 }
400 }
401 Expr::Template(parts) => {
402 let mut out = String::new();
403 for p in parts {
404 let mut node = build(p)?;
407 while let Node::Group(inner) = node {
408 node = *inner;
409 }
410 match node {
411 Node::Const(ConstVal::Str(s)) => out.push_str(&s),
412 Node::Const(ConstVal::Num(n)) => {
413 out.push_str(&format_num(n));
414 }
415 Node::Const(ConstVal::Bool(b)) => {
416 out.push_str(if b { "true" } else { "false" })
417 }
418 Node::Const(ConstVal::Null) => out.push_str("null"),
419 Node::Const(ConstVal::Undefined) => out.push_str("undefined"),
420 _ => {
421 return Err(unsupported(
422 "模板字面量目前只支持常量片段,运行期拼接不在契约内",
423 ));
424 }
425 }
426 }
427 Node::Const(ConstVal::Str(out.into()))
428 }
429 Expr::DateNew(arg) => Node::DateNew(match arg {
430 Some(a) => Some(Box::new(build(a)?)),
431 None => None,
432 }),
433 Expr::DateNow => Node::DateNow,
434 Expr::MathFloor(inner) => Node::MathFloor(Box::new(build(inner)?)),
435 Expr::Arrow { .. } => return Err(unsupported("回调只能出现在 `.some` 里")),
436 })
437}
438
439fn path_of(e: &Expr) -> Option<(PathBase, Vec<PathSeg>)> {
441 fn walk(e: &Expr, segs: &mut Vec<PathSeg>) -> Option<PathBase> {
442 match e {
443 Expr::Member {
444 base,
445 name,
446 optional,
447 } => {
448 if &**name == "length" {
449 return None;
450 }
451 let root = walk(base, segs)?;
452 segs.push(PathSeg {
453 name: name.clone(),
454 optional: *optional,
455 });
456 Some(root)
457 }
458 Expr::Item => Some(PathBase::Item),
459 Expr::Params => Some(PathBase::Params),
460 Expr::Local(i) => Some(PathBase::Local(*i)),
461 _ => None,
462 }
463 }
464 let mut segs = Vec::new();
465 let root = walk(e, &mut segs)?;
466 if segs.is_empty() {
467 return None;
468 }
469 Some((root, segs))
470}
471
472fn is_date_expr(e: &Expr) -> bool {
477 match e {
478 Expr::DateNew(_) => true,
479 Expr::Group(inner) => is_date_expr(inner),
480 _ => false,
481 }
482}
483
484fn unsupported(msg: &str) -> Error {
485 Error::new(ErrorKind::Unsupported, msg.to_string())
486}
487
488fn const_truthy(c: &ConstVal) -> bool {
489 match c {
490 ConstVal::Undefined | ConstVal::Null => false,
491 ConstVal::Bool(b) => *b,
492 ConstVal::Num(n) => *n != 0.0 && !n.is_nan(),
493 ConstVal::Str(s) => !s.is_empty(),
494 }
495}
496
497fn const_nullish(c: &ConstVal) -> bool {
498 matches!(c, ConstVal::Undefined | ConstVal::Null)
499}
500
501fn const_strict_eq(a: &ConstVal, b: &ConstVal) -> bool {
502 match (a, b) {
503 (ConstVal::Undefined, ConstVal::Undefined) => true,
504 (ConstVal::Null, ConstVal::Null) => true,
505 (ConstVal::Bool(x), ConstVal::Bool(y)) => x == y,
506 (ConstVal::Num(x), ConstVal::Num(y)) => x == y,
507 (ConstVal::Str(x), ConstVal::Str(y)) => x == y,
508 _ => false,
509 }
510}
511
512pub(crate) fn format_num(n: f64) -> String {
525 if n.is_nan() {
526 return "NaN".to_string();
527 }
528 if n.is_infinite() {
529 return if n > 0.0 {
530 "Infinity".into()
531 } else {
532 "-Infinity".into()
533 };
534 }
535 if n == 0.0 {
536 return "0".to_string();
537 }
538 let sci = format!("{n:e}");
539 let (mant, exp) = sci.split_once('e').unwrap_or((&sci, "0"));
540 let exp: i32 = exp.parse().unwrap_or(0);
541 if !(-6..=20).contains(&exp) {
542 let sign = if exp >= 0 { '+' } else { '-' };
543 return format!("{mant}e{sign}{}", exp.abs());
544 }
545 plain_from_scientific(mant, exp)
546}
547
548fn plain_from_scientific(mant: &str, exp: i32) -> String {
550 let (sign, rest) = match mant.strip_prefix('-') {
551 Some(r) => ("-", r),
552 None => ("", mant),
553 };
554 let digits: String = rest.chars().filter(|c| *c != '.').collect();
555 let int_len = i64::from(exp) + 1;
556 let body = if int_len <= 0 {
557 format!("0.{}{digits}", "0".repeat((-int_len) as usize))
558 } else if int_len as usize >= digits.len() {
559 format!("{digits}{}", "0".repeat(int_len as usize - digits.len()))
560 } else {
561 let (head, tail) = digits.split_at(int_len as usize);
562 format!("{head}.{tail}")
563 };
564 format!("{sign}{body}")
565}
566
567fn const_set(items: &[Expr]) -> Result<ConstSet, Error> {
569 if items.is_empty() {
571 return Ok(ConstSet::from_strs(Vec::new()));
572 }
573 if items.iter().all(|it| matches!(it, Expr::Str(_))) {
574 let mut strs = Vec::with_capacity(items.len());
575 for it in items {
576 if let Expr::Str(v) = it {
577 strs.push(v.as_str().into());
578 }
579 }
580 return Ok(ConstSet::from_strs(strs));
581 }
582 if items.iter().all(|it| matches!(it, Expr::Num(_))) {
583 let mut ints = Vec::with_capacity(items.len());
584 let mut nums = Vec::with_capacity(items.len());
585 for it in items {
586 let Expr::Num(n) = it else { continue };
587 if n.fract() == 0.0 && n.abs() < 2f64.powi(63) {
590 ints.push(*n as i64);
591 }
592 nums.push(*n);
593 }
594 if ints.len() == items.len() {
595 return Ok(ConstSet::from_ints(ints));
596 }
597 return Ok(ConstSet::from_nums(nums));
598 }
599 Err(unsupported("字面量数组元素必须同类型(全字符串或全数字)"))
600}
601
602#[cfg(test)]
603mod tests {
604 use super::format_num;
605
606 #[test]
607 fn js_number_to_string_table() {
608 let cases = [
610 (0.0, "0"),
611 (-0.0, "0"),
612 (1.0, "1"),
613 (1.5, "1.5"),
614 (-2.25, "-2.25"),
615 (1e21, "1e+21"),
616 (1.000001e21, "1.000001e+21"),
617 (1e20, "100000000000000000000"),
618 (123456789012345680000.0, "123456789012345680000"),
619 (1e-7, "1e-7"),
620 (1.5e-7, "1.5e-7"),
621 (1e-6, "0.000001"),
622 (0.000001234, "0.000001234"),
623 (9007199254740992.0, "9007199254740992"),
624 (1e19, "10000000000000000000"),
625 (9223372036854775808.0, "9223372036854776000"),
626 (1e300, "1e+300"),
627 (1e-300, "1e-300"),
628 (0.1 + 0.2, "0.30000000000000004"),
629 ];
630 for (n, want) in cases {
631 assert_eq!(format_num(n), want, "String({n})");
632 }
633 assert_eq!(format_num(f64::NAN), "NaN");
634 assert_eq!(format_num(f64::INFINITY), "Infinity");
635 assert_eq!(format_num(f64::NEG_INFINITY), "-Infinity");
636 }
637}