use crate::host::{self, ops, with_host, PropAccess};
use crate::stdlib::common::bytes_arg;
use fusevm::{NumOp, NumericCall, Value, VM};
macro_rules! reg {
($vm:expr, $op:expr, $f:path) => {{
fn wrapped(vm: &mut VM, argc: u8) -> Value {
if host::drain_error_handlers() {
vm.ip = vm.chunk.ops.len();
return Value::Undef;
}
let v = $f(vm, argc);
if crate::stdlib::output::drain_chunks() {
vm.ip = vm.chunk.ops.len();
}
if host::drain_error_handlers() {
vm.ip = vm.chunk.ops.len();
}
v
}
$vm.register_builtin($op, wrapped);
}};
}
pub fn install(vm: &mut VM) {
reg!(vm, ops::ECHO, b_echo);
reg!(vm, ops::INCLUDE, b_include);
reg!(vm, ops::EVAL, b_eval);
reg!(vm, ops::GETVAR, b_getvar);
reg!(vm, ops::GETSLOT, b_getslot);
reg!(vm, ops::INCDEC_SLOT, b_incdec_slot);
reg!(vm, ops::GETSLOT_Q, b_getslot_q);
reg!(vm, ops::SETSLOT, b_setslot);
reg!(vm, ops::SETVAR, b_setvar);
reg!(vm, ops::COPY, b_copy);
reg!(vm, ops::CONCAT, b_concat);
reg!(vm, ops::CONCAT_ASSIGN_FSLOT, b_concat_assign_fslot);
reg!(vm, ops::CONCAT_ASSIGN_SLOT, b_concat_assign_slot);
reg!(vm, ops::CONCAT_ASSIGN_VAR, b_concat_assign_var);
reg!(vm, ops::FOREACH_KEYS, b_foreach_keys);
reg!(vm, ops::IS_PLAIN_OBJECT, b_is_plain_object);
reg!(vm, ops::PROP_DIM_WRITEBACK, b_prop_dim_writeback);
reg!(vm, ops::SPROP_DIM_WRITEBACK, b_sprop_dim_writeback);
reg!(vm, ops::TRUTHY, b_truthy);
reg!(vm, ops::CALL, b_call);
reg!(vm, ops::MINMAX_FLF2, b_minmax_flf2);
reg!(vm, ops::BYREF_ARG_DIAG, b_byref_arg_diag);
reg!(vm, ops::GLOBAL_BIND, b_global_bind);
reg!(vm, ops::INCDEC_STEP, b_incdec_step);
reg!(vm, ops::MATCH_ERROR_MSG, b_match_error_msg);
reg!(vm, ops::CALL_SPREAD, b_call_spread);
reg!(vm, ops::MKARRAY, b_mkarray);
reg!(vm, ops::MKARRAY_ADD, b_mkarray_add);
reg!(vm, ops::INDEX_GET, b_index_get);
reg!(vm, ops::INDEX_SET, b_index_set);
reg!(vm, ops::ARR_APPEND, b_arr_append);
reg!(vm, ops::SET_PATH, b_set_path);
reg!(vm, ops::APPEND_PATH, b_append_path);
reg!(vm, ops::GET_PATH, b_get_path);
reg!(vm, ops::INCDEC_PATH, b_incdec_path);
reg!(vm, ops::PATH_APPEND_CHILD, b_path_append_child);
reg!(vm, ops::DIV, b_div);
reg!(vm, ops::MOD, b_mod);
reg!(vm, ops::POW, b_pow);
reg!(vm, ops::LOOSE_EQ, b_loose_eq);
reg!(vm, ops::LOOSE_NE, b_loose_ne);
reg!(vm, ops::STRICT_EQ, b_strict_eq);
reg!(vm, ops::STRICT_NE, b_strict_ne);
reg!(vm, ops::LT, b_lt);
reg!(vm, ops::GT, b_gt);
reg!(vm, ops::LE, b_le);
reg!(vm, ops::GE, b_ge);
reg!(vm, ops::SIG_RETURN, b_sig_return);
reg!(vm, ops::INCDEC, b_incdec);
reg!(vm, ops::ARRAYKEYS, b_arraykeys);
reg!(vm, ops::ARRAYLEN, b_arraylen);
reg!(vm, ops::BITAND, b_bitand);
reg!(vm, ops::BITOR, b_bitor);
reg!(vm, ops::BITXOR, b_bitxor);
reg!(vm, ops::SHL, b_shl);
reg!(vm, ops::SHR, b_shr);
reg!(vm, ops::BITNOT, b_bitnot);
reg!(vm, ops::SPACESHIP, b_spaceship);
reg!(vm, ops::DBG_LINE, b_dbg_line);
reg!(vm, ops::ARR_MUT, b_arr_mut);
reg!(vm, ops::MKCLOSURE, b_mkclosure);
reg!(vm, ops::CALL_VALUE, b_call_value);
reg!(vm, ops::NEW, b_new);
reg!(vm, ops::PROP_GET, b_prop_get);
reg!(vm, ops::PROP_SET, b_prop_set);
reg!(vm, ops::PROP_ENSURE_ARRAY, b_prop_ensure_array);
reg!(vm, ops::PROP_TOUCH, b_prop_touch);
reg!(vm, ops::PROP_SET_RW, b_prop_set_rw);
reg!(vm, ops::PROP_UNSET, b_prop_unset);
reg!(vm, ops::PROP_ISSET, b_prop_isset);
reg!(vm, ops::INDEX_ISSET, b_index_isset);
reg!(vm, ops::DECL_FATAL, b_decl_fatal);
reg!(vm, ops::DECLARE_FN, b_declare_fn);
reg!(vm, ops::DECLARE_CLASS, b_declare_class);
reg!(vm, ops::FINAL_CHECK, b_final_check);
reg!(vm, ops::DYN_CLASS, b_dyn_class);
reg!(vm, ops::DYN_CLASS_CONST, b_dyn_class_const);
reg!(vm, ops::CLONE, b_clone);
reg!(vm, ops::CLONE_WITH, b_clone_with);
reg!(vm, ops::GLOBALS_ARRAY, b_globals_array);
reg!(vm, ops::GLOBALS_GET, b_globals_get);
reg!(vm, ops::GLOBALS_GET_Q, b_globals_get_q);
reg!(vm, ops::GLOBALS_BIND, b_globals_bind);
reg!(vm, ops::GLOBALS_UNSET, b_globals_unset);
reg!(vm, ops::GLOBALS_ISSET, b_globals_isset);
reg!(vm, ops::NS_FN_NAME, b_ns_fn_name);
reg!(vm, ops::CONST_FETCH_NS, b_const_fetch_ns);
reg!(vm, ops::CLASS_LINK_CHECK, b_class_link_check);
reg!(vm, ops::REF_SLOT_SPROP, b_ref_slot_sprop);
reg!(vm, ops::REF_TO_SPROP, b_ref_to_sprop);
reg!(vm, ops::STATIC_HAS, b_static_has);
reg!(vm, ops::CONST_DECL, b_const_decl);
reg!(vm, ops::PROP_GET_EMPTY, b_prop_get_empty);
reg!(vm, ops::PROP_INCDEC, b_prop_incdec);
reg!(vm, ops::SUPPRESS_PUSH, b_suppress_push);
reg!(vm, ops::SUPPRESS_POP, b_suppress_pop);
reg!(vm, ops::MCALL, b_mcall);
reg!(vm, ops::MCALL_RECV_CHECK, b_mcall_recv_check);
reg!(vm, ops::CALL_NAME_CHECK, b_call_name_check);
reg!(vm, ops::CALL_CLASS_CHECK, b_call_class_check);
reg!(vm, ops::CALLVALUE_CHECK, b_callvalue_check);
reg!(vm, ops::SCALL_CALLEE_CHECK, b_scall_callee_check);
reg!(vm, ops::FCC_CHECK, b_fcc_check);
reg!(vm, ops::SCALL, b_scall);
reg!(vm, ops::SCONST, b_sconst);
reg!(vm, ops::THROW, b_throw);
reg!(vm, ops::RUN_TRY, b_run_try);
reg!(vm, ops::SIG_HALT, b_sig_halt);
reg!(vm, ops::SIG_BREAK, b_sig_break);
reg!(vm, ops::SIG_CONTINUE, b_sig_continue);
reg!(vm, ops::SIG_LEVEL, b_sig_level);
reg!(vm, ops::CONST_FETCH, b_const_fetch);
reg!(vm, ops::MAGIC_FILE, b_magic_file);
reg!(vm, ops::MAGIC_DIR, b_magic_dir);
reg!(vm, ops::MAGIC_CLASS, b_magic_class);
reg!(vm, ops::SELF_CLASS, b_self_class);
reg!(vm, ops::PARENT_CLASS, b_parent_class);
reg!(vm, ops::UNSET_VAR, b_unset_var);
reg!(vm, ops::UNSET_PATH, b_unset_path);
reg!(vm, ops::FOREACH_PREP, b_foreach_prep);
reg!(vm, ops::INSTANCEOF, b_instanceof);
reg!(vm, ops::REF_BIND, b_ref_bind);
reg!(vm, ops::REF_CELL, b_ref_cell);
reg!(vm, ops::REF_SLOT_VAR, b_ref_slot_var);
reg!(vm, ops::REF_SLOT_ELEM, b_ref_slot_elem);
reg!(vm, ops::REF_SLOT_PROP, b_ref_slot_prop);
reg!(vm, ops::REF_TO_VAR, b_ref_to_var);
reg!(vm, ops::REF_TO_ELEM, b_ref_to_elem);
reg!(vm, ops::REF_TO_APPEND, b_ref_to_append);
reg!(vm, ops::REF_TO_PROP, b_ref_to_prop);
reg!(vm, ops::GETVAR_Q, b_getvar_q);
reg!(vm, ops::INDEX_GET_Q, b_index_get_q);
reg!(vm, ops::INDEX_GET_EMPTY, b_index_get_empty);
reg!(vm, ops::LIST_ELEM_GET, b_list_elem_get);
reg!(vm, ops::PROP_GET_Q, b_prop_get_q);
reg!(vm, ops::LSB_CLASS, b_lsb_class);
reg!(vm, ops::LSB_FORWARD, b_lsb_forward);
reg!(vm, ops::RET_REF, b_ret_ref);
reg!(vm, ops::REF_SLOT_RET, b_ref_slot_ret);
reg!(vm, ops::BYREF_OUT, b_byref_out);
reg!(vm, ops::BYREF_LIVE, b_byref_live);
reg!(vm, ops::SPROP_GET, b_sprop_get);
reg!(vm, ops::SPROP_SET, b_sprop_set);
reg!(vm, ops::SPROP_INCDEC, b_sprop_incdec);
reg!(vm, ops::SPROP_GET_Q, b_sprop_get_q);
reg!(vm, ops::STATIC_BIND, b_static_bind);
reg!(vm, ops::CALL_NAMED, b_call_named);
reg!(vm, ops::MCALL_NAMED, b_mcall_named);
reg!(vm, ops::SCALL_NAMED, b_scall_named);
reg!(vm, ops::NEW_NAMED, b_new_named);
reg!(vm, ops::NEW_ALLOC, b_new_alloc);
reg!(vm, ops::SPROP_ENSURE_ARRAY, b_sprop_ensure_array);
reg!(vm, ops::NEW_INIT, b_new_init);
reg!(vm, ops::NEW_INIT_NAMED, b_new_init_named);
reg!(vm, ops::CALLVALUE_NAMED, b_callvalue_named);
reg!(vm, ops::YIELD, b_yield);
reg!(vm, ops::YIELD_KV, b_yield_kv);
reg!(vm, ops::YIELD_FROM, b_yield_from);
reg!(vm, ops::IS_GENERATOR, b_is_generator);
reg!(vm, ops::GEN_REWIND, b_gen_rewind);
reg!(vm, ops::GEN_RELEASE, b_gen_release);
reg!(vm, ops::GEN_MARK, b_gen_mark);
reg!(vm, ops::PROP_FETCH_W, b_prop_fetch_w);
reg!(vm, ops::BYREF_ARG_DIAG_M, b_byref_arg_diag_m);
reg!(vm, ops::GEN_VALID, b_gen_valid);
reg!(vm, ops::GEN_KEY, b_gen_key);
reg!(vm, ops::GEN_CURRENT, b_gen_current);
reg!(vm, ops::GEN_NEXT, b_gen_next);
reg!(vm, ops::FOREACH_ITER, b_foreach_iter);
reg!(vm, ops::IS_LAZY_ITER, b_is_lazy_iter);
}
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() || e == host::GEN_DESTROY {
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 mark_foreach_line(vm: &VM) {
if cur_op_line(vm) > 0 {
mark_frame_line(vm);
}
}
fn b_is_lazy_iter(vm: &mut VM, _: u8) -> Value {
let v = vm.pop();
Value::bool(host::is_lazy_iter(&v))
}
fn b_foreach_iter(vm: &mut VM, _: u8) -> Value {
let v = vm.pop();
mark_foreach_line(vm);
match host::foreach_iter(v) {
Ok(it) => bubbled(vm, it),
Err(e) => fail_or_throw(vm, e),
}
}
fn b_gen_mark(_: &mut VM, _: u8) -> Value {
Value::int(host::gen_mark())
}
fn b_gen_release(vm: &mut VM, _: u8) -> Value {
let mark = vm.pop().to_int();
let g = vm.pop();
match host::gen_release(&g, mark) {
Ok(()) => bubbled(vm, Value::Undef),
Err(e) => yield_err(vm, e),
}
}
fn b_gen_rewind(vm: &mut VM, _: u8) -> Value {
let g = vm.pop();
mark_foreach_line(vm);
let r = if with_host(|h| h.is_generator_val(&g)) {
host::gen_foreach_rewind(&g).map(|()| Value::Undef)
} else {
host::iter_call(&g, "rewind").map(|_| Value::Undef)
};
match r {
Ok(v) => bubbled(vm, v),
Err(e) => yield_err(vm, e),
}
}
fn b_gen_valid(vm: &mut VM, _: u8) -> Value {
let g = vm.pop();
mark_foreach_line(vm);
let r = if with_host(|h| h.is_generator_val(&g)) {
host::gen_valid(&g)
} else {
host::iter_call(&g, "valid").map(|v| with_host(|h| h.is_truthy(&v)))
};
match r {
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();
mark_foreach_line(vm);
let r = if with_host(|h| h.is_generator_val(&g)) {
host::gen_key(&g)
} else {
host::iter_call(&g, "key")
};
match r {
Ok(v) => bubbled(vm, v),
Err(e) => yield_err(vm, e),
}
}
fn b_gen_current(vm: &mut VM, _: u8) -> Value {
let g = vm.pop();
mark_foreach_line(vm);
let r = if with_host(|h| h.is_generator_val(&g)) {
host::gen_current(&g)
} else {
host::iter_call(&g, "current")
};
match r {
Ok(v) => bubbled(vm, v),
Err(e) => yield_err(vm, e),
}
}
fn b_gen_next(vm: &mut VM, _: u8) -> Value {
let g = vm.pop();
mark_foreach_line(vm);
let r = if with_host(|h| h.is_generator_val(&g)) {
host::gen_next(&g)
} else {
host::iter_call(&g, "next")
};
match r {
Ok(v) => bubbled(vm, v),
Err(e) => yield_err(vm, e),
}
}
type SplitArgs = (Vec<Value>, Vec<(String, Value)>);
fn split_named(pairs: Vec<Value>) -> Result<SplitArgs, String> {
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)),
Value::Bool(true) => {
for (k, v) in spread_entries(&val).map_err(|(_, e)| e)? {
match k {
Value::Str(_) => named.push((with_host(|h| h.to_str(&k)), v)),
_ => positional.push(v),
}
}
}
_ => positional.push(val),
}
}
Ok((positional, named))
}
macro_rules! split_named_or_throw {
($vm:expr, $pairs:expr) => {
match split_named($pairs) {
Ok(v) => v,
Err(e) => return throw_php($vm, "TypeError", &e),
}
};
}
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_or_throw!(vm, pairs);
mark_frame_line(vm);
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_or_throw!(vm, 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_or_throw!(vm, 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_or_throw(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_or_throw!(vm, 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_alloc(vm: &mut VM, _: u8) -> Value {
let class = pop_name(vm);
mark_frame_line(vm);
match host::new_alloc(&class) {
Ok(v) => bubbled(vm, v),
Err(e) => fail_or_throw(vm, e),
}
}
fn b_new_init(vm: &mut VM, argc: u8) -> Value {
let mut args = pop_args(vm, argc as usize);
let obj = args.remove(0);
let class = with_host(|h| h.object_class(&obj)).unwrap_or_default();
mark_frame_line(vm);
match host::construct_object(&obj, &class, args, Vec::new()) {
Ok(()) => bubbled(vm, obj),
Err(e) => fail_or_throw(vm, e),
}
}
fn b_new_init_named(vm: &mut VM, argc: u8) -> Value {
let pairs = pop_args(vm, argc as usize - 1);
let obj = vm.pop();
let (pos, named) = split_named_or_throw!(vm, pairs);
let class = with_host(|h| h.object_class(&obj)).unwrap_or_default();
mark_frame_line(vm);
match host::construct_object(&obj, &class, pos, named) {
Ok(()) => bubbled(vm, obj),
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_or_throw!(vm, 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_ensure_array(vm: &mut VM, _: u8) -> Value {
let name = pop_name(vm);
let class = pop_name(vm);
mark_warn_site(vm);
match host::static_prop_ensure_array(&class, &name) {
Ok(v) => v,
Err(e) => fail_or_throw(vm, e),
}
}
fn b_prop_dim_writeback(vm: &mut VM, _: u8) -> Value {
let container = vm.pop();
let name = pop_name(vm);
let recv = vm.pop();
let val = vm.pop();
if matches!(container, Value::Str(_)) {
with_host(|h| h.prop_set(&recv, &name, container));
}
val
}
fn b_sprop_dim_writeback(vm: &mut VM, _: u8) -> Value {
let container = vm.pop();
let name = pop_name(vm);
let class = pop_name(vm);
let val = vm.pop();
if matches!(container, Value::Str(_)) {
if let Err(e) = host::static_prop_set(&class, &name, container) {
return fail_or_throw(vm, e);
}
}
val
}
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_get_q(vm: &mut VM, _: u8) -> Value {
let name = pop_name(vm);
let class = pop_name(vm);
match host::static_prop_get_quiet(&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);
let declared = with_host(|h| {
h.resolve_static_owner(&class, &name)
.and_then(|owner| h.prop_type(&owner, &name))
});
let val = match declared {
Some((owner, ty)) => match check_prop_type(vm, &owner, &name, &ty, val) {
Some(v) => v,
None => return Value::Undef,
},
None => val,
};
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 overflowed_to_float(&old, &newv) {
let declared = with_host(|h| {
h.resolve_static_owner(&class, &name)
.and_then(|owner| h.prop_type(&owner, &name))
});
if let Some((owner, ty)) = declared {
if incdec_overflow_refused(vm, &owner, &name, &ty, inc) {
return Value::Undef;
}
}
}
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_has(vm: &mut VM, _: u8) -> Value {
let key = pop_name(vm);
Value::bool(with_host(|h| h.static_initialized(&key)))
}
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);
if let Some(thrown) =
guard_array_write(vm, &name, &keys[..keys.len() - 1], host::WriteTail::Ref)
{
return thrown;
}
Value::int(with_host(|h| h.elem_ref_slot(&name, &keys)) as i64)
}
fn indirect_write_refusal(recv: &Value, prop: &str) -> Option<String> {
with_host(|h| {
h.set_visibility_error(recv, prop, "indirectly modify")
.or_else(|| h.readonly_indirect_error(recv, prop))
})
}
fn b_ref_slot_prop(vm: &mut VM, _: u8) -> Value {
let prop = pop_name(vm);
let recv = vm.pop();
if let Some(msg) = indirect_write_refusal(&recv, &prop) {
return throw_php(vm, "Error", &msg);
}
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);
if let Some(thrown) = guard_array_write(vm, &name, &keys, host::WriteTail::Append) {
return thrown;
}
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_slot_sprop(vm: &mut VM, _: u8) -> Value {
let name = pop_name(vm);
let class = pop_name(vm);
match host::static_prop_ref_slot(&class, &name) {
Ok(slot) => Value::int(slot as i64),
Err(e) => fail_or_throw(vm, e),
}
}
fn b_ref_to_sprop(vm: &mut VM, _: u8) -> Value {
let slot = vm.pop().to_int() as usize;
let name = pop_name(vm);
let class = pop_name(vm);
match host::static_prop_bind(&class, &name, slot) {
Ok(v) => v,
Err(e) => fail_or_throw(vm, 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();
if let Some(msg) = indirect_write_refusal(&recv, &prop) {
return throw_php(vm, "Error", &msg);
}
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.instance_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(host::anchored_class(s));
}
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.instance_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_clone_with(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc as usize);
mark_frame_line(vm);
let line = with_host(|h| h.cur_frame_line());
let shown = crate::stdlib::common::make_list(args.clone());
let scoped = with_host(|h| h.enter_clone_frame(line, shown));
let out = clone_with(vm, args);
with_host(|h| h.leave_clone_frame(scoped));
out
}
fn clone_with(vm: &mut VM, args: Vec<Value>) -> Value {
if args.is_empty() {
return throw_php(
vm,
"ArgumentCountError",
"clone() expects at least 1 argument, 0 given",
);
}
if args.len() > 2 {
return throw_php(
vm,
"ArgumentCountError",
&format!("clone() expects at most 2 arguments, {} given", args.len()),
);
}
let (obj, props) = (args[0].clone(), args[1].clone());
if !with_host(|h| h.is_array(&props)) {
let given = with_host(|h| h.type_name_for_error(&props));
return throw_php(
vm,
"TypeError",
&format!("clone(): Argument #2 ($withProperties) must be of type array, {given} given"),
);
}
let copy = match host::clone_object(obj) {
Ok(copy) => copy,
Err(e) => return fail_or_throw(vm, e),
};
if bubble_throw(vm) {
return Value::Undef;
}
let pairs = with_host(|h| h.array_pairs(&props)).unwrap_or_default();
for (key, value) in pairs {
let name = std::sync::Arc::new(with_host(|h| h.to_str(&key)));
host::in_clone_with(©, || prop_assign(vm, copy.clone(), name, value));
if bubble_throw(vm) {
return Value::Undef;
}
}
copy
}
fn b_globals_array(_: &mut VM, _: u8) -> Value {
with_host(|h| h.globals_array())
}
fn b_globals_get(vm: &mut VM, _: u8) -> Value {
let name = pop_name(vm);
mark_frame_line(vm);
match with_host(|h| h.global_value(&name)) {
Some(v) => v,
None => {
mark_warn_site(vm);
with_host(|h| h.warn(format!("Undefined global variable ${name}")));
Value::Undef
}
}
}
fn b_globals_get_q(vm: &mut VM, _: u8) -> Value {
let name = pop_name(vm);
with_host(|h| h.global_value(&name)).unwrap_or(Value::Undef)
}
fn b_globals_bind(vm: &mut VM, _: u8) -> Value {
let name = pop_name(vm);
let local = pop_name(vm);
with_host(|h| h.globals_bind(&local, &name));
Value::Undef
}
fn b_globals_unset(vm: &mut VM, _: u8) -> Value {
let name = pop_name(vm);
with_host(|h| h.globals_unset(&name));
Value::Undef
}
fn b_globals_isset(vm: &mut VM, _: u8) -> Value {
let name = pop_name(vm);
let set = with_host(|h| h.global_value(&name)).is_some_and(|v| !matches!(v, Value::Undef));
Value::bool(set)
}
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);
mark_warn_site(vm);
match with_host(|h| h.const_use(&name)) {
Some(_) if bubble_throw(vm) => Value::Undef,
Some(v) => v,
None => {
mark_frame_line(vm);
throw_php(vm, "Error", &undefined_constant(&name))
}
}
}
fn b_ns_fn_name(vm: &mut VM, _: u8) -> Value {
let site = pop_name(vm).to_string();
let qualified = pop_name(vm);
if let Some(name) = with_host(|h| h.ns_call_sites.get(&site).cloned()) {
return name;
}
let global = qualified.rsplit('\\').next().unwrap_or(&qualified);
let name = if crate::stdlib::callable::dispatches(&qualified) {
Value::Str(qualified.clone())
} else if crate::stdlib::callable::dispatches(global) {
Value::str(format!("\\{global}"))
} else {
return Value::Str(qualified);
};
with_host(|h| h.ns_call_sites.insert(site, name.clone()));
name
}
fn b_class_link_check(vm: &mut VM, _: u8) -> Value {
let interface = vm.pop().to_int() != 0;
let name = pop_name(vm);
match class_or_autoload(vm, &name) {
Ok(true) => Value::Undef,
Ok(false) => {
mark_frame_line(vm);
let kind = if interface { "Interface" } else { "Class" };
throw_php(vm, "Error", &format!("{kind} \"{name}\" not found"))
}
Err(v) => v,
}
}
fn b_const_fetch_ns(vm: &mut VM, _: u8) -> Value {
let qualified = pop_name(vm);
let global = qualified.rsplit('\\').next().unwrap_or(&qualified);
mark_warn_site(vm);
match with_host(|h| h.const_use(&qualified).or_else(|| h.const_use(global))) {
Some(_) if bubble_throw(vm) => Value::Undef,
Some(v) => v,
None => {
mark_frame_line(vm);
throw_php(vm, "Error", &undefined_constant(&qualified))
}
}
}
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.current_file().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_self_class(vm: &mut VM, argc: u8) -> Value {
let (kw, name_fetch) = scope_operands(vm, argc);
let class = with_host(|h| h.magic_class());
if class.is_empty() {
return no_class_scope(vm, &kw, name_fetch);
}
Value::str(class)
}
fn scope_operands(vm: &mut VM, argc: u8) -> (String, bool) {
if argc == 0 {
return ("self".to_string(), false);
}
let name_fetch = argc == 2 && vm.pop().is_truthy();
(with_host(|h| h.to_str(&vm.pop())), name_fetch)
}
fn no_class_scope(vm: &mut VM, kw: &str, name_fetch: bool) -> Value {
let msg = if name_fetch {
format!("Cannot use \"{kw}\" in the global scope")
} else {
format!("Cannot access \"{kw}\" when no class scope is active")
};
throw_php(vm, "Error", &msg)
}
fn b_parent_class(vm: &mut VM, argc: u8) -> Value {
let from_trait = argc == 0;
let (kw, name_fetch) = scope_operands(vm, argc);
let class = with_host(|h| h.magic_class());
if class.is_empty() {
return no_class_scope(vm, &kw, name_fetch);
}
let parent = with_host(|h| h.magic_parent_class());
if parent.is_empty() {
let verb = if from_trait || name_fetch {
"use"
} else {
"access"
};
return throw_php(
vm,
"Error",
&format!("Cannot {verb} \"parent\" when current class scope has no parent"),
);
}
Value::str(parent)
}
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),
};
}
}
if let Some(issue) = with_host(|h| h.unset_container_issue(&name, &keys)) {
return container_issue(vm, issue).unwrap_or(Value::Undef);
}
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 = crate::stdlib::types::serialize_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 = crate::stdlib::types::serialize_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) = (
(*crate::bytes::to_bytes(x)).to_vec(),
(*crate::bytes::to_bytes(y)).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())
};
let out: Vec<u8> = (0..n)
.map(|i| {
f(
x.get(i).copied().unwrap_or(0),
y.get(i).copied().unwrap_or(0),
)
})
.collect();
Value::str(crate::bytes::from_bytes(&out))
}
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(
&crate::bytes::to_bytes(s),
&crate::bytes::to_bytes(s),
false,
|p, _| !p,
),
Value::Int(n) => Value::int(!n),
Value::Float(f) => {
mark_warn_site(vm);
Value::int(!with_host(|h| h.dval_to_lval_reported(*f)))
}
_ => {
let what = match v {
Value::Bool(true) => "true".to_string(),
Value::Bool(false) => "false".to_string(),
_ => with_host(|h| host::arith_type_name(h, &v)),
};
mark_frame_line(vm);
throw_php(
vm,
"TypeError",
&format!("Cannot perform bitwise not on {what}"),
)
}
}
}
fn b_spaceship(vm: &mut VM, _: u8) -> Value {
let b = vm.pop();
let a = vm.pop();
let (a, b) = cast_for_compare(&a, &b).unwrap_or((a, b));
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 !class_or_autoload(vm, 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)
}
pub(crate) 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);
if host::unwinding() {
return Value::Undef;
}
if host::drain_error_handlers() {
vm.ip = vm.chunk.ops.len();
return Value::Undef;
}
with_host(|h| h.write_out(&s));
if crate::stdlib::output::drain_chunks() {
vm.ip = vm.chunk.ops.len();
return Value::Undef;
}
}
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);
if name.as_str() == "this" {
return read_this(vm);
}
with_host(|h| h.get_var_warn(&name))
}
fn read_this(vm: &mut VM) -> Value {
let this = with_host(|h| h.get_var("this"));
if matches!(this, Value::Undef) {
mark_frame_line(vm);
return throw_php(vm, "Error", "Using $this when not in object context");
}
this
}
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_match_error_msg(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc as usize);
let msg = with_host(|h| h.match_error_message(&args[0]));
Value::str(msg)
}
fn b_concat(vm: &mut VM, _: u8) -> Value {
let b = vm.pop();
let a = vm.pop();
mark_warn_site(vm);
concat_values(&a, &b)
}
fn concat_values(a: &Value, b: &Value) -> Value {
if let (Value::Str(x), Value::Str(y)) = (a, b) {
return Value::str(crate::bytes::concat(x, y));
}
let (a, b) = (host::to_str_ext(a), host::to_str_ext(b));
if host::unwinding() {
return Value::Undef;
}
Value::str(crate::bytes::concat(&a, &b))
}
fn b_concat_assign_fslot(vm: &mut VM, _: u8) -> Value {
let y = vm.pop();
let i = vm.pop().to_int() as usize;
mark_warn_site(vm);
if let Value::Str(ys) = &y {
let slot = vm.frames.last_mut().and_then(|f| f.slots.get_mut(i));
if let Some(Value::Str(s)) = slot {
crate::bytes::append(std::sync::Arc::make_mut(s), ys);
return Value::Str(s.clone());
}
}
let r = concat_values(&vm.get_slot(i as u16), &y);
if !host::unwinding() {
vm.set_slot(i as u16, r.clone());
}
r
}
fn b_concat_assign_slot(vm: &mut VM, _: u8) -> Value {
let y = vm.pop();
let i = vm.pop().to_int() as u32;
mark_warn_site(vm);
if let Value::Str(ys) = &y {
if let Some(v) = with_host(|h| h.slot_append_str(i, ys)) {
return v;
}
}
let cur = with_host(|h| h.slot_get(i));
let r = concat_values(&cur, &y);
if !host::unwinding() {
with_host(|h| h.slot_set(i, r.clone()));
}
r
}
fn b_concat_assign_var(vm: &mut VM, _: u8) -> Value {
let y = vm.pop();
let name = pop_name(vm);
mark_warn_site(vm);
if let Value::Str(ys) = &y {
if let Some(v) = with_host(|h| h.var_append_str(&name, ys)) {
return v;
}
}
let cur = with_host(|h| h.get_var_warn(&name));
let r = concat_values(&cur, &y);
if !host::unwinding() {
with_host(|h| h.set_var(&name, r.clone()));
}
r
}
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 b_byref_arg_diag_m(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc as usize);
let method = with_host(|h| h.to_str(&args[1]));
let (argno, kind) = (args[2].to_int(), args[3].to_int());
let Some((callee, param)) =
with_host(|h| h.method_byref_param(&args[0], &method, argno as usize))
else {
return Value::Undef;
};
mark_frame_line(vm);
if kind == 0 {
with_host(|h| h.notice("Only variables should be passed by reference"));
return Value::Undef;
}
fail_or_throw(
vm,
throws_bare(
"Error",
format!("{callee}(): Argument #{argno} (${param}) could not be passed by reference"),
),
)
}
fn bubbled(vm: &mut VM, v: Value) -> Value {
if bubble_throw(vm) {
Value::Undef
} else {
v
}
}
fn class_or_autoload(vm: &mut VM, class: &str) -> Result<bool, Value> {
match host::class_known(class) {
Ok(found) if !bubble_throw(vm) => Ok(found),
Ok(_) => Err(Value::Undef),
Err(e) => Err(fail(vm, e)),
}
}
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);
let mut named: Vec<(String, Value)> = Vec::new();
let mut it = pairs.into_iter();
while let (Some(flag), Some(val)) = (it.next(), it.next()) {
if !with_host(|h| h.is_truthy(&flag)) {
args.push(val);
continue;
}
match spread_entries(&val) {
Ok(entries) => {
for (k, v) in entries {
match k {
Value::Str(_) => named.push((with_host(|h| h.to_str(&k)), v)),
_ => args.push(v),
}
}
}
Err((_, e)) => return throw_php(vm, "TypeError", &e),
}
}
mark_frame_line(vm);
let out = if named.is_empty() {
host::call_function(&name, args)
} else {
host::call_function_named(&name, args, named)
};
match out {
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));
if let Some(bare) = name.strip_prefix('\0') {
if with_host(|h| h.var_defined(bare)) {
captured.push((bare.to_string(), v));
}
continue;
}
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 spread_entries(v: &Value) -> Result<Vec<(Value, Value)>, (&'static str, String)> {
if !host::is_unpackable(v) {
let what = with_host(|h| h.type_name_for_error(v));
let class = if with_host(|h| matches!(v, Value::Obj(_)) && !h.is_array(v)) {
"TypeError"
} else {
"Error"
};
return Err((
class,
format!("Only arrays and Traversables can be unpacked, {what} given"),
));
}
if let Some(pairs) = with_host(|h| h.array_pairs(v)) {
return Ok(pairs);
}
let arr = host::foreach_prep(v.clone()).map_err(|e| ("Error", e))?;
Ok(with_host(|h| h.array_pairs(&arr)).unwrap_or_default())
}
fn b_mkarray(vm: &mut VM, argc: u8) -> Value {
let raw = pop_args(vm, argc as usize);
mark_warn_site(vm);
let arr = with_host(|h| h.new_array());
match fill_array_spreading(&arr, raw.into_iter()) {
Ok(()) => arr,
Err((class, e)) => throw_php(vm, class, &e),
}
}
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;
};
match fill_array_spreading(&arr, it) {
Ok(()) => arr,
Err((class, e)) => throw_php(vm, class, &e),
}
}
fn fill_array(
h: &mut host::PhpHost,
arr: &Value,
mut it: impl Iterator<Item = Value>,
) -> Option<Value> {
while let Some(k) = it.next() {
let Some(v) = it.next() else { break };
if host::is_spread_key(&k) {
return Some(v);
}
if host::is_auto_index(&k) {
h.arr_push_auto(arr, v);
} else {
h.arr_set_key(arr, &k, v);
}
}
None
}
fn fill_array_spreading(
arr: &Value,
mut it: impl Iterator<Item = Value>,
) -> Result<(), (&'static str, String)> {
loop {
let Some(spread) = with_host(|h| fill_array(h, arr, &mut it)) else {
return Ok(());
};
for (k, v) in spread_entries(&spread)? {
with_host(|h| match k {
Value::Int(_) => h.arr_push_auto(arr, v),
other => h.arr_set_key(arr, &other, 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 bad_offset_type(recv: &Value, key: &Value, tail: &str) -> Option<String> {
if matches!(recv, Value::Str(_)) {
return None;
}
let name = with_host(|h| {
if h.array_access_class(recv).is_some() {
None
} else {
h.bad_offset_type(key)
}
})?;
Some(throws_bare(
"TypeError",
format!("Cannot access offset of type {name} {tail}"),
))
}
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_offset_type(&recv, &key, "on array") {
return fail_or_throw(vm, e);
}
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, argc: u8) -> Value {
index_get_quiet(vm, argc, "on array")
}
fn b_index_get_empty(vm: &mut VM, argc: u8) -> Value {
index_get_quiet(vm, argc, "in isset or empty")
}
fn index_get_quiet(vm: &mut VM, _: u8, tail: &str) -> 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,
};
}
if let Some(e) = bad_offset_type(&recv, &key, tail) {
return fail_or_throw(vm, e);
}
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_declare_fn(vm: &mut VM, _: u8) -> Value {
let ns = with_host(|h| h.to_str(&vm.pop()));
let name = with_host(|h| h.to_str(&vm.pop()));
let key = with_host(|h| h.to_str(&vm.pop()));
let line = cur_op_line(vm);
match with_host(|h| h.declare_fn_at(&key, &name, &ns, line)) {
Ok(()) => Value::Undef,
Err(msg) => runtime_decl_fatal(vm, &msg),
}
}
fn b_declare_class(vm: &mut VM, _: u8) -> Value {
let ns = with_host(|h| h.to_str(&vm.pop()));
let key = with_host(|h| h.to_str(&vm.pop()));
let line = cur_op_line(vm);
match with_host(|h| h.declare_class_at(&key, &ns, line)) {
Ok(()) => Value::Undef,
Err(msg) => runtime_decl_fatal(vm, &msg),
}
}
fn b_decl_fatal(vm: &mut VM, _: u8) -> Value {
let msg = with_host(|h| h.to_str(&vm.pop()));
runtime_decl_fatal(vm, &msg)
}
fn b_final_check(vm: &mut VM, _: u8) -> Value {
let class = with_host(|h| h.to_str(&vm.pop()));
match with_host(|h| h.final_check(&class)) {
None => Value::Undef,
Some((msg, line)) => {
let line = line.unwrap_or_else(|| cur_op_line(vm));
runtime_decl_fatal_at(vm, &msg, line)
}
}
}
fn runtime_decl_fatal(vm: &mut VM, msg: &str) -> Value {
let line = cur_op_line(vm);
runtime_decl_fatal_at(vm, msg, line)
}
fn runtime_decl_fatal_at(vm: &mut VM, msg: &str, line: u32) -> Value {
let body = with_host(|h| {
let trace = h.backtrace();
format!(
"{msg} in {} on line {line}\nStack trace:\n{trace}",
h.current_file()
)
});
with_host(|h| h.fatal("Fatal error", &body));
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),
};
}
if let Some(e) = bad_offset_type(&recv, &key, "in isset or empty") {
return fail_or_throw(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 guard_array_write(
vm: &mut VM,
name: &str,
keys: &[Value],
tail: host::WriteTail,
) -> Option<Value> {
let issue = with_host(|h| h.write_container_issue(name, keys, tail))?;
container_issue(vm, issue)
}
fn container_issue(vm: &mut VM, issue: host::ContainerIssue) -> Option<Value> {
match issue {
host::ContainerIssue::Refused(msg) => Some(throw_php(vm, "Error", &msg)),
host::ContainerIssue::Scalar => Some(throw_php(
vm,
"Error",
"Cannot use a scalar value as an array",
)),
host::ContainerIssue::FalseToArray => {
mark_warn_site(vm);
with_host(|h| {
h.deprecated("Automatic conversion of false to array is deprecated");
});
None
}
}
}
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);
}
if let Some(e) = bad_offset_type(&recv, &key, "on array") {
return fail_or_throw(vm, e);
}
if let Some(thrown) = guard_array_write(vm, &name, &[], host::WriteTail::Set) {
return thrown;
}
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 Some(thrown) = guard_array_write(vm, &name, &[], host::WriteTail::Append) {
return thrown;
}
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);
dim_op(vm, &name, &keys, DimOp::Set, 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);
dim_op(vm, &name, &keys, DimOp::Append, 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);
dim_op(vm, &name, &keys, DimOp::Read, Value::Undef)
}
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 op = DimOp::IncDec {
inc: code & 1 != 0,
prefix: code & 2 != 0,
};
dim_op(vm, &name, &keys, op, Value::Undef)
}
#[derive(Clone, Copy)]
enum DimOp {
Set,
Append,
Read,
IncDec { inc: bool, prefix: bool },
}
impl DimOp {
fn container_depth(self, keys: &[Value]) -> usize {
match self {
DimOp::Append => keys.len(),
_ => keys.len() - 1,
}
}
fn tail(self) -> host::WriteTail {
match self {
DimOp::Set => host::WriteTail::Set,
DimOp::Append => host::WriteTail::Append,
DimOp::Read => host::WriteTail::AssignOp,
DimOp::IncDec { .. } => host::WriteTail::IncDec,
}
}
}
fn dim_op(vm: &mut VM, name: &str, keys: &[Value], op: DimOp, val: Value) -> Value {
let depth = op.container_depth(keys);
match with_host(|h| h.write_container_issue(name, &keys[..depth], op.tail())) {
Some(host::ContainerIssue::FalseToArray) if matches!(op, DimOp::Read) => {}
Some(issue) => {
if let Some(thrown) = container_issue(vm, issue) {
return thrown;
}
}
None => {}
}
if let Some((at, obj)) = array_access_container(name, &keys[..depth]) {
return array_access_dim(vm, &obj, &keys[at..], op, val);
}
match op {
DimOp::Set => {
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_path(name, keys, val.clone())
}) {
return fail_or_throw(vm, e);
}
val
}
DimOp::Append => {
with_host(|h| h.append_path(name, keys, val.clone()));
val
}
DimOp::Read => {
mark_warn_site(vm);
with_host(|h| h.index_get_path_warn(name, keys))
}
DimOp::IncDec { inc, prefix } => {
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);
let _ = h.index_set_path(name, keys, newv.clone());
if prefix {
newv
} else {
old
}
})
}
}
}
fn array_access_container(name: &str, keys: &[Value]) -> Option<(usize, Value)> {
with_host(|h| {
let mut cur = h.get_var(name);
for i in 0..=keys.len() {
if h.array_access_class(&cur).is_some() {
return Some((i, cur));
}
if !h.is_array(&cur) {
return None;
}
cur = h.index_get(&cur, keys.get(i)?);
}
None
})
}
const DIM_ROOT: &str = "@dim";
fn reroot_dim(storage: Option<Value>, slot: Option<usize>) {
with_host(|h| {
h.unset_var(DIM_ROOT);
match (storage, slot) {
(_, Some(slot)) => h.bind_ref_slot(DIM_ROOT, slot),
(Some(v), None) => h.set_var(DIM_ROOT, v),
(None, None) => {}
}
});
}
fn rerooted_dim_op(vm: &mut VM, keys: &[Value], op: DimOp, val: Value) -> Value {
let r = dim_op(vm, DIM_ROOT, keys, op, val);
with_host(|h| h.unset_var(DIM_ROOT));
r
}
fn array_access_dim(vm: &mut VM, obj: &Value, keys: &[Value], op: DimOp, val: Value) -> Value {
let class = with_host(|h| h.array_access_class(obj)).unwrap_or_default();
let last = match op {
DimOp::Append => keys.is_empty(),
_ => keys.len() == 1,
};
let through_storage = !last || matches!(op, DimOp::IncDec { .. });
if through_storage {
if let Some(storage) = with_host(|h| h.spl_native_storage(obj)) {
reroot_dim(Some(storage), None);
return rerooted_dim_op(vm, keys, op, val);
}
}
let call = |vm: &mut VM, method: &str, args: Vec<Value>| -> Option<(Value, Option<usize>)> {
with_host(|h| h.take_published_ret_ref());
match array_access_call(vm, obj, method, args)? {
Ok(v) if !bubble_throw(vm) => Some((v, with_host(|h| h.take_published_ret_ref()))),
Ok(_) => None,
Err(e) => {
fail(vm, e);
None
}
}
};
let indirect = |vm: &mut VM| {
mark_warn_site(vm);
with_host(|h| {
h.notice(format!(
"Indirect modification of overloaded element of {} has no effect",
host::display_class(&class)
))
});
};
if last {
return match op {
DimOp::Set => call(vm, "offsetSet", vec![keys[0].clone(), val.clone()]).map(|_| val),
DimOp::Append => call(vm, "offsetSet", vec![Value::Undef, val.clone()]).map(|_| val),
DimOp::Read => call(vm, "offsetGet", vec![keys[0].clone()]).map(|(v, _)| v),
DimOp::IncDec { inc, prefix } => {
call(vm, "offsetGet", vec![keys[0].clone()]).map(|(old, slot)| {
let newv = with_host(|h| h.incdec_value(&old, inc));
match slot {
Some(slot) => {
reroot_dim(None, Some(slot));
with_host(|h| {
h.set_var(DIM_ROOT, newv.clone());
h.unset_var(DIM_ROOT);
});
}
None => indirect(vm),
}
if prefix {
newv
} else {
old
}
})
}
}
.unwrap_or(Value::Undef);
}
let Some((child, slot)) = call(vm, "offsetGet", vec![keys[0].clone()]) else {
return Value::Undef;
};
if let Some(slot) = slot {
reroot_dim(None, Some(slot));
return rerooted_dim_op(vm, &keys[1..], op, val);
}
if with_host(|h| h.is_object_value(&child)) {
if with_host(|h| h.array_access_class(&child)).is_some() {
return array_access_dim(vm, &child, &keys[1..], op, val);
}
let issue = with_host(|h| h.object_as_array_refusal(&child));
return container_issue(vm, issue).unwrap_or(Value::Undef);
}
indirect(vm);
match op {
DimOp::Read => with_host(|h| keys[1..].iter().fold(child, |cur, k| h.index_get(&cur, k))),
DimOp::IncDec { .. } => Value::Undef,
DimOp::Set | DimOp::Append => val,
}
}
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);
if let Some(thrown) = guard_array_write(vm, &name, &keys, host::WriteTail::Append) {
return thrown;
}
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);
if name.as_str() == "this" {
let this = read_this(vm);
if !host::unwinding() {
incdec_refused(vm, &this, inc);
}
return Value::Undef;
}
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_is_plain_object(vm: &mut VM, _: u8) -> Value {
let v = vm.pop();
Value::bool(with_host(|h| h.is_plain_foreach_object(&v)))
}
fn b_foreach_keys(vm: &mut VM, _: u8) -> Value {
let arr = vm.pop();
let subj = vm.pop();
host::foreach_keys(&subj, &arr)
}
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 target = with_host(|h| h.get_var(&name));
if !with_host(|h| h.is_array(&target)) {
let func = match sub {
arrmut::PUSH => "array_push",
arrmut::POP => "array_pop",
arrmut::SHIFT => "array_shift",
arrmut::UNSHIFT => "array_unshift",
_ => "array_splice",
};
let given = with_host(|h| h.type_name_for_error(&target));
let mut shown = vec![target];
shown.extend(extra);
mark_frame_line(vm);
return match host::throw_from_internal(
func,
&shown,
"TypeError",
&format!("{func}(): Argument #1 ($array) must be of type array, {given} given"),
) {
Ok(v) => bubbled(vm, v),
Err(e) => fail(vm, e),
};
}
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 | PropAccess::Absent => plain_prop_read(vm, &recv, &name),
PropAccess::Magic => {
if let Some(msg) = with_host(|h| h.uninit_magic_blocked(&recv, &name)) {
return throw_php(vm, "Error", &msg);
}
let v = call_magic(&recv, &name, "__get", vec![Value::Str(name.clone())]);
bubbled(vm, v)
}
PropAccess::Denied(msg) => throw_php(vm, "Error", &msg),
}
}
fn plain_prop_read(vm: &mut VM, recv: &Value, name: &str) -> Value {
if let Some(msg) = with_host(|h| h.uninit_read_error(recv, name)) {
return throw_php(vm, "Error", &msg);
}
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();
prop_assign(vm, recv, name, val)
}
fn prop_assign(vm: &mut VM, recv: Value, name: std::sync::Arc<String>, val: Value) -> Value {
if let Some(msg) = with_host(|h| h.prop_write_refusal(&recv, &name, "assign")) {
return throw_php(vm, "Error", &msg);
}
match prop_plan!(vm, recv, name, "__set") {
PropAccess::Direct | PropAccess::Absent => {
if readonly_refused(vm, &recv, &name) {
return Value::Undef;
}
mark_warn_site(vm);
let Some(val) = typed_prop_value(vm, &recv, &name, val) else {
return Value::Undef;
};
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 {
if let Some(msg) = with_host(|h| h.set_visibility_error(recv, name, "modify")) {
throw_php(vm, "Error", &msg);
return true;
}
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);
let Some(val) = typed_prop_value(vm, &recv, &name, val) else {
return Value::Undef;
};
with_host(|h| h.prop_set_checked(&recv, &name, val.clone()));
val
}
_ => {
if readonly_refused(vm, &recv, &name) {
return Value::Undef;
}
mark_warn_site(vm);
let Some(val) = typed_prop_value(vm, &recv, &name, val) else {
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.set_visibility_error(&recv, &name, "unset")) {
return throw_php(vm, "Error", &msg);
}
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 => {
with_host(|h| h.note_unset(&recv, &name));
Value::Undef
}
}
}
fn b_prop_touch(vm: &mut VM, _: u8) -> Value {
let name = pop_name(vm);
let recv = vm.pop();
if let Some(msg) = with_host(|h| h.prop_write_refusal(&recv, &name, "assign")) {
return throw_php(vm, "Error", &msg);
}
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_fetch_w(vm: &mut VM, _: u8) -> Value {
let rw = vm.pop().to_int() != 0;
let name = pop_name(vm);
let recv = vm.pop();
if let Some(msg) = with_host(|h| h.prop_write_refusal(&recv, &name, "modify")) {
return throw_php(vm, "Error", &msg);
}
match prop_plan!(vm, recv, name, "__get") {
PropAccess::Denied(msg) => throw_php(vm, "Error", &msg),
PropAccess::Magic => {
let v = call_magic(&recv, &name, "__get", vec![Value::Str(name.clone())]);
if bubble_throw(vm) {
return Value::Undef;
}
if let Some(slot) = with_host(|h| h.take_published_ret_ref()) {
return with_host(|h| h.ref_cell_value(slot));
}
let lost = with_host(|h| h.object_class(&v).is_none());
if lost {
mark_warn_site(vm);
with_host(|h| {
let class = h.object_class(&recv).unwrap_or_default();
h.notice(format!(
"Indirect modification of overloaded property {class}::${name} has no effect"
))
});
}
v
}
PropAccess::Direct | PropAccess::Absent => {
if with_host(|h| h.uninit_read_error(&recv, &name)).is_some() {
return Value::Undef;
}
mark_warn_site(vm);
with_host(|h| {
if h.obj_has_prop(&recv, &name) {
h.prop_get(&recv, &name)
} else {
h.warn_dynamic_prop(&recv, &name);
if rw {
h.prop_get_warn(&recv, &name);
}
h.prop_set(&recv, &name, Value::Undef);
Value::Undef
}
})
}
}
}
fn b_prop_ensure_array(vm: &mut VM, _: u8) -> Value {
let name = pop_name(vm);
let recv = vm.pop();
if let Some(msg) = with_host(|h| h.prop_write_refusal(&recv, &name, "modify")) {
return throw_php(vm, "Error", &msg);
}
match prop_plan!(vm, recv, name, "__get") {
PropAccess::Denied(msg) => return throw_php(vm, "Error", &msg),
PropAccess::Magic => return prop_ensure_array_magic(vm, &recv, &name),
PropAccess::Direct | PropAccess::Absent => {}
}
if let Some(msg) = with_host(|h| h.set_visibility_error(&recv, &name, "indirectly modify")) {
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 prop_ensure_array_magic(vm: &mut VM, recv: &Value, name: &str) -> Value {
if let Some(dim) = with_host(|h| h.spl_array_dim_for_write(recv, name)) {
return dim;
}
let v = call_magic(recv, name, "__get", vec![Value::str(name)]);
if bubble_throw(vm) {
return Value::Undef;
}
if let Some(slot) = with_host(|h| h.take_published_ret_ref()) {
return with_host(|h| h.ref_cell_ensure_array(slot));
}
if with_host(|h| h.object_class(&v).is_some()) {
return v;
}
mark_warn_site(vm);
with_host(|h| {
let class = h.object_class(recv).unwrap_or_default();
h.notice(format!(
"Indirect modification of overloaded property {class}::${name} has no effect"
));
if h.is_array(&v) {
h.copy_on_assign(v)
} else {
h.new_array()
}
})
}
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();
if let Some(msg) = with_host(|h| h.prop_write_refusal(&recv, &name, "increment/decrement")) {
return throw_php(vm, "Error", &msg);
}
let inc = code & 1 != 0;
let prefix = code & 2 != 0;
let magic_blocked = with_host(|h| h.uninit_magic_blocked(&recv, &name));
let uninit = with_host(|h| h.uninit_read_error(&recv, &name));
match prop_plan!(vm, recv, name, "__get") {
PropAccess::Denied(msg) => throw_php(vm, "Error", &msg),
PropAccess::Magic if magic_blocked.is_some() => {
throw_php(vm, "Error", &magic_blocked.unwrap_or_default())
}
PropAccess::Direct | PropAccess::Absent if uninit.is_some() => {
throw_php(vm, "Error", &uninit.unwrap_or_default())
}
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;
}
let newv = with_host(|h| h.incdec_value(&old, inc));
if overflowed_to_float(&old, &newv) {
let declared =
with_host(|h| h.object_class(&recv).and_then(|c| h.prop_type(&c, &name)));
if let Some((owner, ty)) = declared {
if incdec_overflow_refused(vm, &owner, &name, &ty, inc) {
return Value::Undef;
}
}
}
with_host(|h| {
h.prop_set(&recv, &name, newv.clone());
if prefix {
newv
} else {
old
}
})
}
}
}
fn b_mcall_recv_check(vm: &mut VM, _: u8) -> Value {
let method = pop_name(vm);
let recv = vm.pop();
if with_host(|h| h.is_object_value(&recv)) {
if let Some(e) = host::engine_method_refusal(&recv, &method) {
mark_frame_line(vm);
return fail_or_throw(vm, e);
}
if with_host(|h| h.is_closure(&recv) || h.is_generator_val(&recv)) {
return recv;
}
let Some(class) = with_host(|h| h.object_class(&recv)) else {
return recv;
};
mark_frame_line(vm);
return match method_plan(vm, &class, &method, true) {
Ok(_) => recv,
Err(v) => v,
};
}
mark_frame_line(vm);
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_fcc_check(vm: &mut VM, _: u8) -> Value {
let instance = matches!(vm.pop(), Value::Bool(true));
let callable = vm.pop();
match host::fcc_refusal(&callable, instance) {
None => callable,
Some(e) => {
mark_frame_line(vm);
fail_or_throw(vm, e)
}
}
}
fn b_scall_callee_check(vm: &mut VM, _: u8) -> Value {
let method = pop_name(vm);
let class = pop_name(vm);
let this = with_host(|h| {
let t = h.get_var("this");
matches!(t, Value::Obj(_)).then_some(t)
});
mark_frame_line(vm);
match static_method_plan(vm, &class, &method, &this) {
Ok(_) => Value::Str(class),
Err(v) => v,
}
}
fn b_call_name_check(vm: &mut VM, _: u8) -> Value {
let name = pop_name(vm);
if crate::stdlib::callable::dispatches(&name) {
return Value::Str(name);
}
mark_frame_line(vm);
fail_or_throw(
vm,
throws_bare("Error", format!("Call to undefined function {name}()")),
)
}
fn b_call_class_check(vm: &mut VM, _: u8) -> Value {
let class = pop_name(vm);
if class.eq_ignore_ascii_case("Closure") {
return Value::Str(class);
}
match class_or_autoload(vm, &class) {
Ok(true) => return Value::Str(class),
Ok(false) => {}
Err(v) => return v,
}
mark_frame_line(vm);
throw_php(
vm,
"Error",
&format!("Class \"{}\" not found", host::display_class(&class)),
)
}
fn b_callvalue_check(vm: &mut VM, _: u8) -> Value {
let callee = vm.pop();
match host::callvalue_refusal(&callee) {
None => callee,
Some(e) => {
mark_frame_line(vm);
fail_or_throw(vm, e)
}
}
}
fn b_mcall(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc as usize - 2);
let method = pop_name(vm);
let recv = vm.pop();
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_or_throw(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 args = pop_args(vm, argc as usize - 2);
let method = pop_name(vm);
let class = pop_name(vm);
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);
mark_warn_site(vm);
match host::class_const(&class, &name) {
Ok(v) => bubbled(vm, 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 is_stringable_object(h: &host::PhpHost, v: &Value) -> bool {
matches!(v, Value::Obj(_))
&& !h.is_array(v)
&& h.object_class(v)
.is_some_and(|c| h.class_has_method(&c, "__tostring"))
}
fn cast_for_compare(a: &Value, b: &Value) -> Option<(Value, Value)> {
if !matches!(
(a, b),
(Value::Obj(_), Value::Str(_)) | (Value::Str(_), Value::Obj(_))
) {
return None;
}
let (a_obj, b_obj) = with_host(|h| (is_stringable_object(h, a), is_stringable_object(h, b)));
match (a_obj, b_obj) {
(true, false) if matches!(b, Value::Str(_)) => {
Some((Value::str(host::to_str_ext(a)), b.clone()))
}
(false, true) if matches!(a, Value::Str(_)) => {
Some((a.clone(), Value::str(host::to_str_ext(b))))
}
_ => None,
}
}
fn needs_stringable_search(lname: &str, args: &[Value]) -> bool {
let (needle, hay, strict) = match lname {
"array_keys" if args.len() >= 2 => (arg(args, 1), arg(args, 0), arg(args, 2)),
"array_keys" => return false,
_ => (arg(args, 0), arg(args, 1), arg(args, 2)),
};
with_host(|h| {
if h.is_truthy(&strict) {
return false;
}
let objects = |v: &Value| is_stringable_object(h, v);
match needle {
Value::Obj(_) if objects(&needle) => true,
Value::Str(_) => h
.array_pairs(&hay)
.unwrap_or_default()
.iter()
.any(|(_, v)| objects(v)),
_ => false,
}
})
}
fn loose_search_hits(needle: &Value, hay: &Value, first_only: bool) -> Vec<Value> {
let pairs = with_host(|h| h.array_pairs(hay)).unwrap_or_default();
let mut hits = Vec::new();
for (k, v) in pairs {
let (a, b) = cast_for_compare(needle, &v).unwrap_or_else(|| (needle.clone(), v));
if with_host(|h| loose_eq(h, &a, &b)) {
hits.push(k);
if first_only {
break;
}
}
}
hits
}
fn b_loose_eq(vm: &mut VM, _: u8) -> Value {
let b = vm.pop();
let a = vm.pop();
let (a, b) = cast_for_compare(&a, &b).unwrap_or((a, b));
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();
let (a, b) = cast_for_compare(&a, &b).unwrap_or((a, b));
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, false, |o| o < 0)
}
fn b_gt(vm: &mut VM, _: u8) -> Value {
cmp_bool(vm, true, |o| o < 0)
}
fn b_le(vm: &mut VM, _: u8) -> Value {
cmp_bool(vm, false, |o| o <= 0)
}
fn b_ge(vm: &mut VM, _: u8) -> Value {
cmp_bool(vm, true, |o| o <= 0)
}
fn cmp_bool(vm: &mut VM, swap: bool, f: impl Fn(i32) -> bool) -> Value {
let b = vm.pop();
let a = vm.pop();
let (a, b) = cast_for_compare(&a, &b).unwrap_or((a, b));
if is_unordered(&a, &b) {
return Value::bool(false);
}
let (a, b) = if swap { (b, a) } else { (a, b) };
Value::bool(f(with_host(|h| php_compare(h, &a, &b))))
}
fn resources_as_ids(h: &host::PhpHost, a: &Value, b: &Value) -> Option<(Value, Value)> {
let id = |v: &Value| h.resource_info(v).map(|(id, _)| Value::int(id));
match (id(a), id(b)) {
(None, None) => None,
(x, y) => Some((
x.unwrap_or_else(|| a.clone()),
y.unwrap_or_else(|| b.clone()),
)),
}
}
fn loose_eq(h: &host::PhpHost, a: &Value, b: &Value) -> bool {
use Value::*;
if let Some((a, b)) = resources_as_ids(h, a, b) {
return loose_eq(h, &a, &b);
}
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(_)) => match crate::stdlib::datefn::compare_dates(h, a, b) {
Some(ord) => ord == 0,
None => 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_value(a) || h.is_object_value(b) {
let (Some(ca), Some(cb)) = (h.instance_class(a), h.instance_class(b)) else {
return false;
};
if !ca.eq_ignore_ascii_case(&cb) {
return false;
}
if h.is_closure(a) {
return matches!((a, b), (Value::Obj(x), Value::Obj(y)) if x == y);
}
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::*;
if let Some((a, b)) = resources_as_ids(h, a, b) {
return php_compare(h, &a, &b);
}
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(_)) => {
crate::stdlib::datefn::compare_dates(h, a, b).unwrap_or_else(|| {
match (h.is_object_value(a), h.is_object_value(b)) {
(true, true) => compare_objects(h, a, b),
(true, false) => 1,
(false, true) => -1,
(false, false) => 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;
};
compare_tables(h, &pa, &pb, |ka, kb| strict_eq(h, ka, kb))
}
fn compare_tables<K>(
h: &host::PhpHost,
pa: &[(K, Value)],
pb: &[(K, Value)],
same_key: impl Fn(&K, &K) -> bool,
) -> i32 {
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, _)| same_key(ka, kb)) else {
return 1;
};
let ord = php_compare(h, va, vb);
if ord != 0 {
return ord;
}
}
0
}
fn compare_objects(h: &host::PhpHost, a: &Value, b: &Value) -> i32 {
const UNCOMPARABLE: i32 = 1;
if matches!((a, b), (Value::Obj(x), Value::Obj(y)) if x == y) {
return 0;
}
let (Some(ca), Some(cb)) = (h.instance_class(a), h.instance_class(b)) else {
return UNCOMPARABLE;
};
if !ca.eq_ignore_ascii_case(&cb) {
return UNCOMPARABLE;
}
if h.is_closure(a) {
let both_fake = h.closure_is_fake(a) && h.closure_is_fake(b);
return if both_fake { 0 } else { UNCOMPARABLE };
}
if h.is_enum_class(&ca) {
return UNCOMPARABLE;
}
let (pa, pb) = (h.object_props(a), h.object_props(b));
if pa
.iter()
.chain(&pb)
.any(|(name, _)| !h.prop_is_declared(&ca, name))
{
return compare_tables(h, &pa, &pb, |x, y| x == y);
}
let mut declared = h.declared_prop_order(&ca);
for (name, _) in pa.iter().chain(&pb) {
if !declared.contains(name) {
declared.push(name.clone());
}
}
let slot = |p: &[(String, Value)], name: &str| {
p.iter().find(|(n, _)| n == name).map(|(_, v)| v.clone())
};
for name in &declared {
match (slot(&pa, name), slot(&pb, name)) {
(Some(va), Some(vb)) => {
let ord = php_compare(h, &va, &vb);
if ord != 0 {
return ord;
}
}
(None, None) => {}
_ => return UNCOMPARABLE,
}
}
0
}
fn strcmp_i32(x: &str, y: &str) -> i32 {
let order = if crate::bytes::has_raw(x) || crate::bytes::has_raw(y) {
crate::bytes::to_bytes(x).cmp(&crate::bytes::to_bytes(y))
} else {
x.cmp(y)
};
match order {
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));
}
let line = lines.get(call.ip).copied().unwrap_or(0);
host::set_warn_line(line);
if line != 0 {
with_host(|h| h.set_cur_line(line));
}
if let Some((swap, want)) = relational(op) {
let cast = cast_for_compare(a, b);
let (a, b) = match &cast {
Some((x, y)) => (x, y),
None => (a, b),
};
if is_unordered(a, b) {
return Ok(Value::bool(false));
}
let (a, b) = if swap { (b, a) } else { (a, b) };
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))
}
type Relation = (bool, fn(i32) -> bool);
fn relational(op: NumOp) -> Option<Relation> {
Some(match op {
NumOp::Lt => (false, |o: i32| o < 0),
NumOp::Gt => (true, |o: i32| o < 0),
NumOp::Le => (false, |o: i32| o <= 0),
NumOp::Ge => (true, |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_shuffle",
"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 = crate::argsig::lower_name(name);
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_ref() {
"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| {
crate::bytes::byte_len(&h.to_str(&arg(args, 0))) as i64
})),
"count" | "sizeof" => {
let a = arg(args, 0);
let mode = args.get(1).map(crate::host::long_of).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| h.type_name_for_error(&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 = host::long_of(&arg(args, 1));
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| {
let mut b = crate::bytes::to_bytes(&h.to_str(&arg(args, 0))).into_owned();
b.reverse();
Value::str(crate::bytes::from_bytes(&b))
}),
"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, false))?,
"str_ireplace" => with_host(|h| php_str_replace(h, args, true))?,
"__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(crate::host::long_of).unwrap_or(0);
let places = p.clamp(i64::from(i32::MIN), i64::from(i32::MAX)) as i32;
let mode = args.get(2).map(crate::host::long_of).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(&lname, args)?,
"explode" => with_host(|h| php_explode(h, args))?,
"in_array" | "array_search" | "array_keys" if needs_stringable_search(&lname, args) => {
let (needle, hay) = if lname == "array_keys" {
(arg(args, 1), arg(args, 0))
} else {
(arg(args, 0), arg(args, 1))
};
let hits = loose_search_hits(&needle, &hay, lname != "array_keys");
match &*lname {
"in_array" => Value::bool(!hits.is_empty()),
"array_search" => hits.into_iter().next().unwrap_or(Value::bool(false)),
_ => with_host(|h| {
let out = h.new_array();
for k in hits {
h.arr_push_auto(&out, k);
}
out
}),
}
}
"in_array" => with_host(|h| php_in_array(h, args)),
"array_keys" if args.len() >= 2 => with_host(|h| {
let needle = arg(args, 1);
let strict = h.is_truthy(&arg(args, 2));
let keys: Vec<Value> = h
.array_pairs(&arg(args, 0))
.unwrap_or_default()
.into_iter()
.filter(|(_, v)| {
if strict {
strict_eq(h, v, &needle)
} else {
loose_eq(h, v, &needle)
}
})
.map(|(k, _)| k)
.collect();
let out = h.new_array();
for k in keys {
h.arr_push_auto(&out, k);
}
out
}),
"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_debug_info(&args[..args.len().min(1)], |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)
}
})
.unwrap_or(Value::Undef),
"var_dump" => with_debug_info(args, |h| {
for a in args {
let s = php_var_dump(h, a, 0);
h.write_out(&s);
}
Value::Undef
})
.unwrap_or(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" => {
let (hay, needle) = (bytes_arg(args, 0), bytes_arg(args, 1));
Value::bool(crate::bytes::find(&hay, &needle).is_some())
}
"str_starts_with" => Value::bool(bytes_arg(args, 0).starts_with(&bytes_arg(args, 1))),
"str_ends_with" => Value::bool(bytes_arg(args, 0).ends_with(&bytes_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,
};
crate::stdlib::textx::check_html_charset(h, &lname, args.get(2));
let named = lname == "htmlentities";
let s = if crate::bytes::has_raw(&s) {
let units = crate::bytes::php_utf8_units(&s);
if flags & 8 != 0 {
units.into_iter().map(|u| u.unwrap_or('\u{FFFD}')).collect()
} else if flags & 4 != 0 || units.iter().all(Option::is_some) {
units.into_iter().flatten().collect()
} else {
return Value::str(String::new());
}
} else {
s
};
let encoded = crate::stdlib::textx::html_encode(&s, flags, named);
Value::str(crate::bytes::from_text(&encoded).into_owned())
}),
"strcmp" => with_host(|h| {
let (a, b) = (h.to_str(&arg(args, 0)), h.to_str(&arg(args, 1)));
Value::int(binary_strcmp(
&crate::bytes::to_bytes(&a),
&crate::bytes::to_bytes(&b),
))
}),
"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(
&crate::bytes::to_bytes(&a),
&crate::bytes::to_bytes(&b),
))
}),
"strncmp" => with_host(|h| {
let a = h.to_str(&arg(args, 0));
let b = h.to_str(&arg(args, 1));
let n = host::long_of(&arg(args, 2)).max(0) as usize;
let (ab, bb) = (
(&*crate::bytes::to_bytes(&a)),
(&*crate::bytes::to_bytes(&b)),
);
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(crate::bytes::from_bytes(&[n]))
}),
"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(crate::bytes::to_bytes(&s).first().copied().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(
crate::bytes::to_bytes(&s)
.iter()
.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" if unique_needs_tostring(args) => {
let pairs = with_host(|h| h.array_pairs(&arg(args, 0))).unwrap_or_default();
let strs: Vec<String> = pairs.iter().map(|(_, v)| host::to_str_ext(v)).collect();
with_host(|h| {
let out = h.new_array();
let mut seen: std::collections::HashSet<String> = std::collections::HashSet::new();
for ((k, v), s) in pairs.into_iter().zip(strs) {
if seen.insert(s) {
h.arr_set_key(&out, &k, v);
}
}
out
})
}
"array_unique" => with_host(|h| php_array_unique(h, args)),
"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 = host::long_of(&arg(args, 1));
let partial = flags & JSON_PARTIAL_OUTPUT_ON_ERROR != 0;
let (prepared, partial_error) = json_prepare(&arg(args, 0), partial);
if let (true, Ok(doc)) = (partial, &prepared) {
let bad_utf8 = flags & (JSON_INVALID_UTF8_IGNORE | JSON_INVALID_UTF8_SUBSTITUTE)
== 0
&& with_host(|h| has_invalid_utf8(h, doc));
let code = if partial_error == 0 && bad_utf8 {
5
} else {
partial_error
};
crate::stdlib::json::set_last_error(code);
return Ok(with_host(|h| json_text(php_json_encode(h, doc, flags, 0))));
}
let prepared = match prepared {
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)),
};
}
let tolerant = flags & (JSON_INVALID_UTF8_IGNORE | JSON_INVALID_UTF8_SUBSTITUTE) != 0;
let mut code = 0;
if !tolerant && with_host(|h| has_invalid_utf8(h, &prepared)) {
if flags & JSON_PARTIAL_OUTPUT_ON_ERROR == 0 {
return match crate::stdlib::json::fail(5, flags) {
Some(e) => Err(e),
None => Ok(Value::bool(false)),
};
}
code = 5;
}
crate::stdlib::json::set_last_error(code);
with_host(|h| json_text(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 = crate::bytes::to_bytes(s);
let len = chars.len() as i64;
let mut start = host::long_of(&arg(args, 1));
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 = host::long_of(v);
if l < 0 {
(len - start as i64 + l).max(0) as usize
} else {
l as usize
}
}
_ => chars.len() - start,
};
crate::bytes::from_bytes(&chars[start..(start + count).min(chars.len())])
}
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 = &*crate::bytes::to_bytes(&hay);
let nb = &*crate::bytes::to_bytes(&needle);
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 spl_array_storage(h: &host::PhpHost, v: &Value) -> Option<Value> {
if h.spl_array_flags(v).is_some_and(|f| f & 1 != 0) {
return None;
}
h.object_props_mangled(v)
.into_iter()
.find(|(n, _)| n == "\0ArrayObject\0storage" || n == "\0ArrayIterator\0storage")
.map(|(_, st)| st)
}
fn spl_storage_pairs(h: &host::PhpHost, v: &Value) -> Option<Vec<(Value, Value)>> {
let st = spl_array_storage(h, v)?;
if h.is_array(&st) {
return h.array_pairs(&st);
}
if spl_array_storage(h, &st).is_some() {
return spl_storage_pairs(h, &st);
}
Some(
h.object_props(&st)
.into_iter()
.map(|(k, val)| (host::prop_key(&k), val))
.collect(),
)
}
const SPL_HIDDEN_SLOTS: [&str; 6] = [
"\0ArrayObject\0",
"\0ArrayIterator\0",
"\0SplDoublyLinkedList\0",
"\0SplObjectStorage\0",
"\0SplHeap\0",
"\0SplPriorityQueue\0",
];
fn spl_view(h: &host::PhpHost, v: &Value) -> Option<Vec<(Value, Value)>> {
if let Some(pairs) = spl_storage_pairs(h, v) {
return Some(pairs);
}
let props = h.object_props_mangled(v);
if let Some((_, el)) = props
.iter()
.find(|(n, _)| n == "\0SplFixedArray\0__elements")
{
return h.array_pairs(el);
}
props
.iter()
.any(|(n, _)| SPL_HIDDEN_SLOTS.iter().any(|s| n.starts_with(s)))
.then(|| {
props
.into_iter()
.filter(|(n, _)| !SPL_HIDDEN_SLOTS.iter().any(|s| n.starts_with(s)))
.map(|(n, val)| (Value::str(n), val))
.collect()
})
}
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) || h.is_generator_val(v) {
if let Some(pairs) = spl_view(h, v) {
for (k, val) in pairs {
h.arr_set_key(&out, &k, val);
}
return out;
}
for (name, val) in h.object_props_mangled(v) {
h.arr_set_key(&out, &host::prop_key(&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], ci: bool) -> Result<Value, String> {
let search = arg(args, 0);
let replace = arg(args, 1);
let subject = arg(args, 2);
if !h.is_array(&search) && h.is_array(&replace) {
let func = if ci { "str_ireplace" } else { "str_replace" };
return Err(throws(
"TypeError",
format!(
"{func}(): Argument #2 ($replace) must be of type string when argument #1 ($search) is a string"
),
));
}
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, ci, &mut count);
h.arr_set_key(&out, &k, Value::str(s));
}
out
} else {
Value::str(replace_all_pairs(
&h.to_str(&subject),
&pairs,
ci,
&mut count,
))
};
h.byref_out_put(3, Value::int(count as i64));
Ok(result)
}
fn replace_all_pairs(
subject: &str,
pairs: &[(String, String)],
ci: bool,
count: &mut usize,
) -> String {
let mut cur = crate::bytes::to_bytes(subject).into_owned();
for (needle, rep) in pairs {
let (n, r) = (crate::bytes::to_bytes(needle), crate::bytes::to_bytes(rep));
if n.is_empty() {
continue;
}
let (next, hits) = if ci {
crate::stdlib::strings::ci_replace(&cur, &n, &r)
} else {
crate::bytes::replace(&cur, &n, &r)
};
*count += hits;
cur = next;
}
crate::bytes::from_bytes(&cur)
}
fn php_implode(name: &str, args: &[Value]) -> Result<Value, String> {
let sep = arg(args, 0);
let if_string = || {
throws(
"TypeError",
format!(
"{name}(): If argument #1 ($separator) is of type string, argument #2 \
($array) must be of type array, null given"
),
)
};
let (glue, arr) = if args.len() < 2 {
if !with_host(|h| h.is_array(&sep)) {
return Err(if_string());
}
(String::new(), sep)
} else {
let refused = with_host(|h| {
let bad = h.is_array(&sep)
|| h.object_class(&sep)
.is_some_and(|c| !h.class_has_method(&c, "__tostring"));
bad.then(|| h.type_name_for_error(&sep))
});
if let Some(given) = refused {
return Err(throws(
"TypeError",
format!("{name}(): Argument #1 ($separator) must be of type string, {given} given"),
));
}
if matches!(sep, Value::Undef) {
with_host(|h| {
h.deprecated(format!(
"{name}(): Passing null to parameter #1 ($separator) of type array|string \
is deprecated"
))
});
}
let pieces = arg(args, 1);
if matches!(pieces, Value::Undef) {
return Err(if_string());
}
if !with_host(|h| h.is_array(&pieces)) {
let given = with_host(|h| h.type_name_for_error(&pieces));
return Err(throws(
"TypeError",
format!("{name}(): Argument #2 ($array) must be of type ?array, {given} given"),
));
}
(host::to_str_ext(&sep), pieces)
};
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();
Ok(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,
&crate::bytes::to_bytes(&list),
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 = &*crate::bytes::to_bytes(&s);
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(crate::bytes::from_bytes(&b[lo..hi]))
}
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 (sep, whole) = (
crate::bytes::to_bytes(&sep),
crate::bytes::to_bytes(&subject),
);
let cap = match limit {
0 => 1,
1.. => usize::try_from(limit).unwrap_or(usize::MAX),
_ => usize::MAX,
};
let mut parts: Vec<&[u8]> = Vec::new();
let mut rest: &[u8] = &whole;
while parts.len() + 1 < cap {
let Some(at) = crate::bytes::find(rest, &sep) else {
break;
};
parts.push(&rest[..at]);
rest = &rest[at + sep.len()..];
}
parts.push(rest);
if limit < 0 {
let drop = limit.unsigned_abs() as usize;
parts.truncate(parts.len().saturating_sub(drop));
}
for part in parts {
h.arr_push_auto(&arr, Value::str(crate::bytes::from_bytes(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 = crate::bytes::to_bytes(&h.to_str(&user_start))[0];
let high = crate::bytes::to_bytes(&h.to_str(&user_end))[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)));
if spec.conv != '\0' {
i -= 1;
}
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 }
};
if matches!(s.conv, 'f' | 'F' | 'e' | 'E' | 'g' | 'G' | 'h' | 'H') {
let f = h.to_number(v).to_float();
if f.is_nan() {
return "NaN".to_string();
}
if f.is_infinite() {
return if f < 0.0 { "-INF" } else { "INF" }.to_string();
}
}
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' => (
crate::bytes::from_bytes(&[(h.to_number(v).to_int() & 0xff) as u8]),
false,
),
'f' | 'F' => {
let f = h.to_number(v).to_float();
let p = s.precision.unwrap_or(6);
(
signed(
locale_point(format!("{:.*}", p, f.abs()), s.conv == 'f'),
f < 0.0,
s,
),
true,
)
}
'e' | 'E' => {
let f = h.to_number(v).to_float();
let mag = fmt_exp(f.abs(), s.precision.unwrap_or(6), s.conv == 'E');
(signed(mag, f < 0.0, s), 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.abs(), p);
let lower = s.conv == 'g' || s.conv == 'h';
let g = if lower { g.to_lowercase() } else { g };
let g = locale_point(g, matches!(s.conv, 'g' | 'G'));
(signed(g, f.is_sign_negative(), s), true)
}
's' => {
let mut txt = h.to_str_diag(v);
if let Some(p) = s.precision {
let b = crate::bytes::to_bytes(&txt);
txt = crate::bytes::from_bytes(&b[..p.min(b.len())]);
}
(txt, false)
}
'%' => return "%".to_string(),
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 {
if s.conv == 'c' {
return body;
}
let len = crate::bytes::byte_len(&body);
if len >= s.width {
return body;
}
let fill = s.width - len;
if s.left {
let pad = if s.pad == '0' && matches!(s.conv, 'd' | 'i' | 'u') {
' '
} else {
s.pad
};
format!("{body}{}", pad.to_string().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 = crate::bytes::to_bytes(&h.to_str(&arg(args, 0))).into_owned();
let width = args.get(1).map(crate::host::long_of).unwrap_or(75);
let brk = match args.get(2) {
Some(v) => crate::bytes::to_bytes(&h.to_str(v)).into_owned(),
None => b"\n".to_vec(),
};
let docut = args.get(3).map(|v| h.is_truthy(v)).unwrap_or(false);
if text.is_empty() {
return Ok(Value::str(""));
}
if brk.is_empty() {
return Err(throws(
"ValueError",
"wordwrap(): Argument #3 ($break) must not be empty",
));
}
if width == 0 && docut {
return Err(throws(
"ValueError",
"wordwrap(): Argument #4 ($cut_long_words) cannot be true when \
argument #2 ($width) is 0",
));
}
let len = text.len() as i64;
let (mut laststart, mut lastspace) = (0i64, 0i64);
if brk.len() == 1 && !docut {
let mut out = text.clone();
for current in 0..len {
let c = text[current as usize];
if c == brk[0] {
laststart = current + 1;
lastspace = current + 1;
} else if c == b' ' {
if current - laststart >= width {
out[current as usize] = brk[0];
laststart = current + 1;
}
lastspace = current;
} else if current - laststart >= width && laststart != lastspace {
out[lastspace as usize] = brk[0];
laststart = lastspace + 1;
}
}
return Ok(Value::str(crate::bytes::from_bytes(&out)));
}
let span = |a: i64, b: i64| &text[a as usize..b as usize];
let mut out = Vec::with_capacity(text.len() + brk.len());
let mut current = 0i64;
while current < len {
let c = text[current as usize];
if c == brk[0] && text[current as usize..].starts_with(&brk) {
out.extend_from_slice(span(laststart, current + brk.len() as i64));
current += brk.len() as i64 - 1;
laststart = current + 1;
lastspace = current + 1;
} else if c == b' ' {
if current - laststart >= width {
out.extend_from_slice(span(laststart, current));
out.extend_from_slice(&brk);
laststart = current + 1;
}
lastspace = current;
} else if current - laststart >= width && docut && laststart >= lastspace {
out.extend_from_slice(span(laststart, current));
out.extend_from_slice(&brk);
laststart = current;
lastspace = current;
} else if current - laststart >= width && laststart < lastspace {
out.extend_from_slice(span(laststart, lastspace));
out.extend_from_slice(&brk);
laststart = lastspace + 1;
lastspace = laststart;
}
current += 1;
}
if laststart != current {
out.extend_from_slice(span(laststart, current));
}
Ok(Value::str(crate::bytes::from_bytes(&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) || is_dumped_closure(h, v) {
php_print_r_object(h, v, depth, seen)
} else {
h.to_str(v)
}
}
fn with_debug_info<T>(roots: &[Value], render: impl FnOnce(&mut host::PhpHost) -> T) -> Option<T> {
let map = host::collect_object_hooks(roots, &["__debugInfo"], &|_, class, _, r| {
Some(with_host(|h| {
if h.is_array(&r) {
return r;
}
if matches!(r, Value::Undef) {
h.deprecated(format!(
"Returning null from {}::__debugInfo() is deprecated, return an empty \
array instead",
host::display_class(class)
));
}
h.new_array()
}))
})?;
Some(with_host(|h| {
let outer = std::mem::replace(&mut h.debug_info, map);
let out = render(h);
h.debug_info = outer;
out
}))
}
fn is_dumped_closure(h: &host::PhpHost, v: &Value) -> bool {
matches!(v, Value::Obj(id) if h.debug_info.contains_key(id))
&& (h.is_closure(v) || h.is_generator_val(v))
}
enum PropRow {
Named(String),
Index(i64),
Protected(String),
Private(String, String),
}
fn prop_row(h: &host::PhpHost, class: &str, name: String) -> PropRow {
if let Value::Int(n) = host::prop_key(&name) {
return PropRow::Index(n);
}
match h.prop_visibility(class, &name) {
Some((_, crate::ast::Visibility::Protected)) => PropRow::Protected(name),
Some((declaring, crate::ast::Visibility::Private)) => PropRow::Private(declaring, name),
_ => PropRow::Named(name),
}
}
fn debug_rows(h: &host::PhpHost, v: &Value, class: &str) -> Vec<(PropRow, Value, bool)> {
let info = match v {
Value::Obj(id) => h.debug_info.get(id),
_ => None,
};
let Some(info) = info else {
let mut rows: Vec<(PropRow, Value, bool)> = h
.object_props_marked(v)
.into_iter()
.map(|(name, val, r)| (prop_row(h, class, name), val, r))
.collect();
if h.spl_array_flags(v).is_some() {
if let Some(i) = rows.iter().position(|(row, ..)| {
matches!(row, PropRow::Private(c, n)
if n == "storage" && (c == "ArrayObject" || c == "ArrayIterator"))
}) {
let storage = rows.remove(i);
rows.push(storage);
}
}
return rows;
};
h.array_pairs_marked(info)
.unwrap_or_default()
.into_iter()
.map(|(k, val, r)| {
let row = match k {
Value::Int(n) => PropRow::Index(n),
k => {
let key = h.to_str(&k);
match key
.strip_prefix('\0')
.and_then(|rest| rest.split_once('\0'))
{
Some(("*", name)) => PropRow::Protected(name.to_string()),
Some((declaring, name)) => {
PropRow::Private(declaring.to_string(), name.to_string())
}
None => PropRow::Named(key),
}
}
};
(row, val, r)
})
.collect()
}
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)
.or_else(|| h.instance_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 (row, val, _) in debug_rows(h, v, &class) {
let label = match row {
PropRow::Named(name) => name,
PropRow::Index(n) => n.to_string(),
PropRow::Protected(name) => format!("{name}:protected"),
PropRow::Private(declaring, name) => format!("{name}:{declaring}:private"),
};
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", crate::bytes::byte_len(s)),
Value::Obj(_) if h.is_stream(v) => {
let s = h.stream_any(v).expect("checked by is_stream");
format!("{pad}{amp}resource({}) of type ({})\n", s.id, s.type_name())
}
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) || is_dumped_closure(h, v) => {
let class = h
.object_class(v)
.or_else(|| h.instance_class(v))
.unwrap_or_else(|| "stdClass".to_string());
let props = debug_rows(h, v, &class);
let mut s = format!(
"{pad}{amp}object({})#{} ({}) {{\n",
host::display_class(&class),
h.object_ordinal(v),
props.len()
);
let label = |row: &PropRow| match row {
PropRow::Named(name) => format!("\"{name}\""),
PropRow::Index(n) => n.to_string(),
PropRow::Protected(name) => format!("\"{name}\":protected"),
PropRow::Private(declaring, name) => {
format!("\"{name}\":\"{declaring}\":private")
}
};
let uninit = match v {
Value::Obj(id) if h.debug_info.contains_key(id) => Vec::new(),
_ => h.uninit_slots(v),
};
let mut uninit = uninit.into_iter().peekable();
let inner = " ".repeat(depth);
for (i, (row, val, pref)) in props.into_iter().enumerate() {
while let Some((_, uname, ty)) = uninit.next_if(|(at, _, _)| *at <= i) {
s.push_str(&format!(
"{inner} [{}]=>\n{inner} uninitialized({ty})\n",
label(&prop_row(h, &class, uname))
));
}
s.push_str(&format!("{inner} [{}]=>\n", label(&row)));
s.push_str(&php_var_dump_ref(h, &val, depth + 1, pref, seen));
}
for (_, uname, ty) in uninit {
s.push_str(&format!(
"{inner} [{}]=>\n{inner} uninitialized({ty})\n",
label(&prop_row(h, &class, uname))
));
}
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 = &*crate::bytes::to_bytes(&main);
let nb = &*crate::bytes::to_bytes(&needle);
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 {
host::long_of(&arg(args, 3))
} 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 = host::long_of(&arg(args, 2));
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(crate::host::long_of).unwrap_or(1);
if raw_len < 1 {
return Err(throws(
"ValueError",
"str_split(): Argument #2 ($length) must be greater than 0",
));
}
let len = usize::try_from(raw_len).unwrap_or(usize::MAX);
let bytes = crate::bytes::to_bytes(&s);
let arr = h.new_array();
for chunk in bytes.chunks(len) {
h.arr_push_auto(&arr, Value::str(crate::bytes::from_bytes(chunk)));
}
Ok(arr)
}
fn php_str_pad(h: &host::PhpHost, args: &[Value]) -> Result<String, String> {
let s = h.to_str(&arg(args, 0));
let target = host::long_of(&arg(args, 1));
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(crate::host::long_of).unwrap_or(1);
let cur = crate::bytes::byte_len(&s) as i64;
if target <= cur {
return Ok(s);
}
let need = (target - cur) as usize;
let make = |n: usize| -> String {
let bytes: Vec<u8> = crate::bytes::to_bytes(&pad)
.iter()
.copied()
.cycle()
.take(n)
.collect();
crate::bytes::from_bytes(&bytes)
};
Ok(crate::bytes::canonical(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 = (*crate::bytes::to_bytes(s)).to_vec();
let mut cap = true;
for b in &mut bytes {
if cap {
b.make_ascii_uppercase();
}
cap = delims.contains(b);
}
crate::bytes::from_bytes(&bytes)
}
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 dec_arg = args.get(1).map(crate::host::long_of).unwrap_or(0);
let dec = dec_arg.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, int_part, frac_part) = match h.to_number(&arg(args, 0)) {
Value::Int(n) => {
let mut mag = (n as i128).abs();
if dec_arg < 0 {
mag = match 10i128.checked_pow(dec_arg.unsigned_abs().min(20) as u32) {
Some(p) if dec_arg >= -19 => (mag + p / 2) / p * p,
_ => 0,
};
}
(n < 0 && mag != 0, mag.to_string(), "0".repeat(dec))
}
v => {
let num = v.to_float();
let rounded = php_round(
num,
dec_arg.clamp(i32::MIN as i64, i32::MAX as i64) as i32,
1,
)
.abs();
let formatted = format!("{:.*}", dec, rounded);
let (i, f) = match formatted.split_once('.') {
Some((i, f)) => (i.to_string(), f.to_string()),
None => (formatted.clone(), String::new()),
};
let nonzero = i.chars().any(|c| c != '0') || f.chars().any(|c| c != '0');
(num < 0.0 && nonzero, i, f)
}
};
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 {
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 (x, y) = with_host(|h| (h.to_number(&a).to_int(), h.to_number(&b).to_int()));
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 = host::long_of(&arg(args, 1));
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 {
if !matches!(v, Value::Int(_) | Value::Str(_)) {
h.warn("array_flip(): Can only flip string and integer values, entry skipped");
continue;
}
h.arr_set_key(&out, &v, k);
}
out
}
fn unique_needs_tostring(args: &[Value]) -> bool {
with_host(|h| {
let string_mode = match args.get(1) {
Some(v) if !matches!(v, Value::Undef) => v.to_int() == 2,
_ => true,
};
string_mode
&& h.array_pairs(&arg(args, 0))
.unwrap_or_default()
.iter()
.any(|(_, v)| is_stringable_object(h, v))
})
}
fn php_array_unique(h: &mut host::PhpHost, args: &[Value]) -> Value {
const SORT_STRING: i64 = 2;
let pairs = h.array_pairs(&arg(args, 0)).unwrap_or_default();
let flags = match args.get(1) {
Some(v) if !matches!(v, Value::Undef) => v.to_int(),
_ => SORT_STRING,
};
let out = h.new_array();
if flags == SORT_STRING {
let mut seen: std::collections::HashSet<String> = std::collections::HashSet::new();
for (k, v) in pairs {
if seen.insert(h.to_str_diag(&v)) {
h.arr_set_key(&out, &k, v);
}
}
return out;
}
let cmp = |h: &host::PhpHost, a: &Value, b: &Value| -> i32 {
let ord = sort_flag_compare(h, a, b, flags);
if ord != 1 || flags & !8 != 0 || h.enum_case_of(b).is_none() {
return ord;
}
match (a, b) {
(Value::Obj(x), Value::Obj(y)) if h.enum_case_of(a).is_some() => sign(x.cmp(y)) as i32,
_ => -1,
}
};
let mut order: Vec<usize> = (0..pairs.len()).collect();
crate::stdlib::zsort::zend_sort(&mut order, &mut |&i, &j| cmp(h, &pairs[i].1, &pairs[j].1));
let mut keep = vec![true; pairs.len()];
let mut last = order.first().copied();
for &cur in order.iter().skip(1) {
let Some(kept) = last else { break };
if cmp(h, &pairs[kept].1, &pairs[cur].1) != 0 {
last = Some(cur);
} else if kept > cur {
keep[kept] = false;
last = Some(cur);
} else {
keep[cur] = false;
}
}
for ((k, v), kept) in pairs.into_iter().zip(keep) {
if kept {
h.arr_set_key(&out, &k, v);
}
}
out
}
fn php_array_key_exists(h: &mut host::PhpHost, args: &[Value]) -> Result<Value, String> {
let mut key = arg(args, 0);
let arr = arg(args, 1);
if h.is_array(&arr) {
if let Some(t) = h.bad_offset_type(&key) {
return Err(throws(
"TypeError",
format!("Cannot access offset of type {t} on array"),
));
}
if matches!(key, Value::Undef) {
h.deprecated(
"Using null as the key parameter for array_key_exists() is deprecated, use an \
empty string instead",
);
key = Value::str("");
}
}
if let Some(found) = h.array_has_key(&arr, &key) {
return Ok(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);
Ok(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();
crate::stdlib::zsort::zend_sort_stable(&mut vals, |a, b| {
let r = sort_flag_compare(h, a, b, flags);
if reverse {
-r
} else {
r
}
});
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();
crate::stdlib::zsort::zend_sort_stable(&mut pairs, |(_, a), (_, b)| {
let r = sort_flag_compare(h, a, b, flags);
if reverse {
-r
} else {
r
}
});
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();
crate::stdlib::zsort::zend_sort_stable(&mut pairs, |(a, _), (b, _)| {
let r = sort_flag_compare(h, a, b, flags);
if reverse {
-r
} else {
r
}
});
h.arr_set_pairs(arr, pairs);
Value::bool(true)
}
fn php_array_fill(h: &mut host::PhpHost, args: &[Value]) -> Result<Value, String> {
let start = host::long_of(&arg(args, 0));
let count = host::long_of(&arg(args, 1));
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) {
let k = string_key(h, k);
h.arr_set_key(&out, &k, v);
}
Ok(out)
}
pub(crate) fn string_key(h: &mut host::PhpHost, k: Value) -> Value {
match k {
Value::Int(_) | Value::Str(_) => k,
other => Value::str(h.to_str_diag(&other)),
}
}
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 export_string(s: &str) -> String {
let escaped = s.replace('\\', "\\\\").replace('\'', "\\'");
format!("'{}'", escaped.replace('\0', "' . \"\\0\" . '"))
}
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(i64::MIN) => "-9223372036854775807-1".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) => export_string(s),
Value::Obj(_) if h.is_object_value(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 => export_string(&h.to_str(&other)),
};
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_value(v)) && body != "NULL" {
format!("\n{}{body}", " ".repeat(depth))
} else {
body
}
}
fn var_export_key(h: &host::PhpHost, k: &Value) -> String {
match k {
Value::Int(i) => i.to_string(),
_ => format!(
"'{}'",
h.to_str(k).replace('\\', "\\\\").replace('\'', "\\'")
),
}
}
fn php_var_export_object(
h: &mut host::PhpHost,
v: &Value,
depth: usize,
seen: &mut host::Visiting,
) -> String {
let class = h
.object_class(v)
.or_else(|| h.instance_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")
};
let pairs: Vec<(String, Value)> = match spl_view(h, v) {
Some(view) => view
.into_iter()
.map(|(k, val)| (var_export_key(h, &k), val))
.collect(),
None => h
.object_props(v)
.into_iter()
.map(|(n, val)| match host::prop_key(&n) {
Value::Int(i) => (i.to_string(), val),
_ => (
format!("'{}'", n.replace('\\', "\\\\").replace('\'', "\\'")),
val,
),
})
.collect(),
};
for (name, val) in pairs {
out.push_str(&format!(
"{inner}{} => {},\n",
name,
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_invalid_utf8(h: &host::PhpHost, v: &Value) -> bool {
match v {
Value::Str(s) => !crate::bytes::is_utf8(s),
Value::Obj(_) if h.is_object(v) => h
.object_props(v)
.iter()
.any(|(k, val)| !crate::bytes::is_utf8(k) || has_invalid_utf8(h, val)),
Value::Obj(_) => h.array_pairs(v).unwrap_or_default().iter().any(|(k, val)| {
matches!(k, Value::Str(s) if !crate::bytes::is_utf8(s)) || has_invalid_utf8(h, val)
}),
_ => false,
}
}
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, partial: bool) -> (Result<Value, i64>, i64) {
let mut prep = JsonPrep {
seen: host::Visiting::default(),
partial,
last_error: 0,
};
let out = json_prepare_seen(v, &mut prep);
(out, prep.last_error)
}
struct JsonPrep {
seen: host::Visiting,
partial: bool,
last_error: i64,
}
impl JsonPrep {
fn refuse(&mut self, code: i64, substitute: Value) -> Result<Value, i64> {
if self.partial {
self.last_error = code;
Ok(substitute)
} else {
Err(code)
}
}
}
fn json_prepare_seen(v: &Value, prep: &mut JsonPrep) -> Result<Value, i64> {
if let Value::Float(f) = v {
if !f.is_finite() && prep.partial {
return prep.refuse(crate::stdlib::json::JSON_ERROR_INF_OR_NAN, Value::int(0));
}
}
if with_host(|h| h.is_stream(v)) {
return prep.refuse(
crate::stdlib::json::JSON_ERROR_UNSUPPORTED_TYPE,
Value::Undef,
);
}
if with_host(|h| h.is_array(v)) {
if !prep.seen.enter(v) {
return prep.refuse(crate::stdlib::json::JSON_ERROR_RECURSION, Value::Undef);
}
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, prep)?));
}
prep.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 !prep.seen.enter(v) {
return prep.refuse(crate::stdlib::json::JSON_ERROR_RECURSION, Value::Undef);
}
let class = with_host(|h| h.object_class(v)).unwrap_or_default();
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, prep);
prep.seen.leave();
return out;
}
if with_host(|h| h.is_enum_class(&class)) {
prep.seen.leave();
return match with_host(|h| h.enum_case_of(v)) {
Some((_, Some(backing))) => Ok(backing),
_ => prep.refuse(
crate::stdlib::json::JSON_ERROR_NON_BACKED_ENUM,
Value::int(0),
),
};
}
let mut out = Vec::new();
if let Some(pairs) = with_host(|h| spl_storage_pairs(h, v)) {
for (k, val) in pairs {
let name = with_host(|h| h.to_str(&k));
out.push((name, json_prepare_seen(&val, prep)?));
}
prep.seen.leave();
return Ok(with_host(|h| h.new_transient_object(out)));
}
for (name, val) in with_host(|h| h.object_props(v)) {
if with_host(|h| h.prop_visibility(&class, &name)).is_some() {
continue;
}
let name = with_host(|h| h.to_str(&host::prop_key(&name)));
out.push((name, json_prepare_seen(&val, prep)?));
}
prep.seen.leave();
Ok(with_host(|h| h.new_transient_object(out)))
}
const JSON_UNESCAPED_SLASHES: i64 = 64;
const JSON_INVALID_UTF8_IGNORE: i64 = 1_048_576;
const JSON_INVALID_UTF8_SUBSTITUTE: i64 = 2_097_152;
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;
const JSON_PARTIAL_OUTPUT_ON_ERROR: i64 = 512;
const JSON_PRESERVE_ZERO_FRACTION: i64 = 1024;
const JSON_UNESCAPED_LINE_TERMINATORS: i64 = 2048;
fn json_float(f: f64, flags: i64) -> String {
let mut s = crate::stdlib::types::serialize_float(f).replace('E', "e");
if flags & JSON_PRESERVE_ZERO_FRACTION != 0 && f.is_finite() && !s.contains(['.', 'e']) {
s.push_str(".0");
}
s
}
fn json_numeric_check(s: &str, flags: i64) -> Option<String> {
match host::parse_php_number_full(s)? {
Value::Int(n) => Some(n.to_string()),
Value::Float(f) if f.is_finite() => Some(json_float(f, flags)),
_ => 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) => json_float(*f, flags),
Value::Str(s) => match (flags & JSON_NUMERIC_CHECK != 0)
.then(|| json_numeric_check(s, flags))
.flatten()
{
Some(n) => n,
None if !crate::bytes::is_utf8(s)
&& flags & (JSON_INVALID_UTF8_IGNORE | JSON_INVALID_UTF8_SUBSTITUTE) == 0 =>
{
"null".to_string()
}
None => json_string(s, flags),
},
Value::Obj(_) => {
let object = h.is_object_value(v);
let pairs = if object {
h.object_props(v)
.into_iter()
.map(|(k, val)| (host::prop_key(&k), val))
.collect()
} else {
h.array_pairs(v).unwrap_or_default()
};
let as_list = is_list(&pairs) && !object && 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_text(doc: String) -> Value {
Value::str(crate::bytes::from_text(&doc).into_owned())
}
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 escape_terminators = flags & JSON_UNESCAPED_LINE_TERMINATORS == 0;
let units: Vec<Option<char>> = if crate::bytes::has_raw(s) {
crate::bytes::php_utf8_units(s)
} else {
s.chars().map(Some).collect()
};
let mut out = String::with_capacity(s.len() + 2);
out.push('"');
for unit in units {
let Some(c) = unit else {
if flags & JSON_INVALID_UTF8_SUBSTITUTE != 0 {
out.push_str(if escape_unicode {
"\\ufffd"
} else {
"\u{FFFD}"
});
}
continue;
};
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)),
'\u{2028}' if escape_terminators => out.push_str("\\u2028"),
'\u{2029}' if escape_terminators => out.push_str("\\u2029"),
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
}
fn b_include(vm: &mut VM, _: u8) -> Value {
let kind = crate::ast::IncludeKind::from_code(vm.pop().to_int());
let path = vm.pop();
mark_frame_line(vm);
match host::run_include(kind, &path) {
Ok(v) => bubbled(vm, v),
Err(e) => fail_or_throw(vm, e),
}
}
fn b_eval(vm: &mut VM, _: u8) -> Value {
let code = vm.pop();
mark_frame_line(vm);
match host::run_eval(&code) {
Ok(v) => bubbled(vm, v),
Err(e) => fail_or_throw(vm, e),
}
}
fn locale_point(num: String, localized: bool) -> String {
if !localized {
return num;
}
match crate::stdlib::system::locale_decimal_point() {
'.' => num,
dp => num.replacen('.', &dp.to_string(), 1),
}
}
fn overflowed_to_float(old: &Value, new: &Value) -> bool {
matches!((old, new), (Value::Int(_), Value::Float(_)))
}
fn incdec_overflow_refused(
vm: &mut VM,
owner: &str,
name: &str,
ty: &crate::ast::TypeHint,
inc: bool,
) -> bool {
if ty
.parts
.iter()
.any(|p| p.eq_ignore_ascii_case("float") || p.eq_ignore_ascii_case("mixed"))
{
return false;
}
let parent = with_host(|h| h.class_parent(owner))
.map(|p| with_host(|h| h.class_display_name(&p.to_ascii_lowercase())));
let shown = ty.declared(owner, parent.as_deref());
let (verb, bound) = if inc {
("increment", "maximal")
} else {
("decrement", "minimal")
};
mark_frame_line(vm);
throw_php(
vm,
"TypeError",
&format!("Cannot {verb} property {owner}::${name} of type {shown} past its {bound} value"),
);
true
}
fn typed_prop_value(vm: &mut VM, recv: &Value, name: &str, val: Value) -> Option<Value> {
let declared = with_host(|h| h.object_class(recv).and_then(|c| h.prop_type(&c, name)));
match declared {
Some((owner, ty)) => check_prop_type(vm, &owner, name, &ty, val),
None => Some(val),
}
}
fn check_prop_type(
vm: &mut VM,
owner: &str,
name: &str,
ty: &crate::ast::TypeHint,
val: Value,
) -> Option<Value> {
let parent = with_host(|h| h.class_parent(owner));
let scope = host::TypeScope {
self_class: Some(owner.to_string()),
parent: parent.clone(),
static_class: None,
};
match host::verify_type(val, ty, &scope) {
Ok(v) => Some(v),
Err(given) => {
let parent_shown =
parent.map(|p| with_host(|h| h.class_display_name(&p.to_ascii_lowercase())));
let shown = ty.declared(owner, parent_shown.as_deref());
mark_frame_line(vm);
throw_php(
vm,
"TypeError",
&format!("Cannot assign {given} to property {owner}::${name} of type {shown}"),
);
None
}
}
}