js2rust-predicate 0.1.3

Compile side-effect-free JavaScript predicates into a zero-allocation Rust evaluator
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
//! 编译:语法树 → 节点树。
//!
//! 编译期做的事:
//!
//! 1. **路径预绑定**:`item.profile.code` 折成 `[item, "profile", "code"]`,求值不再切字符串;
//! 2. **字面量数组特化**:`["a","b"].includes(x)` → 编译期排序常量表(≤31 元素二分、≥32 哈希);
//! 3. **常量折叠**:`!true`、`true && x` 之类直接折掉;
//! 4. **模板字面量**:仅当全部片段为常量时折叠为常量字符串;运行期片段按契约返回 `Unsupported`。
//!
//! 编译失败的表达式不会进 `Program`,因此求值路径可以假设结构合法。

use crate::ast::{BinOp, Binding, Expr, Global, Method, Program as Ast};
use crate::error::{Error, ErrorKind};
use crate::parser;
use crate::set::ConstSet;

/// 编译期常量。
#[derive(Clone, Debug)]
pub(crate) enum ConstVal {
    /// `undefined`
    Undefined,
    /// `null`
    Null,
    /// 布尔
    Bool(bool),
    /// 数字
    Num(f64),
    /// 字符串
    Str(Box<str>),
}

/// 路径根。
#[derive(Clone, Copy, Debug)]
pub(crate) enum PathBase {
    /// `item`
    Item,
    /// `params`
    Params,
    /// 槽位
    Local(u16),
}

/// 路径上的一段。
#[derive(Clone, Debug)]
pub(crate) struct PathSeg {
    /// 属性名
    pub name: Box<str>,
    /// 该段是否为 `?.`
    pub optional: bool,
}

/// 关系运算符。
#[derive(Clone, Copy, Debug)]
pub(crate) enum RelOp {
    /// `<`
    Lt,
    /// `<=`
    Le,
    /// `>`
    Gt,
    /// `>=`
    Ge,
}

/// 节点树。求值只走这棵树,零分配。
#[derive(Debug)]
pub(crate) enum Node {
    /// 常量
    Const(ConstVal),
    /// `item`
    Item,
    /// `params`
    Params,
    /// 槽位
    Local(u16),
    /// 预绑定路径
    Path {
        base: PathBase,
        segs: Box<[PathSeg]>,
    },
    /// 动态基座上的成员访问
    Member {
        base: Box<Node>,
        name: Box<str>,
        optional: bool,
    },
    /// `.length`
    Length { base: Box<Node>, optional: bool },
    /// 下标访问
    Index {
        base: Box<Node>,
        index: Box<Node>,
        optional: bool,
    },
    /// `.includes(x)` / `.indexOf(x)`
    Call {
        base: Box<Node>,
        method: Method,
        optional: bool,
        arg: Box<Node>,
    },
    /// 字面量数组上的 `.includes`
    ConstIncludes { set: ConstSet, hay: Box<Node> },
    /// `.some(x => expr)`
    Some {
        base: Box<Node>,
        slot: u16,
        body: Box<Node>,
        optional: bool,
    },
    /// `parseInt(x)`
    ParseInt(Box<Node>),
    /// `Array.isArray(x)`
    IsArray(Box<Node>),
    /// 括号边界:求值期把内部的可选链短路哨兵归一成 `undefined`
    Group(Box<Node>),
    /// `!x`
    Not(Box<Node>),
    /// `&&`
    And(Box<Node>, Box<Node>),
    /// `||`
    Or(Box<Node>, Box<Node>),
    /// `??`:左值 null/undefined 时求右值,其余情况返回左值
    Nullish(Box<Node>, Box<Node>),
    /// `===`
    StrictEq(Box<Node>, Box<Node>),
    /// `==`
    LooseEq(Box<Node>, Box<Node>),
    /// 关系比较
    Rel {
        op: RelOp,
        lhs: Box<Node>,
        rhs: Box<Node>,
    },
    /// 绑定语句
    Set { slot: u16, value: Box<Node> },
}

/// 编译产物。
#[derive(Debug)]
pub struct Program {
    pub(crate) steps: Box<[Node]>,
    pub(crate) result: Node,
    pub(crate) slots: u16,
}

/// 编译入口。
pub fn compile(src: &str) -> Result<Program, Error> {
    let ast = parser::parse(src)?;
    compile_ast(&ast)
}

fn compile_ast(ast: &Ast) -> Result<Program, Error> {
    let mut steps = Vec::with_capacity(ast.bindings.len());
    for Binding { slot, value } in &ast.bindings {
        let node = build(value)?;
        steps.push(Node::Set {
            slot: *slot,
            value: Box::new(node),
        });
    }
    let result = build(&ast.result)?;
    Ok(Program {
        steps: steps.into_boxed_slice(),
        result,
        slots: ast.slots,
    })
}

fn build(e: &Expr) -> Result<Node, Error> {
    Ok(match e {
        Expr::Undefined => Node::Const(ConstVal::Undefined),
        Expr::Null => Node::Const(ConstVal::Null),
        Expr::Bool(b) => Node::Const(ConstVal::Bool(*b)),
        Expr::Num(n) => Node::Const(ConstVal::Num(*n)),
        Expr::Str(s) => Node::Const(ConstVal::Str(s.as_str().into())),
        Expr::Item => Node::Item,
        Expr::Params => Node::Params,
        Expr::Local(i) => Node::Local(*i),
        Expr::Array(items) => {
            // 数组字面量只在 `.includes` 里出现;独立出现则无法用游标表达
            if items.is_empty() {
                return Err(unsupported("空数组字面量只能用于 `.includes`"));
            }
            return Err(unsupported("数组字面量只能作为 `.includes` 的接收者"));
        }
        Expr::Member {
            base,
            name,
            optional,
        } => {
            if &**name == "length" {
                Node::Length {
                    base: Box::new(build(base)?),
                    optional: *optional,
                }
            } else {
                match path_of(e) {
                    Some((root, segs)) => Node::Path {
                        base: root,
                        segs: segs.into_boxed_slice(),
                    },
                    None => Node::Member {
                        base: Box::new(build(base)?),
                        name: name.clone(),
                        optional: *optional,
                    },
                }
            }
        }
        Expr::Index {
            base,
            index,
            optional,
        } => Node::Index {
            base: Box::new(build(base)?),
            index: Box::new(build(index)?),
            optional: *optional,
        },
        Expr::Call {
            base,
            method,
            optional,
            args,
        } => {
            let arg = args.first().ok_or_else(|| unsupported("方法缺少参数"))?;
            // 字面量数组特化:`["a","b"].includes(x)`
            if matches!(method, Method::Includes) {
                if let Expr::Array(items) = &**base {
                    return Ok(Node::ConstIncludes {
                        set: const_set(items)?,
                        hay: Box::new(build(arg)?),
                    });
                }
            }
            match method {
                Method::Some => {
                    let Expr::Arrow { slot, body } = arg else {
                        return Err(unsupported("`.some` 只支持 `x => expr`"));
                    };
                    Node::Some {
                        base: Box::new(build(base)?),
                        slot: *slot,
                        body: Box::new(build(body)?),
                        optional: *optional,
                    }
                }
                Method::Includes | Method::IndexOf | Method::StartsWith | Method::EndsWith => {
                    Node::Call {
                        base: Box::new(build(base)?),
                        method: *method,
                        optional: *optional,
                        arg: Box::new(build(arg)?),
                    }
                }
            }
        }
        Expr::GlobalCall { global, args } => {
            let arg = args.first().ok_or_else(|| unsupported("调用缺少参数"))?;
            let inner = build(arg)?;
            match global {
                Global::ParseInt => Node::ParseInt(Box::new(inner)),
                Global::IsArray => Node::IsArray(Box::new(inner)),
            }
        }
        Expr::Group(inner) => Node::Group(Box::new(build(inner)?)),
        Expr::Not(inner) => {
            let node = build(inner)?;
            match node {
                Node::Const(c) => Node::Const(ConstVal::Bool(!const_truthy(&c))),
                other => Node::Not(Box::new(other)),
            }
        }
        Expr::Binary { op, lhs, rhs } => {
            let l = build(lhs)?;
            // JS 的 `&&` / `||` 会短路:左值已能定结果时右值根本不求值。
            // 编译期也不能因为右值含契约外语法而拒绝整条表达式。
            if let Node::Const(c) = &l {
                let short = match op {
                    BinOp::And => !const_truthy(c),
                    BinOp::Or => const_truthy(c),
                    // 左值已确定非空值时可跳过右值,与 `&&` / `||` 同一约定:
                    // 契约外的语法出现在右值里不影响整条表达式成立。
                    BinOp::Nullish => !const_nullish(c),
                    _ => false,
                };
                if short {
                    return Ok(Node::Const(c.clone()));
                }
            }
            let r = build(rhs)?;
            match op {
                BinOp::And => match (&l, &r) {
                    (Node::Const(c), _) if !const_truthy(c) => Node::Const(c.clone()),
                    (Node::Const(_), _) => r,
                    _ => Node::And(Box::new(l), Box::new(r)),
                },
                BinOp::Or => match (&l, &r) {
                    (Node::Const(c), _) if const_truthy(c) => Node::Const(c.clone()),
                    (Node::Const(_), _) => r,
                    _ => Node::Or(Box::new(l), Box::new(r)),
                },
                BinOp::Nullish => match (&l, &r) {
                    (Node::Const(c), _) if const_nullish(c) => r,
                    (Node::Const(c), _) => Node::Const(c.clone()),
                    _ => Node::Nullish(Box::new(l), Box::new(r)),
                },
                BinOp::Eq3 => match (&l, &r) {
                    (Node::Const(a), Node::Const(b)) => {
                        Node::Const(ConstVal::Bool(const_strict_eq(a, b)))
                    }
                    _ => Node::StrictEq(Box::new(l), Box::new(r)),
                },
                BinOp::Ne3 => match (&l, &r) {
                    (Node::Const(a), Node::Const(b)) => {
                        Node::Const(ConstVal::Bool(!const_strict_eq(a, b)))
                    }
                    _ => Node::Not(Box::new(Node::StrictEq(Box::new(l), Box::new(r)))),
                },
                BinOp::Eq2 => Node::LooseEq(Box::new(l), Box::new(r)),
                BinOp::Ne2 => Node::Not(Box::new(Node::LooseEq(Box::new(l), Box::new(r)))),
                BinOp::Lt => Node::Rel {
                    op: RelOp::Lt,
                    lhs: Box::new(l),
                    rhs: Box::new(r),
                },
                BinOp::Le => Node::Rel {
                    op: RelOp::Le,
                    lhs: Box::new(l),
                    rhs: Box::new(r),
                },
                BinOp::Gt => Node::Rel {
                    op: RelOp::Gt,
                    lhs: Box::new(l),
                    rhs: Box::new(r),
                },
                BinOp::Ge => Node::Rel {
                    op: RelOp::Ge,
                    lhs: Box::new(l),
                    rhs: Box::new(r),
                },
            }
        }
        Expr::Template(parts) => {
            let mut out = String::new();
            for p in parts {
                // 括号只影响可选链的短路边界,不改变常量性:`${(1)}` 与 `${1}`
                // 在 JS 等价,折叠前要剥掉 Group 才能识别内层常量。
                let mut node = build(p)?;
                while let Node::Group(inner) = node {
                    node = *inner;
                }
                match node {
                    Node::Const(ConstVal::Str(s)) => out.push_str(&s),
                    Node::Const(ConstVal::Num(n)) => {
                        out.push_str(&format_num(n));
                    }
                    Node::Const(ConstVal::Bool(b)) => {
                        out.push_str(if b { "true" } else { "false" })
                    }
                    Node::Const(ConstVal::Null) => out.push_str("null"),
                    Node::Const(ConstVal::Undefined) => out.push_str("undefined"),
                    _ => {
                        return Err(unsupported(
                            "模板字面量目前只支持常量片段,运行期拼接不在契约内",
                        ));
                    }
                }
            }
            Node::Const(ConstVal::Str(out.into()))
        }
        Expr::Arrow { .. } => return Err(unsupported("回调只能出现在 `.some` 里")),
    })
}

/// 把成员链折成 `(根, 段列表)`;根不是 `item`/`params`/局部变量时返回 `None`。
fn path_of(e: &Expr) -> Option<(PathBase, Vec<PathSeg>)> {
    fn walk(e: &Expr, segs: &mut Vec<PathSeg>) -> Option<PathBase> {
        match e {
            Expr::Member {
                base,
                name,
                optional,
            } => {
                if &**name == "length" {
                    return None;
                }
                let root = walk(base, segs)?;
                segs.push(PathSeg {
                    name: name.clone(),
                    optional: *optional,
                });
                Some(root)
            }
            Expr::Item => Some(PathBase::Item),
            Expr::Params => Some(PathBase::Params),
            Expr::Local(i) => Some(PathBase::Local(*i)),
            _ => None,
        }
    }
    let mut segs = Vec::new();
    let root = walk(e, &mut segs)?;
    if segs.is_empty() {
        return None;
    }
    Some((root, segs))
}

fn unsupported(msg: &str) -> Error {
    Error::new(ErrorKind::Unsupported, msg.to_string())
}

fn const_truthy(c: &ConstVal) -> bool {
    match c {
        ConstVal::Undefined | ConstVal::Null => false,
        ConstVal::Bool(b) => *b,
        ConstVal::Num(n) => *n != 0.0 && !n.is_nan(),
        ConstVal::Str(s) => !s.is_empty(),
    }
}

fn const_nullish(c: &ConstVal) -> bool {
    matches!(c, ConstVal::Undefined | ConstVal::Null)
}

fn const_strict_eq(a: &ConstVal, b: &ConstVal) -> bool {
    match (a, b) {
        (ConstVal::Undefined, ConstVal::Undefined) => true,
        (ConstVal::Null, ConstVal::Null) => true,
        (ConstVal::Bool(x), ConstVal::Bool(y)) => x == y,
        (ConstVal::Num(x), ConstVal::Num(y)) => x == y,
        (ConstVal::Str(x), ConstVal::Str(y)) => x == y,
        _ => false,
    }
}

/// JS 数字转字符串(`String(n)`)。
///
/// 复刻 ECMAScript 的两条边界:十进制指数 `>= 21` 或 `<= -7` 时用指数记法
/// (`1e+21` / `1e-7`),其余用普通的定点记法;`-0` 输出 `"0"`。
///
/// 最短往返的十进制尾数直接取自 Rust 的 `{:e}`。
///
/// 已知极窄边界:当 f64 精确值恰好落在两个最短十进制表示的中点时
/// (如 `771558860699787.3` 的真实值是 `.25`),ECMAScript 取偶数尾数(`.2`),
/// Rust 取较大的(`.3`)。这类值在 20000 个随机 f64 中约 5 个,且只影响
/// 数字的字符串展示;本 crate 的谓词语料不含模板常量数字比较,故不引入
/// 高精度的等距判定(那会牺牲零依赖与热路径开销)。
pub(crate) fn format_num(n: f64) -> String {
    if n.is_nan() {
        return "NaN".to_string();
    }
    if n.is_infinite() {
        return if n > 0.0 {
            "Infinity".into()
        } else {
            "-Infinity".into()
        };
    }
    if n == 0.0 {
        return "0".to_string();
    }
    let sci = format!("{n:e}");
    let (mant, exp) = sci.split_once('e').unwrap_or((&sci, "0"));
    let exp: i32 = exp.parse().unwrap_or(0);
    if !(-6..=20).contains(&exp) {
        let sign = if exp >= 0 { '+' } else { '-' };
        return format!("{mant}e{sign}{}", exp.abs());
    }
    plain_from_scientific(mant, exp)
}

/// 把 `1.5e3` 形态的尾数展开成定点记法(只在 `-6 <= exp <= 20` 时调用)。
fn plain_from_scientific(mant: &str, exp: i32) -> String {
    let (sign, rest) = match mant.strip_prefix('-') {
        Some(r) => ("-", r),
        None => ("", mant),
    };
    let digits: String = rest.chars().filter(|c| *c != '.').collect();
    let int_len = i64::from(exp) + 1;
    let body = if int_len <= 0 {
        format!("0.{}{digits}", "0".repeat((-int_len) as usize))
    } else if int_len as usize >= digits.len() {
        format!("{digits}{}", "0".repeat(int_len as usize - digits.len()))
    } else {
        let (head, tail) = digits.split_at(int_len as usize);
        format!("{head}.{tail}")
    };
    format!("{sign}{body}")
}

/// 字面量数组 → 常量集合。元素必须同类型(全字符串或全数字)。
fn const_set(items: &[Expr]) -> Result<ConstSet, Error> {
    // `[].includes(x)` 恒为 false:给一个空集,`hay` 照常求值(JS 也会先求右侧)
    if items.is_empty() {
        return Ok(ConstSet::from_strs(Vec::new()));
    }
    if items.iter().all(|it| matches!(it, Expr::Str(_))) {
        let mut strs = Vec::with_capacity(items.len());
        for it in items {
            if let Expr::Str(v) = it {
                strs.push(v.as_str().into());
            }
        }
        return Ok(ConstSet::from_strs(strs));
    }
    if items.iter().all(|it| matches!(it, Expr::Num(_))) {
        let mut ints = Vec::with_capacity(items.len());
        let mut nums = Vec::with_capacity(items.len());
        for it in items {
            let Expr::Num(n) = it else { continue };
            // 只有落在 i64 精确范围内的整数才走整数集:超出范围的 `as i64`
            // 会饱和,两个不同的大整数会塌成同一个值
            if n.fract() == 0.0 && n.abs() < 2f64.powi(63) {
                ints.push(*n as i64);
            }
            nums.push(*n);
        }
        if ints.len() == items.len() {
            return Ok(ConstSet::from_ints(ints));
        }
        return Ok(ConstSet::from_nums(nums));
    }
    Err(unsupported("字面量数组元素必须同类型(全字符串或全数字)"))
}

#[cfg(test)]
mod tests {
    use super::format_num;

    #[test]
    fn js_number_to_string_table() {
        // 期望值由 node 的 `String(n)` 生成
        let cases = [
            (0.0, "0"),
            (-0.0, "0"),
            (1.0, "1"),
            (1.5, "1.5"),
            (-2.25, "-2.25"),
            (1e21, "1e+21"),
            (1.000001e21, "1.000001e+21"),
            (1e20, "100000000000000000000"),
            (123456789012345680000.0, "123456789012345680000"),
            (1e-7, "1e-7"),
            (1.5e-7, "1.5e-7"),
            (1e-6, "0.000001"),
            (0.000001234, "0.000001234"),
            (9007199254740992.0, "9007199254740992"),
            (1e19, "10000000000000000000"),
            (9223372036854775808.0, "9223372036854776000"),
            (1e300, "1e+300"),
            (1e-300, "1e-300"),
            (0.1 + 0.2, "0.30000000000000004"),
        ];
        for (n, want) in cases {
            assert_eq!(format_num(n), want, "String({n})");
        }
        assert_eq!(format_num(f64::NAN), "NaN");
        assert_eq!(format_num(f64::INFINITY), "Infinity");
        assert_eq!(format_num(f64::NEG_INFINITY), "-Infinity");
    }
}