use std::borrow::Cow;
use std::marker::PhantomData;
use crate::ast::Method;
use crate::compile::{ArithOp, ConstVal, Node, PathBase, PathSeg, Program, RelOp, format_num};
use crate::date;
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 to_primitive_number<'a, D: Data<'a>>(v: &Val<'a, D>) -> Result<f64, Error> {
match v {
Val::Arr(d) => Ok(semantics::str_to_number(&array_to_js_string(*d)?)),
Val::Obj(_) | Val::EmptyObj => Ok(f64::NAN),
other => semantics::to_number(other)
.ok_or_else(|| type_err("数值转换需要 ToNumber(该类型契约外)")),
}
}
fn needs_identity<'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,
}
}
const OBJECT_PROTO: &[&str] = &[
"constructor",
"hasOwnProperty",
"isPrototypeOf",
"propertyIsEnumerable",
"toLocaleString",
"toString",
"valueOf",
"__proto__",
"__defineGetter__",
"__defineSetter__",
"__lookupGetter__",
"__lookupSetter__",
];
const ARRAY_PROTO: &[&str] = &[
"at",
"concat",
"constructor",
"copyWithin",
"entries",
"every",
"fill",
"filter",
"find",
"findIndex",
"findLast",
"findLastIndex",
"flat",
"flatMap",
"forEach",
"includes",
"indexOf",
"join",
"keys",
"lastIndexOf",
"map",
"pop",
"push",
"reduce",
"reduceRight",
"reverse",
"shift",
"slice",
"some",
"sort",
"splice",
"toLocaleString",
"toString",
"unshift",
"values",
];
const STRING_PROTO: &[&str] = &[
"anchor",
"at",
"big",
"blink",
"bold",
"charAt",
"charCodeAt",
"codePointAt",
"concat",
"constructor",
"endsWith",
"fixed",
"fontcolor",
"fontsize",
"includes",
"indexOf",
"isWellFormed",
"italics",
"lastIndexOf",
"link",
"localeCompare",
"match",
"matchAll",
"normalize",
"padEnd",
"padStart",
"repeat",
"replace",
"replaceAll",
"search",
"slice",
"small",
"split",
"startsWith",
"strike",
"sub",
"substr",
"substring",
"sup",
"toLocaleLowerCase",
"toLocaleUpperCase",
"toLowerCase",
"toString",
"toUpperCase",
"toWellFormed",
"trim",
"trimEnd",
"trimStart",
"valueOf",
];
const NUMBER_PROTO: &[&str] = &[
"constructor",
"toExponential",
"toFixed",
"toLocaleString",
"toPrecision",
"toString",
"valueOf",
];
const BOOLEAN_PROTO: &[&str] = &["constructor", "toString", "valueOf"];
const DATE_PROTO: &[&str] = &[
"constructor",
"getDate",
"getDay",
"getFullYear",
"getHours",
"getMilliseconds",
"getMinutes",
"getMonth",
"getSeconds",
"getTime",
"getTimezoneOffset",
"getUTCDate",
"getUTCDay",
"getUTCFullYear",
"getUTCHours",
"getUTCMilliseconds",
"getUTCMinutes",
"getUTCMonth",
"getUTCSeconds",
"getYear",
"setDate",
"setFullYear",
"setHours",
"setMilliseconds",
"setMinutes",
"setMonth",
"setSeconds",
"setTime",
"setUTCDate",
"setUTCFullYear",
"setUTCHours",
"setUTCMilliseconds",
"setUTCMinutes",
"setUTCMonth",
"setUTCSeconds",
"setYear",
"toDateString",
"toISOString",
"toJSON",
"toLocaleDateString",
"toLocaleString",
"toLocaleTimeString",
"toString",
"toTimeString",
"toUTCString",
"valueOf",
];
fn is_prototype_member<'a, D: Data<'a>>(v: &Val<'a, D>, name: &str) -> bool {
match v {
Val::Str(_) => STRING_PROTO.contains(&name),
Val::Num(_) => NUMBER_PROTO.contains(&name),
Val::Bool(_) => BOOLEAN_PROTO.contains(&name),
Val::Arr(_) => ARRAY_PROTO.contains(&name),
Val::Obj(_) | Val::EmptyObj => OBJECT_PROTO.contains(&name),
Val::Date(_) => DATE_PROTO.contains(&name),
Val::Undefined | Val::Null | Val::ShortCircuit => false,
}
}
fn prototype_error(name: &str) -> Error {
Error::new(
ErrorKind::Unsupported,
format!("属性 `{name}` 是内置原型方法/属性,本 crate 没有函数值,契约外"),
)
}
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::Date(_) => None,
Val::Arr(_) | Val::Obj(_) => None,
Val::EmptyObj => None,
}
}
fn array_to_js_string<'a, D: Data<'a>>(d: D) -> Result<String, Error> {
let mut out = String::new();
for i in 0..d.len() {
if i > 0 {
out.push(',');
}
let Some(el) = d.at(i) else { continue };
match val_of(el) {
Val::Null | Val::Undefined => {}
Val::Str(s) => out.push_str(s),
Val::Num(n) => out.push_str(&format_num(n)),
Val::Bool(b) => out.push_str(if b { "true" } else { "false" }),
Val::Date(_) | Val::Arr(_) | Val::Obj(_) | Val::EmptyObj | Val::ShortCircuit => {
return Err(Error::new(
ErrorKind::Unsupported,
"`parseInt` 的数组参数含引用元素,需要完整 ToString,契约外",
));
}
}
}
Ok(out)
}
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(_) | Val::Date(_) => 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);
}
if *optional && matches!(b, Val::Undefined | Val::Null) {
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);
}
if *optional && matches!(b, Val::Undefined | Val::Null) {
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)
}
Val::Date(_) => f64::NAN,
Val::Arr(d) => semantics::parse_int(&array_to_js_string(d)?),
_ => 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)?);
if matches!((&lv, &rv), (Val::Date(_), Val::Date(_))) {
return Err(Error::new(
ErrorKind::Unsupported,
"Date 之间的 `===`/`!==` 需要引用身份,契约外".to_string(),
));
}
if needs_identity(&lv) && needs_identity(&rv) {
return Err(Error::new(
ErrorKind::Unsupported,
"对象/数组之间的 `===`/`!==` 需要引用身份,契约外".to_string(),
));
}
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 matches!(lv, Val::Date(_)) || matches!(rv, Val::Date(_)) {
let other = if matches!(lv, Val::Date(_)) { &rv } else { &lv };
return match other {
Val::Null | Val::Undefined => Ok(Val::Bool(false)),
Val::Num(_) | Val::Bool(_) => Ok(Val::Bool(false)),
_ => Err(Error::new(
ErrorKind::Unsupported,
"Date 参与 `==`/`!=` 需要 ToPrimitive 或引用身份,契约外".to_string(),
)),
};
}
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::DateNew(arg) => {
let ms = match arg {
None => date::now_ms(),
Some(a) => match norm(eval_node(a, cx, slots)?) {
Val::Num(n) => date::clip(n),
Val::Date(n) => date::clip(n),
Val::Str(s) => date::parse(s),
Val::Null => 0.0,
Val::Bool(b) => {
if b {
1.0
} else {
0.0
}
}
Val::Undefined => f64::NAN,
Val::Arr(d) => date::parse(&array_to_js_string(d)?),
Val::Obj(_) | Val::EmptyObj => f64::NAN,
Val::ShortCircuit => f64::NAN,
},
};
Ok(Val::Date(ms))
}
Node::DateNow => Ok(Val::Num(date::now_ms())),
Node::GetTime { base, optional } => {
let v = eval_node(base, cx, slots)?;
if matches!(v, Val::ShortCircuit) {
return Ok(Val::ShortCircuit);
}
if *optional && matches!(v, Val::Undefined | Val::Null) {
return Ok(Val::ShortCircuit);
}
match v {
Val::Date(n) => Ok(Val::Num(n)),
other => Err(type_err(&format!(
"`.getTime()` 的基座不是 Date(得到 {other:?})"
))),
}
}
Node::MathFloor(inner) => {
let v = norm(eval_node(inner, cx, slots)?);
let n = to_primitive_number(&v)?;
Ok(Val::Num(n.floor()))
}
Node::Arith { op, lhs, rhs } => {
let lv = norm(eval_node(lhs, cx, slots)?);
let rv = norm(eval_node(rhs, cx, slots)?);
let a = to_primitive_number(&lv)?;
let b = to_primitive_number(&rv)?;
Ok(Val::Num(match op {
ArithOp::Sub => a - b,
ArithOp::Mul => a * b,
ArithOp::Div => a / b,
}))
}
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) => match d.get(&seg.name) {
Some(x) => val_of(x),
None if is_prototype_member(&v, &seg.name) => {
return Err(prototype_error(&seg.name));
}
None => Val::Undefined,
},
_ if is_prototype_member(&v, &seg.name) => {
return Err(prototype_error(&seg.name));
}
_ => 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) => match d.get(name) {
Some(x) => Ok(val_of(x)),
None if is_prototype_member(&Val::Obj(d), name) => Err(prototype_error(name)),
None => Ok(Val::Undefined),
},
Val::ShortCircuit => Ok(Val::ShortCircuit),
Val::Undefined | Val::Null => {
if optional {
Ok(Val::ShortCircuit)
} else {
Err(runtime(&format!(
"读取 `{name}` 时基座是 null/undefined(JS 会抛 TypeError)"
)))
}
}
other if is_prototype_member(&other, name) => Err(prototype_error(name)),
_ => Ok(Val::Undefined),
}
}
fn object_property<'a, D: Data<'a>>(d: D, key: &str) -> Result<Val<'a, D>, Error> {
match d.get(key) {
Some(x) => Ok(val_of(x)),
None if OBJECT_PROTO.contains(&key) => Err(prototype_error(key)),
None => 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 !(0.0..(d.len() as f64)).contains(&n) || 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)) => object_property(d, s),
(Val::Obj(d), Val::Bool(b)) => object_property(d, if b { "true" } else { "false" }),
(Val::Obj(d), Val::Null) => object_property(d, "null"),
(Val::Obj(d), Val::Undefined) => object_property(d, "undefined"),
(Val::Obj(_), Val::Date(_) | Val::Arr(_) | Val::Obj(_) | Val::EmptyObj) => Err(Error::new(
ErrorKind::Unsupported,
"对象下标是引用类型,需要 ToPropertyKey,契约外".to_string(),
)),
(Val::Arr(d), Val::Str(s)) => {
if s == "length" {
return Ok(Val::Num(d.len() as f64));
}
match canonical_index(s) {
Some(k) if k < d.len() => Ok(d.at(k).map_or(Val::Undefined, val_of)),
_ if ARRAY_PROTO.contains(&s) => Err(prototype_error(s)),
_ => Ok(Val::Undefined),
}
}
(Val::Arr(_), Val::Bool(_) | Val::Null | Val::Undefined | Val::Date(_)) => {
Ok(Val::Undefined)
}
(Val::Arr(_), Val::Arr(_) | Val::Obj(_) | Val::EmptyObj) => Err(Error::new(
ErrorKind::Unsupported,
"数组下标是引用类型,需要 ToPropertyKey,契约外".to_string(),
)),
(Val::Str(s), Val::Str(idx)) => {
if idx == "length" {
return Ok(Val::Num(semantics::utf16_len(s) as f64));
}
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 表示",
)),
},
_ if STRING_PROTO.contains(&idx) => Err(prototype_error(idx)),
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::Str(_), Val::Bool(_) | Val::Null | Val::Undefined | Val::Date(_)) => {
Ok(Val::Undefined)
}
(Val::Str(_), Val::Arr(_) | Val::Obj(_) | Val::EmptyObj) => Err(Error::new(
ErrorKind::Unsupported,
"字符串下标是引用类型,需要 ToPropertyKey,契约外".to_string(),
)),
(Val::Date(_), Val::Str(s)) => {
if DATE_PROTO.contains(&s) {
Err(prototype_error(s))
} else {
Ok(Val::Undefined)
}
}
(Val::Date(_), Val::Bool(_) | Val::Null | Val::Undefined | Val::Num(_) | Val::Date(_)) => {
Ok(Val::Undefined)
}
(Val::Date(_), Val::Arr(_) | Val::Obj(_) | Val::EmptyObj) => Err(Error::new(
ErrorKind::Unsupported,
"Date 下标是引用类型,需要 ToPropertyKey,契约外".to_string(),
)),
(Val::Undefined | Val::Null, _) if optional => Ok(Val::ShortCircuit),
(Val::Undefined | Val::Null, _) => Err(runtime("对 null/undefined 取下标")),
(Val::Num(_), Val::Str(s)) => {
if NUMBER_PROTO.contains(&s) {
Err(prototype_error(s))
} else {
Ok(Val::Undefined)
}
}
(Val::Bool(_), Val::Str(s)) => {
if BOOLEAN_PROTO.contains(&s) {
Err(prototype_error(s))
} else {
Ok(Val::Undefined)
}
}
(Val::EmptyObj, Val::Str(s)) => {
if OBJECT_PROTO.contains(&s) {
Err(prototype_error(s))
} else {
Ok(Val::Undefined)
}
}
(Val::Num(_) | Val::Bool(_) | Val::EmptyObj, _) => Ok(Val::Undefined),
(Val::Arr(_), _) => Err(type_err("数组下标必须是整数")),
(Val::Str(_), _) => 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() {
let units = ch.len_utf16();
if pos == idx {
return if units == 1 {
match s.get(byte..byte + ch.len_utf8()) {
Some(c) => Utf16At::Char(c),
None => Utf16At::None,
}
} else {
Utf16At::Surrogate
};
}
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::StartsWith => Ok(Val::Bool(s.starts_with(needle.as_ref()))),
Method::EndsWith => Ok(Val::Bool(s.ends_with(needle.as_ref()))),
Method::Some => Err(type_err("`.some` 只能用于数组")),
Method::GetTime => Err(runtime("`.getTime()` 走独立节点")),
}
}
Val::Arr(d) => match method {
Method::Includes | Method::IndexOf if needs_identity(&arg) => Err(Error::new(
ErrorKind::Unsupported,
"数组方法的引用参数需要身份比较,契约外".to_string(),
)),
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::StartsWith => Err(type_err("`.startsWith` 只能用于字符串")),
Method::EndsWith => Err(type_err("`.endsWith` 只能用于字符串")),
Method::Some => Err(type_err("`.some` 走独立节点")),
Method::GetTime => Err(runtime("`.getTime()` 走独立节点")),
},
Val::Undefined | Val::Null => Err(runtime("对 null/undefined 调用方法")),
_ => Err(type_err("基座不是数组或字符串")),
}
}