use crate::host::{self, ops, with_host, PropAccess};
use fusevm::{NumOp, NumericCall, Value, VM};
pub fn install(vm: &mut VM) {
vm.register_builtin(ops::ECHO, b_echo);
vm.register_builtin(ops::GETVAR, b_getvar);
vm.register_builtin(ops::GETSLOT, b_getslot);
vm.register_builtin(ops::INCDEC_SLOT, b_incdec_slot);
vm.register_builtin(ops::GETSLOT_Q, b_getslot_q);
vm.register_builtin(ops::SETSLOT, b_setslot);
vm.register_builtin(ops::SETVAR, b_setvar);
vm.register_builtin(ops::COPY, b_copy);
vm.register_builtin(ops::CONCAT, b_concat);
vm.register_builtin(ops::TRUTHY, b_truthy);
vm.register_builtin(ops::CALL, b_call);
vm.register_builtin(ops::MINMAX_FLF2, b_minmax_flf2);
vm.register_builtin(ops::BYREF_ARG_DIAG, b_byref_arg_diag);
vm.register_builtin(ops::GLOBAL_BIND, b_global_bind);
vm.register_builtin(ops::INCDEC_STEP, b_incdec_step);
vm.register_builtin(ops::CALL_SPREAD, b_call_spread);
vm.register_builtin(ops::MKARRAY, b_mkarray);
vm.register_builtin(ops::MKARRAY_ADD, b_mkarray_add);
vm.register_builtin(ops::INDEX_GET, b_index_get);
vm.register_builtin(ops::INDEX_SET, b_index_set);
vm.register_builtin(ops::ARR_APPEND, b_arr_append);
vm.register_builtin(ops::SET_PATH, b_set_path);
vm.register_builtin(ops::APPEND_PATH, b_append_path);
vm.register_builtin(ops::GET_PATH, b_get_path);
vm.register_builtin(ops::INCDEC_PATH, b_incdec_path);
vm.register_builtin(ops::PATH_APPEND_CHILD, b_path_append_child);
vm.register_builtin(ops::DIV, b_div);
vm.register_builtin(ops::MOD, b_mod);
vm.register_builtin(ops::POW, b_pow);
vm.register_builtin(ops::LOOSE_EQ, b_loose_eq);
vm.register_builtin(ops::LOOSE_NE, b_loose_ne);
vm.register_builtin(ops::STRICT_EQ, b_strict_eq);
vm.register_builtin(ops::STRICT_NE, b_strict_ne);
vm.register_builtin(ops::LT, b_lt);
vm.register_builtin(ops::GT, b_gt);
vm.register_builtin(ops::LE, b_le);
vm.register_builtin(ops::GE, b_ge);
vm.register_builtin(ops::SIG_RETURN, b_sig_return);
vm.register_builtin(ops::INCDEC, b_incdec);
vm.register_builtin(ops::ARRAYKEYS, b_arraykeys);
vm.register_builtin(ops::ARRAYLEN, b_arraylen);
vm.register_builtin(ops::BITAND, b_bitand);
vm.register_builtin(ops::BITOR, b_bitor);
vm.register_builtin(ops::BITXOR, b_bitxor);
vm.register_builtin(ops::SHL, b_shl);
vm.register_builtin(ops::SHR, b_shr);
vm.register_builtin(ops::BITNOT, b_bitnot);
vm.register_builtin(ops::SPACESHIP, b_spaceship);
vm.register_builtin(ops::DBG_LINE, b_dbg_line);
vm.register_builtin(ops::ARR_MUT, b_arr_mut);
vm.register_builtin(ops::MKCLOSURE, b_mkclosure);
vm.register_builtin(ops::CALL_VALUE, b_call_value);
vm.register_builtin(ops::NEW, b_new);
vm.register_builtin(ops::PROP_GET, b_prop_get);
vm.register_builtin(ops::PROP_SET, b_prop_set);
vm.register_builtin(ops::PROP_ENSURE_ARRAY, b_prop_ensure_array);
vm.register_builtin(ops::PROP_TOUCH, b_prop_touch);
vm.register_builtin(ops::PROP_SET_RW, b_prop_set_rw);
vm.register_builtin(ops::PROP_UNSET, b_prop_unset);
vm.register_builtin(ops::PROP_ISSET, b_prop_isset);
vm.register_builtin(ops::INDEX_ISSET, b_index_isset);
vm.register_builtin(ops::DECL_FATAL, b_decl_fatal);
vm.register_builtin(ops::DYN_CLASS, b_dyn_class);
vm.register_builtin(ops::DYN_CLASS_CONST, b_dyn_class_const);
vm.register_builtin(ops::CLONE, b_clone);
vm.register_builtin(ops::CONST_DECL, b_const_decl);
vm.register_builtin(ops::PROP_GET_EMPTY, b_prop_get_empty);
vm.register_builtin(ops::PROP_INCDEC, b_prop_incdec);
vm.register_builtin(ops::SUPPRESS_PUSH, b_suppress_push);
vm.register_builtin(ops::SUPPRESS_POP, b_suppress_pop);
vm.register_builtin(ops::MCALL, b_mcall);
vm.register_builtin(ops::SCALL, b_scall);
vm.register_builtin(ops::SCONST, b_sconst);
vm.register_builtin(ops::THROW, b_throw);
vm.register_builtin(ops::RUN_TRY, b_run_try);
vm.register_builtin(ops::SIG_HALT, b_sig_halt);
vm.register_builtin(ops::SIG_BREAK, b_sig_break);
vm.register_builtin(ops::SIG_CONTINUE, b_sig_continue);
vm.register_builtin(ops::SIG_LEVEL, b_sig_level);
vm.register_builtin(ops::CONST_FETCH, b_const_fetch);
vm.register_builtin(ops::MAGIC_FILE, b_magic_file);
vm.register_builtin(ops::MAGIC_DIR, b_magic_dir);
vm.register_builtin(ops::MAGIC_CLASS, b_magic_class);
vm.register_builtin(ops::UNSET_VAR, b_unset_var);
vm.register_builtin(ops::UNSET_PATH, b_unset_path);
vm.register_builtin(ops::FOREACH_PREP, b_foreach_prep);
vm.register_builtin(ops::INSTANCEOF, b_instanceof);
vm.register_builtin(ops::REF_BIND, b_ref_bind);
vm.register_builtin(ops::REF_CELL, b_ref_cell);
vm.register_builtin(ops::REF_SLOT_VAR, b_ref_slot_var);
vm.register_builtin(ops::REF_SLOT_ELEM, b_ref_slot_elem);
vm.register_builtin(ops::REF_SLOT_PROP, b_ref_slot_prop);
vm.register_builtin(ops::REF_TO_VAR, b_ref_to_var);
vm.register_builtin(ops::REF_TO_ELEM, b_ref_to_elem);
vm.register_builtin(ops::REF_TO_APPEND, b_ref_to_append);
vm.register_builtin(ops::REF_TO_PROP, b_ref_to_prop);
vm.register_builtin(ops::GETVAR_Q, b_getvar_q);
vm.register_builtin(ops::INDEX_GET_Q, b_index_get_q);
vm.register_builtin(ops::LIST_ELEM_GET, b_list_elem_get);
vm.register_builtin(ops::PROP_GET_Q, b_prop_get_q);
vm.register_builtin(ops::LSB_CLASS, b_lsb_class);
vm.register_builtin(ops::LSB_FORWARD, b_lsb_forward);
vm.register_builtin(ops::RET_REF, b_ret_ref);
vm.register_builtin(ops::REF_SLOT_RET, b_ref_slot_ret);
vm.register_builtin(ops::BYREF_OUT, b_byref_out);
vm.register_builtin(ops::BYREF_LIVE, b_byref_live);
vm.register_builtin(ops::SPROP_GET, b_sprop_get);
vm.register_builtin(ops::SPROP_SET, b_sprop_set);
vm.register_builtin(ops::SPROP_INCDEC, b_sprop_incdec);
vm.register_builtin(ops::STATIC_BIND, b_static_bind);
vm.register_builtin(ops::CALL_NAMED, b_call_named);
vm.register_builtin(ops::MCALL_NAMED, b_mcall_named);
vm.register_builtin(ops::SCALL_NAMED, b_scall_named);
vm.register_builtin(ops::NEW_NAMED, b_new_named);
vm.register_builtin(ops::CALLVALUE_NAMED, b_callvalue_named);
vm.register_builtin(ops::YIELD, b_yield);
vm.register_builtin(ops::YIELD_KV, b_yield_kv);
vm.register_builtin(ops::YIELD_FROM, b_yield_from);
vm.register_builtin(ops::IS_GENERATOR, b_is_generator);
vm.register_builtin(ops::GEN_REWIND, b_gen_rewind);
vm.register_builtin(ops::GEN_VALID, b_gen_valid);
vm.register_builtin(ops::GEN_KEY, b_gen_key);
vm.register_builtin(ops::GEN_CURRENT, b_gen_current);
vm.register_builtin(ops::GEN_NEXT, b_gen_next);
}
fn b_yield(vm: &mut VM, _: u8) -> Value {
let val = vm.pop();
match host::yield_value(val) {
Ok(v) => bubbled(vm, v),
Err(e) => yield_err(vm, e),
}
}
fn b_yield_kv(vm: &mut VM, _: u8) -> Value {
let key = vm.pop();
let val = vm.pop();
match host::yield_kv(key, val) {
Ok(v) => bubbled(vm, v),
Err(e) => yield_err(vm, e),
}
}
fn b_yield_from(vm: &mut VM, _: u8) -> Value {
let src = vm.pop();
match host::yield_from(src) {
Ok(v) => bubbled(vm, v),
Err(e) => yield_err(vm, e),
}
}
fn yield_err(vm: &mut VM, e: String) -> Value {
if host::unwinding() {
vm.ip = vm.chunk.ops.len();
Value::Undef
} else {
fail_or_throw(vm, e)
}
}
fn b_is_generator(vm: &mut VM, _: u8) -> Value {
let v = vm.pop();
Value::bool(with_host(|h| h.is_generator_val(&v)))
}
fn b_gen_rewind(vm: &mut VM, _: u8) -> Value {
let g = vm.pop();
match host::gen_rewind(&g) {
Ok(()) => bubbled(vm, Value::Undef),
Err(e) => yield_err(vm, e),
}
}
fn b_gen_valid(vm: &mut VM, _: u8) -> Value {
let g = vm.pop();
match host::gen_valid(&g) {
Ok(b) => bubbled(vm, Value::bool(b)),
Err(e) => yield_err(vm, e),
}
}
fn b_gen_key(vm: &mut VM, _: u8) -> Value {
let g = vm.pop();
match host::gen_key(&g) {
Ok(v) => bubbled(vm, v),
Err(e) => yield_err(vm, e),
}
}
fn b_gen_current(vm: &mut VM, _: u8) -> Value {
let g = vm.pop();
match host::gen_current(&g) {
Ok(v) => bubbled(vm, v),
Err(e) => yield_err(vm, e),
}
}
fn b_gen_next(vm: &mut VM, _: u8) -> Value {
let g = vm.pop();
match host::gen_next(&g) {
Ok(v) => bubbled(vm, v),
Err(e) => yield_err(vm, e),
}
}
fn split_named(pairs: Vec<Value>) -> (Vec<Value>, Vec<(String, Value)>) {
let mut positional = Vec::new();
let mut named = Vec::new();
let mut it = pairs.into_iter();
while let (Some(name), Some(val)) = (it.next(), it.next()) {
match name {
Value::Str(s) => named.push((s.to_string(), val)),
_ => positional.push(val),
}
}
(positional, named)
}
fn b_call_named(vm: &mut VM, argc: u8) -> Value {
let pairs = pop_args(vm, argc as usize - 1);
let name = pop_name(vm);
let (pos, named) = split_named(pairs);
match host::call_function_named(&name, pos, named) {
Ok(v) => bubbled(vm, v),
Err(e) => fail(vm, e),
}
}
fn b_callvalue_named(vm: &mut VM, argc: u8) -> Value {
let pairs = pop_args(vm, argc as usize - 1);
let callee = vm.pop();
let (pos, named) = split_named(pairs);
mark_frame_line(vm);
match host::call_value_named(callee, pos, named) {
Ok(v) => bubbled(vm, v),
Err(e) => fail_or_throw(vm, e),
}
}
fn b_mcall_named(vm: &mut VM, argc: u8) -> Value {
let pairs = pop_args(vm, argc as usize - 2);
let method = pop_name(vm);
let recv = vm.pop();
let (pos, named) = split_named(pairs);
mark_frame_line(vm);
if with_host(|h| h.is_closure(&recv)) {
return match host::call_closure_method(&recv, &method, pos) {
Ok(v) => bubbled(vm, v),
Err(e) => fail(vm, e),
};
}
if with_host(|h| h.is_generator_val(&recv)) {
return match host::call_generator_method(&recv, &method, pos) {
Ok(v) => bubbled(vm, v),
Err(e) => yield_err(vm, e),
};
}
match with_host(|h| h.object_class(&recv)) {
Some(c) => {
let magic = match method_plan(vm, &c, &method, true) {
Ok(m) => m,
Err(v) => return v,
};
let r = if magic {
host::call_magic_call_named(&c, &method, Some(recv), pos, named)
} else {
host::call_method_named(&c, &method, Some(recv), pos, named)
};
match r {
Ok(v) => bubbled(vm, v),
Err(e) => fail(vm, e),
}
}
None => {
let ty = with_host(|h| receiver_type_name(h, &recv));
throw_php(
vm,
"Error",
&format!("Call to a member function {method}() on {ty}"),
)
}
}
}
fn b_scall_named(vm: &mut VM, argc: u8) -> Value {
let pairs = pop_args(vm, argc as usize - 2);
let method = pop_name(vm);
let class = pop_name(vm);
let (pos, named) = split_named(pairs);
let this = with_host(|h| {
let t = h.get_var("this");
matches!(t, Value::Obj(_)).then_some(t)
});
mark_frame_line(vm);
let magic = match static_method_plan(vm, &class, &method, &this) {
Ok(m) => m,
Err(v) => return v,
};
let r = if magic {
host::call_magic_call_named(&class, &method, this, pos, named)
} else {
host::call_method_named(&class, &method, this, pos, named)
};
match r {
Ok(v) => bubbled(vm, v),
Err(e) => fail_or_throw(vm, e),
}
}
fn b_new_named(vm: &mut VM, argc: u8) -> Value {
let pairs = pop_args(vm, argc as usize - 1);
let class = pop_name(vm);
let (pos, named) = split_named(pairs);
mark_frame_line(vm);
match host::new_object_named(&class, pos, named) {
Ok(v) => bubbled(vm, v),
Err(e) => fail_or_throw(vm, e),
}
}
fn b_sprop_get(vm: &mut VM, _: u8) -> Value {
let name = pop_name(vm);
let class = pop_name(vm);
match host::static_prop_get(&class, &name) {
Ok(v) => v,
Err(e) => fail_or_throw(vm, e),
}
}
fn b_sprop_set(vm: &mut VM, _: u8) -> Value {
let val = vm.pop();
let name = pop_name(vm);
let class = pop_name(vm);
match host::static_prop_set(&class, &name, val) {
Ok(v) => v,
Err(e) => fail_or_throw(vm, e),
}
}
fn b_sprop_incdec(vm: &mut VM, _: u8) -> Value {
let code = vm.pop().to_int();
let name = pop_name(vm);
let class = pop_name(vm);
let inc = code & 1 != 0;
let prefix = code & 2 != 0;
let old = match host::static_prop_get(&class, &name) {
Ok(v) => v,
Err(e) => return fail_or_throw(vm, e),
};
mark_warn_site(vm);
if incdec_refused(vm, &old, inc) {
return Value::Undef;
}
let newv = with_host(|h| h.incdec_value(&old, inc));
if let Err(e) = host::static_prop_set(&class, &name, newv.clone()) {
return fail_or_throw(vm, e);
}
if prefix {
newv
} else {
old
}
}
fn b_static_bind(vm: &mut VM, _: u8) -> Value {
let init = vm.pop();
let slot_key = pop_name(vm);
let name = pop_name(vm);
with_host(|h| h.bind_static_local(&name, &slot_key, init));
Value::Undef
}
fn b_byref_out(vm: &mut VM, _: u8) -> Value {
let pos = vm.pop().to_int().max(0) as usize;
with_host(|h| h.byref_out_get(pos))
}
fn b_byref_live(vm: &mut VM, _: u8) -> Value {
let pos = vm.pop().to_int().max(0) as usize;
Value::bool(with_host(|h| h.byref_out_live(pos)))
}
fn b_ref_cell(vm: &mut VM, _: u8) -> Value {
let name = pop_name(vm);
with_host(|h| h.ref_cell_of(&name))
}
fn b_ref_bind(vm: &mut VM, _: u8) -> Value {
let source = pop_name(vm);
let target = pop_name(vm);
with_host(|h| {
h.ref_bind(&target, &source);
h.get_var(&target)
})
}
fn b_ref_slot_var(vm: &mut VM, _: u8) -> Value {
let name = pop_name(vm);
Value::int(with_host(|h| h.elem_ref_slot(&name, &[])) as i64)
}
fn b_ref_slot_elem(vm: &mut VM, argc: u8) -> Value {
let keys = pop_args(vm, argc as usize - 1);
let name = pop_name(vm);
Value::int(with_host(|h| h.elem_ref_slot(&name, &keys)) as i64)
}
fn b_ref_slot_prop(vm: &mut VM, _: u8) -> Value {
let prop = pop_name(vm);
let recv = vm.pop();
Value::int(with_host(|h| h.prop_ref_slot_ensure(&recv, &prop)) as i64)
}
fn b_ref_to_var(vm: &mut VM, _: u8) -> Value {
let slot = vm.pop().to_int() as usize;
let name = pop_name(vm);
with_host(|h| {
h.bind_ref_slot(&name, slot);
h.get_var(&name)
})
}
fn b_ref_to_elem(vm: &mut VM, argc: u8) -> Value {
let slot = vm.pop().to_int() as usize;
let keys = pop_args(vm, argc as usize - 2);
let name = pop_name(vm);
with_host(|h| {
h.bind_elem_to_slot(&name, &keys, slot);
h.ref_cell_value(slot)
})
}
fn b_ref_to_append(vm: &mut VM, argc: u8) -> Value {
let slot = vm.pop().to_int() as usize;
let keys = pop_args(vm, argc as usize - 2);
let name = pop_name(vm);
match with_host(|h| -> Result<Value, String> {
h.append_elem_to_slot(&name, &keys, slot)?;
Ok(h.ref_cell_value(slot))
}) {
Ok(v) => v,
Err(e) => fail_or_throw(vm, throws_bare("Error", e)),
}
}
fn b_ref_to_prop(vm: &mut VM, _: u8) -> Value {
let slot = vm.pop().to_int() as usize;
let prop = pop_name(vm);
let recv = vm.pop();
with_host(|h| {
h.bind_prop_to_slot(&recv, &prop, slot);
h.ref_cell_value(slot)
})
}
fn b_ret_ref(vm: &mut VM, _: u8) -> Value {
let slot = vm.pop().to_int() as usize;
with_host(|h| {
h.set_ret_ref_slot(slot);
h.ref_cell_value(slot)
})
}
fn b_ref_slot_ret(vm: &mut VM, _: u8) -> Value {
let v = vm.pop();
Value::int(with_host(|h| h.take_ret_ref_slot(v)) as i64)
}
fn b_lsb_class(vm: &mut VM, _: u8) -> Value {
let fallback = pop_name(vm);
Value::str(with_host(|h| h.lsb_class(&fallback)))
}
fn b_lsb_forward(_: &mut VM, _: u8) -> Value {
with_host(|h| h.lsb_forward());
Value::Undef
}
fn b_instanceof(vm: &mut VM, _: u8) -> Value {
let target = pop_name(vm);
let obj = vm.pop();
Value::bool(with_host(|h| match h.object_class(&obj) {
Some(class) => h.is_a_class(&class, &target),
None => false,
}))
}
fn b_dyn_class(vm: &mut VM, _: u8) -> Value {
let v = vm.pop();
if let Value::Str(s) = &v {
return Value::str(s.to_string());
}
match with_host(|h| h.object_class(&v)) {
Some(class) => Value::str(class),
None => throw_php(vm, "Error", "Class name must be a valid object or a string"),
}
}
fn b_dyn_class_const(vm: &mut VM, _: u8) -> Value {
let v = vm.pop();
match with_host(|h| h.object_class(&v).filter(|_| !h.is_array(&v))) {
Some(class) => Value::str(class),
None => {
let what = with_host(|h| crate::stdlib::types::value_name(h, &v));
throw_php(
vm,
"TypeError",
&format!("Cannot use \"::class\" on {what}"),
)
}
}
}
fn b_clone(vm: &mut VM, _: u8) -> Value {
let v = vm.pop();
mark_frame_line(vm);
match host::clone_object(v) {
Ok(copy) => bubbled(vm, copy),
Err(e) => fail_or_throw(vm, e),
}
}
fn b_foreach_prep(vm: &mut VM, _: u8) -> Value {
let v = vm.pop();
match host::foreach_prep(v) {
Ok(a) => {
if bubble_throw(vm) {
Value::Undef
} else {
a
}
}
Err(e) => fail(vm, e),
}
}
fn b_const_fetch(vm: &mut VM, _: u8) -> Value {
let name = pop_name(vm);
match with_host(|h| h.const_fetch(&name)) {
Some(v) => v,
None => {
mark_frame_line(vm);
throw_php(vm, "Error", &undefined_constant(&name))
}
}
}
fn b_magic_file(vm: &mut VM, _: u8) -> Value {
let suffix = pop_name(vm);
let prefix = pop_name(vm);
let file = with_host(|h| h.script_name().to_string());
Value::str(format!("{prefix}{file}{suffix}"))
}
fn b_magic_dir(vm: &mut VM, _: u8) -> Value {
let _ = vm;
Value::str(with_host(|h| h.magic_dir()))
}
fn b_magic_class(vm: &mut VM, _: u8) -> Value {
let suffix = pop_name(vm);
let prefix = pop_name(vm);
let class = with_host(|h| h.magic_class());
Value::str(format!("{prefix}{class}{suffix}"))
}
pub(crate) fn undefined_constant(name: &str) -> String {
format!("Undefined constant \"{name}\"")
}
fn b_unset_var(vm: &mut VM, _: u8) -> Value {
let name = pop_name(vm);
with_host(|h| h.unset_var(&name));
Value::Undef
}
fn b_unset_path(vm: &mut VM, argc: u8) -> Value {
let keys = pop_args(vm, argc as usize - 1);
let name = pop_name(vm);
mark_warn_site(vm);
let recv = with_host(|h| h.get_var(&name));
if keys.len() == 1 {
if let Some(r) = array_access_call(vm, &recv, "offsetUnset", vec![keys[0].clone()]) {
return match r {
Ok(_) => bubbled(vm, Value::Undef),
Err(e) => fail(vm, e),
};
}
}
with_host(|h| h.unset_path(&name, &keys));
Value::Undef
}
fn bubble_throw(vm: &mut VM) -> bool {
if host::unwinding() {
vm.ip = vm.chunk.ops.len();
true
} else {
false
}
}
fn b_throw(vm: &mut VM, _: u8) -> Value {
let exc = vm.pop();
host::set_pending_throw(exc);
vm.ip = vm.chunk.ops.len();
Value::Undef
}
fn b_run_try(vm: &mut VM, _: u8) -> Value {
let id = vm.pop().to_int();
match host::run_try_orchestrator(id) {
Ok(status) => Value::int(status),
Err(e) => fail(vm, e),
}
}
fn b_sig_halt(vm: &mut VM, _: u8) -> Value {
vm.ip = vm.chunk.ops.len();
Value::Undef
}
fn b_sig_break(vm: &mut VM, argc: u8) -> Value {
let level = sig_level_arg(vm, argc);
host::set_break(level);
vm.ip = vm.chunk.ops.len();
Value::Undef
}
fn b_sig_continue(vm: &mut VM, argc: u8) -> Value {
let level = sig_level_arg(vm, argc);
host::set_continue(level);
vm.ip = vm.chunk.ops.len();
Value::Undef
}
fn sig_level_arg(vm: &mut VM, argc: u8) -> u32 {
if argc == 0 {
return 1;
}
vm.pop().to_int().max(1) as u32
}
fn b_sig_level(_: &mut VM, _: u8) -> Value {
Value::int(host::last_break_level() as i64)
}
fn pop_two_ints(vm: &mut VM, sym: &str) -> Option<(i64, i64)> {
let b = vm.pop();
let a = vm.pop();
int_args(vm, sym, &a, &b)
}
fn int_args(vm: &mut VM, sym: &str, a: &Value, b: &Value) -> Option<(i64, i64)> {
mark_warn_site(vm);
let resolve = || -> Result<(i64, i64), String> {
Ok((
int_arith_operand(sym, a, b, true)?,
int_arith_operand(sym, a, b, false)?,
))
};
match resolve() {
Ok(pair) => Some(pair),
Err(_) => {
mark_frame_line(vm);
vm.ip = vm.chunk.ops.len();
None
}
}
}
fn int_operand(orig: &Value, coerced: &Value) -> i64 {
let Value::Float(f) = *coerced else {
return coerced.to_int();
};
let out_of_range = !f.is_finite() || f < i64::MIN as f64 || f > i64::MAX as f64;
let lossy = out_of_range || f.fract() != 0.0;
if let Value::Str(s) = orig {
if lossy && host::numeric_prefix_is_float(s) {
with_host(|h| {
h.deprecated(format!(
"Implicit conversion from float-string \"{s}\" to int loses precision"
))
});
}
return if f.is_finite() { f as i64 } else { 0 };
}
if out_of_range {
let shown = with_host(|h| h.to_str(&Value::float(f)));
with_host(|h| {
h.warn(format!(
"The float {shown} is not representable as an int, cast occurred"
))
});
return 0;
}
if f.fract() != 0.0 {
let shown = with_host(|h| h.to_str(&Value::float(f)));
with_host(|h| {
h.deprecated(format!(
"Implicit conversion from float {shown} to int loses precision"
))
});
}
f as i64
}
fn int_arith_operand(sym: &str, a: &Value, b: &Value, left: bool) -> Result<i64, String> {
let n = coerce_arith(sym, a, b, left)?;
Ok(int_operand(if left { a } else { b }, &n))
}
fn pop_two_strs(vm: &mut VM) -> Option<(Vec<u8>, Vec<u8>)> {
match (vm.stack.iter().nth_back(1), vm.stack.last()) {
(Some(Value::Str(x)), Some(Value::Str(y))) => {
let (x, y) = (x.as_bytes().to_vec(), y.as_bytes().to_vec());
vm.pop();
vm.pop();
Some((x, y))
}
_ => None,
}
}
fn b_bitand(vm: &mut VM, _: u8) -> Value {
if let Some((x, y)) = pop_two_strs(vm) {
return str_bitop(&x, &y, false, |p, q| p & q);
}
let Some((a, b)) = pop_two_ints(vm, "&") else {
return Value::Undef;
};
Value::int(a & b)
}
fn b_bitor(vm: &mut VM, _: u8) -> Value {
if let Some((x, y)) = pop_two_strs(vm) {
return str_bitop(&x, &y, true, |p, q| p | q);
}
let Some((a, b)) = pop_two_ints(vm, "|") else {
return Value::Undef;
};
Value::int(a | b)
}
fn b_bitxor(vm: &mut VM, _: u8) -> Value {
if let Some((x, y)) = pop_two_strs(vm) {
return str_bitop(&x, &y, false, |p, q| p ^ q);
}
let Some((a, b)) = pop_two_ints(vm, "^") else {
return Value::Undef;
};
Value::int(a ^ b)
}
fn str_bitop(x: &[u8], y: &[u8], pad: bool, f: impl Fn(u8, u8) -> u8) -> Value {
let n = if pad {
x.len().max(y.len())
} else {
x.len().min(y.len())
};
Value::str(
(0..n)
.map(|i| {
f(
x.get(i).copied().unwrap_or(0),
y.get(i).copied().unwrap_or(0),
) as char
})
.collect::<String>(),
)
}
fn b_shl(vm: &mut VM, _: u8) -> Value {
let Some((a, b)) = pop_two_ints(vm, "<<") else {
return Value::Undef;
};
if b < 0 {
return throw_php(vm, "ArithmeticError", "Bit shift by negative number");
}
if b >= 64 {
return Value::int(0);
}
Value::int(a.wrapping_shl(b as u32))
}
fn b_shr(vm: &mut VM, _: u8) -> Value {
let Some((a, b)) = pop_two_ints(vm, ">>") else {
return Value::Undef;
};
if b < 0 {
return throw_php(vm, "ArithmeticError", "Bit shift by negative number");
}
Value::int(a >> b.min(63))
}
fn b_bitnot(vm: &mut VM, _: u8) -> Value {
let v = vm.pop();
match &v {
Value::Str(s) => str_bitop(s.as_bytes(), s.as_bytes(), false, |p, _| !p),
Value::Obj(_) => {
let what = with_host(|h| host::arith_type_name(h, &v));
mark_frame_line(vm);
throw_php(
vm,
"TypeError",
&format!("Cannot perform bitwise not on {what}"),
)
}
_ => Value::int(!with_host(|h| h.to_number(&v).to_int())),
}
}
fn b_spaceship(vm: &mut VM, _: u8) -> Value {
let b = vm.pop();
let a = vm.pop();
Value::int(with_host(|h| php_compare(h, &a, &b)) as i64)
}
fn b_dbg_line(vm: &mut VM, _: u8) -> Value {
let _line = vm.pop();
crate::dap::on_debug_line(vm);
Value::Undef
}
fn pop_args(vm: &mut VM, n: usize) -> Vec<Value> {
let mut v = Vec::with_capacity(n);
for _ in 0..n {
v.push(vm.pop());
}
v.reverse();
v
}
fn pop_name(vm: &mut VM) -> std::sync::Arc<String> {
match vm.pop() {
Value::Str(s) => s,
other => std::sync::Arc::new(with_host(|h| h.to_str(&other))),
}
}
fn fail(vm: &mut VM, msg: impl Into<String>) -> Value {
with_host(|h| h.set_error(msg));
vm.ip = vm.chunk.ops.len();
Value::Undef
}
fn incdec_refused(vm: &mut VM, old: &Value, inc: bool) -> bool {
if !matches!(old, Value::Obj(_)) {
return false;
}
let what = with_host(|h| host::arith_type_name(h, old));
let word = if inc { "increment" } else { "decrement" };
mark_frame_line(vm);
throw_php(vm, "TypeError", &format!("Cannot {word} {what}"));
true
}
fn fail_or_throw(vm: &mut VM, e: String) -> Value {
match untag_bare_throw(&e) {
Some((class, message)) => {
let (class, message) = (class.to_string(), message.to_string());
throw_php(vm, &class, &message)
}
None => fail(vm, e),
}
}
fn throw_php(vm: &mut VM, class: &str, message: &str) -> Value {
mark_frame_line(vm);
match pending_php_throw(class, message) {
Ok(_) => {
vm.ip = vm.chunk.ops.len();
Value::Undef
}
Err(e) => fail(vm, e),
}
}
fn method_plan(vm: &mut VM, class: &str, method: &str, has_this: bool) -> Result<bool, Value> {
match with_host(|h| h.method_dispatch(class, method, has_this)) {
host::MethodDispatch::Direct => Ok(false),
host::MethodDispatch::Magic => Ok(true),
host::MethodDispatch::Denied(msg) => Err(throw_php(vm, "Error", &msg)),
host::MethodDispatch::Undefined => Err(throw_php(
vm,
"Error",
&format!(
"Call to undefined method {}::{method}()",
host::display_class(class)
),
)),
}
}
fn static_method_plan(
vm: &mut VM,
class: &str,
method: &str,
this: &Option<Value>,
) -> Result<bool, Value> {
if class.eq_ignore_ascii_case("Closure") {
return Ok(false);
}
if !with_host(|h| h.class_exists(class)) {
return Err(throw_php(
vm,
"Error",
&format!("Class \"{}\" not found", host::display_class(class)),
));
}
if with_host(|h| h.is_enum_class(class))
&& matches!(
method.to_ascii_lowercase().as_str(),
"cases" | "from" | "tryfrom"
)
{
return Ok(false);
}
let has_this = this
.as_ref()
.and_then(|t| with_host(|h| h.object_class(t)))
.is_some_and(|c| with_host(|h| h.class_is_a_pub(&c, class)));
method_plan(vm, class, method, has_this)
}
fn receiver_type_name(h: &host::PhpHost, v: &Value) -> &'static str {
match v {
Value::Undef => "null",
Value::Bool(true) => "true",
Value::Bool(false) => "false",
Value::Int(_) => "int",
Value::Float(_) => "float",
Value::Str(_) => "string",
Value::Obj(_) if h.is_array(v) => "array",
_ => "mixed",
}
}
fn pending_php_throw(class: &str, message: &str) -> Result<Value, String> {
let exc = host::new_object(class, vec![Value::str(message.to_string())])?;
host::set_pending_throw(exc);
Ok(Value::Undef)
}
fn b_echo(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc as usize);
mark_warn_site(vm);
for a in &args {
let s = host::to_str_ext(a);
with_host(|h| h.write_out(&s));
}
Value::Undef
}
fn mark_warn_site(vm: &VM) {
host::set_warn_line(cur_op_line(vm));
}
fn cur_op_line(vm: &VM) -> u32 {
vm.ip
.checked_sub(1)
.and_then(|i| vm.chunk.lines.get(i))
.copied()
.unwrap_or(0)
}
fn mark_frame_line(vm: &VM) {
let line = cur_op_line(vm);
with_host(|h| {
h.set_cur_line(line);
host::set_warn_line(line);
});
}
fn b_getslot(vm: &mut VM, _: u8) -> Value {
let i = vm.pop().to_int() as u32;
mark_warn_site(vm);
with_host(|h| h.slot_get(i))
}
fn b_getslot_q(vm: &mut VM, _: u8) -> Value {
let i = vm.pop().to_int() as u32;
with_host(|h| h.slot_get_quiet(i))
}
fn b_setslot(vm: &mut VM, _: u8) -> Value {
let val = vm.pop();
let i = vm.pop().to_int() as u32;
with_host(|h| h.slot_set(i, val.clone()));
val
}
fn b_getvar(vm: &mut VM, _: u8) -> Value {
let name = pop_name(vm);
mark_warn_site(vm);
with_host(|h| h.get_var_warn(&name))
}
fn b_getvar_q(vm: &mut VM, _: u8) -> Value {
let name = pop_name(vm);
with_host(|h| h.get_var(&name))
}
fn b_setvar(vm: &mut VM, _: u8) -> Value {
let val = vm.pop();
let name = pop_name(vm);
with_host(|h| h.set_var(&name, val.clone()));
val
}
fn b_copy(vm: &mut VM, _: u8) -> Value {
let val = vm.pop();
with_host(|h| h.copy_on_assign(val))
}
fn b_concat(vm: &mut VM, _: u8) -> Value {
let b = vm.pop();
let a = vm.pop();
mark_warn_site(vm);
let (a, b) = (host::to_str_ext(&a), host::to_str_ext(&b));
Value::str(format!("{a}{b}"))
}
fn b_truthy(vm: &mut VM, _: u8) -> Value {
let v = vm.pop();
Value::bool(with_host(|h| h.is_truthy(&v)))
}
fn b_call(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc as usize - 1);
let name = pop_name(vm);
mark_frame_line(vm);
match host::call_function(&name, args) {
Ok(v) => bubbled(vm, v),
Err(e) => fail(vm, e),
}
}
fn b_minmax_flf2(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc as usize - 1);
let name = pop_name(vm);
mark_frame_line(vm);
if with_host(|h| h.function_defined(&name)) {
return match host::call_function(&name, args) {
Ok(v) => bubbled(vm, v),
Err(e) => fail(vm, e),
};
}
let want_max = name.eq_ignore_ascii_case("max");
let v = with_host(|h| minmax_frameless(h, &args[0], &args[1], want_max));
bubbled(vm, v)
}
fn b_incdec_step(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc as usize);
let inc = args[1].to_int() != 0;
let old = args[0].clone();
mark_warn_site(vm);
if incdec_refused(vm, &old, inc) {
return Value::Undef;
}
with_host(|h| h.incdec_value(&old, inc))
}
fn b_global_bind(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc as usize);
let name = with_host(|h| h.to_str(&args[0]));
with_host(|h| h.bind_global(&name));
Value::Undef
}
fn b_byref_arg_diag(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc as usize);
let (kind, callee, argno, param) = (
args[0].to_int(),
with_host(|h| h.to_str(&args[1])),
args[2].to_int(),
with_host(|h| h.to_str(&args[3])),
);
mark_frame_line(vm);
if kind == 0 {
with_host(|h| h.notice("Only variables should be passed by reference"));
return Value::Undef;
}
let named = if param.is_empty() {
String::new()
} else {
format!(" (${param})")
};
fail_or_throw(
vm,
throws_bare(
"Error",
format!("{callee}(): Argument #{argno}{named} could not be passed by reference"),
),
)
}
fn bubbled(vm: &mut VM, v: Value) -> Value {
if bubble_throw(vm) {
Value::Undef
} else {
v
}
}
fn b_call_spread(vm: &mut VM, argc: u8) -> Value {
let pairs = pop_args(vm, argc as usize - 1);
let name = pop_name(vm);
let mut args = Vec::with_capacity(pairs.len() / 2);
with_host(|h| {
let mut it = pairs.into_iter();
while let (Some(flag), Some(val)) = (it.next(), it.next()) {
if h.is_truthy(&flag) {
if let Some(entries) = h.array_pairs(&val) {
args.extend(entries.into_iter().map(|(_, v)| v));
}
} else {
args.push(val);
}
}
});
mark_frame_line(vm);
match host::call_function(&name, args) {
Ok(v) => bubbled(vm, v),
Err(e) => fail(vm, e),
}
}
fn b_mkclosure(vm: &mut VM, argc: u8) -> Value {
let raw = pop_args(vm, argc as usize);
let mut it = raw.into_iter();
let def_name = match it.next() {
Some(v) => with_host(|h| h.to_str(&v)),
None => return Value::Undef,
};
let mut captured = Vec::new();
while let Some(k) = it.next() {
let Some(v) = it.next() else { break };
let name = with_host(|h| h.to_str(&k));
captured.push((name, v));
}
with_host(|h| h.make_closure(&def_name, captured))
}
fn b_call_value(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc as usize - 1);
let callee = vm.pop();
mark_frame_line(vm);
match host::call_value(callee, args) {
Ok(v) => bubbled(vm, v),
Err(e) => fail_or_throw(vm, e),
}
}
fn b_mkarray(vm: &mut VM, argc: u8) -> Value {
let raw = pop_args(vm, argc as usize);
mark_warn_site(vm);
with_host(|h| {
let arr = h.new_array();
fill_array(h, &arr, raw.into_iter());
arr
})
}
fn b_mkarray_add(vm: &mut VM, argc: u8) -> Value {
let raw = pop_args(vm, argc as usize);
mark_warn_site(vm);
let mut it = raw.into_iter();
let Some(arr) = it.next() else {
return Value::Undef;
};
with_host(|h| fill_array(h, &arr, it));
arr
}
fn fill_array(h: &mut host::PhpHost, arr: &Value, mut it: impl Iterator<Item = Value>) {
while let Some(k) = it.next() {
let Some(v) = it.next() else { break };
if host::is_auto_index(&k) {
h.arr_push_auto(arr, v);
} else {
h.arr_set_key(arr, &k, v);
}
}
}
fn array_access_call(
vm: &mut VM,
recv: &Value,
method: &str,
args: Vec<Value>,
) -> Option<Result<Value, String>> {
let class = with_host(|h| h.array_access_class(recv))?;
mark_frame_line(vm);
Some(host::call_method(&class, method, Some(recv.clone()), args))
}
fn array_access_result(vm: &mut VM, r: Result<Value, String>) -> Value {
match r {
Ok(v) => bubbled(vm, v),
Err(e) => fail(vm, e),
}
}
fn b_index_get(vm: &mut VM, _: u8) -> Value {
let key = vm.pop();
let recv = vm.pop();
if let Some(r) = array_access_call(vm, &recv, "offsetGet", vec![key.clone()]) {
return array_access_result(vm, r);
}
if let Some(e) = bad_string_offset(&recv, &key) {
return fail_or_throw(vm, e);
}
mark_warn_site(vm);
with_host(|h| h.index_get_warn(&recv, &key))
}
fn bad_string_offset(recv: &Value, key: &Value) -> Option<String> {
if !matches!(recv, Value::Str(_)) {
return None;
}
if !matches!(host::classify_string_offset(key), host::StrOffset::Bad) {
return None;
}
let t = with_host(|h| h.type_name_for_error(key));
Some(throws_bare(
"TypeError",
format!("Cannot access offset of type {t} on string"),
))
}
fn b_index_get_q(vm: &mut VM, _: u8) -> Value {
let key = vm.pop();
let recv = vm.pop();
if with_host(|h| h.array_access_class(&recv)).is_some() {
let present = match array_access_call(vm, &recv, "offsetExists", vec![key.clone()]) {
Some(Ok(v)) => with_host(|h| h.is_truthy(&v)),
Some(Err(e)) => return fail(vm, e),
None => false,
};
if !present {
return Value::Undef;
}
let r = array_access_call(vm, &recv, "offsetGet", vec![key]);
return match r {
Some(r) => array_access_result(vm, r),
None => Value::Undef,
};
}
mark_warn_site(vm);
with_host(|h| {
h.diagnose_quiet_offset(&recv, &key);
h.index_get(&recv, &key)
})
}
fn b_list_elem_get(vm: &mut VM, _: u8) -> Value {
let key = vm.pop();
let recv = vm.pop();
let is_obj = with_host(|h| matches!(recv, Value::Obj(_)) && !h.is_array(&recv));
if is_obj {
let cls = with_host(|h| h.object_class(&recv).unwrap_or_else(|| "object".into()));
return throw_php(
vm,
"Error",
&format!("Cannot use object of type {cls} as array"),
);
}
if with_host(|h| h.is_array(&recv)) {
mark_warn_site(vm);
return with_host(|h| h.index_get_warn(&recv, &key));
}
if matches!(recv, Value::Undef) {
return Value::Undef;
}
let ty = match recv {
Value::Bool(_) => "bool",
Value::Int(_) => "int",
Value::Float(_) => "float",
Value::Str(_) => "string",
_ => "mixed",
};
mark_warn_site(vm);
with_host(|h| h.warn(format_args!("Cannot use {ty} as array")));
Value::Undef
}
fn b_const_decl(vm: &mut VM, _: u8) -> Value {
let value = vm.pop();
let name = pop_name(vm);
let line = cur_op_line(vm);
with_host(|h| {
host::set_warn_line(line);
h.const_define(&name, value)
});
Value::Undef
}
fn b_decl_fatal(vm: &mut VM, _: u8) -> Value {
let msg = with_host(|h| h.to_str(&vm.pop()));
let line = cur_op_line(vm);
let body = with_host(|h| {
let trace = h.backtrace();
format!(
"{msg} in {} on line {line}\nStack trace:\n{trace}",
h.script_name()
)
});
with_host(|h| {
h.fatal("Fatal error", &body);
h.ob_flush_all();
});
fail(vm, format!("Fatal error: {body}"))
}
fn b_index_isset(vm: &mut VM, _: u8) -> Value {
let key = vm.pop();
let recv = vm.pop();
if let Some(r) = array_access_call(vm, &recv, "offsetExists", vec![key.clone()]) {
return match r {
Ok(v) => {
let b = with_host(|h| h.is_truthy(&v));
bubbled(vm, Value::bool(b))
}
Err(e) => fail(vm, e),
};
}
mark_warn_site(vm);
with_host(|h| {
h.diagnose_quiet_offset(&recv, &key);
Value::bool(!matches!(h.index_get(&recv, &key), Value::Undef))
})
}
fn b_index_set(vm: &mut VM, _: u8) -> Value {
let val = vm.pop();
let key = vm.pop();
let name = pop_name(vm);
let recv = with_host(|h| h.get_var(&name));
if let Some(r) = array_access_call(vm, &recv, "offsetSet", vec![key.clone(), val.clone()]) {
if let Err(e) = r {
return fail(vm, e);
}
return bubbled(vm, val);
}
let line = cur_op_line(vm);
mark_frame_line(vm);
if let Err(e) = with_host(|h| {
host::set_warn_line(line);
h.index_set_var(&name, &key, val.clone())
}) {
return fail_or_throw(vm, e);
}
val
}
fn b_arr_append(vm: &mut VM, _: u8) -> Value {
let val = vm.pop();
let name = pop_name(vm);
let recv = with_host(|h| h.get_var(&name));
if let Some(r) = array_access_call(vm, &recv, "offsetSet", vec![Value::Undef, val.clone()]) {
if let Err(e) = r {
return fail(vm, e);
}
return bubbled(vm, val);
}
if let Err(e) = with_host(|h| h.append_var(&name, val.clone())) {
return fail_or_throw(vm, throws_bare("Error", e));
}
val
}
fn b_set_path(vm: &mut VM, argc: u8) -> Value {
let val = vm.pop();
let keys = pop_args(vm, argc as usize - 2);
let name = pop_name(vm);
with_host(|h| h.index_set_path(&name, &keys, val.clone()));
val
}
fn b_append_path(vm: &mut VM, argc: u8) -> Value {
let val = vm.pop();
let keys = pop_args(vm, argc as usize - 2);
let name = pop_name(vm);
with_host(|h| h.append_path(&name, &keys, val.clone()));
val
}
fn b_get_path(vm: &mut VM, argc: u8) -> Value {
let keys = pop_args(vm, argc as usize - 1);
let name = pop_name(vm);
mark_warn_site(vm);
with_host(|h| h.index_get_path_warn(&name, &keys))
}
fn b_incdec_path(vm: &mut VM, argc: u8) -> Value {
let code = vm.pop().to_int();
let keys = pop_args(vm, argc as usize - 2);
let name = pop_name(vm);
let inc = code & 1 != 0;
let prefix = code & 2 != 0;
mark_warn_site(vm);
let old = with_host(|h| h.index_get_path_warn(&name, &keys));
if incdec_refused(vm, &old, inc) {
return Value::Undef;
}
with_host(|h| {
let newv = h.incdec_value(&old, inc);
h.index_set_path(&name, &keys, newv.clone());
if prefix {
newv
} else {
old
}
})
}
fn b_path_append_child(vm: &mut VM, argc: u8) -> Value {
let keys = pop_args(vm, argc as usize - 1);
let name = pop_name(vm);
with_host(|h| h.path_append_child(&name, &keys))
}
fn b_sig_return(vm: &mut VM, _: u8) -> Value {
let v = vm.pop();
host::set_return(v);
vm.ip = vm.chunk.ops.len();
Value::Undef
}
fn b_incdec(vm: &mut VM, _: u8) -> Value {
let code = vm.pop().to_int();
let name = pop_name(vm);
let inc = code & 1 != 0;
let prefix = code & 2 != 0;
mark_warn_site(vm);
let old = with_host(|h| h.get_var_warn(&name));
if incdec_refused(vm, &old, inc) {
return Value::Undef;
}
with_host(|h| {
let newv = h.incdec_value(&old, inc);
h.set_var(&name, newv.clone());
if prefix {
newv
} else {
old
}
})
}
fn b_incdec_slot(vm: &mut VM, _: u8) -> Value {
let code = vm.pop().to_int();
let i = vm.pop().to_int() as u32;
let inc = code & 1 != 0;
let prefix = code & 2 != 0;
mark_warn_site(vm);
let old = with_host(|h| h.slot_get(i));
if incdec_refused(vm, &old, inc) {
return Value::Undef;
}
with_host(|h| {
let newv = h.incdec_value(&old, inc);
h.slot_set(i, newv.clone());
if prefix {
newv
} else {
old
}
})
}
fn b_arraykeys(vm: &mut VM, _: u8) -> Value {
let recv = vm.pop();
with_host(|h| h.array_keys(&recv))
}
fn b_arraylen(vm: &mut VM, _: u8) -> Value {
let recv = vm.pop();
Value::int(with_host(|h| h.array_len(&recv)))
}
fn b_arr_mut(vm: &mut VM, argc: u8) -> Value {
use host::arrmut;
let mut args = pop_args(vm, argc as usize);
let name = with_host(|h| h.to_str(&args[0]));
let sub = args[1].to_int();
let extra: Vec<Value> = args.split_off(2);
let r = with_host(|h| match sub {
arrmut::PUSH => h.arr_push_var(&name, extra),
arrmut::POP => Ok(h.arr_pop_var(&name)),
arrmut::SHIFT => Ok(h.arr_shift_var(&name)),
arrmut::UNSHIFT => Ok(h.arr_unshift_var(&name, extra)),
arrmut::SPLICE => Ok(h.arr_splice_var(&name, &extra)),
_ => Ok(Value::Undef),
});
match r {
Ok(v) => v,
Err(e) => fail_or_throw(vm, throws_bare("Error", e)),
}
}
fn b_new(vm: &mut VM, argc: u8) -> Value {
let mut args = pop_args(vm, argc as usize);
let class = with_host(|h| h.to_str(&args.remove(0)));
mark_frame_line(vm);
match host::new_object(&class, args) {
Ok(v) => bubbled(vm, v),
Err(e) => fail_or_throw(vm, e),
}
}
fn call_magic(recv: &Value, name: &str, magic: &'static str, args: Vec<Value>) -> Value {
let Some(class) = with_host(|h| h.object_class(recv)) else {
return Value::Undef;
};
with_host(|h| h.magic_enter(recv, name, magic));
let out = host::call_method(&class, magic, Some(recv.clone()), args);
with_host(|h| h.magic_leave());
out.unwrap_or(Value::Undef)
}
macro_rules! prop_plan {
($vm:expr, $recv:expr, $name:expr, $magic:expr) => {{
mark_frame_line($vm);
with_host(|h| h.prop_access(&$recv, &$name, $magic))
}};
}
fn b_prop_get(vm: &mut VM, _: u8) -> Value {
let name = pop_name(vm);
let recv = vm.pop();
match prop_plan!(vm, recv, name, "__get") {
PropAccess::Direct => {
mark_warn_site(vm);
with_host(|h| h.prop_get_warn(&recv, &name))
}
PropAccess::Magic => {
let v = call_magic(&recv, &name, "__get", vec![Value::Str(name.clone())]);
bubbled(vm, v)
}
PropAccess::Denied(msg) => throw_php(vm, "Error", &msg),
PropAccess::Absent => {
mark_warn_site(vm);
with_host(|h| h.prop_get_warn(&recv, &name))
}
}
}
fn b_prop_get_q(vm: &mut VM, _: u8) -> Value {
let name = pop_name(vm);
let recv = vm.pop();
prop_quiet_read(vm, &recv, &name, true)
}
fn b_prop_get_empty(vm: &mut VM, _: u8) -> Value {
let name = pop_name(vm);
let recv = vm.pop();
prop_quiet_read(vm, &recv, &name, false)
}
fn prop_quiet_read(vm: &mut VM, recv: &Value, name: &str, get_without_isset: bool) -> Value {
let recv = recv.clone();
let name = name.to_string();
if let PropAccess::Direct = prop_plan!(vm, recv, name, "__isset") {
return with_host(|h| h.prop_get(&recv, &name));
}
let has_isset = matches!(prop_plan!(vm, recv, name, "__isset"), PropAccess::Magic);
if has_isset {
let present = call_magic(&recv, &name, "__isset", vec![Value::str(name.clone())]);
if bubble_throw(vm) {
return Value::Undef;
}
if !with_host(|h| h.is_truthy(&present)) {
return Value::Undef;
}
} else if !get_without_isset {
return Value::Undef;
}
match prop_plan!(vm, recv, name, "__get") {
PropAccess::Magic => {
let v = call_magic(&recv, &name, "__get", vec![Value::str(name.clone())]);
bubbled(vm, v)
}
PropAccess::Direct => with_host(|h| h.prop_get(&recv, &name)),
PropAccess::Denied(_) | PropAccess::Absent => Value::Undef,
}
}
fn b_prop_set(vm: &mut VM, _: u8) -> Value {
let val = vm.pop();
let name = pop_name(vm);
let recv = vm.pop();
match prop_plan!(vm, recv, name, "__set") {
PropAccess::Direct | PropAccess::Absent => {
if readonly_refused(vm, &recv, &name) {
return Value::Undef;
}
mark_warn_site(vm);
with_host(|h| h.prop_set_checked(&recv, &name, val.clone()));
val
}
PropAccess::Magic => {
call_magic(
&recv,
&name,
"__set",
vec![Value::Str(name.clone()), val.clone()],
);
bubbled(vm, val)
}
PropAccess::Denied(msg) => throw_php(vm, "Error", &msg),
}
}
fn readonly_refused(vm: &mut VM, recv: &Value, name: &str) -> bool {
match with_host(|h| h.readonly_write_error(recv, name)) {
Some(msg) => {
throw_php(vm, "Error", &msg);
true
}
None => {
with_host(|h| h.readonly_note_init(recv, name));
false
}
}
}
fn b_prop_set_rw(vm: &mut VM, _: u8) -> Value {
let val = vm.pop();
let name = pop_name(vm);
let recv = vm.pop();
let has_get = with_host(|h| {
h.object_class(&recv)
.is_some_and(|c| h.class_has_method(&c, "__get"))
});
match prop_plan!(vm, recv, name, "__set") {
PropAccess::Magic if has_get => {
call_magic(
&recv,
&name,
"__set",
vec![Value::Str(name.clone()), val.clone()],
);
bubbled(vm, val)
}
PropAccess::Denied(msg) => throw_php(vm, "Error", &msg),
_ if has_get => {
if readonly_refused(vm, &recv, &name) {
return Value::Undef;
}
mark_warn_site(vm);
with_host(|h| h.prop_set_checked(&recv, &name, val.clone()));
val
}
_ => {
if readonly_refused(vm, &recv, &name) {
return Value::Undef;
}
with_host(|h| h.prop_set(&recv, &name, val.clone()));
val
}
}
}
fn b_prop_isset(vm: &mut VM, _: u8) -> Value {
let name = pop_name(vm);
let recv = vm.pop();
match prop_plan!(vm, recv, name, "__isset") {
PropAccess::Direct => {
let v = with_host(|h| h.prop_get(&recv, &name));
Value::bool(!matches!(v, Value::Undef))
}
PropAccess::Magic => {
let present = call_magic(&recv, &name, "__isset", vec![Value::Str(name.clone())]);
if bubble_throw(vm) {
return Value::Undef;
}
Value::bool(with_host(|h| h.is_truthy(&present)))
}
PropAccess::Denied(_) | PropAccess::Absent => Value::bool(false),
}
}
fn b_prop_unset(vm: &mut VM, _: u8) -> Value {
let name = pop_name(vm);
let recv = vm.pop();
match prop_plan!(vm, recv, name, "__unset") {
PropAccess::Direct => {
if let Some(msg) = with_host(|h| h.readonly_unset_error(&recv, &name)) {
return throw_php(vm, "Error", &msg);
}
with_host(|h| h.prop_remove(&recv, &name));
Value::Undef
}
PropAccess::Magic => {
call_magic(&recv, &name, "__unset", vec![Value::Str(name.clone())]);
bubbled(vm, Value::Undef)
}
PropAccess::Denied(msg) => throw_php(vm, "Error", &msg),
PropAccess::Absent => Value::Undef,
}
}
fn b_prop_touch(vm: &mut VM, _: u8) -> Value {
let name = pop_name(vm);
let recv = vm.pop();
if let PropAccess::Magic = prop_plan!(vm, recv, name, "__get") {
return recv;
}
mark_warn_site(vm);
with_host(|h| h.warn_dynamic_prop(&recv, &name));
recv
}
fn b_prop_ensure_array(vm: &mut VM, _: u8) -> Value {
let name = pop_name(vm);
let recv = vm.pop();
if let PropAccess::Denied(msg) = prop_plan!(vm, recv, name, "__get") {
return throw_php(vm, "Error", &msg);
}
if let Some(msg) = with_host(|h| h.readonly_indirect_error(&recv, &name)) {
return throw_php(vm, "Error", &msg);
}
mark_warn_site(vm);
with_host(|h| {
h.warn_dynamic_prop(&recv, &name);
h.prop_ensure_array(&recv, &name)
})
}
fn b_suppress_push(_: &mut VM, _: u8) -> Value {
with_host(|h| h.suppress_push());
Value::Undef
}
fn b_suppress_pop(vm: &mut VM, _: u8) -> Value {
let v = vm.pop();
with_host(|h| h.suppress_pop());
v
}
fn b_prop_incdec(vm: &mut VM, _: u8) -> Value {
let code = vm.pop().to_int();
let name = pop_name(vm);
let recv = vm.pop();
let inc = code & 1 != 0;
let prefix = code & 2 != 0;
match prop_plan!(vm, recv, name, "__get") {
PropAccess::Denied(msg) => throw_php(vm, "Error", &msg),
PropAccess::Magic => {
let old = call_magic(&recv, &name, "__get", vec![Value::Str(name.clone())]);
if bubble_throw(vm) {
return Value::Undef;
}
if incdec_refused(vm, &old, inc) {
return Value::Undef;
}
let newv = with_host(|h| h.incdec_value(&old, inc));
let has_set = with_host(|h| {
h.object_class(&recv)
.is_some_and(|c| h.class_has_method(&c, "__set"))
});
if has_set {
call_magic(
&recv,
&name,
"__set",
vec![Value::Str(name.clone()), newv.clone()],
);
} else {
if readonly_refused(vm, &recv, &name) {
return Value::Undef;
}
mark_warn_site(vm);
with_host(|h| h.prop_set_checked(&recv, &name, newv.clone()));
}
bubbled(vm, if prefix { newv } else { old })
}
_ => {
mark_warn_site(vm);
let old = with_host(|h| {
h.warn_dynamic_prop(&recv, &name);
h.prop_get_warn(&recv, &name)
});
if incdec_refused(vm, &old, inc) {
return Value::Undef;
}
if readonly_refused(vm, &recv, &name) {
return Value::Undef;
}
with_host(|h| {
let newv = h.incdec_value(&old, inc);
h.prop_set(&recv, &name, newv.clone());
if prefix {
newv
} else {
old
}
})
}
}
}
fn b_mcall(vm: &mut VM, argc: u8) -> Value {
let mut args = pop_args(vm, argc as usize);
let recv = args.remove(0);
let method = with_host(|h| h.to_str(&args.remove(0)));
mark_frame_line(vm);
if with_host(|h| h.is_closure(&recv)) {
return match host::call_closure_method(&recv, &method, args) {
Ok(v) => bubbled(vm, v),
Err(e) => fail(vm, e),
};
}
if with_host(|h| h.is_generator_val(&recv)) {
return match host::call_generator_method(&recv, &method, args) {
Ok(v) => bubbled(vm, v),
Err(e) => yield_err(vm, e),
};
}
let class = with_host(|h| h.object_class(&recv));
match class {
Some(c) => {
let magic = match method_plan(vm, &c, &method, true) {
Ok(m) => m,
Err(v) => return v,
};
let r = if magic {
host::call_magic_call(&c, &method, Some(recv), args)
} else {
host::call_method(&c, &method, Some(recv), args)
};
match r {
Ok(v) => bubbled(vm, v),
Err(e) => fail(vm, e),
}
}
None => {
let ty = with_host(|h| receiver_type_name(h, &recv));
throw_php(
vm,
"Error",
&format!("Call to a member function {method}() on {ty}"),
)
}
}
}
fn b_scall(vm: &mut VM, argc: u8) -> Value {
let mut args = pop_args(vm, argc as usize);
let class = with_host(|h| h.to_str(&args.remove(0)));
let method = with_host(|h| h.to_str(&args.remove(0)));
let this = with_host(|h| {
let t = h.get_var("this");
matches!(t, Value::Obj(_)).then_some(t)
});
mark_frame_line(vm);
let magic = match static_method_plan(vm, &class, &method, &this) {
Ok(m) => m,
Err(v) => return v,
};
let r = if magic {
host::call_magic_call(&class, &method, this, args)
} else {
host::call_method(&class, &method, this, args)
};
match r {
Ok(v) => bubbled(vm, v),
Err(e) => fail_or_throw(vm, e),
}
}
fn b_sconst(vm: &mut VM, _: u8) -> Value {
let name = pop_name(vm);
let class = pop_name(vm);
match host::class_const(&class, &name) {
Ok(v) => v,
Err(e) => fail_or_throw(vm, e),
}
}
fn arith_args(vm: &mut VM, sym: &str, a: &Value, b: &Value) -> Option<(Value, Value)> {
mark_warn_site(vm);
match coerce_arith_pair(sym, a, b) {
Ok(pair) => Some(pair),
Err(_) => {
mark_frame_line(vm);
vm.ip = vm.chunk.ops.len();
None
}
}
}
fn b_div(vm: &mut VM, _: u8) -> Value {
let b = vm.pop();
let a = vm.pop();
let Some((an, bn)) = arith_args(vm, "/", &a, &b) else {
return Value::Undef;
};
if bn.to_float() == 0.0 {
return throw_php(vm, "DivisionByZeroError", "Division by zero");
}
match (an, bn) {
(Value::Int(i64::MIN), Value::Int(-1)) => Value::float(-(i64::MIN as f64)),
(Value::Int(x), Value::Int(y)) if x % y == 0 => Value::int(x / y),
(an, bn) => Value::float(an.to_float() / bn.to_float()),
}
}
fn b_mod(vm: &mut VM, _: u8) -> Value {
let b = vm.pop();
let a = vm.pop();
let Some((x, y)) = int_args(vm, "%", &a, &b) else {
return Value::Undef;
};
if y == 0 {
return throw_php(vm, "DivisionByZeroError", "Modulo by zero");
}
Value::int(x.wrapping_rem(y))
}
fn deprecate_zero_base_negative_exponent(an: &Value, bn: &Value) {
if an.to_float() == 0.0 && bn.to_float() < 0.0 {
with_host(|h| h.deprecated("Power of base 0 and negative exponent is deprecated"));
}
}
fn b_pow(vm: &mut VM, _: u8) -> Value {
let b = vm.pop();
let a = vm.pop();
let Some((an, bn)) = arith_args(vm, "**", &a, &b) else {
return Value::Undef;
};
deprecate_zero_base_negative_exponent(&an, &bn);
match (an, bn) {
(Value::Int(x), Value::Int(y)) if y >= 0 => {
if let Some(v) = checked_ipow(x, y as u32) {
Value::int(v)
} else {
Value::float((x as f64).powf(y as f64))
}
}
(an, bn) => Value::float(an.to_float().powf(bn.to_float())),
}
}
fn checked_ipow(mut base: i64, mut exp: u32) -> Option<i64> {
let mut acc: i64 = 1;
while exp > 0 {
if exp & 1 == 1 {
acc = acc.checked_mul(base)?;
}
exp >>= 1;
if exp > 0 {
base = base.checked_mul(base)?;
}
}
Some(acc)
}
fn b_loose_eq(vm: &mut VM, _: u8) -> Value {
let b = vm.pop();
let a = vm.pop();
Value::bool(with_host(|h| loose_eq(h, &a, &b)))
}
fn b_loose_ne(vm: &mut VM, _: u8) -> Value {
let b = vm.pop();
let a = vm.pop();
Value::bool(with_host(|h| !loose_eq(h, &a, &b)))
}
fn b_strict_eq(vm: &mut VM, _: u8) -> Value {
let b = vm.pop();
let a = vm.pop();
Value::bool(with_host(|h| strict_eq(h, &a, &b)))
}
fn b_strict_ne(vm: &mut VM, _: u8) -> Value {
let b = vm.pop();
let a = vm.pop();
Value::bool(with_host(|h| !strict_eq(h, &a, &b)))
}
fn b_lt(vm: &mut VM, _: u8) -> Value {
cmp_bool(vm, |o| o < 0)
}
fn b_gt(vm: &mut VM, _: u8) -> Value {
cmp_bool(vm, |o| o > 0)
}
fn b_le(vm: &mut VM, _: u8) -> Value {
cmp_bool(vm, |o| o <= 0)
}
fn b_ge(vm: &mut VM, _: u8) -> Value {
cmp_bool(vm, |o| o >= 0)
}
fn cmp_bool(vm: &mut VM, f: impl Fn(i32) -> bool) -> Value {
let b = vm.pop();
let a = vm.pop();
if is_unordered(&a, &b) {
return Value::bool(false);
}
Value::bool(f(with_host(|h| php_compare(h, &a, &b))))
}
fn loose_eq(h: &host::PhpHost, a: &Value, b: &Value) -> bool {
use Value::*;
match (a, b) {
(Bool(_), _) | (_, Bool(_)) => h.is_truthy(a) == h.is_truthy(b),
(Undef, x) | (x, Undef) => match x {
Int(n) => *n == 0,
Float(f) => *f == 0.0,
Str(s) => s.is_empty(),
Obj(_) => h.array_len(x) == 0,
Undef => true,
_ => false,
},
(Str(x), Str(y)) => {
if host::is_numeric_string(x) && host::is_numeric_string(y) {
num_eq(&as_php_number(h, a), &as_php_number(h, b))
} else {
x == y
}
}
(Obj(_), Obj(_)) => arrays_loose_eq(h, a, b),
(Obj(_), _) | (_, Obj(_)) => false,
(Float(f), Str(_)) | (Str(_), Float(f)) if f.is_nan() => false,
_ => {
if let Str(s) = a {
if !host::is_numeric_string(s) {
return h.to_str(a) == h.to_str(b);
}
}
if let Str(s) = b {
if !host::is_numeric_string(s) {
return h.to_str(a) == h.to_str(b);
}
}
num_eq(&h.to_number(a), &h.to_number(b))
}
}
}
fn num_eq(a: &Value, b: &Value) -> bool {
match (a, b) {
(Value::Int(x), Value::Int(y)) => x == y,
_ => a.to_float() == b.to_float(),
}
}
fn arrays_loose_eq(h: &host::PhpHost, a: &Value, b: &Value) -> bool {
if h.is_object(a) || h.is_object(b) {
let (Some(ca), Some(cb)) = (h.object_class(a), h.object_class(b)) else {
return false;
};
if !ca.eq_ignore_ascii_case(&cb) {
return false;
}
let (pa, pb) = (h.object_props(a), h.object_props(b));
return pa.len() == pb.len()
&& pa
.iter()
.all(|(name, va)| pb.iter().any(|(n, vb)| n == name && loose_eq(h, va, vb)));
}
let (Some(pa), Some(pb)) = (h.array_pairs(a), h.array_pairs(b)) else {
return false;
};
if pa.len() != pb.len() {
return false;
}
pa.iter().all(|(ka, va)| {
pb.iter()
.any(|(kb, vb)| strict_eq(h, ka, kb) && loose_eq(h, va, vb))
})
}
fn strict_eq(h: &host::PhpHost, a: &Value, b: &Value) -> bool {
use Value::*;
match (a, b) {
(Int(x), Int(y)) => x == y,
(Float(x), Float(y)) => x == y,
(Str(x), Str(y)) => x == y,
(Bool(x), Bool(y)) => x == y,
(Undef, Undef) => true,
(Obj(x), Obj(y)) => {
if x == y {
return true;
}
let (Some(pa), Some(pb)) = (h.array_pairs(a), h.array_pairs(b)) else {
return false;
};
pa.len() == pb.len()
&& pa
.iter()
.zip(pb.iter())
.all(|((ka, va), (kb, vb))| strict_eq(h, ka, kb) && strict_eq(h, va, vb))
}
_ => false,
}
}
fn php_compare(h: &host::PhpHost, a: &Value, b: &Value) -> i32 {
use Value::*;
match (a, b) {
(Undef, Str(y)) => strcmp_i32("", y),
(Str(x), Undef) => strcmp_i32(x, ""),
(Bool(_) | Undef, _) | (_, Bool(_) | Undef) => {
i32::from(h.is_truthy(a)) - i32::from(h.is_truthy(b))
}
(Obj(_), Obj(_)) => compare_arrays(h, a, b),
(Obj(_), _) => 1,
(_, Obj(_)) => -1,
(Float(f), Str(_)) | (Str(_), Float(f)) if f.is_nan() => 1,
(Str(x), Str(y)) => {
if host::is_numeric_string(x) && host::is_numeric_string(y) {
cmp_php_num(&as_php_number(h, a), &as_php_number(h, b))
} else {
strcmp_i32(x, y)
}
}
(Str(x), Int(_) | Float(_)) => {
if host::is_numeric_string(x) {
cmp_php_num(&as_php_number(h, a), &as_php_number(h, b))
} else {
strcmp_i32(x, &h.to_str(b))
}
}
(Int(_) | Float(_), Str(y)) => {
if host::is_numeric_string(y) {
cmp_php_num(&as_php_number(h, a), &as_php_number(h, b))
} else {
strcmp_i32(&h.to_str(a), y)
}
}
_ => cmp_php_num(&h.to_number(a), &h.to_number(b)),
}
}
fn compare_arrays(h: &host::PhpHost, a: &Value, b: &Value) -> i32 {
let (Some(pa), Some(pb)) = (h.array_pairs(a), h.array_pairs(b)) else {
return 0;
};
if pa.len() != pb.len() {
return if pa.len() < pb.len() { -1 } else { 1 };
}
for (ka, va) in &pa {
let Some((_, vb)) = pb.iter().find(|(kb, _)| strict_eq(h, ka, kb)) else {
return 1;
};
let ord = php_compare(h, va, vb);
if ord != 0 {
return ord;
}
}
0
}
fn strcmp_i32(x: &str, y: &str) -> i32 {
match x.cmp(y) {
std::cmp::Ordering::Less => -1,
std::cmp::Ordering::Equal => 0,
std::cmp::Ordering::Greater => 1,
}
}
fn cmp_f64(x: f64, y: f64) -> i32 {
if x == y {
0
} else if x < y {
-1
} else {
1
}
}
#[inline]
fn is_unordered(a: &Value, b: &Value) -> bool {
#[inline]
fn is_nan(v: &Value) -> bool {
matches!(v, Value::Float(f) if f.is_nan())
}
if !is_nan(a) && !is_nan(b) {
return false;
}
#[inline]
fn decided_by_type(v: &Value) -> bool {
matches!(v, Value::Bool(_) | Value::Undef | Value::Obj(_))
}
!decided_by_type(a) && !decided_by_type(b)
}
fn as_php_number(h: &host::PhpHost, v: &Value) -> Value {
match v {
Value::Str(s) => host::parse_php_number_full(s).unwrap_or_else(|| h.to_number(v)),
_ => h.to_number(v),
}
}
fn cmp_php_num(a: &Value, b: &Value) -> i32 {
match (a, b) {
(Value::Int(x), Value::Int(y)) => match x.cmp(y) {
std::cmp::Ordering::Less => -1,
std::cmp::Ordering::Equal => 0,
std::cmp::Ordering::Greater => 1,
},
_ => cmp_f64(a.to_float(), b.to_float()),
}
}
fn op_symbol(op: NumOp) -> &'static str {
match op {
NumOp::Add => "+",
NumOp::Sub => "-",
NumOp::Mul | NumOp::Neg => "*",
NumOp::Div => "/",
NumOp::Mod => "%",
NumOp::Pow => "**",
_ => "?",
}
}
pub(crate) fn unsupported_operands(sym: &str, a: &Value, b: &Value) -> String {
let msg = with_host(|h| {
format!(
"Unsupported operand types: {} {sym} {}",
host::arith_type_name(h, a),
host::arith_type_name(h, b)
)
});
let _ = pending_php_throw("TypeError", &msg);
msg
}
pub(crate) fn coerce_arith(sym: &str, a: &Value, b: &Value, left: bool) -> Result<Value, String> {
let v = if left { a } else { b };
match host::classify_arith(v) {
host::ArithOperand::Numeric(n) => Ok(n),
host::ArithOperand::Leading(n) => {
with_host(|h| h.warn("A non-numeric value encountered"));
Ok(n)
}
host::ArithOperand::Unsupported => Err(unsupported_operands(sym, a, b)),
}
}
pub(crate) fn coerce_arith_pair(sym: &str, a: &Value, b: &Value) -> Result<(Value, Value), String> {
let an = coerce_arith(sym, a, b, true)?;
let bn = coerce_arith(sym, a, b, false)?;
Ok((an, bn))
}
pub fn numeric_hook_sited(call: NumericCall<'_>, lines: &[u32]) -> Result<Value, String> {
let (op, a, b) = (call.op, call.a, call.b);
if op == NumOp::Add && with_host(|h| h.is_array(a) && h.is_array(b)) {
return Ok(array_union(a, b));
}
host::set_warn_line(lines.get(call.ip).copied().unwrap_or(0));
if let Some(want) = relational(op) {
if is_unordered(a, b) {
return Ok(Value::bool(false));
}
let ord = with_host(|h| php_compare(h, a, b));
return Ok(Value::bool(want(ord)));
}
let sym = op_symbol(op);
if op == NumOp::Neg {
let an = coerce_arith(sym, a, &Value::Int(-1), true)?;
return Ok(match an {
Value::Int(n) => n
.checked_neg()
.map(Value::int)
.unwrap_or(Value::float(-(n as f64))),
Value::Float(f) => Value::float(-f),
_ => Value::int(0),
});
}
let (an, bn) = coerce_arith_pair(sym, a, b)?;
Ok(arith(op, an, bn))
}
fn relational(op: NumOp) -> Option<fn(i32) -> bool> {
Some(match op {
NumOp::Lt => |o: i32| o < 0,
NumOp::Gt => |o: i32| o > 0,
NumOp::Le => |o: i32| o <= 0,
NumOp::Ge => |o: i32| o >= 0,
_ => return None,
})
}
fn array_union(a: &Value, b: &Value) -> Value {
with_host(|h| {
let pa = h.array_pairs(a).unwrap_or_default();
let pb = h.array_pairs(b).unwrap_or_default();
let out = h.new_array();
for (k, v) in &pa {
h.arr_set_key(&out, k, v.clone());
}
for (k, v) in &pb {
if !pa.iter().any(|(ka, _)| same_key(ka, k)) {
h.arr_set_key(&out, k, v.clone());
}
}
out
})
}
fn same_key(a: &Value, b: &Value) -> bool {
match (a, b) {
(Value::Int(x), Value::Int(y)) => x == y,
(Value::Str(x), Value::Str(y)) => x == y,
_ => false,
}
}
fn arith(op: NumOp, an: Value, bn: Value) -> Value {
if let (Value::Int(x), Value::Int(y)) = (&an, &bn) {
let r = match op {
NumOp::Add => x.checked_add(*y),
NumOp::Sub => x.checked_sub(*y),
NumOp::Mul => x.checked_mul(*y),
_ => None,
};
if let Some(v) = r {
return Value::int(v);
}
}
let (x, y) = (an.to_float(), bn.to_float());
Value::float(match op {
NumOp::Add => x + y,
NumOp::Sub => x - y,
NumOp::Mul => x * y,
NumOp::Div => x / y,
NumOp::Mod => x % y,
NumOp::Pow => x.powf(y),
_ => 0.0,
})
}
pub(crate) fn arg(args: &[Value], i: usize) -> Value {
args.get(i).cloned().unwrap_or(Value::Undef)
}
const STRING_PARAM_BUILTINS: &[&str] = &[
"addslashes",
"base64_decode",
"base64_encode",
"bin2hex",
"chunk_split",
"crc32",
"exit",
"explode",
"hex2bin",
"html_entity_decode",
"htmlentities",
"htmlspecialchars",
"htmlspecialchars_decode",
"lcfirst",
"levenshtein",
"ltrim",
"md5",
"metaphone",
"nl2br",
"ord",
"preg_quote",
"printf",
"quotemeta",
"rawurldecode",
"rawurlencode",
"rtrim",
"sha1",
"similar_text",
"soundex",
"sprintf",
"str_contains",
"str_ends_with",
"str_pad",
"str_repeat",
"str_split",
"str_starts_with",
"str_word_count",
"strcasecmp",
"strcmp",
"stripos",
"stripslashes",
"stristr",
"strlen",
"strnatcasecmp",
"strnatcmp",
"strncasecmp",
"strncmp",
"strpbrk",
"strpos",
"strrchr",
"strrev",
"strripos",
"strrpos",
"strstr",
"strtolower",
"strtoupper",
"strtr",
"substr",
"substr_count",
"substr_replace",
"trim",
"ucfirst",
"ucwords",
"urldecode",
"urlencode",
"vprintf",
"vsprintf",
"wordwrap",
];
fn coerce_stringable_args(lname: &str, args: &[Value]) -> Option<Vec<Value>> {
if !args.iter().any(|a| matches!(a, Value::Obj(_))) || !STRING_PARAM_BUILTINS.contains(&lname) {
return None;
}
Some(
args.iter()
.map(|a| {
let stringable = with_host(|h| {
h.object_class(a)
.is_some_and(|c| h.class_has_method(&c, "__tostring"))
});
if stringable {
Value::str(host::to_str_ext(a))
} else {
a.clone()
}
})
.collect(),
)
}
const THROW_TAG: &str = "\u{1}throw\u{1}";
pub fn throws(class: &str, message: impl std::fmt::Display) -> String {
format!("{THROW_TAG}{class}{THROW_TAG}{message}")
}
pub fn untag_throw(e: &str) -> Option<(&str, &str)> {
e.strip_prefix(THROW_TAG)?.split_once(THROW_TAG)
}
const CODE_THROW_TAG: &str = "\u{1}cthrow\u{1}";
pub fn throws_code(class: &str, code: i64, message: impl std::fmt::Display) -> String {
format!("{CODE_THROW_TAG}{class}{CODE_THROW_TAG}{code}{CODE_THROW_TAG}{message}")
}
pub fn untag_throw_code(e: &str) -> Option<(&str, i64, &str)> {
let rest = e.strip_prefix(CODE_THROW_TAG)?;
let (class, rest) = rest.split_once(CODE_THROW_TAG)?;
let (code, message) = rest.split_once(CODE_THROW_TAG)?;
Some((class, code.parse().ok()?, message))
}
const FATAL_TAG: &str = "\u{1}lfatal\u{1}";
pub fn fatals(message: impl std::fmt::Display) -> String {
format!("{FATAL_TAG}{message}")
}
pub fn untag_fatal(e: &str) -> Option<&str> {
e.strip_prefix(FATAL_TAG)
}
const BARE_THROW_TAG: &str = "\u{1}bthrow\u{1}";
pub fn throws_bare(class: &str, message: impl std::fmt::Display) -> String {
format!("{BARE_THROW_TAG}{class}{BARE_THROW_TAG}{message}")
}
pub fn untag_bare_throw(e: &str) -> Option<(&str, &str)> {
e.strip_prefix(BARE_THROW_TAG)?.split_once(BARE_THROW_TAG)
}
pub fn call_library(name: &str, args: &[Value]) -> Result<Value, String> {
let lname = name.to_ascii_lowercase();
let coerced = coerce_stringable_args(&lname, args);
let args: &[Value] = coerced.as_deref().unwrap_or(args);
with_host(|h| h.byref_out_clear());
let v = match lname.as_str() {
"exit" | "die" => {
let status = match args.first() {
None => 0,
Some(Value::Undef) => {
with_host(|h| {
h.deprecated(
"exit(): Passing null to parameter #1 ($status) of type string|int \
is deprecated",
)
});
0
}
Some(Value::Str(s)) => {
with_host(|h| h.write_out(s));
0
}
Some(v @ (Value::Int(_) | Value::Bool(_) | Value::Float(_))) => int_operand(v, v),
Some(other) => {
let t = with_host(|h| crate::stdlib::types::debug_type(h, other));
return Err(throws(
"TypeError",
format!(
"exit(): Argument #1 ($status) must be of type string|int, {t} given"
),
));
}
};
host::set_pending_exit((status & 0xFF) as i32);
Value::Undef
}
"strlen" => Value::int(with_host(|h| h.to_str(&arg(args, 0)).len() as i64)),
"count" | "sizeof" => {
let a = arg(args, 0);
let mode = args.get(1).map(|m| m.to_int()).unwrap_or(0);
if mode != 0 && mode != 1 {
return Err(throws(
"ValueError",
format!(
"{name}(): Argument #2 ($mode) must be either COUNT_NORMAL or COUNT_RECURSIVE"
),
));
}
if with_host(|h| h.is_array(&a)) {
Value::int(with_host(|h| {
if mode == 1 {
count_recursive(h, &a)
} else {
h.array_len(&a)
}
}))
} else if let Some(class) = with_host(|h| {
h.object_class(&a)
.filter(|c| h.class_is_a_pub(c, "Countable"))
}) {
let n = host::call_method(&class, "count", Some(a), Vec::new())?;
Value::int(n.to_int())
} else {
let t = with_host(|h| crate::stdlib::types::debug_type(h, &a));
return Err(throws(
"TypeError",
format!(
"{name}(): Argument #1 ($value) must be of type Countable|array, {t} given"
),
));
}
}
"strtoupper" => with_host(|h| Value::str(ascii_upper(&h.to_str(&arg(args, 0))))),
"strtolower" => with_host(|h| Value::str(ascii_lower(&h.to_str(&arg(args, 0))))),
"ucfirst" => with_host(|h| Value::str(ucfirst(&h.to_str(&arg(args, 0))))),
"trim" => with_host(|h| php_trim(h, args, true, true)),
"ltrim" => with_host(|h| php_trim(h, args, true, false)),
"rtrim" | "chop" => with_host(|h| php_trim(h, args, false, true)),
"str_repeat" => {
let n = arg(args, 1).to_int();
if n < 0 {
return Err(throws(
"ValueError",
"str_repeat(): Argument #2 ($times) must be greater than or equal to 0",
));
}
let src = with_host(|h| h.to_str(&arg(args, 0)));
let len = src.len();
if len
.checked_mul(n as usize)
.and_then(|p| p.checked_add(32))
.is_none()
{
return Err(fatals(format!(
"Possible integer overflow in memory allocation ({len} * {n} + 32)"
)));
}
Value::str(src.repeat(n as usize))
}
"strrev" => {
with_host(|h| Value::str(h.to_str(&arg(args, 0)).chars().rev().collect::<String>()))
}
"wordwrap" => with_host(|h| php_wordwrap(h, args))?,
"substr" => with_host(|h| Value::str(php_substr(&h.to_str(&arg(args, 0)), args))),
"strpos" => with_host(|h| php_strpos(h, args))?,
"str_replace" => with_host(|h| php_str_replace(h, args)),
"__cast_array" => with_host(|h| php_cast_array(h, &arg(args, 0))),
"__cast_object" => php_cast_object(&arg(args, 0))?,
"abs" => with_host(|h| match h.to_number(&arg(args, 0)) {
Value::Int(i64::MIN) => Value::float(-(i64::MIN as f64)),
Value::Int(n) => Value::int(n.abs()),
Value::Float(f) => Value::float(f.abs()),
other => other,
}),
"floor" => with_host(|h| Value::float(h.to_number(&arg(args, 0)).to_float().floor())),
"ceil" => with_host(|h| Value::float(h.to_number(&arg(args, 0)).to_float().ceil())),
"sqrt" => with_host(|h| Value::float(h.to_number(&arg(args, 0)).to_float().sqrt())),
"round" => with_host(|h| {
let x = h.to_number(&arg(args, 0)).to_float();
let p = args.get(1).map(|v| v.to_int()).unwrap_or(0);
let places = p.clamp(i64::from(i32::MIN), i64::from(i32::MAX)) as i32;
let mode = args.get(2).map(|v| v.to_int()).unwrap_or(1);
Value::float(php_round(x, places, mode))
}),
"intval" => with_host(|h| {
let v = arg(args, 0);
match args.get(1) {
Some(b)
if !matches!(b, Value::Undef)
&& matches!(v, Value::Str(_))
&& b.to_int() != 10 =>
{
Value::int(intval_base(&h.to_str(&v), b.to_int()))
}
_ => Value::int(h.to_int_cast(&v)),
}
}),
"floatval" | "doubleval" => {
with_host(|h| Value::float(h.to_number(&arg(args, 0)).to_float()))
}
"strval" => Value::str(host::to_str_ext(&arg(args, 0))),
"max" => with_host(|h| fold_cmp(h, args, true))?,
"min" => with_host(|h| fold_cmp(h, args, false))?,
"gettype" => with_host(|h| Value::str(h.type_name(&arg(args, 0)).to_string())),
"settype" => php_settype(args)?,
"is_array" => with_host(|h| Value::bool(h.is_array(&arg(args, 0)))),
"is_int" | "is_integer" | "is_long" => Value::bool(matches!(arg(args, 0), Value::Int(_))),
"is_float" | "is_double" => Value::bool(matches!(arg(args, 0), Value::Float(_))),
"is_string" => Value::bool(matches!(arg(args, 0), Value::Str(_))),
"is_bool" => Value::bool(matches!(arg(args, 0), Value::Bool(_))),
"is_null" => Value::bool(matches!(arg(args, 0), Value::Undef)),
"is_numeric" => Value::bool(match arg(args, 0) {
Value::Int(_) | Value::Float(_) => true,
Value::Str(s) => host::is_numeric_string(&s),
_ => false,
}),
"implode" | "join" => php_implode(args),
"explode" => with_host(|h| php_explode(h, args))?,
"in_array" => with_host(|h| php_in_array(h, args)),
"array_keys" => with_host(|h| h.array_keys(&arg(args, 0))),
"array_values" => with_host(|h| php_array_values(h, &arg(args, 0))),
"array_push" => with_host(|h| php_array_push(h, args))?,
"range" => with_host(|h| php_range(h, args))?,
"sprintf" => with_host(|h| php_sprintf(h, args, false)).map(Value::str)?,
"printf" => {
let s = with_host(|h| php_sprintf(h, args, false))?;
with_host(|h| h.write_out(&s));
Value::int(s.len() as i64)
}
"print_r" => with_host(|h| {
let s = php_print_r(h, &arg(args, 0), 0, &mut host::Visiting::default());
if args.get(1).map(|v| h.is_truthy(v)).unwrap_or(false) {
Value::str(s)
} else {
h.write_out(&s);
Value::bool(true)
}
}),
"var_dump" => with_host(|h| {
for a in args {
let s = php_var_dump(h, a, 0);
h.write_out(&s);
}
Value::Undef
}),
"str_split" => with_host(|h| php_str_split(h, args))?,
"str_pad" => with_host(|h| php_str_pad(h, args)).map(Value::str)?,
"str_contains" => {
with_host(|h| Value::bool(h.to_str(&arg(args, 0)).contains(&h.to_str(&arg(args, 1)))))
}
"str_starts_with" => with_host(|h| {
Value::bool(
h.to_str(&arg(args, 0))
.starts_with(&h.to_str(&arg(args, 1))),
)
}),
"str_ends_with" => {
with_host(|h| Value::bool(h.to_str(&arg(args, 0)).ends_with(&h.to_str(&arg(args, 1)))))
}
"ucwords" => with_host(|h| {
let seps = match args.get(1) {
Some(v) if !matches!(v, Value::Undef) => h.to_str(v),
_ => " \t\r\n\x0c\x0b".to_string(),
};
Value::str(ucwords(&h.to_str(&arg(args, 0)), &seps))
}),
"lcfirst" => with_host(|h| Value::str(lcfirst(&h.to_str(&arg(args, 0))))),
"number_format" => with_host(|h| Value::str(php_number_format(h, args))),
"htmlspecialchars" | "htmlentities" => with_host(|h| {
let s = h.to_str(&arg(args, 0));
let flags = match args.get(1) {
Some(v) if !matches!(v, Value::Undef) => h.to_number(v).to_int(),
_ => crate::stdlib::textx::ENT_DEFAULT,
};
let named = lname == "htmlentities";
Value::str(crate::stdlib::textx::html_encode(&s, flags, named))
}),
"strcmp" => with_host(|h| {
let (a, b) = (h.to_str(&arg(args, 0)), h.to_str(&arg(args, 1)));
Value::int(binary_strcmp(a.as_bytes(), b.as_bytes()))
}),
"strcasecmp" => with_host(|h| {
let a = ascii_lower(&h.to_str(&arg(args, 0)));
let b = ascii_lower(&h.to_str(&arg(args, 1)));
Value::int(binary_strcmp(a.as_bytes(), b.as_bytes()))
}),
"strncmp" => with_host(|h| {
let a = h.to_str(&arg(args, 0));
let b = h.to_str(&arg(args, 1));
let n = arg(args, 2).to_int().max(0) as usize;
let (ab, bb) = (a.as_bytes(), b.as_bytes());
Value::int(binary_strcmp(
&ab[..n.min(ab.len())],
&bb[..n.min(bb.len())],
))
}),
"substr_compare" => return with_host(|h| php_substr_compare(h, args)),
"chr" => with_host(|h| {
let raw = h.to_number(&arg(args, 0)).to_int();
if !(0..=255).contains(&raw) {
h.deprecated(
"chr(): Providing a value not in-between 0 and 255 is deprecated, this \
is because a byte value must be in the [0, 255] interval. The value \
used will be constrained using % 256",
);
}
let n = raw.rem_euclid(256) as u8;
Value::str((n as char).to_string())
}),
"ord" => with_host(|h| {
let s = h.to_str(&arg(args, 0));
if s.is_empty() {
h.deprecated("ord(): Providing an empty string is deprecated");
}
Value::int(s.bytes().next().unwrap_or(0) as i64)
}),
"dechex" => with_host(|h| Value::str(format!("{:x}", h.to_number(&arg(args, 0)).to_int()))),
"bin2hex" => with_host(|h| {
let s = h.to_str(&arg(args, 0));
Value::str(s.bytes().map(|b| format!("{b:02x}")).collect::<String>())
}),
"pow" => php_pow(args),
"intdiv" => return php_intdiv(args),
"fmod" => with_host(|h| {
Value::float(
h.to_number(&arg(args, 0)).to_float() % h.to_number(&arg(args, 1)).to_float(),
)
}),
"sin" => with_host(|h| Value::float(h.to_number(&arg(args, 0)).to_float().sin())),
"cos" => with_host(|h| Value::float(h.to_number(&arg(args, 0)).to_float().cos())),
"tan" => with_host(|h| Value::float(h.to_number(&arg(args, 0)).to_float().tan())),
"exp" => with_host(|h| Value::float(h.to_number(&arg(args, 0)).to_float().exp())),
"log" => with_host(|h| {
let x = h.to_number(&arg(args, 0)).to_float();
match args.get(1) {
Some(b) if !matches!(b, Value::Undef) => {
Value::float(x.log(h.to_number(b).to_float()))
}
_ => Value::float(x.ln()),
}
}),
"log10" => with_host(|h| Value::float(h.to_number(&arg(args, 0)).to_float().log10())),
"pi" => Value::float(std::f64::consts::PI),
"array_merge" => with_host(|h| php_array_merge(h, args)),
"array_map" => return php_array_map(args),
"array_filter" => return php_array_filter(args),
"array_reduce" => return php_array_reduce(args),
"array_slice" => with_host(|h| php_array_slice(h, args)),
"array_reverse" => with_host(|h| php_array_reverse(h, args)),
"array_sum" => with_host(|h| php_array_fold(h, &arg(args, 0), false)),
"array_product" => with_host(|h| php_array_fold(h, &arg(args, 0), true)),
"array_flip" => with_host(|h| php_array_flip(h, &arg(args, 0))),
"array_unique" => with_host(|h| php_array_unique(h, &arg(args, 0))),
"array_key_exists" | "key_exists" => with_host(|h| php_array_key_exists(h, args)),
"array_search" => with_host(|h| php_array_search(h, args)),
"sort" => with_host(|h| php_sort(h, &arg(args, 0), false, sort_flags(args))),
"rsort" => with_host(|h| php_sort(h, &arg(args, 0), true, sort_flags(args))),
"asort" => with_host(|h| php_asort(h, &arg(args, 0), false, sort_flags(args))),
"arsort" => with_host(|h| php_asort(h, &arg(args, 0), true, sort_flags(args))),
"ksort" => with_host(|h| php_ksort(h, &arg(args, 0), false, sort_flags(args))),
"krsort" => with_host(|h| php_ksort(h, &arg(args, 0), true, sort_flags(args))),
"array_fill" => with_host(|h| php_array_fill(h, args))?,
"array_combine" => with_host(|h| php_array_combine(h, args))?,
"array_diff" => with_host(|h| php_array_diff(h, args, false)),
"array_intersect" => with_host(|h| php_array_diff(h, args, true)),
"boolval" => with_host(|h| Value::bool(h.is_truthy(&arg(args, 0)))),
"var_export" => with_host(|h| {
let s = php_var_export(h, &arg(args, 0), 0, &mut host::Visiting::default());
if args.get(1).map(|v| h.is_truthy(v)).unwrap_or(false) {
Value::str(s)
} else {
h.write_out(&s);
Value::Undef
}
}),
"json_encode" => {
let flags = arg(args, 1).to_int();
let prepared = match json_prepare(&arg(args, 0)) {
Ok(v) => v,
Err(code) => {
return match crate::stdlib::json::fail(code, flags) {
Some(e) => Err(e),
None => Ok(Value::bool(false)),
}
}
};
if with_host(|h| has_nonfinite_float(h, &prepared)) {
return match crate::stdlib::json::fail(
crate::stdlib::json::JSON_ERROR_INF_OR_NAN,
flags,
) {
Some(e) => Err(e),
None => Ok(Value::bool(false)),
};
}
crate::stdlib::json::set_last_error(0);
with_host(|h| Value::str(php_json_encode(h, &prepared, flags, 0)))
}
_ => {
return crate::stdlib::dispatch(&lname, args).unwrap_or_else(|| {
Err(throws_bare(
"Error",
format!("Call to undefined function {name}()"),
))
})
}
};
Ok(v)
}
fn ascii_upper(s: &str) -> String {
s.chars()
.map(|c| {
if c.is_ascii() {
c.to_ascii_uppercase()
} else {
c
}
})
.collect()
}
fn ascii_lower(s: &str) -> String {
s.chars()
.map(|c| {
if c.is_ascii() {
c.to_ascii_lowercase()
} else {
c
}
})
.collect()
}
fn ucfirst(s: &str) -> String {
let mut c = s.chars();
match c.next() {
Some(first) if first.is_ascii() => std::iter::once(first.to_ascii_uppercase())
.chain(c)
.collect(),
_ => s.to_string(),
}
}
fn long_fits_double(n: i64) -> bool {
let d = n as f64;
const TWO_POW_63: f64 = 9_223_372_036_854_775_808.0;
(-TWO_POW_63..TWO_POW_63).contains(&d) && d as i64 == n
}
pub(crate) fn minmax_frameless(
h: &host::PhpHost,
lhs: &Value,
rhs: &Value,
want_max: bool,
) -> Value {
let pick = |keep_lhs: bool| if keep_lhs { lhs.clone() } else { rhs.clone() };
let keep = |a: f64, b: f64| if want_max { a >= b } else { a < b };
match (lhs, rhs) {
(Value::Int(l), Value::Int(r)) => {
return pick(if want_max { l >= r } else { l < r });
}
(Value::Int(l), Value::Float(r)) if long_fits_double(*l) => {
return pick(keep(*l as f64, *r));
}
(Value::Float(l), Value::Float(r)) => return pick(keep(*l, *r)),
(Value::Float(l), Value::Int(r)) if long_fits_double(*r) => {
return pick(keep(*l, *r as f64));
}
_ => {}
}
let ord = php_compare(h, lhs, rhs);
pick(if want_max { ord >= 0 } else { ord < 0 })
}
#[derive(Clone, Copy, PartialEq)]
enum FoldMode {
Long,
Double,
Generic,
}
fn fold_cmp(h: &host::PhpHost, args: &[Value], want_max: bool) -> Result<Value, String> {
let who = if want_max { "max" } else { "min" };
if args.is_empty() {
return Err(throws(
"ArgumentCountError",
format!("{who}() expects at least 1 argument, 0 given"),
));
}
if args.len() == 1 {
if !h.is_array(&args[0]) {
let given = h.type_name_for_error(&args[0]);
return Err(throws(
"TypeError",
format!("{who}(): Argument #1 ($value) must be of type array, {given} given"),
));
}
let items: Vec<Value> = h
.array_pairs(&args[0])
.unwrap_or_default()
.into_iter()
.map(|(_, v)| v)
.collect();
let Some(first) = items.first() else {
return Err(throws(
"ValueError",
format!("{who}(): Argument #1 ($value) must contain at least one element"),
));
};
let mut best = first.clone();
for v in &items[1..] {
let ord = php_compare(h, &best, v);
if (want_max && ord < 0) || (!want_max && ord > 0) {
best = v.clone();
}
}
return Ok(best);
}
let mut best = 0usize;
let mut i = 1usize;
let mut lval = 0i64;
let mut dval = 0f64;
let mut mode = match &args[0] {
Value::Int(n) => {
lval = *n;
FoldMode::Long
}
Value::Float(d) => {
dval = *d;
FoldMode::Double
}
_ => FoldMode::Generic,
};
loop {
match mode {
FoldMode::Long => {
let Some(v) = args.get(i) else {
return Ok(Value::int(lval));
};
match v {
Value::Int(r) => {
if if want_max { lval < *r } else { lval > *r } {
lval = *r;
best = i;
}
i += 1;
}
Value::Float(_) if long_fits_double(lval) => {
dval = lval as f64;
mode = FoldMode::Double;
}
_ => mode = FoldMode::Generic,
}
}
FoldMode::Double => {
let Some(v) = args.get(i) else { break };
match v {
Value::Float(r) => {
if if want_max { dval < *r } else { dval > *r } {
dval = *r;
best = i;
}
i += 1;
}
Value::Int(r) if long_fits_double(*r) => {
let r = *r as f64;
if if want_max { dval < r } else { dval > r } {
dval = r;
best = i;
}
i += 1;
}
_ => mode = FoldMode::Generic,
}
}
FoldMode::Generic => {
let Some(v) = args.get(i) else { break };
let ord = php_compare(h, v, &args[best]);
if (want_max && ord > 0) || (!want_max && ord < 0) {
best = i;
}
i += 1;
}
}
}
Ok(args[best].clone())
}
fn php_substr(s: &str, args: &[Value]) -> String {
let chars: Vec<char> = s.chars().collect();
let len = chars.len() as i64;
let mut start = arg(args, 1).to_int();
if start < 0 {
start = (len + start).max(0);
}
let start = start.min(len).max(0) as usize;
let count = match args.get(2) {
Some(v) if !matches!(v, Value::Undef) => {
let l = v.to_int();
if l < 0 {
(len - start as i64 + l).max(0) as usize
} else {
l as usize
}
}
_ => chars.len() - start,
};
chars[start..(start + count).min(chars.len())]
.iter()
.collect()
}
fn php_strpos(h: &host::PhpHost, args: &[Value]) -> Result<Value, String> {
let hay = h.to_str(&arg(args, 0));
let needle = h.to_str(&arg(args, 1));
let len = hay.len() as i64;
let raw = args.get(2).map(|v| h.to_number(v).to_int()).unwrap_or(0);
let start = if raw < 0 { len + raw } else { raw };
if start < 0 || start > len {
return Err(throws(
"ValueError",
"strpos(): Argument #3 ($offset) must be contained in argument #1 ($haystack)",
));
}
let from = start as usize;
let hb = hay.as_bytes();
let nb = needle.as_bytes();
if nb.is_empty() {
return Ok(Value::int(start));
}
if nb.len() > hb.len() - from {
return Ok(Value::bool(false));
}
for i in from..=(hb.len() - nb.len()) {
if &hb[i..i + nb.len()] == nb {
return Ok(Value::int(i as i64));
}
}
Ok(Value::bool(false))
}
fn intval_base(s: &str, base: i64) -> i64 {
let t = s.trim_start();
let (neg, t) = match t.strip_prefix('-') {
Some(rest) => (true, rest),
None => (false, t.strip_prefix('+').unwrap_or(t)),
};
let lower = t.to_ascii_lowercase();
let (base, digits) = match base {
0 if lower.starts_with("0x") => (16, &t[2..]),
0 if lower.starts_with("0b") => (2, &t[2..]),
0 if t.len() > 1 && t.starts_with('0') => (8, &t[1..]),
0 => (10, t),
16 if lower.starts_with("0x") => (16, &t[2..]),
2 if lower.starts_with("0b") => (2, &t[2..]),
8 if lower.starts_with("0o") => (8, &t[2..]),
b => (b, t),
};
if !(2..=36).contains(&base) {
return 0;
}
let mut acc: i64 = 0;
for c in digits.chars() {
let Some(d) = c.to_digit(base as u32) else {
break;
};
acc = acc.saturating_mul(base).saturating_add(d as i64);
}
if neg {
-acc
} else {
acc
}
}
fn php_cast_array(h: &mut host::PhpHost, v: &Value) -> Value {
if h.is_array(v) {
return v.clone();
}
let out = h.new_array();
if matches!(v, Value::Undef) {
return out;
}
if h.is_object(v) {
for (name, val) in h.object_props_mangled(v) {
h.arr_set_key(&out, &Value::str(name), val);
}
return out;
}
h.arr_push_auto(&out, v.clone());
out
}
fn php_settype(args: &[Value]) -> Result<Value, String> {
let v = arg(args, 0);
let ty = with_host(|h| h.to_str(&arg(args, 1))).to_ascii_lowercase();
let out = match ty.as_str() {
"bool" | "boolean" => Value::bool(with_host(|h| h.is_truthy(&v))),
"int" | "integer" => Value::int(with_host(|h| h.to_number(&v)).to_int()),
"float" | "double" => Value::float(with_host(|h| h.to_number(&v)).to_float()),
"string" => Value::str(host::to_str_ext(&v)),
"array" => with_host(|h| php_cast_array(h, &v)),
"object" => php_cast_object(&v)?,
"null" => Value::Undef,
_ => {
return Err(throws(
"ValueError",
"settype(): Argument #2 ($type) must be a valid type",
))
}
};
with_host(|h| h.byref_out_put(0, out));
Ok(Value::bool(true))
}
fn php_cast_object(v: &Value) -> Result<Value, String> {
if with_host(|h| h.is_object(v)) {
return Ok(v.clone());
}
let obj = host::new_object("stdClass", Vec::new())?;
with_host(|h| {
if h.is_array(v) {
for (k, val) in h.array_pairs(v).unwrap_or_default() {
let name = h.to_str(&k);
h.prop_set(&obj, &name, val);
}
} else if !matches!(v, Value::Undef) {
h.prop_set(&obj, "scalar", v.clone());
}
});
Ok(obj)
}
fn php_str_replace(h: &mut host::PhpHost, args: &[Value]) -> Value {
let search = arg(args, 0);
let replace = arg(args, 1);
let subject = arg(args, 2);
let pairs: Vec<(String, String)> = if h.is_array(&search) {
let searches = h.array_pairs(&search).unwrap_or_default();
let replaces = if h.is_array(&replace) {
h.array_pairs(&replace)
.unwrap_or_default()
.into_iter()
.map(|(_, v)| h.to_str(&v))
.collect()
} else {
vec![h.to_str(&replace); searches.len()]
};
searches
.into_iter()
.enumerate()
.map(|(i, (_, s))| (h.to_str(&s), replaces.get(i).cloned().unwrap_or_default()))
.collect()
} else {
vec![(h.to_str(&search), h.to_str(&replace))]
};
let mut count = 0usize;
let result = if h.is_array(&subject) {
let out = h.new_array();
for (k, v) in h.array_pairs(&subject).unwrap_or_default() {
let s = replace_all_pairs(&h.to_str(&v), &pairs, &mut count);
h.arr_set_key(&out, &k, Value::str(s));
}
out
} else {
Value::str(replace_all_pairs(&h.to_str(&subject), &pairs, &mut count))
};
h.byref_out_put(3, Value::int(count as i64));
result
}
fn replace_all_pairs(subject: &str, pairs: &[(String, String)], count: &mut usize) -> String {
let mut cur = subject.to_string();
for (needle, rep) in pairs {
if needle.is_empty() {
continue;
}
*count += cur.matches(needle.as_str()).count();
cur = cur.replace(needle.as_str(), rep);
}
cur
}
fn php_implode(args: &[Value]) -> Value {
let (glue, arr) = with_host(|h| {
if h.is_array(&arg(args, 0)) {
(String::new(), arg(args, 0))
} else {
(h.to_str(&arg(args, 0)), arg(args, 1))
}
});
let vals: Vec<Value> = with_host(|h| h.array_pairs(&arr).unwrap_or_default())
.into_iter()
.map(|(_, v)| v)
.collect();
let parts: Vec<String> = vals.iter().map(host::to_str_ext).collect();
Value::str(parts.join(&glue))
}
fn trim_fname(start: bool, end: bool) -> &'static str {
match (start, end) {
(true, true) => "trim",
(true, false) => "ltrim",
_ => "rtrim",
}
}
fn php_trim(h: &mut host::PhpHost, args: &[Value], start: bool, end: bool) -> Value {
let s = h.to_str(&arg(args, 0));
let mask = match args.get(1) {
Some(v) if !matches!(v, Value::Undef) => {
let list = h.to_str(v);
crate::stdlib::common::charmask(h, list.as_bytes(), trim_fname(start, end))
}
_ => {
let mut m = [false; 256];
for c in [b' ', b'\t', b'\n', b'\r', 0, 0x0b] {
m[c as usize] = true;
}
m
}
};
let b = s.as_bytes();
let mut lo = 0usize;
let mut hi = b.len();
if start {
while lo < hi && mask[b[lo] as usize] {
lo += 1;
}
}
if end {
while hi > lo && mask[b[hi - 1] as usize] {
hi -= 1;
}
}
Value::str(String::from_utf8_lossy(&b[lo..hi]).into_owned())
}
fn php_explode(h: &mut host::PhpHost, args: &[Value]) -> Result<Value, String> {
let sep = h.to_str(&arg(args, 0));
let subject = h.to_str(&arg(args, 1));
let arr = h.new_array();
if sep.is_empty() {
return Err(throws(
"ValueError",
"explode(): Argument #1 ($separator) must not be empty",
));
}
let limit = match args.get(2) {
Some(v) if !matches!(v, Value::Undef) => v.to_int(),
_ => i64::MAX,
};
let mut parts: Vec<String> = if limit > 0 && limit != i64::MAX {
subject
.splitn(limit as usize, sep.as_str())
.map(str::to_string)
.collect()
} else {
subject.split(sep.as_str()).map(str::to_string).collect()
};
if limit == 0 {
parts = vec![subject];
} else if limit < 0 {
let drop = (-limit) as usize;
parts.truncate(parts.len().saturating_sub(drop));
}
for part in parts {
h.arr_push_auto(&arr, Value::str(part));
}
Ok(arr)
}
fn php_in_array(h: &host::PhpHost, args: &[Value]) -> Value {
let needle = arg(args, 0);
let hay = arg(args, 1);
let strict = args.get(2).map(|v| h.is_truthy(v)).unwrap_or(false);
let found = h
.array_pairs(&hay)
.unwrap_or_default()
.iter()
.any(|(_, v)| {
if strict {
strict_eq(h, &needle, v)
} else {
loose_eq(h, &needle, v)
}
});
Value::bool(found)
}
fn php_array_values(h: &mut host::PhpHost, v: &Value) -> Value {
let pairs = h.array_pairs(v).unwrap_or_default();
let arr = h.new_array();
for (_, val) in pairs {
h.arr_push_auto(&arr, val);
}
arr
}
fn php_array_push(h: &mut host::PhpHost, args: &[Value]) -> Result<Value, String> {
let arr = arg(args, 0);
for v in &args[1.min(args.len())..] {
if h.append_slot_taken(&arr) {
return Err(throws_bare("Error", host::NEXT_ELEMENT_OCCUPIED));
}
h.arr_push_auto(&arr, v.clone());
}
Ok(Value::int(h.array_len(&arr)))
}
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
enum RangeInput {
Long,
Double,
Str,
Ambig,
}
fn range_process_input(
h: &mut host::PhpHost,
input: &Value,
arg_num: u32,
arg_name: &str,
) -> Result<(RangeInput, i64, f64), String> {
let finite = |d: f64, h: &mut host::PhpHost| -> Result<(), String> {
let _ = h;
if d.is_infinite() {
return Err(throws(
"ValueError",
format!(
"range(): Argument #{arg_num} (${arg_name}) must be a finite number, \
INF provided"
),
));
}
if d.is_nan() {
return Err(throws(
"ValueError",
format!(
"range(): Argument #{arg_num} (${arg_name}) must be a finite number, \
NAN provided"
),
));
}
Ok(())
};
match input {
Value::Int(n) => Ok((RangeInput::Long, *n, *n as f64)),
Value::Float(d) => {
finite(*d, h)?;
Ok((RangeInput::Double, 0, *d))
}
Value::Str(s) => {
if s.is_empty() {
h.warn(format_args!(
"range(): Argument #{arg_num} (${arg_name}) must not be empty, casted to 0"
));
return Ok((RangeInput::Long, 0, 0.0));
}
match host::parse_php_number_full(s) {
Some(Value::Float(d)) => {
finite(d, h)?;
Ok((RangeInput::Double, 0, d))
}
Some(Value::Int(n)) => Ok((
if s.len() == 1 {
RangeInput::Ambig
} else {
RangeInput::Long
},
n,
n as f64,
)),
_ => {
if s.len() != 1 {
h.warn(format_args!(
"range(): Argument #{arg_num} (${arg_name}) must be a single byte, \
subsequent bytes are ignored"
));
}
Ok((RangeInput::Str, 0, 0.0))
}
}
}
Value::Bool(b) => Ok((RangeInput::Long, i64::from(*b), f64::from(*b))),
Value::Undef => {
h.deprecated(format_args!(
"range(): Passing null to parameter #{arg_num} (${arg_name}) of type \
string|int|float is deprecated"
));
Ok((RangeInput::Long, 0, 0.0))
}
other => {
let t = h.type_name_for_error(other);
Err(throws(
"TypeError",
format!(
"range(): Argument #{arg_num} (${arg_name}) must be of type \
string|int|float, {t} given"
),
))
}
}
}
const HT_MAX_SIZE: u64 = 1 << 30;
fn php_range(h: &mut host::PhpHost, args: &[Value]) -> Result<Value, String> {
const NEGATIVE_STEP_ERR: &str =
"range(): Argument #3 ($step) must be greater than 0 for increasing ranges";
const BOUNDARY_ERR: &str = "range(): Argument #3 ($step) must be less than the range \
spanned by argument #1 ($start) and argument #2 ($end)";
let mut is_step_double = false;
let mut is_step_negative = false;
let mut step_double = 1.0f64;
let mut step: i64 = 1;
if let Some(user_step) = args.get(2) {
let num = match user_step {
Value::Int(_) | Value::Float(_) => user_step.clone(),
Value::Bool(b) => Value::int(i64::from(*b)),
Value::Undef => {
h.deprecated(
"range(): Passing null to parameter #3 ($step) of type int|float \
is deprecated",
);
Value::int(0)
}
Value::Str(s) => match host::parse_php_number_full(s) {
Some(v) => v,
None => {
return Err(throws(
"TypeError",
"range(): Argument #3 ($step) must be of type int|float, string given",
))
}
},
other => {
let t = h.type_name_for_error(other);
return Err(throws(
"TypeError",
format!("range(): Argument #3 ($step) must be of type int|float, {t} given"),
));
}
};
match num {
Value::Float(mut d) => {
if d.is_infinite() {
return Err(throws(
"ValueError",
"range(): Argument #3 ($step) must be a finite number, INF provided",
));
}
if d.is_nan() {
return Err(throws(
"ValueError",
"range(): Argument #3 ($step) must be a finite number, NAN provided",
));
}
if d < 0.0 {
is_step_negative = true;
d *= -1.0;
}
step_double = d;
step = d as i64;
if (step as f64) != d {
is_step_double = true;
}
}
other => {
step = other.to_int();
if step < 0 {
if step == i64::MIN {
return Err(throws(
"ValueError",
format!("range(): Argument #3 ($step) must be greater than {step}"),
));
}
is_step_negative = true;
step = -step;
}
step_double = step as f64;
}
}
if step_double == 0.0 {
return Err(throws(
"ValueError",
"range(): Argument #3 ($step) cannot be 0",
));
}
}
let user_start = arg(args, 0);
let user_end = arg(args, 1);
let (mut start_type, start_long, start_double) =
range_process_input(h, &user_start, 1, "start")?;
let (mut end_type, end_long, end_double) = range_process_input(h, &user_end, 2, "end")?;
let arr = h.new_array();
if start_type >= RangeInput::Str || end_type >= RangeInput::Str {
let mut fall_through_to_numeric = false;
if start_type < RangeInput::Str || end_type < RangeInput::Str {
if start_type < RangeInput::Str {
if end_type != RangeInput::Ambig {
h.warn(
"range(): Argument #1 ($start) must be a single byte string if \
argument #2 ($end) is a single byte string, argument #2 ($end) \
converted to 0",
);
}
end_type = RangeInput::Long;
} else {
if start_type != RangeInput::Ambig {
h.warn(
"range(): Argument #2 ($end) must be a single byte string if \
argument #1 ($start) is a single byte string, argument #1 ($start) \
converted to 0",
);
}
start_type = RangeInput::Long;
}
fall_through_to_numeric = true;
} else if is_step_double {
if start_type == RangeInput::Str || end_type == RangeInput::Str {
h.warn(
"range(): Argument #3 ($step) must be of type int when generating an \
array of characters, inputs converted to 0",
);
}
start_type = RangeInput::Long;
end_type = RangeInput::Long;
fall_through_to_numeric = true;
}
if !fall_through_to_numeric {
let low = h.to_str(&user_start).as_bytes()[0];
let high = h.to_str(&user_end).as_bytes()[0];
let ustep = step as u64;
match low.cmp(&high) {
std::cmp::Ordering::Greater => {
if u64::from(low - high) < ustep {
return Err(throws("ValueError", BOUNDARY_ERR));
}
let mut c = low;
while c >= high {
h.arr_push_auto(&arr, Value::str((c as char).to_string()));
if (c as i64) - (step) < 0 {
break;
}
c -= step as u8;
}
}
std::cmp::Ordering::Less => {
if is_step_negative {
return Err(throws("ValueError", NEGATIVE_STEP_ERR));
}
if u64::from(high - low) < ustep {
return Err(throws("ValueError", BOUNDARY_ERR));
}
let mut c = low;
while c <= high {
h.arr_push_auto(&arr, Value::str((c as char).to_string()));
if (c as i64) + step > 255 {
break;
}
c += step as u8;
}
}
std::cmp::Ordering::Equal => {
h.arr_push_auto(&arr, Value::str((low as char).to_string()));
}
}
return Ok(arr);
}
}
if start_type == RangeInput::Double || end_type == RangeInput::Double || is_step_double {
let check = |span_hi: f64, span_lo: f64| -> Result<u64, String> {
let calc = ((span_hi - span_lo) / step_double) + 1.0;
if calc >= HT_MAX_SIZE as f64 {
let exceed = calc - HT_MAX_SIZE as f64;
return Err(throws(
"ValueError",
format!(
"The supplied range exceeds the maximum array size by {exceed:.1} \
elements: start={span_lo:.1}, end={span_hi:.1}, step={step_double:.1}. \
Max size: {}",
HT_MAX_SIZE
),
));
}
Ok(calc.round() as u64)
};
if start_double > end_double {
if start_double - end_double < step_double {
return Err(throws("ValueError", BOUNDARY_ERR));
}
let size = check(start_double, end_double)?;
let mut element = start_double;
let mut i = 0u64;
while i < size && element >= end_double {
h.arr_push_auto(&arr, Value::float(element));
i += 1;
element = start_double - (i as f64 * step_double);
}
} else if end_double > start_double {
if is_step_negative {
return Err(throws("ValueError", NEGATIVE_STEP_ERR));
}
if end_double - start_double < step_double {
return Err(throws("ValueError", BOUNDARY_ERR));
}
let size = check(end_double, start_double)?;
let mut element = start_double;
let mut i = 0u64;
while i < size && element <= end_double {
h.arr_push_auto(&arr, Value::float(element));
i += 1;
element = start_double + (i as f64 * step_double);
}
} else {
h.arr_push_auto(&arr, Value::float(start_double));
}
return Ok(arr);
}
let ustep = step as u64;
let check = |span_hi: i64, span_lo: i64| -> Result<u64, String> {
let calc = (span_hi as u64).wrapping_sub(span_lo as u64) / ustep;
if calc >= HT_MAX_SIZE - 1 {
let excess = calc - (HT_MAX_SIZE - 1);
return Err(throws(
"ValueError",
format!(
"The supplied range exceeds the maximum array size by {excess} elements: \
start={span_lo}, end={span_hi}, step={step}. Calculated size: {calc}. \
Maximum size: {HT_MAX_SIZE}."
),
));
}
Ok(calc + 1)
};
match start_long.cmp(&end_long) {
std::cmp::Ordering::Greater => {
if (start_long as u64).wrapping_sub(end_long as u64) < ustep {
return Err(throws("ValueError", BOUNDARY_ERR));
}
let size = check(start_long, end_long)?;
for i in 0..size {
let v = (start_long as u64).wrapping_sub(i.wrapping_mul(ustep)) as i64;
h.arr_push_auto(&arr, Value::int(v));
}
}
std::cmp::Ordering::Less => {
if is_step_negative {
return Err(throws("ValueError", NEGATIVE_STEP_ERR));
}
if (end_long as u64).wrapping_sub(start_long as u64) < ustep {
return Err(throws("ValueError", BOUNDARY_ERR));
}
let size = check(end_long, start_long)?;
for i in 0..size {
let v = (start_long as u64).wrapping_add(i.wrapping_mul(ustep)) as i64;
h.arr_push_auto(&arr, Value::int(v));
}
}
std::cmp::Ordering::Equal => {
h.arr_push_auto(&arr, Value::int(start_long));
}
}
Ok(arr)
}
const KNOWN_CONVERSIONS: &str = "sdugGhHeEfFcoxXb%";
#[derive(Clone, Copy)]
struct FmtSpec {
argnum: Option<usize>,
left: bool,
plus: bool,
pad: char,
width: usize,
precision: Option<usize>,
conv: char,
}
pub(crate) fn php_sprintf(
h: &mut host::PhpHost,
args: &[Value],
array_form: bool,
) -> Result<String, String> {
let fmt: Vec<char> = h.to_str(&arg(args, 0)).chars().collect();
let mut out = String::new();
let mut i = 0;
let mut next_arg = 1usize;
let mut max_missing: Option<usize> = None;
while i < fmt.len() {
if fmt[i] != '%' {
out.push(fmt[i]);
i += 1;
continue;
}
i += 1;
if i < fmt.len() && fmt[i] == '%' {
out.push('%');
i += 1;
continue;
}
let Some(spec) = parse_spec(&fmt, &mut i)? else {
out.push('%');
continue;
};
let ai = spec.argnum.unwrap_or_else(|| {
let a = next_arg;
next_arg += 1;
a
});
if ai >= args.len() {
max_missing = Some(max_missing.map_or(ai, |m: usize| m.max(ai)));
continue;
}
if spec.conv == '\0' {
return Err(throws(
"ValueError",
"Missing format specifier at end of string",
));
}
if !KNOWN_CONVERSIONS.contains(spec.conv) {
return Err(throws(
"ValueError",
format!("Unknown format specifier \"{}\"", spec.conv),
));
}
out.push_str(&render_spec(h, &spec, &arg(args, ai)));
}
if let Some(missing) = max_missing {
let supplied = args.len() - 1;
return Err(if array_form {
throws(
"ValueError",
format!("The arguments array must contain {missing} items, {supplied} given"),
)
} else {
throws(
"ArgumentCountError",
format!(
"{} arguments are required, {} given",
missing + 1,
supplied + 1
),
)
});
}
Ok(out)
}
fn parse_spec(fmt: &[char], i: &mut usize) -> Result<Option<FmtSpec>, String> {
let mut j = *i;
let mut argnum = None;
let mut k = j;
while k < fmt.len() && fmt[k].is_ascii_digit() {
k += 1;
}
if k > j && k < fmt.len() && fmt[k] == '$' {
argnum = fmt[j..k].iter().collect::<String>().parse::<usize>().ok();
j = k + 1;
}
let (mut left, mut plus, mut pad) = (false, false, ' ');
loop {
match fmt.get(j) {
Some('-') => left = true,
Some('+') => plus = true,
Some(' ') => pad = ' ',
Some('0') => pad = '0',
Some('\'') => {
let Some(c) = fmt.get(j + 1) else {
return Err(throws("ValueError", "Missing padding character"));
};
pad = *c;
j += 2;
continue;
}
_ => break,
}
j += 1;
}
let mut width = 0usize;
let mut saw_width = false;
while let Some(d) = fmt.get(j).filter(|c| c.is_ascii_digit()) {
saw_width = true;
width = width
.saturating_mul(10)
.saturating_add(*d as usize - '0' as usize);
j += 1;
}
if saw_width && width >= i32::MAX as usize {
return Err(throws(
"ValueError",
format!("Width must be between 0 and {}", i32::MAX),
));
}
let mut precision = None;
if fmt.get(j) == Some(&'.') {
j += 1;
let mut p = 0usize;
let mut saw_prec = false;
while let Some(d) = fmt.get(j).filter(|c| c.is_ascii_digit()) {
saw_prec = true;
p = p
.saturating_mul(10)
.saturating_add(*d as usize - '0' as usize);
j += 1;
}
if saw_prec && p >= i32::MAX as usize {
return Err(throws(
"ValueError",
format!("Precision must be between 0 and {}", i32::MAX),
));
}
precision = Some(p);
}
if fmt.get(j) == Some(&'l') {
j += 1;
}
let conv = fmt.get(j).copied().unwrap_or('\0');
if conv != '\0' {
j += 1;
}
*i = j;
Ok(Some(FmtSpec {
argnum,
left,
plus,
pad,
width,
precision,
conv,
}))
}
fn render_spec(h: &mut host::PhpHost, s: &FmtSpec, v: &Value) -> String {
const MAX_FLOAT_PRECISION: usize = 53;
let s = &if matches!(s.conv, 'f' | 'F' | 'e' | 'E' | 'g' | 'G' | 'h' | 'H')
&& s.precision.is_some_and(|p| p > MAX_FLOAT_PRECISION)
{
let asked = s.precision.unwrap_or(0);
h.notice(format_args!(
"sprintf(): Requested precision of {asked} digits was truncated to \
PHP maximum of {MAX_FLOAT_PRECISION} digits"
));
FmtSpec {
precision: Some(MAX_FLOAT_PRECISION),
..*s
}
} else {
FmtSpec { ..*s }
};
let (body, is_num) = match s.conv {
'd' | 'i' => {
let n = h.to_number(v).to_int();
(signed(n.unsigned_abs().to_string(), n < 0, s), true)
}
'u' => ((h.to_number(v).to_int() as u64).to_string(), true),
'b' => (
(h.to_number(v).to_int() as u64).pipe(|u| format!("{u:b}")),
true,
),
'o' => (
(h.to_number(v).to_int() as u64).pipe(|u| format!("{u:o}")),
true,
),
'x' => (
(h.to_number(v).to_int() as u64).pipe(|u| format!("{u:x}")),
true,
),
'X' => (
(h.to_number(v).to_int() as u64).pipe(|u| format!("{u:X}")),
true,
),
'c' => (
char::from_u32(h.to_number(v).to_int() as u32 & 0xff)
.map(|c| c.to_string())
.unwrap_or_default(),
false,
),
'f' | 'F' => {
let f = h.to_number(v).to_float();
let p = s.precision.unwrap_or(6);
(
signed(format!("{:.*}", p, f.abs()), f.is_sign_negative(), s),
true,
)
}
'e' | 'E' => {
let f = h.to_number(v).to_float();
(fmt_exp(f, s.precision.unwrap_or(6), s.conv == 'E'), true)
}
'g' | 'G' | 'h' | 'H' => {
let f = h.to_number(v).to_float();
let p = s.precision.unwrap_or(6).max(1);
let g = host::php_gcvt(f, p);
let lower = s.conv == 'g' || s.conv == 'h';
(if lower { g.to_lowercase() } else { g }, true)
}
's' => {
let mut txt = h.to_str_diag(v);
if let Some(p) = s.precision {
txt = txt.chars().take(p).collect();
}
(txt, false)
}
other => return format!("%{other}"),
};
pad_field(body, s, is_num)
}
fn signed(mag: String, neg: bool, s: &FmtSpec) -> String {
if neg {
format!("-{mag}")
} else if s.plus {
format!("+{mag}")
} else {
mag
}
}
fn fmt_exp(f: f64, prec: usize, upper: bool) -> String {
let raw = format!("{:.*e}", prec, f);
let (mant, ex) = raw.split_once('e').unwrap_or((raw.as_str(), "0"));
let exp_n: i32 = ex.parse().unwrap_or(0);
let e = if upper { 'E' } else { 'e' };
format!(
"{mant}{e}{}{}",
if exp_n < 0 { "-" } else { "+" },
exp_n.abs()
)
}
fn pad_field(body: String, s: &FmtSpec, is_num: bool) -> String {
let len = body.chars().count();
if len >= s.width {
return body;
}
let fill = s.width - len;
if s.left {
format!("{body}{}", " ".repeat(fill))
} else if s.pad == '0' && is_num {
let mut chars = body.chars();
match body.chars().next() {
Some(sign @ ('-' | '+' | ' ')) => {
chars.next();
format!("{sign}{}{}", "0".repeat(fill), chars.as_str())
}
_ => format!("{}{body}", "0".repeat(fill)),
}
} else {
format!("{}{body}", s.pad.to_string().repeat(fill))
}
}
fn php_wordwrap(h: &host::PhpHost, args: &[Value]) -> Result<Value, String> {
let text = h.to_str(&arg(args, 0));
let raw_width = args.get(1).map(|v| v.to_int()).unwrap_or(75);
let cut_flag = args.get(3).map(|v| h.is_truthy(v)).unwrap_or(false);
if raw_width == 0 && cut_flag {
return Err(throws(
"ValueError",
"wordwrap(): Argument #4 ($cut_long_words) cannot be true when \
argument #2 ($width) is 0",
));
}
let width = raw_width.max(1) as usize;
let brk = args
.get(2)
.map(|v| h.to_str(v))
.unwrap_or_else(|| "\n".to_string());
let cut = args.get(3).map(|v| h.is_truthy(v)).unwrap_or(false);
let mut out = String::new();
for (li, line) in text.split('\n').enumerate() {
if li > 0 {
out.push('\n');
}
let mut cur = 0usize; let mut first = true;
for word in line.split(' ') {
let wlen = word.chars().count();
if !first {
if cur + 1 + wlen <= width {
out.push(' ');
cur += 1;
} else {
out.push_str(&brk);
cur = 0;
}
}
first = false;
if cut && wlen > width {
let chars: Vec<char> = word.chars().collect();
let mut idx = 0;
while idx < chars.len() {
if cur == width {
out.push_str(&brk);
cur = 0;
}
let take = (width - cur).min(chars.len() - idx);
out.extend(&chars[idx..idx + take]);
cur += take;
idx += take;
}
} else {
out.push_str(word);
cur += wlen;
}
}
}
Ok(Value::str(out))
}
trait Pipe: Sized {
fn pipe<R>(self, f: impl FnOnce(Self) -> R) -> R {
f(self)
}
}
impl Pipe for u64 {}
fn php_print_r(h: &host::PhpHost, v: &Value, depth: usize, seen: &mut host::Visiting) -> String {
if let Some(pairs) = h.array_pairs(v) {
if !seen.enter(v) {
return "Array\n *RECURSION*".to_string();
}
let pad = " ".repeat(depth);
let inner = " ".repeat(depth + 1);
let mut s = format!("Array\n{pad}(\n");
for (k, val) in pairs {
s.push_str(&format!(
"{inner}[{}] => {}\n",
h.to_str(&k),
php_print_r(h, &val, depth + 2, seen)
));
}
s.push_str(&format!("{pad})\n"));
seen.leave();
s
} else if h.is_object(v) {
php_print_r_object(h, v, depth, seen)
} else {
h.to_str(v)
}
}
fn php_print_r_object(
h: &host::PhpHost,
v: &Value,
depth: usize,
seen: &mut host::Visiting,
) -> String {
let pad = " ".repeat(depth);
let inner = " ".repeat(depth + 1);
let class = h.object_class(v).unwrap_or_else(|| "stdClass".to_string());
let shown = host::display_class(&class);
let head = match h.enum_case_of(v) {
Some((_, Some(backing))) => format!("{shown} Enum:{}", enum_backing_type(&backing)),
Some((_, None)) => format!("{shown} Enum"),
None => format!("{shown} Object"),
};
if !seen.enter(v) {
return format!("{head}\n *RECURSION*");
}
let mut s = format!("{head}\n{pad}(\n");
for (name, val) in h.object_props(v) {
let label = match h.prop_visibility(&class, &name) {
Some((_, crate::ast::Visibility::Protected)) => format!("{name}:protected"),
Some((declaring, crate::ast::Visibility::Private)) => {
format!("{name}:{declaring}:private")
}
_ => name,
};
s.push_str(&format!(
"{inner}[{label}] => {}\n",
php_print_r(h, &val, depth + 2, seen)
));
}
s.push_str(&format!("{pad})\n"));
seen.leave();
s
}
fn enum_backing_type(backing: &Value) -> &'static str {
match backing {
Value::Int(_) => "int",
_ => "string",
}
}
fn php_var_dump(h: &host::PhpHost, v: &Value, depth: usize) -> String {
php_var_dump_ref(h, v, depth, false, &mut host::Visiting::default())
}
fn php_var_dump_ref(
h: &host::PhpHost,
v: &Value,
depth: usize,
is_ref: bool,
seen: &mut host::Visiting,
) -> String {
let pad = " ".repeat(depth);
if h.is_object(v) || h.is_array(v) {
if !seen.enter(v) {
return format!("{pad}*RECURSION*\n");
}
let out = php_var_dump_body(h, v, depth, is_ref, seen);
seen.leave();
return out;
}
php_var_dump_body(h, v, depth, is_ref, seen)
}
fn php_var_dump_body(
h: &host::PhpHost,
v: &Value,
depth: usize,
is_ref: bool,
seen: &mut host::Visiting,
) -> String {
let pad = " ".repeat(depth);
let amp = if is_ref { "&" } else { "" };
match v {
Value::Undef => format!("{pad}NULL\n"),
Value::Bool(b) => format!("{pad}{amp}bool({})\n", if *b { "true" } else { "false" }),
Value::Int(n) => format!("{pad}{amp}int({n})\n"),
Value::Float(f) => format!(
"{pad}{amp}float({})\n",
crate::stdlib::types::serialize_float(*f)
),
Value::Str(s) => format!("{pad}{amp}string({}) \"{s}\"\n", s.len()),
Value::Obj(_) if h.enum_case_of(v).is_some() => {
let class = h.object_class(v).unwrap_or_default();
let (case, _) = h.enum_case_of(v).unwrap_or_default();
format!("{pad}{amp}enum({class}::{case})\n")
}
Value::Obj(_) if h.is_object(v) => {
let props = h.object_props_marked(v);
let class = h.object_class(v).unwrap_or_else(|| "stdClass".to_string());
let mut s = format!(
"{pad}{amp}object({})#{} ({}) {{\n",
host::display_class(&class),
h.object_ordinal(v),
props.len()
);
for (name, val, pref) in props {
let label = match h.prop_visibility(&class, &name) {
Some((_, crate::ast::Visibility::Protected)) => {
format!("\"{name}\":protected")
}
Some((declaring, crate::ast::Visibility::Private)) => {
format!("\"{name}\":\"{declaring}\":private")
}
_ => format!("\"{name}\""),
};
s.push_str(&format!("{} [{label}]=>\n", " ".repeat(depth)));
s.push_str(&php_var_dump_ref(h, &val, depth + 1, pref, seen));
}
s.push_str(&format!("{pad}}}\n"));
s
}
Value::Obj(_) => {
let pairs = h.array_pairs_marked(v).unwrap_or_default();
let mut s = format!("{pad}{amp}array({}) {{\n", pairs.len());
for (k, val, eref) in pairs {
let key = match k {
Value::Int(n) => format!("{} [{n}]=>\n", " ".repeat(depth)),
other => format!("{} [\"{}\"]=>\n", " ".repeat(depth), h.to_str(&other)),
};
s.push_str(&key);
s.push_str(&php_var_dump_ref(h, &val, depth + 1, eref, seen));
}
s.push_str(&format!("{pad}}}\n"));
s
}
_ => format!("{pad}NULL\n"),
}
}
pub(crate) fn binary_strcmp(a: &[u8], b: &[u8]) -> i64 {
for (x, y) in a.iter().zip(b) {
if x != y {
return *x as i64 - *y as i64;
}
}
match a.len().cmp(&b.len()) {
std::cmp::Ordering::Less => -1,
std::cmp::Ordering::Equal => 0,
std::cmp::Ordering::Greater => 1,
}
}
fn sign(o: std::cmp::Ordering) -> i64 {
match o {
std::cmp::Ordering::Less => -1,
std::cmp::Ordering::Equal => 0,
std::cmp::Ordering::Greater => 1,
}
}
fn php_substr_compare(h: &mut host::PhpHost, args: &[Value]) -> Result<Value, String> {
let main = h.to_str(&arg(args, 0));
let needle = h.to_str(&arg(args, 1));
let mb = main.as_bytes();
let nb = needle.as_bytes();
let slen = mb.len() as i64;
let len_given = matches!(args.get(3), Some(v) if !matches!(v, Value::Undef));
let len = if len_given { arg(args, 3).to_int() } else { 0 };
if len_given && len <= 0 {
if len == 0 {
return Ok(Value::int(0));
}
return Err(throws(
"ValueError",
"substr_compare(): Argument #4 ($length) must be greater than or equal to 0",
));
}
let mut off = arg(args, 2).to_int();
if off < 0 {
off = (slen + off).max(0);
}
if off > slen {
return Err(throws(
"ValueError",
"substr_compare(): Argument #3 ($offset) must be contained in argument #1 ($haystack)",
));
}
let off = off as usize;
let ci = args.get(4).map(|v| h.is_truthy(v)).unwrap_or(false);
let hay = &mb[off..];
let cmp_len = if len != 0 {
len as usize
} else {
nb.len().max(hay.len())
};
let n = cmp_len.min(hay.len()).min(nb.len());
for i in 0..n {
let (a, b) = if ci {
(
hay[i].to_ascii_lowercase() as i64,
nb[i].to_ascii_lowercase() as i64,
)
} else {
(hay[i] as i64, nb[i] as i64)
};
if a != b {
return Ok(Value::int(a - b));
}
}
Ok(Value::int(sign(
cmp_len.min(hay.len()).cmp(&cmp_len.min(nb.len())),
)))
}
fn php_str_split(h: &mut host::PhpHost, args: &[Value]) -> Result<Value, String> {
let s = h.to_str(&arg(args, 0));
let raw_len = args.get(1).map(|v| v.to_int()).unwrap_or(1);
if raw_len < 1 {
return Err(throws(
"ValueError",
"str_split(): Argument #2 ($length) must be greater than 0",
));
}
let len = raw_len as usize;
let chars: Vec<char> = s.chars().collect();
let arr = h.new_array();
for chunk in chars.chunks(len) {
h.arr_push_auto(&arr, Value::str(chunk.iter().collect::<String>()));
}
Ok(arr)
}
fn php_str_pad(h: &host::PhpHost, args: &[Value]) -> Result<String, String> {
let s = h.to_str(&arg(args, 0));
let target = arg(args, 1).to_int();
let pad = match args.get(2) {
Some(v) if !matches!(v, Value::Undef) => {
let p = h.to_str(v);
if p.is_empty() {
return Err(throws(
"ValueError",
"str_pad(): Argument #3 ($pad_string) must not be empty",
));
}
p
}
_ => " ".to_string(),
};
let ty = args.get(3).map(|v| v.to_int()).unwrap_or(1);
let cur = s.chars().count() as i64;
if target <= cur {
return Ok(s);
}
let need = (target - cur) as usize;
let make = |n: usize| -> String { pad.chars().cycle().take(n).collect::<String>() };
Ok(match ty {
0 => format!("{}{}", make(need), s),
2 => {
let left = need / 2;
let right = need - left;
format!("{}{}{}", make(left), s, make(right))
}
_ => format!("{}{}", s, make(need)),
})
}
fn ucwords(s: &str, separators: &str) -> String {
let delims: Vec<u8> = separators.bytes().collect();
let mut bytes = s.as_bytes().to_vec();
let mut cap = true;
for b in &mut bytes {
if cap {
b.make_ascii_uppercase();
}
cap = delims.contains(b);
}
String::from_utf8(bytes).unwrap_or_else(|_| s.to_string())
}
fn lcfirst(s: &str) -> String {
let mut c = s.chars();
match c.next() {
Some(first) if first.is_ascii() => std::iter::once(first.to_ascii_lowercase())
.chain(c)
.collect(),
_ => s.to_string(),
}
}
fn php_number_format(h: &host::PhpHost, args: &[Value]) -> String {
let num = h.to_number(&arg(args, 0)).to_float();
let dec = args.get(1).map(|v| v.to_int()).unwrap_or(0).max(0) as usize;
let dp = args
.get(2)
.map(|v| h.to_str(v))
.unwrap_or_else(|| ".".to_string());
let ts = args
.get(3)
.map(|v| h.to_str(v))
.unwrap_or_else(|| ",".to_string());
let neg = num < 0.0;
let rounded = php_round(num, dec as i32, 1).abs();
let formatted = format!("{:.*}", dec, rounded);
let (int_part, frac_part) = match formatted.split_once('.') {
Some((i, f)) => (i.to_string(), f.to_string()),
None => (formatted.clone(), String::new()),
};
let bytes: Vec<char> = int_part.chars().collect();
let mut grouped = String::new();
for (i, c) in bytes.iter().enumerate() {
if i > 0 && (bytes.len() - i) % 3 == 0 {
grouped.push_str(&ts);
}
grouped.push(*c);
}
let mut out = String::new();
if neg && (grouped.chars().any(|c| c != '0') || frac_part.chars().any(|c| c != '0')) {
out.push('-');
}
out.push_str(&grouped);
if dec > 0 {
out.push_str(&dp);
out.push_str(&frac_part);
}
out
}
fn round_half(value: f64, mode: i64) -> f64 {
let away = value.round();
if (value - value.trunc()).abs() != 0.5 {
return away;
}
let toward = value.trunc();
match mode {
PHP_ROUND_HALF_DOWN => toward,
PHP_ROUND_HALF_EVEN => {
if away % 2.0 == 0.0 {
away
} else {
toward
}
}
PHP_ROUND_HALF_ODD => {
if away % 2.0 == 0.0 {
toward
} else {
away
}
}
_ => away,
}
}
const PHP_ROUND_HALF_DOWN: i64 = 2;
const PHP_ROUND_HALF_EVEN: i64 = 3;
const PHP_ROUND_HALF_ODD: i64 = 4;
pub(crate) fn php_round(value: f64, places: i32, mode: i64) -> f64 {
if !value.is_finite() || value == 0.0 {
return value;
}
let places = places.max(i32::MIN + 1);
let precision_places = 14 - value.abs().log10().floor() as i32;
let f1 = 10f64.powi(places.abs());
let tmp_value = if precision_places > places && precision_places - 15 < places {
let f2 = 10f64.powi(precision_places.abs());
let mut t = if precision_places >= 0 {
value * f2
} else {
value / f2
};
t = round_half(t, mode);
let up = places - precision_places;
let f3 = 10f64.powi(up.abs());
t = if up >= 0 { t * f3 } else { t / f3 };
round_half(t, mode)
} else {
let t = if places >= 0 { value * f1 } else { value / f1 };
if t.abs() >= 1e15 {
return value;
}
round_half(t, mode)
};
if places.abs() < 23 {
if places > 0 {
tmp_value / f1
} else {
tmp_value * f1
}
} else {
format!("{:15.6}e{}", tmp_value, -i64::from(places))
.trim()
.parse::<f64>()
.unwrap_or(tmp_value)
}
}
fn php_pow(args: &[Value]) -> Value {
let (an, bn) = with_host(|h| (h.to_number(&arg(args, 0)), h.to_number(&arg(args, 1))));
deprecate_zero_base_negative_exponent(&an, &bn);
match (an, bn) {
(Value::Int(x), Value::Int(y)) if y >= 0 => match checked_ipow(x, y as u32) {
Some(v) => Value::int(v),
None => Value::float((x as f64).powf(y as f64)),
},
(an, bn) => Value::float(an.to_float().powf(bn.to_float())),
}
}
fn php_intdiv(args: &[Value]) -> Result<Value, String> {
let (a, b) = (arg(args, 0), arg(args, 1));
let (an, bn) = with_host(|h| (h.to_number(&a), h.to_number(&b)));
let (x, y) = (int_operand(&a, &an), int_operand(&b, &bn));
if y == 0 {
return Err(throws("DivisionByZeroError", "Division by zero"));
}
if x == i64::MIN && y == -1 {
return Err(throws(
"ArithmeticError",
"Division of PHP_INT_MIN by -1 is not an integer",
));
}
Ok(Value::int(x / y))
}
fn is_list(pairs: &[(Value, Value)]) -> bool {
pairs
.iter()
.enumerate()
.all(|(i, (k, _))| matches!(k, Value::Int(n) if *n == i as i64))
}
fn php_array_merge(h: &mut host::PhpHost, args: &[Value]) -> Value {
let all: Vec<Vec<(Value, Value)>> = args.iter().filter_map(|a| h.array_pairs(a)).collect();
let out = h.new_array();
for pairs in all {
for (k, v) in pairs {
match k {
Value::Int(_) => h.arr_push_auto(&out, v),
_ => h.arr_set_key(&out, &k, v),
}
}
}
out
}
fn is_callable_arg(cb: &Value) -> bool {
match cb {
Value::Str(s) => !s.is_empty(),
v => with_host(|h| h.is_closure(v)) || host::callable_method(v).is_some(),
}
}
fn php_array_map(args: &[Value]) -> Result<Value, String> {
let cb = arg(args, 0);
let callable = is_callable_arg(&cb);
if args.len() <= 2 {
let arr = arg(args, 1);
let pairs = with_host(|h| h.array_pairs(&arr)).unwrap_or_default();
let mut mapped: Vec<(Value, Value)> = Vec::with_capacity(pairs.len());
for (k, v) in pairs {
let out = if callable {
host::call_value(cb.clone(), vec![v])?
} else {
v
};
if host::unwinding() {
return Ok(Value::Undef);
}
mapped.push((k, out));
}
return Ok(with_host(|h| {
let out = h.new_array();
for (k, v) in mapped {
h.arr_set_key(&out, &k, v);
}
out
}));
}
let arrays: Vec<Vec<Value>> = args[1..]
.iter()
.map(|a| {
with_host(|h| h.array_pairs(a))
.unwrap_or_default()
.into_iter()
.map(|(_, v)| v)
.collect()
})
.collect();
let len = arrays.iter().map(|a| a.len()).max().unwrap_or(0);
let mut result: Vec<Value> = Vec::with_capacity(len);
for i in 0..len {
let row: Vec<Value> = arrays
.iter()
.map(|a| a.get(i).cloned().unwrap_or(Value::Undef))
.collect();
if callable {
let out = host::call_value(cb.clone(), row)?;
if host::unwinding() {
return Ok(Value::Undef);
}
result.push(out);
} else {
result.push(with_host(|h| {
let sub = h.new_array();
for v in row {
h.arr_push_auto(&sub, v);
}
sub
}));
}
}
Ok(with_host(|h| {
let out = h.new_array();
for v in result {
h.arr_push_auto(&out, v);
}
out
}))
}
fn php_array_filter(args: &[Value]) -> Result<Value, String> {
let arr = arg(args, 0);
let cb = arg(args, 1);
let mode = with_host(|h| h.to_number(&arg(args, 2))).to_int();
let pairs = with_host(|h| h.array_pairs(&arr)).unwrap_or_default();
let callable = is_callable_arg(&cb);
let mut kept: Vec<(Value, Value)> = Vec::new();
for (k, v) in pairs {
let keep = if callable {
let cb_args = match mode {
host::ARRAY_FILTER_USE_KEY => vec![k.clone()],
host::ARRAY_FILTER_USE_BOTH => vec![v.clone(), k.clone()],
_ => vec![v.clone()],
};
let r = host::call_value(cb.clone(), cb_args)?;
if host::unwinding() {
return Ok(Value::Undef);
}
with_host(|h| h.is_truthy(&r))
} else {
with_host(|h| h.is_truthy(&v))
};
if keep {
kept.push((k, v));
}
}
Ok(with_host(|h| {
let out = h.new_array();
for (k, v) in kept {
h.arr_set_key(&out, &k, v);
}
out
}))
}
fn php_array_reduce(args: &[Value]) -> Result<Value, String> {
let arr = arg(args, 0);
let cb = arg(args, 1);
let init = arg(args, 2);
let pairs = with_host(|h| h.array_pairs(&arr)).unwrap_or_default();
if !is_callable_arg(&cb) {
return Ok(init);
}
let mut acc = init;
for (_, v) in pairs {
acc = host::call_value(cb.clone(), vec![acc, v])?;
if host::unwinding() {
return Ok(Value::Undef);
}
}
Ok(acc)
}
fn php_array_slice(h: &mut host::PhpHost, args: &[Value]) -> Value {
let arr = arg(args, 0);
let pairs = h.array_pairs(&arr).unwrap_or_default();
let n = pairs.len() as i64;
let mut off = arg(args, 1).to_int();
if off < 0 {
off = (n + off).max(0);
}
let off = off.min(n).max(0) as usize;
let len = match args.get(2) {
Some(v) if !matches!(v, Value::Undef) => {
let l = v.to_int();
if l < 0 {
(n - off as i64 + l).max(0) as usize
} else {
l as usize
}
}
_ => pairs.len() - off,
};
let preserve = args.get(3).map(|v| h.is_truthy(v)).unwrap_or(false);
let end = (off + len).min(pairs.len());
let out = h.new_array();
for (k, v) in &pairs[off..end] {
match k {
Value::Int(_) if !preserve => h.arr_push_auto(&out, v.clone()),
_ => h.arr_set_key(&out, k, v.clone()),
}
}
out
}
fn php_array_reverse(h: &mut host::PhpHost, args: &[Value]) -> Value {
let arr = arg(args, 0);
let pairs = h.array_pairs(&arr).unwrap_or_default();
let preserve = args.get(1).map(|v| h.is_truthy(v)).unwrap_or(false);
let out = h.new_array();
for (k, v) in pairs.into_iter().rev() {
match k {
Value::Int(_) if !preserve => h.arr_push_auto(&out, v),
_ => h.arr_set_key(&out, &k, v),
}
}
out
}
fn php_array_fold(h: &mut host::PhpHost, arr: &Value, product: bool) -> Value {
let op_name = if product {
"Multiplication"
} else {
"Addition"
};
let fname = if product {
"array_product"
} else {
"array_sum"
};
let mut pairs = h.array_pairs(arr).unwrap_or_default();
let mut terms: Vec<Value> = Vec::with_capacity(pairs.len());
for (_, v) in pairs.drain(..) {
let n = match host::classify_arith(&v) {
host::ArithOperand::Numeric(n) => n,
host::ArithOperand::Leading(n) => {
h.warn("A non-numeric value encountered");
n
}
host::ArithOperand::Unsupported => {
let ty = host::arith_type_name(h, &v);
h.warn(format!(
"{fname}(): {op_name} is not supported on type {ty}"
));
match v {
Value::Str(_) => Value::int(0),
_ => continue,
}
}
};
terms.push(n);
}
let pairs: Vec<(Value, Value)> = terms.into_iter().map(|n| (Value::Undef, n)).collect();
let all_int = pairs
.iter()
.all(|(_, v)| matches!(h.to_number(v), Value::Int(_)));
if all_int {
let mut acc: i64 = if product { 1 } else { 0 };
for (_, v) in &pairs {
let n = h.to_number(v).to_int();
let stepped = if product {
acc.checked_mul(n)
} else {
acc.checked_add(n)
};
match stepped {
Some(next) => acc = next,
None => return fold_as_float(h, &pairs, product),
}
}
Value::int(acc)
} else {
fold_as_float(h, &pairs, product)
}
}
fn fold_as_float(h: &host::PhpHost, pairs: &[(Value, Value)], product: bool) -> Value {
let mut acc: f64 = if product { 1.0 } else { 0.0 };
for (_, v) in pairs {
let n = h.to_number(v).to_float();
if product {
acc *= n;
} else {
acc += n;
}
}
Value::float(acc)
}
fn php_array_flip(h: &mut host::PhpHost, arr: &Value) -> Value {
let pairs = h.array_pairs(arr).unwrap_or_default();
let out = h.new_array();
for (k, v) in pairs {
h.arr_set_key(&out, &v, k);
}
out
}
fn php_array_unique(h: &mut host::PhpHost, arr: &Value) -> Value {
let pairs = h.array_pairs(arr).unwrap_or_default();
let out = h.new_array();
let mut seen: std::collections::HashSet<String> = std::collections::HashSet::new();
for (k, v) in pairs {
if seen.insert(h.to_str(&v)) {
h.arr_set_key(&out, &k, v);
}
}
out
}
fn php_array_key_exists(h: &mut host::PhpHost, args: &[Value]) -> Value {
let key = arg(args, 0);
let arr = arg(args, 1);
if let Some(found) = h.array_has_key(&arr, &key) {
return Value::bool(found);
}
let want = h.to_str(&key);
let found = h
.array_pairs(&arr)
.unwrap_or_default()
.iter()
.any(|(k, _)| h.to_str(k) == want);
Value::bool(found)
}
fn php_array_search(h: &host::PhpHost, args: &[Value]) -> Value {
let needle = arg(args, 0);
let arr = arg(args, 1);
let strict = args.get(2).map(|v| h.is_truthy(v)).unwrap_or(false);
for (k, v) in h.array_pairs(&arr).unwrap_or_default() {
let hit = if strict {
strict_eq(h, &needle, &v)
} else {
loose_eq(h, &needle, &v)
};
if hit {
return k;
}
}
Value::bool(false)
}
fn sort_flags(args: &[Value]) -> i64 {
match args.get(1) {
Some(v) if !matches!(v, Value::Undef) => v.to_int(),
_ => 0,
}
}
fn sort_flag_compare(h: &host::PhpHost, a: &Value, b: &Value, flags: i64) -> i32 {
const SORT_FLAG_CASE: i64 = 8;
let fold_case = flags & SORT_FLAG_CASE != 0;
match flags & !SORT_FLAG_CASE {
1 => cmp_f64(h.to_number(a).to_float(), h.to_number(b).to_float()),
2 | 5 => {
let (x, y) = (h.to_str(a), h.to_str(b));
if fold_case {
strcmp_i32(&ascii_lower(&x), &ascii_lower(&y))
} else {
strcmp_i32(&x, &y)
}
}
6 => sign(crate::stdlib::arrays::nat_cmp(
&h.to_str(a),
&h.to_str(b),
fold_case,
)) as i32,
_ => php_compare(h, a, b),
}
}
fn php_sort(h: &mut host::PhpHost, arr: &Value, reverse: bool, flags: i64) -> Value {
let mut vals: Vec<Value> = h
.array_pairs(arr)
.unwrap_or_default()
.into_iter()
.map(|(_, v)| v)
.collect();
vals.sort_by(|a, b| {
if reverse {
sort_flag_compare(h, b, a, flags)
} else {
sort_flag_compare(h, a, b, flags)
}
.cmp(&0)
});
h.arr_set_reindexed(arr, vals);
Value::bool(true)
}
fn php_asort(h: &mut host::PhpHost, arr: &Value, reverse: bool, flags: i64) -> Value {
let mut pairs = h.array_pairs(arr).unwrap_or_default();
pairs.sort_by(|(_, a), (_, b)| {
if reverse {
sort_flag_compare(h, b, a, flags)
} else {
sort_flag_compare(h, a, b, flags)
}
.cmp(&0)
});
h.arr_set_pairs(arr, pairs);
Value::bool(true)
}
fn php_ksort(h: &mut host::PhpHost, arr: &Value, reverse: bool, flags: i64) -> Value {
let mut pairs = h.array_pairs(arr).unwrap_or_default();
pairs.sort_by(|(a, _), (b, _)| {
if reverse {
sort_flag_compare(h, b, a, flags)
} else {
sort_flag_compare(h, a, b, flags)
}
.cmp(&0)
});
h.arr_set_pairs(arr, pairs);
Value::bool(true)
}
fn php_array_fill(h: &mut host::PhpHost, args: &[Value]) -> Result<Value, String> {
let start = arg(args, 0).to_int();
let count = arg(args, 1).to_int();
let val = arg(args, 2);
if count < 0 {
return Err(throws(
"ValueError",
"array_fill(): Argument #2 ($count) must be greater than or equal to 0",
));
}
if count > i64::from(i32::MAX) {
return Err(throws(
"ValueError",
"array_fill(): Argument #2 ($count) is too large",
));
}
let out = h.new_array();
if count == 0 {
return Ok(out);
}
if start > i64::MAX - count + 1 {
return Err(throws_bare("Error", host::NEXT_ELEMENT_OCCUPIED));
}
for i in 0..count {
h.arr_set_key(&out, &Value::int(start + i), val.clone());
}
Ok(out)
}
fn php_array_combine(h: &mut host::PhpHost, args: &[Value]) -> Result<Value, String> {
let keys = h.array_pairs(&arg(args, 0)).unwrap_or_default();
let vals = h.array_pairs(&arg(args, 1)).unwrap_or_default();
if keys.len() != vals.len() {
return Err(throws(
"ValueError",
"array_combine(): Argument #1 ($keys) and argument #2 ($values) \
must have the same number of elements",
));
}
let out = h.new_array();
for ((_, k), (_, v)) in keys.into_iter().zip(vals) {
h.arr_set_key(&out, &k, v);
}
Ok(out)
}
fn php_array_diff(h: &mut host::PhpHost, args: &[Value], intersect: bool) -> Value {
let first = h.array_pairs(&arg(args, 0)).unwrap_or_default();
let others: Vec<std::collections::HashSet<String>> = args[1.min(args.len())..]
.iter()
.map(|a| {
h.array_pairs(a)
.unwrap_or_default()
.into_iter()
.map(|(_, v)| h.to_str(&v))
.collect()
})
.collect();
let out = h.new_array();
for (k, v) in first {
let s = h.to_str(&v);
let in_all = others.iter().all(|set| set.contains(&s));
let in_any = others.iter().any(|set| set.contains(&s));
let keep = if intersect { in_all } else { !in_any };
if keep {
h.arr_set_key(&out, &k, v);
}
}
out
}
fn php_var_export(
h: &mut host::PhpHost,
v: &Value,
depth: usize,
seen: &mut host::Visiting,
) -> String {
if (h.is_array(v) || h.is_object(v)) && !seen.enter(v) {
h.warn("var_export does not handle circular references");
return "NULL".to_string();
}
let out = php_var_export_body(h, v, depth, seen);
if h.is_array(v) || h.is_object(v) {
seen.leave();
}
out
}
fn php_var_export_body(
h: &mut host::PhpHost,
v: &Value,
depth: usize,
seen: &mut host::Visiting,
) -> String {
match v {
Value::Undef => "NULL".to_string(),
Value::Bool(b) => if *b { "true" } else { "false" }.to_string(),
Value::Int(n) => n.to_string(),
Value::Float(f) => {
let s = crate::stdlib::types::serialize_float(*f);
if f.is_finite() && !s.contains('.') {
format!("{s}.0")
} else {
s
}
}
Value::Str(s) => format!("'{}'", s.replace('\\', "\\\\").replace('\'', "\\'")),
Value::Obj(_) if h.is_object(v) => php_var_export_object(h, v, depth, seen),
Value::Obj(_) if h.is_array(v) => {
let pad = " ".repeat(depth);
let inner = " ".repeat(depth + 1);
let mut out = "array (\n".to_string();
for (k, val) in h.array_pairs(v).unwrap_or_default() {
let key = match k {
Value::Int(n) => n.to_string(),
other => format!("'{}'", h.to_str(&other).replace('\'', "\\'")),
};
out.push_str(&format!(
"{inner}{key} => {},\n",
var_export_item(h, &val, depth + 1, seen)
));
}
out.push_str(&format!("{pad})"));
out
}
_ => "NULL".to_string(),
}
}
fn var_export_item(
h: &mut host::PhpHost,
v: &Value,
depth: usize,
seen: &mut host::Visiting,
) -> String {
let body = php_var_export(h, v, depth, seen);
if (h.is_array(v) || h.is_object(v)) && body != "NULL" {
format!("\n{}{body}", " ".repeat(depth))
} else {
body
}
}
fn php_var_export_object(
h: &mut host::PhpHost,
v: &Value,
depth: usize,
seen: &mut host::Visiting,
) -> String {
let class = h.object_class(v).unwrap_or_else(|| "stdClass".to_string());
if let Some((case, _)) = h.enum_case_of(v) {
return format!("\\{class}::{case}");
}
let pad = " ".repeat(depth);
let inner = format!("{pad} ");
let std = class == "stdClass";
let mut out = if std {
"(object) array(\n".to_string()
} else {
format!("\\{class}::__set_state(array(\n")
};
for (name, val) in h.object_props(v) {
out.push_str(&format!(
"{inner}'{}' => {},\n",
name.replace('\'', "\\'"),
var_export_item(h, &val, depth + 1, seen)
));
}
out.push_str(&format!("{pad}{}", if std { ")" } else { "))" }));
out
}
fn count_recursive(h: &mut host::PhpHost, v: &Value) -> i64 {
count_recursive_seen(h, v, &mut host::Visiting::default())
}
fn count_recursive_seen(h: &mut host::PhpHost, v: &Value, seen: &mut host::Visiting) -> i64 {
if !seen.enter(v) {
h.warn("count(): Recursion detected");
return 0;
}
let total = h
.array_pairs(v)
.unwrap_or_default()
.iter()
.map(|(_, val)| {
if h.is_array(val) {
1 + count_recursive_seen(h, val, seen)
} else {
1
}
})
.sum();
seen.leave();
total
}
fn has_nonfinite_float(h: &host::PhpHost, v: &Value) -> bool {
match v {
Value::Float(f) => !f.is_finite(),
Value::Obj(_) if h.is_object(v) => h
.object_props(v)
.iter()
.any(|(_, val)| has_nonfinite_float(h, val)),
Value::Obj(_) => h
.array_pairs(v)
.unwrap_or_default()
.iter()
.any(|(_, val)| has_nonfinite_float(h, val)),
_ => false,
}
}
fn json_prepare(v: &Value) -> Result<Value, i64> {
json_prepare_seen(v, &mut host::Visiting::default())
}
fn json_prepare_seen(v: &Value, seen: &mut host::Visiting) -> Result<Value, i64> {
if with_host(|h| h.is_array(v)) {
if !seen.enter(v) {
return Err(crate::stdlib::json::JSON_ERROR_RECURSION);
}
let pairs = with_host(|h| h.array_pairs(v)).unwrap_or_default();
let mut out = Vec::with_capacity(pairs.len());
for (k, val) in pairs {
out.push((k, json_prepare_seen(&val, seen)?));
}
seen.leave();
return Ok(with_host(|h| {
let arr = h.new_array();
h.arr_set_pairs(&arr, out);
arr
}));
}
if !with_host(|h| h.is_object(v)) {
return Ok(v.clone());
}
if !seen.enter(v) {
return Err(crate::stdlib::json::JSON_ERROR_RECURSION);
}
let class = with_host(|h| h.object_class(v)).unwrap_or_default();
if with_host(|h| h.is_enum_class(&class)) {
seen.leave();
return match with_host(|h| h.enum_case_of(v)) {
Some((_, Some(backing))) => Ok(backing),
_ => Err(crate::stdlib::json::JSON_ERROR_NON_BACKED_ENUM),
};
}
if with_host(|h| h.class_is_a_pub(&class, "JsonSerializable")) {
let produced = host::call_method(&class, "jsonSerialize", Some(v.clone()), Vec::new())
.map_err(|_| crate::stdlib::json::JSON_ERROR_NON_BACKED_ENUM)?;
let out = json_prepare_seen(&produced, seen);
seen.leave();
return out;
}
let mut out = Vec::new();
for (name, val) in with_host(|h| h.object_props(v)) {
if with_host(|h| h.prop_visibility(&class, &name)).is_some() {
continue;
}
out.push((name, json_prepare_seen(&val, seen)?));
}
seen.leave();
Ok(with_host(|h| h.new_transient_object(out)))
}
const JSON_UNESCAPED_SLASHES: i64 = 64;
const JSON_FORCE_OBJECT: i64 = 16;
const JSON_PRETTY_PRINT: i64 = 128;
const JSON_UNESCAPED_UNICODE: i64 = 256;
const JSON_HEX_TAG: i64 = 1;
const JSON_HEX_AMP: i64 = 2;
const JSON_HEX_APOS: i64 = 4;
const JSON_HEX_QUOT: i64 = 8;
const JSON_NUMERIC_CHECK: i64 = 32;
fn json_numeric_check(s: &str) -> Option<String> {
match host::parse_php_number_full(s)? {
Value::Int(n) => Some(n.to_string()),
Value::Float(f) if f.is_finite() => {
Some(crate::stdlib::types::serialize_float(f).replace('E', "e"))
}
_ => None,
}
}
fn php_json_encode(h: &host::PhpHost, v: &Value, flags: i64, depth: usize) -> String {
let pretty = flags & JSON_PRETTY_PRINT != 0;
match v {
Value::Undef => "null".to_string(),
Value::Bool(b) => if *b { "true" } else { "false" }.to_string(),
Value::Int(n) => n.to_string(),
Value::Float(f) => crate::stdlib::types::serialize_float(*f).replace('E', "e"),
Value::Str(s) => match (flags & JSON_NUMERIC_CHECK != 0)
.then(|| json_numeric_check(s))
.flatten()
{
Some(n) => n,
None => json_string(s, flags),
},
Value::Obj(_) => {
let pairs = if h.is_object(v) {
h.object_props(v)
.into_iter()
.map(|(k, val)| (Value::str(k), val))
.collect()
} else {
h.array_pairs(v).unwrap_or_default()
};
let as_list = is_list(&pairs) && !h.is_object(v) && flags & JSON_FORCE_OBJECT == 0;
let (open, close) = if as_list { ('[', ']') } else { ('{', '}') };
if pairs.is_empty() {
return format!("{open}{close}");
}
let items: Vec<String> = pairs
.iter()
.map(|(k, val)| {
let encoded = php_json_encode(h, val, flags, depth + 1);
if as_list {
encoded
} else {
let key = json_string(&h.to_str(k), flags);
let sep = if pretty { ": " } else { ":" };
format!("{key}{sep}{encoded}")
}
})
.collect();
if pretty {
let inner = " ".repeat(depth + 1);
let outer = " ".repeat(depth);
format!(
"{open}\n{inner}{}\n{outer}{close}",
items.join(&format!(",\n{inner}"))
)
} else {
format!("{open}{}{close}", items.join(","))
}
}
_ => "null".to_string(),
}
}
fn json_string(s: &str, flags: i64) -> String {
let escape_slashes = flags & JSON_UNESCAPED_SLASHES == 0;
let escape_unicode = flags & JSON_UNESCAPED_UNICODE == 0;
let mut out = String::with_capacity(s.len() + 2);
out.push('"');
for c in s.chars() {
match c {
'<' if flags & JSON_HEX_TAG != 0 => out.push_str("\\u003C"),
'>' if flags & JSON_HEX_TAG != 0 => out.push_str("\\u003E"),
'&' if flags & JSON_HEX_AMP != 0 => out.push_str("\\u0026"),
'\'' if flags & JSON_HEX_APOS != 0 => out.push_str("\\u0027"),
'"' if flags & JSON_HEX_QUOT != 0 => out.push_str("\\u0022"),
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
'\n' => out.push_str("\\n"),
'\r' => out.push_str("\\r"),
'\t' => out.push_str("\\t"),
'\u{8}' => out.push_str("\\b"),
'\u{c}' => out.push_str("\\f"),
'/' if escape_slashes => out.push_str("\\/"),
c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
c if escape_unicode && !c.is_ascii() => {
let mut buf = [0u16; 2];
for unit in c.encode_utf16(&mut buf) {
out.push_str(&format!("\\u{unit:04x}"));
}
}
c => out.push(c),
}
}
out.push('"');
out
}