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