Skip to main content

js2rust_predicate/
compile.rs

1//! 编译:语法树 → 节点树。
2//!
3//! 编译期做的事:
4//!
5//! 1. **路径预绑定**:`item.profile.code` 折成 `[item, "profile", "code"]`,求值不再切字符串;
6//! 2. **字面量数组特化**:`["a","b"].includes(x)` → 编译期排序常量表(≤31 元素二分、≥32 哈希);
7//! 3. **常量折叠**:`!true`、`true && x` 之类直接折掉;
8//! 4. **模板字面量**:仅当全部片段为常量时折叠为常量字符串;运行期片段按契约返回 `Unsupported`。
9//!
10//! 编译失败的表达式不会进 `Program`,因此求值路径可以假设结构合法。
11
12use crate::ast::{BinOp, Binding, Expr, Global, Method, Program as Ast};
13use crate::error::{Error, ErrorKind};
14use crate::parser;
15use crate::set::ConstSet;
16
17/// 编译期常量。
18#[derive(Clone, Debug)]
19pub(crate) enum ConstVal {
20    /// `undefined`
21    Undefined,
22    /// `null`
23    Null,
24    /// 布尔
25    Bool(bool),
26    /// 数字
27    Num(f64),
28    /// 字符串
29    Str(Box<str>),
30}
31
32/// 路径根。
33#[derive(Clone, Copy, Debug)]
34pub(crate) enum PathBase {
35    /// `item`
36    Item,
37    /// `params`
38    Params,
39    /// 槽位
40    Local(u16),
41}
42
43/// 路径上的一段。
44#[derive(Clone, Debug)]
45pub(crate) struct PathSeg {
46    /// 属性名
47    pub name: Box<str>,
48    /// 该段是否为 `?.`
49    pub optional: bool,
50}
51
52/// 算术运算符。
53#[derive(Clone, Copy, Debug)]
54pub(crate) enum ArithOp {
55    /// `-`
56    Sub,
57    /// `*`
58    Mul,
59    /// `/`
60    Div,
61}
62
63/// 关系运算符。
64#[derive(Clone, Copy, Debug)]
65pub(crate) enum RelOp {
66    /// `<`
67    Lt,
68    /// `<=`
69    Le,
70    /// `>`
71    Gt,
72    /// `>=`
73    Ge,
74}
75
76/// 节点树。求值只走这棵树,零分配。
77#[derive(Debug)]
78pub(crate) enum Node {
79    /// 常量
80    Const(ConstVal),
81    /// `item`
82    Item,
83    /// `params`
84    Params,
85    /// 槽位
86    Local(u16),
87    /// 预绑定路径
88    Path {
89        base: PathBase,
90        segs: Box<[PathSeg]>,
91    },
92    /// 动态基座上的成员访问
93    Member {
94        base: Box<Node>,
95        name: Box<str>,
96        optional: bool,
97    },
98    /// `.length`
99    Length { base: Box<Node>, optional: bool },
100    /// 下标访问
101    Index {
102        base: Box<Node>,
103        index: Box<Node>,
104        optional: bool,
105    },
106    /// `.includes(x)` / `.indexOf(x)`
107    Call {
108        base: Box<Node>,
109        method: Method,
110        optional: bool,
111        arg: Box<Node>,
112    },
113    /// 字面量数组上的 `.includes`
114    ConstIncludes { set: ConstSet, hay: Box<Node> },
115    /// `.some(x => expr)`
116    Some {
117        base: Box<Node>,
118        slot: u16,
119        body: Box<Node>,
120        optional: bool,
121    },
122    /// `parseInt(x)`
123    ParseInt(Box<Node>),
124    /// `Array.isArray(x)`
125    IsArray(Box<Node>),
126    /// 括号边界:求值期把内部的可选链短路哨兵归一成 `undefined`
127    Group(Box<Node>),
128    /// `!x`
129    Not(Box<Node>),
130    /// `&&`
131    And(Box<Node>, Box<Node>),
132    /// `||`
133    Or(Box<Node>, Box<Node>),
134    /// `??`:左值 null/undefined 时求右值,其余情况返回左值
135    Nullish(Box<Node>, Box<Node>),
136    /// `===`
137    StrictEq(Box<Node>, Box<Node>),
138    /// `==`
139    LooseEq(Box<Node>, Box<Node>),
140    /// `new Date()` / `new Date(x)`
141    DateNew(Option<Box<Node>>),
142    /// `Date.now()`
143    DateNow,
144    /// `.getTime()`:求值期要求基座是真正的 Date 对象,`?.` 可短路
145    GetTime { base: Box<Node>, optional: bool },
146    /// `Math.floor(x)`
147    MathFloor(Box<Node>),
148    /// 算术:`-` `*` `/`(数值域)
149    Arith {
150        op: ArithOp,
151        lhs: Box<Node>,
152        rhs: Box<Node>,
153    },
154    /// 关系比较
155    Rel {
156        op: RelOp,
157        lhs: Box<Node>,
158        rhs: Box<Node>,
159    },
160    /// 绑定语句
161    Set { slot: u16, value: Box<Node> },
162}
163
164/// 编译产物。
165#[derive(Debug)]
166pub struct Program {
167    pub(crate) steps: Box<[Node]>,
168    pub(crate) result: Node,
169    pub(crate) slots: u16,
170}
171
172/// 编译入口。
173pub 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            // 数组字面量只在 `.includes` 里出现;独立出现则无法用游标表达
207            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            // `.getTime()` 的基座在运行时校验必须是真正 Date:这样
252            // `const d = new Date(); d.getTime()` 可用(JS 合法),
253            // 而 `Date.now().getTime()` / `item.a.getTime()` 会在求值期报错
254            // (JS 对 number/string 调 getTime 也是 TypeError),不会静默返回数字。
255            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            // 字面量数组特化:`["a","b"].includes(x)`
266            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                // `.getTime()` 已在上面的前置分支返回,这里只为穷尽性
287                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            // JS 的 Date 是对象:`d1 === d2` 比的是引用(恒 false),而本 crate 把
316            // 日期降成数字,`===` 会变成比时刻——静默差一整个语义。要求改 `.getTime()`
317            // 或关系比较,别让 `===` 悄悄换掉含义。`==` 在 JS 走 ToPrimitive,恰好等价。
318            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            // JS 的 `&&` / `||` 会短路:左值已能定结果时右值根本不求值。
325            // 编译期也不能因为右值含契约外语法而拒绝整条表达式。
326            if let Node::Const(c) = &l {
327                let short = match op {
328                    BinOp::And => !const_truthy(c),
329                    BinOp::Or => const_truthy(c),
330                    // 左值已确定非空值时可跳过右值,与 `&&` / `||` 同一约定:
331                    // 契约外的语法出现在右值里不影响整条表达式成立。
332                    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                // 括号只影响可选链的短路边界,不改变常量性:`${(1)}` 与 `${1}`
405                // 在 JS 等价,折叠前要剥掉 Group 才能识别内层常量。
406                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
439/// 把成员链折成 `(根, 段列表)`;根不是 `item`/`params`/局部变量时返回 `None`。
440fn 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
472/// AST 上是否为 Date 对象表达式(括号不算语义边界)。
473///
474/// `Date.now()` 返回的是数字,不是 Date 对象:`Date.now() === item.t` 是合法的
475/// 数值比较,不能按 Date 引用比较拒绝。
476fn 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
512/// JS 数字转字符串(`String(n)`)。
513///
514/// 复刻 ECMAScript 的两条边界:十进制指数 `>= 21` 或 `<= -7` 时用指数记法
515/// (`1e+21` / `1e-7`),其余用普通的定点记法;`-0` 输出 `"0"`。
516///
517/// 最短往返的十进制尾数直接取自 Rust 的 `{:e}`。
518///
519/// 已知极窄边界:当 f64 精确值恰好落在两个最短十进制表示的中点时
520/// (如 `771558860699787.3` 的真实值是 `.25`),ECMAScript 取偶数尾数(`.2`),
521/// Rust 取较大的(`.3`)。这类值在 20000 个随机 f64 中约 5 个,且只影响
522/// 数字的字符串展示;本 crate 的谓词语料不含模板常量数字比较,故不引入
523/// 高精度的等距判定(那会牺牲零依赖与热路径开销)。
524pub(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
548/// 把 `1.5e3` 形态的尾数展开成定点记法(只在 `-6 <= exp <= 20` 时调用)。
549fn 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
567/// 字面量数组 → 常量集合。元素必须同类型(全字符串或全数字)。
568fn const_set(items: &[Expr]) -> Result<ConstSet, Error> {
569    // `[].includes(x)` 恒为 false:给一个空集,`hay` 照常求值(JS 也会先求右侧)
570    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            // 只有落在 i64 精确范围内的整数才走整数集:超出范围的 `as i64`
588            // 会饱和,两个不同的大整数会塌成同一个值
589            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        // 期望值由 node 的 `String(n)` 生成
609        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}