use std::borrow::Cow;
use std::marker::PhantomData;
use crate::ast::Method;
use crate::compile::{ConstVal, Node, PathBase, PathSeg, Program, RelOp, format_num};
use crate::error::{Error, ErrorKind};
use crate::semantics;
use crate::set::Probe;
use crate::value::{Data, Kind, Val};
const MAX_SLOTS: usize = 16;
struct Cx<'a, D: Data<'a>> {
row: D,
params: Option<D>,
_l: PhantomData<&'a ()>,
}
impl Program {
pub fn eval<'a, D: Data<'a>>(&'a self, row: D, params: Option<D>) -> Result<bool, Error> {
debug_assert!(usize::from(self.slots) <= MAX_SLOTS, "槽位数超出上限");
let mut slots: [Option<Val<'a, D>>; MAX_SLOTS] = [None; MAX_SLOTS];
let cx = Cx {
row,
params,
_l: PhantomData,
};
for step in self.steps.iter() {
match step {
Node::Set { slot, value } => {
let v = norm(eval_node(value, &cx, &mut slots)?);
slot_set(&mut slots, *slot, v)?;
}
_ => {
return Err(Error::new(ErrorKind::Runtime, "非绑定步骤"));
}
}
}
let out = norm(eval_node(&self.result, &cx, &mut slots)?);
match out {
Val::Bool(b) => Ok(b),
other => Err(runtime(&format!(
"filter 表达式结果不是布尔(完成值 {:?},生产端会抛转换错误)",
other
))),
}
}
}
fn runtime(msg: &str) -> Error {
Error::new(ErrorKind::Runtime, msg.to_string())
}
fn type_err(msg: &str) -> Error {
Error::new(ErrorKind::Type, msg.to_string())
}
fn needs_to_primitive<'a, D: Data<'a>>(v: &Val<'a, D>) -> bool {
matches!(v, Val::Arr(_) | Val::Obj(_) | Val::EmptyObj)
}
fn norm<'a, D: Data<'a>>(v: Val<'a, D>) -> Val<'a, D> {
match v {
Val::ShortCircuit => Val::Undefined,
other => other,
}
}
fn slot_ref<'a, D: Data<'a>>(slots: &[Option<Val<'a, D>>], i: u16) -> Result<Val<'a, D>, Error> {
slots
.get(usize::from(i))
.copied()
.flatten()
.ok_or_else(|| runtime("槽位越界或未初始化"))
}
fn slot_set<'a, D: Data<'a>>(
slots: &mut [Option<Val<'a, D>>],
i: u16,
v: Val<'a, D>,
) -> Result<(), Error> {
match slots.get_mut(usize::from(i)) {
Some(slot) => {
*slot = Some(v);
Ok(())
}
None => Err(runtime("槽位越界")),
}
}
fn val_of<'a, D: Data<'a>>(d: D) -> Val<'a, D> {
match d.kind() {
Kind::Null => Val::Null,
Kind::Bool => Val::Bool(d.as_bool().unwrap_or(false)),
Kind::Number => Val::Num(d.as_f64().unwrap_or(f64::NAN)),
Kind::String => Val::Str(d.as_str().unwrap_or("")),
Kind::Array => Val::Arr(d),
Kind::Object => Val::Obj(d),
}
}
fn const_to_val<'a, D: Data<'a>>(c: &'a ConstVal) -> Val<'a, D> {
match c {
ConstVal::Undefined => Val::Undefined,
ConstVal::Null => Val::Null,
ConstVal::Bool(b) => Val::Bool(*b),
ConstVal::Num(n) => Val::Num(*n),
ConstVal::Str(s) => Val::Str(s),
}
}
fn to_js_string<'a, D: Data<'a>>(v: &Val<'a, D>) -> Option<Cow<'a, str>> {
match v {
Val::Str(s) => Some(Cow::Borrowed(*s)),
Val::Num(n) => Some(Cow::Owned(format_num(*n))),
Val::Bool(b) => Some(Cow::Borrowed(if *b { "true" } else { "false" })),
Val::Null => Some(Cow::Borrowed("null")),
Val::Undefined | Val::ShortCircuit => Some(Cow::Borrowed("undefined")),
Val::Arr(_) | Val::Obj(_) => None,
Val::EmptyObj => None,
}
}
fn eval_node<'a, D: Data<'a>>(
n: &'a Node,
cx: &Cx<'a, D>,
slots: &mut [Option<Val<'a, D>>],
) -> Result<Val<'a, D>, Error> {
match n {
Node::Const(c) => Ok(const_to_val(c)),
Node::Item => Ok(val_of(cx.row)),
Node::Group(inner) => Ok(norm(eval_node(inner, cx, slots)?)),
Node::Params => Ok(match cx.params {
Some(p) => val_of(p),
None => Val::EmptyObj,
}),
Node::Local(i) => slot_ref(slots, *i),
Node::Path { base, segs } => resolve(*base, segs, cx, slots),
Node::Member {
base,
name,
optional,
} => {
let v = eval_node(base, cx, slots)?;
if matches!(v, Val::ShortCircuit) {
return Ok(Val::ShortCircuit);
}
lookup(v, name, *optional)
}
Node::Length { base, optional } => {
let v = eval_node(base, cx, slots)?;
if matches!(v, Val::ShortCircuit) {
return Ok(Val::ShortCircuit);
}
match v {
Val::Str(s) => Ok(Val::Num(semantics::utf16_len(s) as f64)),
Val::Arr(d) => Ok(Val::Num(d.len() as f64)),
Val::Obj(d) => Ok(d.get("length").map_or(Val::Undefined, val_of)),
Val::EmptyObj => Ok(Val::Undefined),
Val::Undefined | Val::Null if *optional => Ok(Val::ShortCircuit),
Val::Undefined | Val::Null => Err(runtime("读取 null/undefined 的 `.length`")),
Val::Num(_) | Val::Bool(_) => Ok(Val::Undefined),
Val::ShortCircuit => Ok(Val::ShortCircuit),
}
}
Node::Index {
base,
index,
optional,
} => {
let b = eval_node(base, cx, slots)?;
if matches!(b, Val::ShortCircuit) {
return Ok(Val::ShortCircuit);
}
let i = eval_node(index, cx, slots)?;
index_into(b, norm(i), *optional)
}
Node::Call {
base,
method,
optional,
arg,
} => {
let b = eval_node(base, cx, slots)?;
if matches!(b, Val::ShortCircuit) {
return Ok(Val::ShortCircuit);
}
let a = eval_node(arg, cx, slots)?;
call_method(b, *method, *optional, norm(a))
}
Node::ConstIncludes { set, hay } => {
let v = norm(eval_node(hay, cx, slots)?);
let probe = match v {
Val::Str(s) => Probe::Str(s),
Val::Num(n) => Probe::Num(n),
_ => Probe::Other,
};
Ok(Val::Bool(set.contains(probe)))
}
Node::Some {
base,
slot,
body,
optional,
} => {
let b = eval_node(base, cx, slots)?;
match b {
Val::ShortCircuit => Ok(Val::ShortCircuit),
Val::Arr(d) => {
for i in 0..d.len() {
let Some(el) = d.at(i) else { continue };
slot_set(slots, *slot, val_of(el))?;
if semantics::truthy(&norm(eval_node(body, cx, slots)?)) {
return Ok(Val::Bool(true));
}
}
Ok(Val::Bool(false))
}
Val::Undefined | Val::Null if *optional => Ok(Val::ShortCircuit),
Val::Undefined | Val::Null => Err(runtime("`.some` 的调用基座是 null/undefined")),
_ => Err(type_err("`.some` 只能用于数组")),
}
}
Node::ParseInt(inner) => {
let v = norm(eval_node(inner, cx, slots)?);
let n = match v {
Val::Str(s) => semantics::parse_int(s),
Val::Num(n) if n.is_finite() => {
let text = format_num(n);
semantics::parse_int(&text)
}
_ => f64::NAN,
};
Ok(Val::Num(n))
}
Node::IsArray(inner) => {
let v = norm(eval_node(inner, cx, slots)?);
Ok(Val::Bool(matches!(v, Val::Arr(_))))
}
Node::Not(inner) => {
let v = norm(eval_node(inner, cx, slots)?);
Ok(Val::Bool(!semantics::truthy(&v)))
}
Node::And(l, r) => {
let lv = norm(eval_node(l, cx, slots)?);
if semantics::truthy(&lv) {
Ok(norm(eval_node(r, cx, slots)?))
} else {
Ok(lv)
}
}
Node::Or(l, r) => {
let lv = norm(eval_node(l, cx, slots)?);
if semantics::truthy(&lv) {
Ok(lv)
} else {
Ok(norm(eval_node(r, cx, slots)?))
}
}
Node::Nullish(l, r) => {
let lv = norm(eval_node(l, cx, slots)?);
match lv {
Val::Null | Val::Undefined => Ok(norm(eval_node(r, cx, slots)?)),
other => Ok(other),
}
}
Node::StrictEq(l, r) => {
let lv = norm(eval_node(l, cx, slots)?);
let rv = norm(eval_node(r, cx, slots)?);
Ok(Val::Bool(semantics::strict_eq(&lv, &rv)))
}
Node::LooseEq(l, r) => {
let lv = norm(eval_node(l, cx, slots)?);
let rv = norm(eval_node(r, cx, slots)?);
if (needs_to_primitive(&lv) || needs_to_primitive(&rv))
&& !matches!(lv, Val::Null | Val::Undefined)
&& !matches!(rv, Val::Null | Val::Undefined)
{
return Err(Error::new(
ErrorKind::Unsupported,
"数组/对象参与 `==`/`!=` 需要 ToPrimitive,契约外".to_string(),
));
}
Ok(Val::Bool(semantics::loose_eq(&lv, &rv)))
}
Node::Rel { op, lhs, rhs } => {
let lv = norm(eval_node(lhs, cx, slots)?);
let rv = norm(eval_node(rhs, cx, slots)?);
if needs_to_primitive(&lv) || needs_to_primitive(&rv) {
return Err(Error::new(
ErrorKind::Unsupported,
"数组/对象参与关系比较需要 ToPrimitive,契约外".to_string(),
));
}
let ord = semantics::compare(&lv, &rv);
let out = match (ord, op) {
(Some(o), RelOp::Lt) => o.is_lt(),
(Some(o), RelOp::Le) => o.is_le(),
(Some(o), RelOp::Gt) => o.is_gt(),
(Some(o), RelOp::Ge) => o.is_ge(),
(None, _) => false,
};
Ok(Val::Bool(out))
}
Node::Set { .. } => Err(runtime("绑定语句不能出现在表达式位置")),
}
}
fn resolve<'a, D: Data<'a>>(
base: PathBase,
segs: &'a [PathSeg],
cx: &Cx<'a, D>,
slots: &mut [Option<Val<'a, D>>],
) -> Result<Val<'a, D>, Error> {
let mut v = match base {
PathBase::Item => val_of(cx.row),
PathBase::Params => match cx.params {
Some(p) => val_of(p),
None => Val::EmptyObj,
},
PathBase::Local(i) => slot_ref(slots, i)?,
};
for seg in segs {
if matches!(v, Val::ShortCircuit) {
return Ok(Val::ShortCircuit);
}
if matches!(v, Val::Undefined | Val::Null) {
if seg.optional {
return Ok(Val::ShortCircuit);
}
return Err(runtime(&format!(
"读取 `{}` 时基座是 null/undefined(JS 会抛 TypeError)",
seg.name
)));
}
v = match v {
Val::Obj(d) => d.get(&seg.name).map_or(Val::Undefined, val_of),
Val::Arr(_) | Val::EmptyObj => Val::Undefined,
_ => Val::Undefined,
};
}
Ok(v)
}
fn lookup<'a, D: Data<'a>>(v: Val<'a, D>, name: &str, optional: bool) -> Result<Val<'a, D>, Error> {
match v {
Val::Obj(d) => Ok(d.get(name).map_or(Val::Undefined, val_of)),
Val::ShortCircuit => Ok(Val::ShortCircuit),
Val::Undefined | Val::Null => {
if optional {
Ok(Val::ShortCircuit)
} else {
Err(runtime(&format!(
"读取 `{name}` 时基座是 null/undefined(JS 会抛 TypeError)"
)))
}
}
Val::Str(_) | Val::Num(_) | Val::Bool(_) => Ok(Val::Undefined),
Val::Arr(_) | Val::EmptyObj => Ok(Val::Undefined),
}
}
fn index_into<'a, D: Data<'a>>(
base: Val<'a, D>,
index: Val<'a, D>,
optional: bool,
) -> Result<Val<'a, D>, Error> {
match (base, index) {
(Val::ShortCircuit, _) => Ok(Val::ShortCircuit),
(Val::Arr(d), Val::Num(n)) => {
if n < 0.0 || n.fract() != 0.0 {
return Ok(Val::Undefined);
}
Ok(d.at(n as usize).map_or(Val::Undefined, val_of))
}
(Val::Obj(d), Val::Num(n)) => {
let key = format_num(n);
Ok(d.get(&key).map_or(Val::Undefined, val_of))
}
(Val::Obj(d), Val::Str(s)) => Ok(d.get(s).map_or(Val::Undefined, val_of)),
(Val::Arr(d), Val::Str(s)) => {
if s == "length" {
return Ok(Val::Num(d.len() as f64));
}
match canonical_index(s) {
Some(k) => Ok(d.at(k).map_or(Val::Undefined, val_of)),
None => Ok(Val::Undefined),
}
}
(Val::Str(s), Val::Str(idx)) => match canonical_index(idx) {
Some(k) => match utf16_char_at(s, k) {
Utf16At::Char(c) => Ok(Val::Str(c)),
Utf16At::None => Ok(Val::Undefined),
Utf16At::Surrogate => Err(Error::new(
ErrorKind::Unsupported,
"非 BMP 字符的 UTF-16 中间码元是孤立代理,无法用 Rust str 表示",
)),
},
None => Ok(Val::Undefined),
},
(Val::Str(s), Val::Num(n)) => {
if n < 0.0 || n.fract() != 0.0 {
return Ok(Val::Undefined);
}
match utf16_char_at(s, n as usize) {
Utf16At::Char(c) => Ok(Val::Str(c)),
Utf16At::None => Ok(Val::Undefined),
Utf16At::Surrogate => Err(Error::new(
ErrorKind::Unsupported,
"非 BMP 字符的 UTF-16 中间码元是孤立代理,无法用 Rust str 表示",
)),
}
}
(Val::Undefined | Val::Null, _) if optional => Ok(Val::ShortCircuit),
(Val::Undefined | Val::Null, _) => Err(runtime("对 null/undefined 取下标")),
(Val::Arr(_), _) => Err(type_err("数组下标必须是整数")),
(Val::EmptyObj, _) => Ok(Val::Undefined),
_ => Ok(Val::Undefined),
}
}
fn canonical_index(s: &str) -> Option<usize> {
let b = s.as_bytes();
if b.is_empty() || !b[0].is_ascii_digit() {
return None;
}
if b.len() > 1 && b[0] == b'0' {
return None;
}
s.parse::<usize>().ok()
}
enum Utf16At<'a> {
Char(&'a str),
Surrogate,
None,
}
fn utf16_char_at(s: &str, idx: usize) -> Utf16At<'_> {
let mut pos = 0usize;
for (byte, ch) in s.char_indices() {
if pos == idx {
let end = byte + ch.len_utf8();
return match s.get(byte..end) {
Some(c) => Utf16At::Char(c),
None => Utf16At::None,
};
}
let units = ch.len_utf16();
if units == 2 && pos < idx && idx < pos + units {
return Utf16At::Surrogate;
}
pos += units;
}
Utf16At::None
}
fn call_method<'a, D: Data<'a>>(
base: Val<'a, D>,
method: Method,
optional: bool,
arg: Val<'a, D>,
) -> Result<Val<'a, D>, Error> {
if matches!(base, Val::ShortCircuit) {
return Ok(Val::ShortCircuit);
}
if matches!(base, Val::Undefined | Val::Null) && optional {
return Ok(Val::ShortCircuit);
}
match base {
Val::Str(s) => {
let Some(needle) = to_js_string(&arg) else {
return Err(type_err("字符串方法的参数不能是数组/对象"));
};
match method {
Method::Includes => Ok(Val::Bool(s.contains(needle.as_ref()))),
Method::IndexOf => Ok(Val::Num(match s.find(needle.as_ref()) {
Some(byte) => semantics::utf16_len(&s[..byte]) as f64,
None => -1.0,
})),
Method::Some => Err(type_err("`.some` 只能用于数组")),
}
}
Val::Arr(d) => match method {
Method::Includes => {
for i in 0..d.len() {
let Some(el) = d.at(i) else { continue };
if semantics::same_value_zero(&val_of(el), &arg) {
return Ok(Val::Bool(true));
}
}
Ok(Val::Bool(false))
}
Method::IndexOf => {
for i in 0..d.len() {
let Some(el) = d.at(i) else { continue };
if semantics::strict_eq(&val_of(el), &arg) {
return Ok(Val::Num(i as f64));
}
}
Ok(Val::Num(-1.0))
}
Method::Some => Err(type_err("`.some` 走独立节点")),
},
Val::Undefined | Val::Null => Err(runtime("对 null/undefined 调用方法")),
_ => Err(type_err("基座不是数组或字符串")),
}
}