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 RelOp {
55    /// `<`
56    Lt,
57    /// `<=`
58    Le,
59    /// `>`
60    Gt,
61    /// `>=`
62    Ge,
63}
64
65/// 节点树。求值只走这棵树,零分配。
66#[derive(Debug)]
67pub(crate) enum Node {
68    /// 常量
69    Const(ConstVal),
70    /// `item`
71    Item,
72    /// `params`
73    Params,
74    /// 槽位
75    Local(u16),
76    /// 预绑定路径
77    Path {
78        base: PathBase,
79        segs: Box<[PathSeg]>,
80    },
81    /// 动态基座上的成员访问
82    Member {
83        base: Box<Node>,
84        name: Box<str>,
85        optional: bool,
86    },
87    /// `.length`
88    Length { base: Box<Node>, optional: bool },
89    /// 下标访问
90    Index {
91        base: Box<Node>,
92        index: Box<Node>,
93        optional: bool,
94    },
95    /// `.includes(x)` / `.indexOf(x)`
96    Call {
97        base: Box<Node>,
98        method: Method,
99        optional: bool,
100        arg: Box<Node>,
101    },
102    /// 字面量数组上的 `.includes`
103    ConstIncludes { set: ConstSet, hay: Box<Node> },
104    /// `.some(x => expr)`
105    Some {
106        base: Box<Node>,
107        slot: u16,
108        body: Box<Node>,
109        optional: bool,
110    },
111    /// `parseInt(x)`
112    ParseInt(Box<Node>),
113    /// `Array.isArray(x)`
114    IsArray(Box<Node>),
115    /// 括号边界:求值期把内部的可选链短路哨兵归一成 `undefined`
116    Group(Box<Node>),
117    /// `!x`
118    Not(Box<Node>),
119    /// `&&`
120    And(Box<Node>, Box<Node>),
121    /// `||`
122    Or(Box<Node>, Box<Node>),
123    /// `??`:左值 null/undefined 时求右值,其余情况返回左值
124    Nullish(Box<Node>, Box<Node>),
125    /// `===`
126    StrictEq(Box<Node>, Box<Node>),
127    /// `==`
128    LooseEq(Box<Node>, Box<Node>),
129    /// 关系比较
130    Rel {
131        op: RelOp,
132        lhs: Box<Node>,
133        rhs: Box<Node>,
134    },
135    /// 绑定语句
136    Set { slot: u16, value: Box<Node> },
137}
138
139/// 编译产物。
140#[derive(Debug)]
141pub struct Program {
142    pub(crate) steps: Box<[Node]>,
143    pub(crate) result: Node,
144    pub(crate) slots: u16,
145}
146
147/// 编译入口。
148pub 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            // 数组字面量只在 `.includes` 里出现;独立出现则无法用游标表达
182            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            // 字面量数组特化:`["a","b"].includes(x)`
228            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 => Node::Call {
249                    base: Box::new(build(base)?),
250                    method: *method,
251                    optional: *optional,
252                    arg: Box::new(build(arg)?),
253                },
254            }
255        }
256        Expr::GlobalCall { global, args } => {
257            let arg = args.first().ok_or_else(|| unsupported("调用缺少参数"))?;
258            let inner = build(arg)?;
259            match global {
260                Global::ParseInt => Node::ParseInt(Box::new(inner)),
261                Global::IsArray => Node::IsArray(Box::new(inner)),
262            }
263        }
264        Expr::Group(inner) => Node::Group(Box::new(build(inner)?)),
265        Expr::Not(inner) => {
266            let node = build(inner)?;
267            match node {
268                Node::Const(c) => Node::Const(ConstVal::Bool(!const_truthy(&c))),
269                other => Node::Not(Box::new(other)),
270            }
271        }
272        Expr::Binary { op, lhs, rhs } => {
273            let l = build(lhs)?;
274            // JS 的 `&&` / `||` 会短路:左值已能定结果时右值根本不求值。
275            // 编译期也不能因为右值含契约外语法而拒绝整条表达式。
276            if let Node::Const(c) = &l {
277                let short = match op {
278                    BinOp::And => !const_truthy(c),
279                    BinOp::Or => const_truthy(c),
280                    // 左值已确定非空值时可跳过右值,与 `&&` / `||` 同一约定:
281                    // 契约外的语法出现在右值里不影响整条表达式成立。
282                    BinOp::Nullish => !const_nullish(c),
283                    _ => false,
284                };
285                if short {
286                    return Ok(Node::Const(c.clone()));
287                }
288            }
289            let r = build(rhs)?;
290            match op {
291                BinOp::And => match (&l, &r) {
292                    (Node::Const(c), _) if !const_truthy(c) => Node::Const(c.clone()),
293                    (Node::Const(_), _) => r,
294                    _ => Node::And(Box::new(l), Box::new(r)),
295                },
296                BinOp::Or => match (&l, &r) {
297                    (Node::Const(c), _) if const_truthy(c) => Node::Const(c.clone()),
298                    (Node::Const(_), _) => r,
299                    _ => Node::Or(Box::new(l), Box::new(r)),
300                },
301                BinOp::Nullish => match (&l, &r) {
302                    (Node::Const(c), _) if const_nullish(c) => r,
303                    (Node::Const(c), _) => Node::Const(c.clone()),
304                    _ => Node::Nullish(Box::new(l), Box::new(r)),
305                },
306                BinOp::Eq3 => match (&l, &r) {
307                    (Node::Const(a), Node::Const(b)) => {
308                        Node::Const(ConstVal::Bool(const_strict_eq(a, b)))
309                    }
310                    _ => Node::StrictEq(Box::new(l), Box::new(r)),
311                },
312                BinOp::Ne3 => match (&l, &r) {
313                    (Node::Const(a), Node::Const(b)) => {
314                        Node::Const(ConstVal::Bool(!const_strict_eq(a, b)))
315                    }
316                    _ => Node::Not(Box::new(Node::StrictEq(Box::new(l), Box::new(r)))),
317                },
318                BinOp::Eq2 => Node::LooseEq(Box::new(l), Box::new(r)),
319                BinOp::Ne2 => Node::Not(Box::new(Node::LooseEq(Box::new(l), Box::new(r)))),
320                BinOp::Lt => Node::Rel {
321                    op: RelOp::Lt,
322                    lhs: Box::new(l),
323                    rhs: Box::new(r),
324                },
325                BinOp::Le => Node::Rel {
326                    op: RelOp::Le,
327                    lhs: Box::new(l),
328                    rhs: Box::new(r),
329                },
330                BinOp::Gt => Node::Rel {
331                    op: RelOp::Gt,
332                    lhs: Box::new(l),
333                    rhs: Box::new(r),
334                },
335                BinOp::Ge => Node::Rel {
336                    op: RelOp::Ge,
337                    lhs: Box::new(l),
338                    rhs: Box::new(r),
339                },
340            }
341        }
342        Expr::Template(parts) => {
343            let mut out = String::new();
344            for p in parts {
345                // 括号只影响可选链的短路边界,不改变常量性:`${(1)}` 与 `${1}`
346                // 在 JS 等价,折叠前要剥掉 Group 才能识别内层常量。
347                let mut node = build(p)?;
348                while let Node::Group(inner) = node {
349                    node = *inner;
350                }
351                match node {
352                    Node::Const(ConstVal::Str(s)) => out.push_str(&s),
353                    Node::Const(ConstVal::Num(n)) => {
354                        out.push_str(&format_num(n));
355                    }
356                    Node::Const(ConstVal::Bool(b)) => {
357                        out.push_str(if b { "true" } else { "false" })
358                    }
359                    Node::Const(ConstVal::Null) => out.push_str("null"),
360                    Node::Const(ConstVal::Undefined) => out.push_str("undefined"),
361                    _ => {
362                        return Err(unsupported(
363                            "模板字面量目前只支持常量片段,运行期拼接不在契约内",
364                        ));
365                    }
366                }
367            }
368            Node::Const(ConstVal::Str(out.into()))
369        }
370        Expr::Arrow { .. } => return Err(unsupported("回调只能出现在 `.some` 里")),
371    })
372}
373
374/// 把成员链折成 `(根, 段列表)`;根不是 `item`/`params`/局部变量时返回 `None`。
375fn path_of(e: &Expr) -> Option<(PathBase, Vec<PathSeg>)> {
376    fn walk(e: &Expr, segs: &mut Vec<PathSeg>) -> Option<PathBase> {
377        match e {
378            Expr::Member {
379                base,
380                name,
381                optional,
382            } => {
383                if &**name == "length" {
384                    return None;
385                }
386                let root = walk(base, segs)?;
387                segs.push(PathSeg {
388                    name: name.clone(),
389                    optional: *optional,
390                });
391                Some(root)
392            }
393            Expr::Item => Some(PathBase::Item),
394            Expr::Params => Some(PathBase::Params),
395            Expr::Local(i) => Some(PathBase::Local(*i)),
396            _ => None,
397        }
398    }
399    let mut segs = Vec::new();
400    let root = walk(e, &mut segs)?;
401    if segs.is_empty() {
402        return None;
403    }
404    Some((root, segs))
405}
406
407fn unsupported(msg: &str) -> Error {
408    Error::new(ErrorKind::Unsupported, msg.to_string())
409}
410
411fn const_truthy(c: &ConstVal) -> bool {
412    match c {
413        ConstVal::Undefined | ConstVal::Null => false,
414        ConstVal::Bool(b) => *b,
415        ConstVal::Num(n) => *n != 0.0 && !n.is_nan(),
416        ConstVal::Str(s) => !s.is_empty(),
417    }
418}
419
420fn const_nullish(c: &ConstVal) -> bool {
421    matches!(c, ConstVal::Undefined | ConstVal::Null)
422}
423
424fn const_strict_eq(a: &ConstVal, b: &ConstVal) -> bool {
425    match (a, b) {
426        (ConstVal::Undefined, ConstVal::Undefined) => true,
427        (ConstVal::Null, ConstVal::Null) => true,
428        (ConstVal::Bool(x), ConstVal::Bool(y)) => x == y,
429        (ConstVal::Num(x), ConstVal::Num(y)) => x == y,
430        (ConstVal::Str(x), ConstVal::Str(y)) => x == y,
431        _ => false,
432    }
433}
434
435/// JS 数字转字符串(`String(n)`)。
436///
437/// 复刻 ECMAScript 的两条边界:十进制指数 `>= 21` 或 `<= -7` 时用指数记法
438/// (`1e+21` / `1e-7`),其余用普通的定点记法;`-0` 输出 `"0"`。
439///
440/// 最短往返的十进制尾数直接取自 Rust 的 `{:e}`。
441///
442/// 已知极窄边界:当 f64 精确值恰好落在两个最短十进制表示的中点时
443/// (如 `771558860699787.3` 的真实值是 `.25`),ECMAScript 取偶数尾数(`.2`),
444/// Rust 取较大的(`.3`)。这类值在 20000 个随机 f64 中约 5 个,且只影响
445/// 数字的字符串展示;本 crate 的谓词语料不含模板常量数字比较,故不引入
446/// 高精度的等距判定(那会牺牲零依赖与热路径开销)。
447pub(crate) fn format_num(n: f64) -> String {
448    if n.is_nan() {
449        return "NaN".to_string();
450    }
451    if n.is_infinite() {
452        return if n > 0.0 {
453            "Infinity".into()
454        } else {
455            "-Infinity".into()
456        };
457    }
458    if n == 0.0 {
459        return "0".to_string();
460    }
461    let sci = format!("{n:e}");
462    let (mant, exp) = sci.split_once('e').unwrap_or((&sci, "0"));
463    let exp: i32 = exp.parse().unwrap_or(0);
464    if !(-6..=20).contains(&exp) {
465        let sign = if exp >= 0 { '+' } else { '-' };
466        return format!("{mant}e{sign}{}", exp.abs());
467    }
468    plain_from_scientific(mant, exp)
469}
470
471/// 把 `1.5e3` 形态的尾数展开成定点记法(只在 `-6 <= exp <= 20` 时调用)。
472fn plain_from_scientific(mant: &str, exp: i32) -> String {
473    let (sign, rest) = match mant.strip_prefix('-') {
474        Some(r) => ("-", r),
475        None => ("", mant),
476    };
477    let digits: String = rest.chars().filter(|c| *c != '.').collect();
478    let int_len = i64::from(exp) + 1;
479    let body = if int_len <= 0 {
480        format!("0.{}{digits}", "0".repeat((-int_len) as usize))
481    } else if int_len as usize >= digits.len() {
482        format!("{digits}{}", "0".repeat(int_len as usize - digits.len()))
483    } else {
484        let (head, tail) = digits.split_at(int_len as usize);
485        format!("{head}.{tail}")
486    };
487    format!("{sign}{body}")
488}
489
490/// 字面量数组 → 常量集合。元素必须同类型(全字符串或全数字)。
491fn const_set(items: &[Expr]) -> Result<ConstSet, Error> {
492    // `[].includes(x)` 恒为 false:给一个空集,`hay` 照常求值(JS 也会先求右侧)
493    if items.is_empty() {
494        return Ok(ConstSet::from_strs(Vec::new()));
495    }
496    if items.iter().all(|it| matches!(it, Expr::Str(_))) {
497        let mut strs = Vec::with_capacity(items.len());
498        for it in items {
499            if let Expr::Str(v) = it {
500                strs.push(v.as_str().into());
501            }
502        }
503        return Ok(ConstSet::from_strs(strs));
504    }
505    if items.iter().all(|it| matches!(it, Expr::Num(_))) {
506        let mut ints = Vec::with_capacity(items.len());
507        let mut nums = Vec::with_capacity(items.len());
508        for it in items {
509            let Expr::Num(n) = it else { continue };
510            // 只有落在 i64 精确范围内的整数才走整数集:超出范围的 `as i64`
511            // 会饱和,两个不同的大整数会塌成同一个值
512            if n.fract() == 0.0 && n.abs() < 2f64.powi(63) {
513                ints.push(*n as i64);
514            }
515            nums.push(*n);
516        }
517        if ints.len() == items.len() {
518            return Ok(ConstSet::from_ints(ints));
519        }
520        return Ok(ConstSet::from_nums(nums));
521    }
522    Err(unsupported("字面量数组元素必须同类型(全字符串或全数字)"))
523}
524
525#[cfg(test)]
526mod tests {
527    use super::format_num;
528
529    #[test]
530    fn js_number_to_string_table() {
531        // 期望值由 node 的 `String(n)` 生成
532        let cases = [
533            (0.0, "0"),
534            (-0.0, "0"),
535            (1.0, "1"),
536            (1.5, "1.5"),
537            (-2.25, "-2.25"),
538            (1e21, "1e+21"),
539            (1.000001e21, "1.000001e+21"),
540            (1e20, "100000000000000000000"),
541            (123456789012345680000.0, "123456789012345680000"),
542            (1e-7, "1e-7"),
543            (1.5e-7, "1.5e-7"),
544            (1e-6, "0.000001"),
545            (0.000001234, "0.000001234"),
546            (9007199254740992.0, "9007199254740992"),
547            (1e19, "10000000000000000000"),
548            (9223372036854775808.0, "9223372036854776000"),
549            (1e300, "1e+300"),
550            (1e-300, "1e-300"),
551            (0.1 + 0.2, "0.30000000000000004"),
552        ];
553        for (n, want) in cases {
554            assert_eq!(format_num(n), want, "String({n})");
555        }
556        assert_eq!(format_num(f64::NAN), "NaN");
557        assert_eq!(format_num(f64::INFINITY), "Infinity");
558        assert_eq!(format_num(f64::NEG_INFINITY), "-Infinity");
559    }
560}