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,
Null,
Bool(bool),
Num(f64),
Str(Box<str>),
}
#[derive(Clone, Copy, Debug)]
pub(crate) enum PathBase {
Item,
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,
Params,
Local(u16),
Path {
base: PathBase,
segs: Box<[PathSeg]>,
},
Member {
base: Box<Node>,
name: Box<str>,
optional: bool,
},
Length { base: Box<Node>, optional: bool },
Index {
base: Box<Node>,
index: Box<Node>,
optional: bool,
},
Call {
base: Box<Node>,
method: Method,
optional: bool,
arg: Box<Node>,
},
ConstIncludes { set: ConstSet, hay: Box<Node> },
Some {
base: Box<Node>,
slot: u16,
body: Box<Node>,
optional: bool,
},
ParseInt(Box<Node>),
IsArray(Box<Node>),
Group(Box<Node>),
Not(Box<Node>),
And(Box<Node>, Box<Node>),
Or(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) => {
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("方法缺少参数"))?;
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 => 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)?;
if let Node::Const(c) = &l {
let short = match op {
BinOp::And => !const_truthy(c),
BinOp::Or => const_truthy(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::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 {
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` 里")),
})
}
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_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,
}
}
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)
}
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> {
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 };
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() {
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");
}
}