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(Box<Node>),
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) {
254 if !args.is_empty() {
255 return Err(unsupported("`.getTime()` 不接受参数"));
256 }
257 if !matches!(&**base, Expr::DateNew(_) | Expr::DateNow) {
258 return Err(unsupported(
259 "`.getTime()` 只允许作用于 `new Date(...)` / `Date.now()`",
260 ));
261 }
262 return Ok(Node::GetTime(Box::new(build(base)?)));
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 {
474 match e {
475 Expr::DateNew(_) | Expr::DateNow => true,
476 Expr::Group(inner) => is_date_expr(inner),
477 _ => false,
478 }
479}
480
481fn unsupported(msg: &str) -> Error {
482 Error::new(ErrorKind::Unsupported, msg.to_string())
483}
484
485fn const_truthy(c: &ConstVal) -> bool {
486 match c {
487 ConstVal::Undefined | ConstVal::Null => false,
488 ConstVal::Bool(b) => *b,
489 ConstVal::Num(n) => *n != 0.0 && !n.is_nan(),
490 ConstVal::Str(s) => !s.is_empty(),
491 }
492}
493
494fn const_nullish(c: &ConstVal) -> bool {
495 matches!(c, ConstVal::Undefined | ConstVal::Null)
496}
497
498fn const_strict_eq(a: &ConstVal, b: &ConstVal) -> bool {
499 match (a, b) {
500 (ConstVal::Undefined, ConstVal::Undefined) => true,
501 (ConstVal::Null, ConstVal::Null) => true,
502 (ConstVal::Bool(x), ConstVal::Bool(y)) => x == y,
503 (ConstVal::Num(x), ConstVal::Num(y)) => x == y,
504 (ConstVal::Str(x), ConstVal::Str(y)) => x == y,
505 _ => false,
506 }
507}
508
509pub(crate) fn format_num(n: f64) -> String {
522 if n.is_nan() {
523 return "NaN".to_string();
524 }
525 if n.is_infinite() {
526 return if n > 0.0 {
527 "Infinity".into()
528 } else {
529 "-Infinity".into()
530 };
531 }
532 if n == 0.0 {
533 return "0".to_string();
534 }
535 let sci = format!("{n:e}");
536 let (mant, exp) = sci.split_once('e').unwrap_or((&sci, "0"));
537 let exp: i32 = exp.parse().unwrap_or(0);
538 if !(-6..=20).contains(&exp) {
539 let sign = if exp >= 0 { '+' } else { '-' };
540 return format!("{mant}e{sign}{}", exp.abs());
541 }
542 plain_from_scientific(mant, exp)
543}
544
545fn plain_from_scientific(mant: &str, exp: i32) -> String {
547 let (sign, rest) = match mant.strip_prefix('-') {
548 Some(r) => ("-", r),
549 None => ("", mant),
550 };
551 let digits: String = rest.chars().filter(|c| *c != '.').collect();
552 let int_len = i64::from(exp) + 1;
553 let body = if int_len <= 0 {
554 format!("0.{}{digits}", "0".repeat((-int_len) as usize))
555 } else if int_len as usize >= digits.len() {
556 format!("{digits}{}", "0".repeat(int_len as usize - digits.len()))
557 } else {
558 let (head, tail) = digits.split_at(int_len as usize);
559 format!("{head}.{tail}")
560 };
561 format!("{sign}{body}")
562}
563
564fn const_set(items: &[Expr]) -> Result<ConstSet, Error> {
566 if items.is_empty() {
568 return Ok(ConstSet::from_strs(Vec::new()));
569 }
570 if items.iter().all(|it| matches!(it, Expr::Str(_))) {
571 let mut strs = Vec::with_capacity(items.len());
572 for it in items {
573 if let Expr::Str(v) = it {
574 strs.push(v.as_str().into());
575 }
576 }
577 return Ok(ConstSet::from_strs(strs));
578 }
579 if items.iter().all(|it| matches!(it, Expr::Num(_))) {
580 let mut ints = Vec::with_capacity(items.len());
581 let mut nums = Vec::with_capacity(items.len());
582 for it in items {
583 let Expr::Num(n) = it else { continue };
584 if n.fract() == 0.0 && n.abs() < 2f64.powi(63) {
587 ints.push(*n as i64);
588 }
589 nums.push(*n);
590 }
591 if ints.len() == items.len() {
592 return Ok(ConstSet::from_ints(ints));
593 }
594 return Ok(ConstSet::from_nums(nums));
595 }
596 Err(unsupported("字面量数组元素必须同类型(全字符串或全数字)"))
597}
598
599#[cfg(test)]
600mod tests {
601 use super::format_num;
602
603 #[test]
604 fn js_number_to_string_table() {
605 let cases = [
607 (0.0, "0"),
608 (-0.0, "0"),
609 (1.0, "1"),
610 (1.5, "1.5"),
611 (-2.25, "-2.25"),
612 (1e21, "1e+21"),
613 (1.000001e21, "1.000001e+21"),
614 (1e20, "100000000000000000000"),
615 (123456789012345680000.0, "123456789012345680000"),
616 (1e-7, "1e-7"),
617 (1.5e-7, "1.5e-7"),
618 (1e-6, "0.000001"),
619 (0.000001234, "0.000001234"),
620 (9007199254740992.0, "9007199254740992"),
621 (1e19, "10000000000000000000"),
622 (9223372036854775808.0, "9223372036854776000"),
623 (1e300, "1e+300"),
624 (1e-300, "1e-300"),
625 (0.1 + 0.2, "0.30000000000000004"),
626 ];
627 for (n, want) in cases {
628 assert_eq!(format_num(n), want, "String({n})");
629 }
630 assert_eq!(format_num(f64::NAN), "NaN");
631 assert_eq!(format_num(f64::INFINITY), "Infinity");
632 assert_eq!(format_num(f64::NEG_INFINITY), "-Infinity");
633 }
634}