js2rust-predicate 0.1.0

Compile side-effect-free JavaScript predicates into a zero-allocation Rust evaluator
Documentation
//! 给 codegen 用的检查 API 演示:把一条链从「JS 里怎么写」推到「Rust 该生成什么」。
//!
//! 运行:`cargo run --example chain_check`
//!
//! 这里手写了几条与 znpt_graphql `@filter` 语料同形的链,以及一段谓词源码。
//! 真实接入时,`segs` 与 `SegType` 来自 js2rust 自己的类型推断(JSDoc → struct)。

use js2rust_predicate::chain::{self, Chain, IndexTy, SegType, Segment, Step};
use js2rust_predicate::nulls::{self, NullMode};

fn main() {
    // 1) 正常形态:`item.detail` 可空,后面下钻写了 `?.`
    let ok: &[Segment<'_>] = &[
        Segment::field("detail", SegType::Optional, false),
        Segment::field("logistics_company", SegType::Optional, true),
    ];

    // 2) 缺 `?.`:`Option` 字段后面还下钻,JS 在缺数据时会抛 TypeError
    let broken: &[Segment<'_>] = &[
        Segment::field("detail", SegType::Optional, false),
        Segment::field("logistics_company", SegType::Optional, false),
    ];

    // 3) 多余 `?.`:容器非空
    let redundant: &[Segment<'_>] = &[
        Segment::field("status", SegType::Present, false),
        Segment::field("status_id", SegType::Present, true),
    ];

    // 4) 字典取键:变量键只允许打在 `Object.<string, T>` 上
    let map_lookup: &[Segment<'_>] = &[
        Segment::field("tags", SegType::Map("string"), false),
        Segment::var_index("key", IndexTy::I64, SegType::Present, false),
    ];

    // 5) 常量下标:负下标在数组上恒 undefined
    let fold: &[Segment<'_>] = &[Segment::const_index(-1.0, SegType::Present, true)];

    // 6) js2rust 里首批要生成的字段,用来演示命名与冲突消解
    let a: &[Segment<'_>] = &[
        Segment::field("a", SegType::Present, false),
        Segment::field("b", SegType::Present, false),
    ];
    let a_flat: &[Segment<'_>] = &[Segment::field("a_b", SegType::Present, false)];

    let chains = [
        Chain::item(ok),
        Chain::item(broken),
        Chain::item(redundant),
        Chain::item(map_lookup),
        Chain::item(fold),
        Chain::item(a),
        Chain::item(a_flat),
    ];

    for c in &chains {
        let p = chain::plan(c);
        println!("--- {}", chain::render_path(c));
        println!(
            "    返回 Option: {}    常量 undefined: {}    错误: {}    告警: {}",
            p.returns_option(),
            p.is_constant_undefined(),
            p.has_errors(),
            p.has_warnings()
        );
        println!("    Rust: {}", render_steps(p.steps(), p.returns_option()));
        for d in p.diagnostics() {
            println!("    {d}");
        }
    }

    // 命名表:确定性、同链去重、`a.b` 与 `a_b` 自动消歧
    let names = chain::assign_names(&chains).expect("命名冲突未超过上限");
    println!("\n=== 命名表 ===");
    for n in &names {
        println!("{}  <=  {}", n.fn_name(), n.js_path());
    }

    // 空值判别扫描:合并模型下严格判别直接报 E_NULL_STRICT
    let src = "item.detail?.logistics_company == null && typeof item.status === 'undefined'";
    println!("\n=== 空值判别({})===", src);
    for c in nulls::scan(src).expect("可扫描") {
        println!("    offset {:>3}  {}", c.offset(), c.form().as_str());
    }
    for d in nulls::check(src, NullMode::Merge).expect("可扫描") {
        println!("    {d}");
    }

    // 校验:合法链不应产生错误
    let ok_plan = chain::plan(&Chain::params(false, ok));
    assert!(!ok_plan.has_errors());
    assert_eq!(ok_plan.steps()[0], Step::OptField("detail"));
    assert_eq!(ok_plan.steps()[1], Step::OptField("logistics_company"));
    assert!(chain::plan(&Chain::item(broken)).has_errors());
    assert!(chain::plan(&Chain::item(fold)).is_constant_undefined());
    assert!(!chain::assign_names(&chains).unwrap().is_empty());

    // `params` 可空:首段就必须写 `?.`
    let params_segs: &[Segment<'_>] = &[Segment::field("status", SegType::Present, false)];
    let params_nullable = Chain::params(true, params_segs);
    let p = chain::plan(&params_nullable);
    assert!(p.has_errors());
    assert_eq!(p.diagnostics()[0].code(), chain::Code::NonOptOnOptional);
    println!("\nparams 可空时:{}", chain::render_path(&params_nullable));
}

/// 把生成计划渲染成 Rust 代码片段(只为演示,真实实现还要处理叶类型与借用)。
///
/// 关键点:`?` 出现在**下一步**的开头——上一步取到 `Option` 就要展开。
/// 链路里出现过任何 `Option`,函数就得返回 `Option`,否则直接返回 `&T`。
fn render_steps(steps: &[Step<'_>], returns_option: bool) -> String {
    let mut out = String::from("self");
    let mut prev_opt = false;
    for s in steps {
        if prev_opt {
            out.push('?');
        }
        match s {
            Step::Field(name) => out.push_str(&format!(".{name}")),
            Step::OptField(name) => out.push_str(&format!(".{name}.as_ref()")),
            Step::MapField(name) => out.push_str(&format!(".get(\"{name}\")")),
            Step::Index(k) => out.push_str(&format!(".get({k})")),
            Step::VarIndex(IndexTy::I64) => out.push_str(".get(usize::try_from(idx).ok()?)"),
            Step::VarIndex(IndexTy::F64) => out.push_str(".get(float_to_index(idx)?)"),
        }
        prev_opt = s.is_option();
    }
    let tail = match (returns_option, prev_opt) {
        (true, false) => format!("Some({out})"),
        _ => out,
    };
    format!(
        "{tail}  -> {}",
        if returns_option { "Option<&T>" } else { "&T" }
    )
}

/// 演示局部绑定基座:`const row = item.a; row.b` 这类链的修复建议会写 `row.a?.b`。
#[allow(dead_code)]
fn local_chain<'a>(segs: &'a [Segment<'a>]) -> Chain<'a> {
    Chain::local("row", false, segs)
}