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 RelOp {
55 Lt,
57 Le,
59 Gt,
61 Ge,
63}
64
65#[derive(Debug)]
67pub(crate) enum Node {
68 Const(ConstVal),
70 Item,
72 Params,
74 Local(u16),
76 Path {
78 base: PathBase,
79 segs: Box<[PathSeg]>,
80 },
81 Member {
83 base: Box<Node>,
84 name: Box<str>,
85 optional: bool,
86 },
87 Length { base: Box<Node>, optional: bool },
89 Index {
91 base: Box<Node>,
92 index: Box<Node>,
93 optional: bool,
94 },
95 Call {
97 base: Box<Node>,
98 method: Method,
99 optional: bool,
100 arg: Box<Node>,
101 },
102 ConstIncludes { set: ConstSet, hay: Box<Node> },
104 Some {
106 base: Box<Node>,
107 slot: u16,
108 body: Box<Node>,
109 optional: bool,
110 },
111 ParseInt(Box<Node>),
113 IsArray(Box<Node>),
115 Group(Box<Node>),
117 Not(Box<Node>),
119 And(Box<Node>, Box<Node>),
121 Or(Box<Node>, Box<Node>),
123 Nullish(Box<Node>, Box<Node>),
125 StrictEq(Box<Node>, Box<Node>),
127 LooseEq(Box<Node>, Box<Node>),
129 Rel {
131 op: RelOp,
132 lhs: Box<Node>,
133 rhs: Box<Node>,
134 },
135 Set { slot: u16, value: Box<Node> },
137}
138
139#[derive(Debug)]
141pub struct Program {
142 pub(crate) steps: Box<[Node]>,
143 pub(crate) result: Node,
144 pub(crate) slots: u16,
145}
146
147pub fn compile(src: &str) -> Result<Program, Error> {
149 let ast = parser::parse(src)?;
150 compile_ast(&ast)
151}
152
153fn compile_ast(ast: &Ast) -> Result<Program, Error> {
154 let mut steps = Vec::with_capacity(ast.bindings.len());
155 for Binding { slot, value } in &ast.bindings {
156 let node = build(value)?;
157 steps.push(Node::Set {
158 slot: *slot,
159 value: Box::new(node),
160 });
161 }
162 let result = build(&ast.result)?;
163 Ok(Program {
164 steps: steps.into_boxed_slice(),
165 result,
166 slots: ast.slots,
167 })
168}
169
170fn build(e: &Expr) -> Result<Node, Error> {
171 Ok(match e {
172 Expr::Undefined => Node::Const(ConstVal::Undefined),
173 Expr::Null => Node::Const(ConstVal::Null),
174 Expr::Bool(b) => Node::Const(ConstVal::Bool(*b)),
175 Expr::Num(n) => Node::Const(ConstVal::Num(*n)),
176 Expr::Str(s) => Node::Const(ConstVal::Str(s.as_str().into())),
177 Expr::Item => Node::Item,
178 Expr::Params => Node::Params,
179 Expr::Local(i) => Node::Local(*i),
180 Expr::Array(items) => {
181 if items.is_empty() {
183 return Err(unsupported("空数组字面量只能用于 `.includes`"));
184 }
185 return Err(unsupported("数组字面量只能作为 `.includes` 的接收者"));
186 }
187 Expr::Member {
188 base,
189 name,
190 optional,
191 } => {
192 if &**name == "length" {
193 Node::Length {
194 base: Box::new(build(base)?),
195 optional: *optional,
196 }
197 } else {
198 match path_of(e) {
199 Some((root, segs)) => Node::Path {
200 base: root,
201 segs: segs.into_boxed_slice(),
202 },
203 None => Node::Member {
204 base: Box::new(build(base)?),
205 name: name.clone(),
206 optional: *optional,
207 },
208 }
209 }
210 }
211 Expr::Index {
212 base,
213 index,
214 optional,
215 } => Node::Index {
216 base: Box::new(build(base)?),
217 index: Box::new(build(index)?),
218 optional: *optional,
219 },
220 Expr::Call {
221 base,
222 method,
223 optional,
224 args,
225 } => {
226 let arg = args.first().ok_or_else(|| unsupported("方法缺少参数"))?;
227 if matches!(method, Method::Includes) {
229 if let Expr::Array(items) = &**base {
230 return Ok(Node::ConstIncludes {
231 set: const_set(items)?,
232 hay: Box::new(build(arg)?),
233 });
234 }
235 }
236 match method {
237 Method::Some => {
238 let Expr::Arrow { slot, body } = arg else {
239 return Err(unsupported("`.some` 只支持 `x => expr`"));
240 };
241 Node::Some {
242 base: Box::new(build(base)?),
243 slot: *slot,
244 body: Box::new(build(body)?),
245 optional: *optional,
246 }
247 }
248 Method::Includes | Method::IndexOf | Method::StartsWith | Method::EndsWith => {
249 Node::Call {
250 base: Box::new(build(base)?),
251 method: *method,
252 optional: *optional,
253 arg: Box::new(build(arg)?),
254 }
255 }
256 }
257 }
258 Expr::GlobalCall { global, args } => {
259 let arg = args.first().ok_or_else(|| unsupported("调用缺少参数"))?;
260 let inner = build(arg)?;
261 match global {
262 Global::ParseInt => Node::ParseInt(Box::new(inner)),
263 Global::IsArray => Node::IsArray(Box::new(inner)),
264 }
265 }
266 Expr::Group(inner) => Node::Group(Box::new(build(inner)?)),
267 Expr::Not(inner) => {
268 let node = build(inner)?;
269 match node {
270 Node::Const(c) => Node::Const(ConstVal::Bool(!const_truthy(&c))),
271 other => Node::Not(Box::new(other)),
272 }
273 }
274 Expr::Binary { op, lhs, rhs } => {
275 let l = build(lhs)?;
276 if let Node::Const(c) = &l {
279 let short = match op {
280 BinOp::And => !const_truthy(c),
281 BinOp::Or => const_truthy(c),
282 BinOp::Nullish => !const_nullish(c),
285 _ => false,
286 };
287 if short {
288 return Ok(Node::Const(c.clone()));
289 }
290 }
291 let r = build(rhs)?;
292 match op {
293 BinOp::And => match (&l, &r) {
294 (Node::Const(c), _) if !const_truthy(c) => Node::Const(c.clone()),
295 (Node::Const(_), _) => r,
296 _ => Node::And(Box::new(l), Box::new(r)),
297 },
298 BinOp::Or => match (&l, &r) {
299 (Node::Const(c), _) if const_truthy(c) => Node::Const(c.clone()),
300 (Node::Const(_), _) => r,
301 _ => Node::Or(Box::new(l), Box::new(r)),
302 },
303 BinOp::Nullish => match (&l, &r) {
304 (Node::Const(c), _) if const_nullish(c) => r,
305 (Node::Const(c), _) => Node::Const(c.clone()),
306 _ => Node::Nullish(Box::new(l), Box::new(r)),
307 },
308 BinOp::Eq3 => match (&l, &r) {
309 (Node::Const(a), Node::Const(b)) => {
310 Node::Const(ConstVal::Bool(const_strict_eq(a, b)))
311 }
312 _ => Node::StrictEq(Box::new(l), Box::new(r)),
313 },
314 BinOp::Ne3 => match (&l, &r) {
315 (Node::Const(a), Node::Const(b)) => {
316 Node::Const(ConstVal::Bool(!const_strict_eq(a, b)))
317 }
318 _ => Node::Not(Box::new(Node::StrictEq(Box::new(l), Box::new(r)))),
319 },
320 BinOp::Eq2 => Node::LooseEq(Box::new(l), Box::new(r)),
321 BinOp::Ne2 => Node::Not(Box::new(Node::LooseEq(Box::new(l), Box::new(r)))),
322 BinOp::Lt => Node::Rel {
323 op: RelOp::Lt,
324 lhs: Box::new(l),
325 rhs: Box::new(r),
326 },
327 BinOp::Le => Node::Rel {
328 op: RelOp::Le,
329 lhs: Box::new(l),
330 rhs: Box::new(r),
331 },
332 BinOp::Gt => Node::Rel {
333 op: RelOp::Gt,
334 lhs: Box::new(l),
335 rhs: Box::new(r),
336 },
337 BinOp::Ge => Node::Rel {
338 op: RelOp::Ge,
339 lhs: Box::new(l),
340 rhs: Box::new(r),
341 },
342 }
343 }
344 Expr::Template(parts) => {
345 let mut out = String::new();
346 for p in parts {
347 let mut node = build(p)?;
350 while let Node::Group(inner) = node {
351 node = *inner;
352 }
353 match node {
354 Node::Const(ConstVal::Str(s)) => out.push_str(&s),
355 Node::Const(ConstVal::Num(n)) => {
356 out.push_str(&format_num(n));
357 }
358 Node::Const(ConstVal::Bool(b)) => {
359 out.push_str(if b { "true" } else { "false" })
360 }
361 Node::Const(ConstVal::Null) => out.push_str("null"),
362 Node::Const(ConstVal::Undefined) => out.push_str("undefined"),
363 _ => {
364 return Err(unsupported(
365 "模板字面量目前只支持常量片段,运行期拼接不在契约内",
366 ));
367 }
368 }
369 }
370 Node::Const(ConstVal::Str(out.into()))
371 }
372 Expr::Arrow { .. } => return Err(unsupported("回调只能出现在 `.some` 里")),
373 })
374}
375
376fn path_of(e: &Expr) -> Option<(PathBase, Vec<PathSeg>)> {
378 fn walk(e: &Expr, segs: &mut Vec<PathSeg>) -> Option<PathBase> {
379 match e {
380 Expr::Member {
381 base,
382 name,
383 optional,
384 } => {
385 if &**name == "length" {
386 return None;
387 }
388 let root = walk(base, segs)?;
389 segs.push(PathSeg {
390 name: name.clone(),
391 optional: *optional,
392 });
393 Some(root)
394 }
395 Expr::Item => Some(PathBase::Item),
396 Expr::Params => Some(PathBase::Params),
397 Expr::Local(i) => Some(PathBase::Local(*i)),
398 _ => None,
399 }
400 }
401 let mut segs = Vec::new();
402 let root = walk(e, &mut segs)?;
403 if segs.is_empty() {
404 return None;
405 }
406 Some((root, segs))
407}
408
409fn unsupported(msg: &str) -> Error {
410 Error::new(ErrorKind::Unsupported, msg.to_string())
411}
412
413fn const_truthy(c: &ConstVal) -> bool {
414 match c {
415 ConstVal::Undefined | ConstVal::Null => false,
416 ConstVal::Bool(b) => *b,
417 ConstVal::Num(n) => *n != 0.0 && !n.is_nan(),
418 ConstVal::Str(s) => !s.is_empty(),
419 }
420}
421
422fn const_nullish(c: &ConstVal) -> bool {
423 matches!(c, ConstVal::Undefined | ConstVal::Null)
424}
425
426fn const_strict_eq(a: &ConstVal, b: &ConstVal) -> bool {
427 match (a, b) {
428 (ConstVal::Undefined, ConstVal::Undefined) => true,
429 (ConstVal::Null, ConstVal::Null) => true,
430 (ConstVal::Bool(x), ConstVal::Bool(y)) => x == y,
431 (ConstVal::Num(x), ConstVal::Num(y)) => x == y,
432 (ConstVal::Str(x), ConstVal::Str(y)) => x == y,
433 _ => false,
434 }
435}
436
437pub(crate) fn format_num(n: f64) -> String {
450 if n.is_nan() {
451 return "NaN".to_string();
452 }
453 if n.is_infinite() {
454 return if n > 0.0 {
455 "Infinity".into()
456 } else {
457 "-Infinity".into()
458 };
459 }
460 if n == 0.0 {
461 return "0".to_string();
462 }
463 let sci = format!("{n:e}");
464 let (mant, exp) = sci.split_once('e').unwrap_or((&sci, "0"));
465 let exp: i32 = exp.parse().unwrap_or(0);
466 if !(-6..=20).contains(&exp) {
467 let sign = if exp >= 0 { '+' } else { '-' };
468 return format!("{mant}e{sign}{}", exp.abs());
469 }
470 plain_from_scientific(mant, exp)
471}
472
473fn plain_from_scientific(mant: &str, exp: i32) -> String {
475 let (sign, rest) = match mant.strip_prefix('-') {
476 Some(r) => ("-", r),
477 None => ("", mant),
478 };
479 let digits: String = rest.chars().filter(|c| *c != '.').collect();
480 let int_len = i64::from(exp) + 1;
481 let body = if int_len <= 0 {
482 format!("0.{}{digits}", "0".repeat((-int_len) as usize))
483 } else if int_len as usize >= digits.len() {
484 format!("{digits}{}", "0".repeat(int_len as usize - digits.len()))
485 } else {
486 let (head, tail) = digits.split_at(int_len as usize);
487 format!("{head}.{tail}")
488 };
489 format!("{sign}{body}")
490}
491
492fn const_set(items: &[Expr]) -> Result<ConstSet, Error> {
494 if items.is_empty() {
496 return Ok(ConstSet::from_strs(Vec::new()));
497 }
498 if items.iter().all(|it| matches!(it, Expr::Str(_))) {
499 let mut strs = Vec::with_capacity(items.len());
500 for it in items {
501 if let Expr::Str(v) = it {
502 strs.push(v.as_str().into());
503 }
504 }
505 return Ok(ConstSet::from_strs(strs));
506 }
507 if items.iter().all(|it| matches!(it, Expr::Num(_))) {
508 let mut ints = Vec::with_capacity(items.len());
509 let mut nums = Vec::with_capacity(items.len());
510 for it in items {
511 let Expr::Num(n) = it else { continue };
512 if n.fract() == 0.0 && n.abs() < 2f64.powi(63) {
515 ints.push(*n as i64);
516 }
517 nums.push(*n);
518 }
519 if ints.len() == items.len() {
520 return Ok(ConstSet::from_ints(ints));
521 }
522 return Ok(ConstSet::from_nums(nums));
523 }
524 Err(unsupported("字面量数组元素必须同类型(全字符串或全数字)"))
525}
526
527#[cfg(test)]
528mod tests {
529 use super::format_num;
530
531 #[test]
532 fn js_number_to_string_table() {
533 let cases = [
535 (0.0, "0"),
536 (-0.0, "0"),
537 (1.0, "1"),
538 (1.5, "1.5"),
539 (-2.25, "-2.25"),
540 (1e21, "1e+21"),
541 (1.000001e21, "1.000001e+21"),
542 (1e20, "100000000000000000000"),
543 (123456789012345680000.0, "123456789012345680000"),
544 (1e-7, "1e-7"),
545 (1.5e-7, "1.5e-7"),
546 (1e-6, "0.000001"),
547 (0.000001234, "0.000001234"),
548 (9007199254740992.0, "9007199254740992"),
549 (1e19, "10000000000000000000"),
550 (9223372036854775808.0, "9223372036854776000"),
551 (1e300, "1e+300"),
552 (1e-300, "1e-300"),
553 (0.1 + 0.2, "0.30000000000000004"),
554 ];
555 for (n, want) in cases {
556 assert_eq!(format_num(n), want, "String({n})");
557 }
558 assert_eq!(format_num(f64::NAN), "NaN");
559 assert_eq!(format_num(f64::INFINITY), "Infinity");
560 assert_eq!(format_num(f64::NEG_INFINITY), "-Infinity");
561 }
562}