use crate::ast::{TypeHint, Visibility};
use crate::errlevel;
use fusevm::{Chunk, VMResult, Value};
use indexmap::IndexMap;
use rustc_hash::{FxHashMap, FxHashSet};
use std::cell::{Cell, RefCell};
pub mod ops {
pub const ECHO: u16 = 1; pub const GETVAR: u16 = 2; pub const SETVAR: u16 = 3; pub const CONCAT: u16 = 4; pub const TRUTHY: u16 = 5; pub const CALL: u16 = 6; pub const MKARRAY: u16 = 7; pub const INDEX_GET: u16 = 8; pub const INDEX_SET: u16 = 9; pub const ARR_APPEND: u16 = 10; pub const DIV: u16 = 11; pub const MOD: u16 = 12; pub const POW: u16 = 13; pub const LOOSE_EQ: u16 = 14; pub const LOOSE_NE: u16 = 15; pub const STRICT_EQ: u16 = 16; pub const STRICT_NE: u16 = 17; pub const LT: u16 = 18; pub const GT: u16 = 19; pub const LE: u16 = 20; pub const GE: u16 = 21; pub const SIG_RETURN: u16 = 22; pub const INCDEC: u16 = 23; pub const ARRAYKEYS: u16 = 24; pub const ARRAYLEN: u16 = 25; pub const BITAND: u16 = 26; pub const BITOR: u16 = 27; pub const BITXOR: u16 = 28; pub const SHL: u16 = 29; pub const SHR: u16 = 30; pub const BITNOT: u16 = 31; pub const SPACESHIP: u16 = 32; pub const DBG_LINE: u16 = 33; pub const ARR_MUT: u16 = 34; pub const GET_PATH: u16 = 35; pub const SET_PATH: u16 = 36; pub const APPEND_PATH: u16 = 37; pub const INCDEC_PATH: u16 = 38; pub const CALL_SPREAD: u16 = 39; pub const MKCLOSURE: u16 = 40; pub const CALL_VALUE: u16 = 41; pub const NEW: u16 = 42; pub const PROP_GET: u16 = 43; pub const PROP_SET: u16 = 44; pub const MCALL: u16 = 45; pub const SCALL: u16 = 46; pub const SCONST: u16 = 47; pub const PATH_APPEND_CHILD: u16 = 48; pub const PROP_ENSURE_ARRAY: u16 = 49; pub const PROP_INCDEC: u16 = 50; pub const THROW: u16 = 51; pub const RUN_TRY: u16 = 52; pub const SIG_HALT: u16 = 53; pub const SIG_BREAK: u16 = 54; pub const SIG_CONTINUE: u16 = 55; pub const CONST_FETCH: u16 = 56; pub const UNSET_VAR: u16 = 57; pub const UNSET_PATH: u16 = 58; pub const FOREACH_PREP: u16 = 59; pub const INSTANCEOF: u16 = 60; pub const REF_BIND: u16 = 61; pub const BYREF_OUT: u16 = 62; pub const COPY: u16 = 81;
pub const REF_CELL: u16 = 82;
pub const SPROP_GET: u16 = 63; pub const SPROP_SET: u16 = 64; pub const SPROP_INCDEC: u16 = 65; pub const STATIC_BIND: u16 = 66; pub const CALL_NAMED: u16 = 67; pub const MCALL_NAMED: u16 = 68; pub const SCALL_NAMED: u16 = 69; pub const NEW_NAMED: u16 = 70; pub const CALLVALUE_NAMED: u16 = 71; pub const YIELD: u16 = 72; pub const YIELD_KV: u16 = 73; pub const YIELD_FROM: u16 = 74; pub const IS_GENERATOR: u16 = 75; pub const GEN_REWIND: u16 = 76; pub const GEN_VALID: u16 = 77; pub const GEN_KEY: u16 = 78; pub const GEN_CURRENT: u16 = 79; pub const GEN_NEXT: u16 = 80;
pub const SIG_LEVEL: u16 = 83;
pub const REF_SLOT_VAR: u16 = 84; pub const REF_SLOT_ELEM: u16 = 85; pub const REF_SLOT_PROP: u16 = 86; pub const REF_TO_VAR: u16 = 87; pub const REF_TO_ELEM: u16 = 88; pub const REF_TO_APPEND: u16 = 89; pub const REF_TO_PROP: u16 = 90; pub const RET_REF: u16 = 91;
pub const REF_SLOT_RET: u16 = 92;
pub const GETVAR_Q: u16 = 93; pub const INDEX_GET_Q: u16 = 94; pub const PROP_GET_Q: u16 = 95;
pub const LIST_ELEM_GET: u16 = 105;
pub const LSB_CLASS: u16 = 96;
pub const LSB_FORWARD: u16 = 97;
pub const PROP_TOUCH: u16 = 98;
pub const PROP_SET_RW: u16 = 99;
pub const SUPPRESS_PUSH: u16 = 100;
pub const SUPPRESS_POP: u16 = 101;
pub const PROP_UNSET: u16 = 102;
pub const PROP_ISSET: u16 = 103;
pub const PROP_GET_EMPTY: u16 = 104;
pub const INDEX_ISSET: u16 = 106;
pub const DECL_FATAL: u16 = 107;
pub const DYN_CLASS: u16 = 108;
pub const DYN_CLASS_CONST: u16 = 109;
pub const CLONE: u16 = 110;
pub const CONST_DECL: u16 = 111;
pub const MAGIC_FILE: u16 = 112;
pub const MAGIC_DIR: u16 = 113;
pub const MAGIC_CLASS: u16 = 114;
pub const BYREF_LIVE: u16 = 115;
pub const GETSLOT: u16 = 116;
pub const GETSLOT_Q: u16 = 117;
pub const SETSLOT: u16 = 118;
pub const INCDEC_SLOT: u16 = 119;
pub const MKARRAY_ADD: u16 = 120;
pub const MINMAX_FLF2: u16 = 121;
pub const BYREF_ARG_DIAG: u16 = 122;
pub const GLOBAL_BIND: u16 = 123;
pub const INCDEC_STEP: u16 = 124;
pub const MATCH_ERROR_MSG: u16 = 125;
pub const SELF_CLASS: u16 = 126;
pub const PARENT_CLASS: u16 = 127;
pub const MCALL_RECV_CHECK: u16 = 128;
pub const INDEX_GET_EMPTY: u16 = 129;
pub const CALL_NAME_CHECK: u16 = 130;
pub const CALL_CLASS_CHECK: u16 = 131;
pub const CALLVALUE_CHECK: u16 = 132;
pub const SCALL_CALLEE_CHECK: u16 = 133;
pub const FCC_CHECK: u16 = 134;
pub const SPROP_GET_Q: u16 = 135;
pub const INCLUDE: u16 = 136;
pub const EVAL: u16 = 137;
pub const DECLARE_FN: u16 = 138;
pub const DECLARE_CLASS: u16 = 139;
pub const FINAL_CHECK: u16 = 140;
pub const GEN_RELEASE: u16 = 141;
pub const GEN_MARK: u16 = 142;
pub const PROP_FETCH_W: u16 = 143;
pub const BYREF_ARG_DIAG_M: u16 = 144;
pub const NEW_ALLOC: u16 = 145;
pub const NEW_INIT: u16 = 146;
pub const NEW_INIT_NAMED: u16 = 147;
pub const SPROP_ENSURE_ARRAY: u16 = 148;
pub const FOREACH_ITER: u16 = 149;
pub const IS_LAZY_ITER: u16 = 150;
pub const CLONE_WITH: u16 = 151;
pub const GLOBALS_ARRAY: u16 = 152;
pub const GLOBALS_GET: u16 = 153;
pub const GLOBALS_GET_Q: u16 = 154;
pub const GLOBALS_BIND: u16 = 155;
pub const GLOBALS_UNSET: u16 = 156;
pub const GLOBALS_ISSET: u16 = 157;
pub const NS_FN_NAME: u16 = 158;
pub const CONST_FETCH_NS: u16 = 159;
pub const CLASS_LINK_CHECK: u16 = 160;
pub const REF_SLOT_SPROP: u16 = 161;
pub const REF_TO_SPROP: u16 = 162;
pub const STATIC_HAS: u16 = 163;
pub const CONCAT_ASSIGN_FSLOT: u16 = 164;
pub const CONCAT_ASSIGN_SLOT: u16 = 165;
pub const CONCAT_ASSIGN_VAR: u16 = 166;
pub const FOREACH_KEYS: u16 = 167;
pub const IS_PLAIN_OBJECT: u16 = 168;
pub const PROP_DIM_WRITEBACK: u16 = 169;
pub const SPROP_DIM_WRITEBACK: u16 = 170;
}
pub const STATIC_CLOSURE_CAPTURE: &str = "@static-closure";
pub const AUTO_INDEX: Value = Value::Status(i32::MIN);
pub const SPREAD_KEY: Value = Value::Status(i32::MIN + 1);
pub const ARRAY_FILTER_USE_KEY: i64 = 2;
pub const ARRAY_FILTER_USE_BOTH: i64 = 1;
pub fn is_auto_index(v: &Value) -> bool {
matches!(v, Value::Status(n) if *n == i32::MIN)
}
pub fn is_spread_key(v: &Value) -> bool {
matches!(v, Value::Status(n) if *n == i32::MIN + 1)
}
pub const MKARRAY_CHUNK_PAIRS: usize = 127;
pub mod arrmut {
pub const PUSH: i64 = 0;
pub const POP: i64 = 1;
pub const SHIFT: i64 = 2;
pub const UNSHIFT: i64 = 3;
pub const SPLICE: i64 = 4;
}
#[derive(Debug, Clone)]
pub struct Param {
pub name: String,
pub line: u32,
pub default: Option<Chunk>,
pub default_text: Option<String>,
pub variadic: bool,
pub by_ref: bool,
pub ty: Option<TypeHint>,
pub attrs: Vec<AttrDef>,
}
#[derive(Debug, Clone)]
pub struct AttrDef {
pub name: String,
pub args: Chunk,
}
#[derive(Debug, Clone)]
pub struct FuncDef {
pub returns_ref: bool,
pub span: Option<DeclSpan>,
pub params: Vec<Param>,
pub chunk: Chunk,
pub locals: Vec<String>,
pub is_generator: bool,
pub ret: Option<TypeHint>,
pub closure_site: Option<DeclSite>,
pub declared: Option<String>,
pub deprecated: Option<crate::ast::Deprecation>,
pub statics: Vec<(String, Option<Chunk>)>,
pub doc: Option<String>,
pub attrs: Vec<AttrDef>,
}
#[derive(Debug, Clone, PartialEq, Default)]
pub enum DeclSite {
#[default]
Script,
Named(String),
Closure(Box<DeclSite>, u32),
}
impl DeclSite {
pub fn render(&self, script: &str) -> String {
match self {
DeclSite::Script => script.to_string(),
DeclSite::Named(name) => name.clone(),
DeclSite::Closure(site, line) => {
format!("{{closure:{}:{line}}}", site.render(script))
}
}
}
}
pub struct ClosureCall {
pub params: Vec<Param>,
pub chunk: Chunk,
pub captured: Vec<(String, Value)>,
pub bound_this: Option<Value>,
pub scope: Option<String>,
pub called_scope: Option<String>,
pub is_generator: bool,
pub ret: Option<TypeHint>,
pub site: Option<DeclSite>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ContainerIssue {
Scalar,
FalseToArray,
Refused(String),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WriteTail {
Set,
Append,
AssignOp,
IncDec,
Ref,
}
impl WriteTail {
fn string_refusal(self) -> Option<&'static str> {
match self {
WriteTail::Set => None,
WriteTail::Append => Some("[] operator not supported for strings"),
WriteTail::AssignOp => Some("Cannot use assign-op operators with string offsets"),
WriteTail::IncDec => Some("Cannot increment/decrement string offsets"),
WriteTail::Ref => Some("Cannot create references to/from string offsets"),
}
}
}
const STRING_OFFSET_AS_ARRAY: &str = "Cannot use string offset as an array";
#[derive(Debug, Clone)]
pub struct ClassDef {
pub is_readonly: bool,
pub enum_backing: Option<String>,
pub default_texts: Vec<(String, String)>,
pub span: Option<DeclSpan>,
pub docs: Vec<(String, String)>,
pub attrs: Vec<(String, Vec<AttrDef>)>,
pub member_deprecated: Vec<(String, crate::ast::Deprecation)>,
pub name: String,
pub parent: Option<String>,
pub interfaces: Vec<String>,
pub consts: Vec<(String, Chunk)>,
pub const_vis: FxHashMap<String, Visibility>,
pub prop_defaults: Vec<(String, Chunk)>,
pub static_prop_defaults: Vec<(String, Chunk)>,
pub methods: FxHashMap<String, FuncDef>,
pub prop_vis: FxHashMap<String, Visibility>,
pub prop_set_vis: FxHashMap<String, Visibility>,
pub readonly_props: FxHashSet<String>,
pub uninit_props: FxHashMap<String, String>,
pub prop_types: FxHashMap<String, crate::ast::TypeHint>,
pub method_vis: FxHashMap<String, Visibility>,
pub static_methods: FxHashSet<String>,
pub is_enum: bool,
pub is_abstract: bool,
pub is_interface: bool,
pub is_trait: bool,
pub uses: Vec<String>,
pub allow_dynamic_props: bool,
pub enum_cases: Vec<(String, Option<Chunk>)>,
pub is_final: bool,
pub final_methods: FxHashSet<String>,
pub final_consts: FxHashSet<String>,
pub final_props: FxHashSet<String>,
pub method_sites: Vec<(String, u32)>,
pub abstract_methods: FxHashSet<String>,
pub prop_order: Vec<String>,
}
#[derive(Debug, Clone)]
pub struct CatchClause {
pub classes: Vec<String>,
pub var: Option<String>,
pub chunk: Chunk,
}
#[derive(Debug, Clone)]
pub struct TryDef {
pub try_chunk: Chunk,
pub catches: Vec<CatchClause>,
pub finally_chunk: Option<Chunk>,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum ArrayKey {
Int(i64),
Str(String),
}
impl ArrayKey {
fn to_value(&self) -> Value {
match self {
ArrayKey::Int(n) => Value::int(*n),
ArrayKey::Str(s) => Value::str(s.clone()),
}
}
}
pub const NO_INDEX: i64 = i64::MIN;
fn next_key(next_index: i64) -> i64 {
if next_index == NO_INDEX {
0
} else {
next_index
}
}
fn take_next_index(next_index: &mut i64) -> i64 {
let k = next_key(*next_index);
*next_index = k.saturating_add(1);
k
}
#[derive(Debug, Clone)]
pub enum PhpObj {
Array {
entries: IndexMap<ArrayKey, Value>,
next_index: i64,
},
Closure {
params: Vec<Param>,
chunk: Box<Chunk>,
captured: Vec<(String, Value)>,
bound_this: Option<Value>,
scope: Option<String>,
called_scope: Option<String>,
is_generator: bool,
ret: Option<TypeHint>,
is_static: bool,
site: Option<DeclSite>,
doc: Option<String>,
attrs: Vec<AttrDef>,
span: Option<DeclSpan>,
},
Generator { id: u32 },
Object {
class: String,
props: IndexMap<String, Value>,
},
Ref { slot: usize },
Resource(Box<crate::stdlib::fileres::Stream>),
}
enum Signal {
Return(Value),
Break(u32),
Continue(u32),
}
#[derive(Default, Clone)]
enum Slot {
#[default]
Unset,
Val(Value),
Ref(usize),
}
#[derive(Default)]
struct Vars {
slots: Vec<Slot>,
index: FxHashMap<String, u32>,
}
impl Vars {
fn slot_of(&self, name: &str) -> Option<u32> {
self.index.get(name).copied()
}
fn ensure_slot(&mut self, name: &str) -> u32 {
if let Some(&i) = self.index.get(name) {
return i;
}
let i = self.slots.len() as u32;
self.slots.push(Slot::Unset);
self.index.insert(name.to_string(), i);
i
}
fn at(&self, i: u32) -> &Slot {
self.slots.get(i as usize).unwrap_or(&Slot::Unset)
}
fn put(&mut self, i: u32, v: Slot) {
if self.slots.len() <= i as usize {
self.slots.resize(i as usize + 1, Slot::Unset);
}
self.slots[i as usize] = v;
}
fn get(&self, name: &str) -> &Slot {
match self.slot_of(name) {
Some(i) => self.at(i),
None => &Slot::Unset,
}
}
fn renumber(&mut self, names: &[String]) {
let mut slots: Vec<Slot> = Vec::with_capacity(names.len() + self.slots.len());
let mut index: FxHashMap<String, u32> = FxHashMap::default();
for n in names {
let cur = self.get(n).clone();
index.insert(n.clone(), slots.len() as u32);
slots.push(cur);
}
for (k, &i) in self.index.iter() {
if index.contains_key(k) {
continue;
}
let v = self.slots.get(i as usize).cloned().unwrap_or(Slot::Unset);
index.insert(k.clone(), slots.len() as u32);
slots.push(v);
}
self.slots = slots;
self.index = index;
}
fn iter(&self) -> impl Iterator<Item = (&String, &Slot)> {
self.index
.iter()
.filter_map(|(k, &i)| match self.slots.get(i as usize) {
Some(Slot::Unset) | None => None,
Some(s) => Some((k, s)),
})
}
}
#[derive(Default)]
struct Scope {
vars: Vars,
line: u32,
name: Option<String>,
static_class: Option<String>,
closure_site: Option<DeclSite>,
internal: bool,
file: Option<std::sync::Arc<str>>,
transparent: bool,
}
pub const FCC_PARAM: &str = "__fcc_args";
#[derive(Clone)]
struct TraceEntry {
site: Option<(String, u32)>,
function: String,
class: Option<(String, &'static str)>,
args: Vec<(Option<String>, Value)>,
object: Option<Value>,
include: bool,
}
struct IncludeFrame {
depth: usize,
file: std::sync::Arc<str>,
construct: &'static str,
arg: Option<String>,
call_line: u32,
}
#[derive(Debug, Clone, PartialEq)]
pub struct DeclSpan {
pub file: String,
pub start: u32,
pub end: u32,
}
#[derive(Debug, Clone)]
pub struct DeclAt {
pub file: String,
pub line: u32,
pub namespace: String,
}
pub struct PhpHost {
objs: Vec<PhpObj>,
scopes: Vec<Scope>,
functions: FxHashMap<String, FuncDef>,
fn_sites: FxHashMap<String, DeclAt>,
class_sites: FxHashMap<String, DeclAt>,
classes: FxHashMap<String, ClassDef>,
class_order: Vec<String>,
capture: Option<String>,
pub(crate) stdin_feed: Option<std::io::Cursor<Vec<u8>>>,
pub(crate) ob: crate::stdlib::output::OutputState,
error: Option<String>,
signal: Option<Signal>,
pending_throw: Option<Value>,
pub(crate) debug_info: FxHashMap<u32, Value>,
pub(crate) serialize_info: FxHashMap<u32, Value>,
pub(crate) pending_exit: Option<i32>,
exception_handlers: Vec<Value>,
exception_handler_enabled: bool,
error_handlers: Vec<(Value, i64)>,
in_error_handler: bool,
queued_errors: Vec<(String, i64, String, String, u32)>,
shutdown_fns: Vec<(Value, Vec<Value>)>,
unknown_site: bool,
destructed: FxHashSet<u32>,
destructors_off: bool,
main_order: Vec<String>,
main_promoted: Vec<String>,
main_frame_slots: Vec<Value>,
last_break_level: u32,
try_defs: Vec<TryDef>,
constants: FxHashMap<String, Value>,
const_ns_keys: FxHashMap<String, String>,
autoloaders: Vec<Value>,
autoloading: FxHashSet<String>,
pub autoload_extensions: String,
pub ns_call_sites: FxHashMap<String, Value>,
next_resource_id: i64,
includes: Vec<IncludeFrame>,
included_files: Vec<String>,
compile_counters: crate::compiler::Counters,
ref_cells: Vec<Value>,
byref_out: Vec<Value>,
byref_live: Vec<bool>,
static_props: FxHashMap<String, Value>,
static_slots: FxHashMap<String, usize>,
static_uninit: FxHashSet<usize>,
enum_case_cache: FxHashMap<String, Value>,
script_name: String,
strict_types: bool,
suppress: usize,
pending_lsb: Option<String>,
pending_closure_site: Option<DeclSite>,
pending_transparent: bool,
ret_ref_slot: Option<usize>,
generators: Vec<GenCell>,
fatal_reported: bool,
error_reporting: i64,
last_error: Option<(i64, String, String, u32)>,
ini: FxHashMap<String, String>,
preg_error: i64,
strtok_state: Option<(String, usize)>,
cloning: Option<u32>,
cloning_with: Option<u32>,
readonly_init: FxHashMap<u32, FxHashSet<String>>,
unset_typed: FxHashMap<u32, FxHashSet<String>>,
magic_in_progress: Vec<(u32, String, &'static str)>,
init_class_scope: Vec<String>,
transient_objs: FxHashSet<u32>,
}
pub enum MethodDispatch {
Direct,
Magic,
Denied(String),
Undefined,
}
pub enum PropAccess {
Direct,
Magic,
Denied(String),
Absent,
}
static INITIAL_INI: std::sync::Mutex<Vec<(String, String)>> = std::sync::Mutex::new(Vec::new());
pub fn add_initial_ini(name: &str, value: &str) {
let mut g = INITIAL_INI.lock().unwrap_or_else(|e| e.into_inner());
g.retain(|(k, _)| k != name);
g.push((name.to_string(), value.to_string()));
}
fn default_ini() -> FxHashMap<String, String> {
[
("error_reporting", "30719"),
("precision", "14"),
("serialize_precision", "-1"),
("display_errors", "1"),
("display_startup_errors", "1"),
("log_errors", "1"),
("error_log", ""),
("html_errors", "0"),
("docref_ext", ""),
("error_append_string", ""),
("error_prepend_string", ""),
("ignore_repeated_errors", "0"),
("ignore_repeated_source", "0"),
("report_memleaks", "1"),
("fatal_error_backtraces", "1"),
("output_buffering", "0"),
("implicit_flush", "1"),
("output_handler", ""),
("memory_limit", "128M"),
("max_memory_limit", "-1"),
("max_execution_time", "0"),
("max_input_time", "-1"),
("max_input_nesting_level", "64"),
("max_input_vars", "1000"),
("post_max_size", "8M"),
("default_socket_timeout", "60"),
("hard_timeout", "2"),
("unserialize_max_depth", "4096"),
("unserialize_callback_func", ""),
("default_charset", "UTF-8"),
("default_mimetype", "text/html"),
("input_encoding", ""),
("internal_encoding", ""),
("output_encoding", ""),
("disable_functions", ""),
("expose_php", "1"),
("ignore_user_abort", "0"),
("register_argc_argv", "0"),
("auto_detect_line_endings", "0"),
("allow_url_fopen", "1"),
("arg_separator.input", "&"),
("arg_separator.output", "&"),
("user_agent", ""),
("from", ""),
("zend.assertions", "1"),
("zend.enable_gc", "1"),
("zend.detect_unicode", "1"),
("zend.multibyte", "0"),
("zend.exception_ignore_args", "0"),
("zend.exception_string_param_max_len", "15"),
("zend.script_encoding", ""),
("date.timezone", "UTC"),
("date.default_latitude", "31.7667"),
("date.default_longitude", "35.2333"),
("date.sunrise_zenith", "90.833333"),
("date.sunset_zenith", "90.833333"),
("pcre.backtrack_limit", "1000000"),
("pcre.recursion_limit", "100000"),
("pcre.jit", "1"),
]
.iter()
.map(|(k, v)| (k.to_string(), v.to_string()))
.collect()
}
const INI_FIXED: &[&str] = &[
"allow_url_fopen",
"arg_separator.input",
"disable_functions",
"expose_php",
"hard_timeout",
"max_input_nesting_level",
"max_input_time",
"max_input_vars",
"max_memory_limit",
"output_buffering",
"output_handler",
"post_max_size",
"register_argc_argv",
"zend.multibyte",
"zend.script_encoding",
];
#[derive(Default)]
pub struct Visiting(Vec<u32>);
impl Visiting {
pub fn enter(&mut self, v: &Value) -> bool {
let Value::Obj(id) = v else { return true };
if self.0.contains(id) {
return false;
}
self.0.push(*id);
true
}
pub fn leave(&mut self) {
self.0.pop();
}
}
fn escape_trace_string(s: &str) -> String {
smart_str_escaped(s, 15)
}
pub fn smart_str_escaped(s: &str, limit: usize) -> String {
const VK_ESCAPE: u8 = 0x1b;
let bytes = &*crate::bytes::to_bytes(s);
let cut = bytes.len().min(limit);
let mut out = String::new();
for &c in &bytes[..cut] {
if c < 32 || c == b'\\' || c > 126 {
out.push('\\');
match c {
b'\n' => out.push('n'),
b'\r' => out.push('r'),
b'\t' => out.push('t'),
0x0c => out.push('f'),
0x0b => out.push('v'),
b'\\' => out.push('\\'),
VK_ESCAPE => out.push('e'),
_ => out.push_str(&format!("x{c:02X}")),
}
} else {
out.push(c as char);
}
}
if bytes.len() > limit {
out.push_str("...");
}
out
}
pub const NEXT_ELEMENT_OCCUPIED: &str =
"Cannot add element to the array as the next element is already occupied";
impl Default for PhpHost {
fn default() -> Self {
Self::new()
}
}
impl PhpHost {
pub fn new() -> Self {
let mut h = PhpHost {
objs: Vec::new(),
scopes: vec![Scope::default()],
functions: FxHashMap::default(),
fn_sites: FxHashMap::default(),
class_sites: FxHashMap::default(),
classes: FxHashMap::default(),
class_order: Vec::new(),
capture: None,
stdin_feed: None,
error: None,
signal: None,
pending_throw: None,
debug_info: FxHashMap::default(),
serialize_info: FxHashMap::default(),
pending_exit: None,
exception_handlers: Vec::new(),
error_handlers: Vec::new(),
in_error_handler: false,
queued_errors: Vec::new(),
exception_handler_enabled: true,
shutdown_fns: Vec::new(),
unknown_site: false,
destructed: Default::default(),
destructors_off: false,
main_order: Vec::new(),
main_promoted: Vec::new(),
main_frame_slots: Vec::new(),
last_break_level: 1,
try_defs: Vec::new(),
constants: predefined_constants(),
const_ns_keys: FxHashMap::default(),
autoloaders: Vec::new(),
autoloading: FxHashSet::default(),
autoload_extensions: ".inc,.php".to_string(),
ns_call_sites: FxHashMap::default(),
next_resource_id: 1,
includes: Vec::new(),
included_files: Vec::new(),
compile_counters: crate::compiler::Counters::default(),
ob: Default::default(),
ref_cells: Vec::new(),
byref_out: Vec::new(),
byref_live: Vec::new(),
static_props: FxHashMap::default(),
static_slots: FxHashMap::default(),
static_uninit: FxHashSet::default(),
enum_case_cache: FxHashMap::default(),
script_name: "Command line code".to_string(),
suppress: 0,
pending_lsb: None,
pending_closure_site: None,
pending_transparent: false,
ret_ref_slot: None,
generators: Vec::new(),
fatal_reported: false,
error_reporting: errlevel::E_ALL,
last_error: None,
ini: default_ini(),
preg_error: 0,
strtok_state: None,
cloning: None,
cloning_with: None,
readonly_init: FxHashMap::default(),
unset_typed: FxHashMap::default(),
magic_in_progress: Vec::new(),
init_class_scope: Vec::new(),
transient_objs: FxHashSet::default(),
strict_types: false,
};
h.init_superglobals();
h.init_stdio();
for (name, value) in INITIAL_INI.lock().unwrap_or_else(|e| e.into_inner()).iter() {
if name == "error_reporting" {
h.set_error_reporting(crate::errlevel::parse_ini_level(value).unwrap_or(0));
} else {
h.ini.insert(name.clone(), value.clone());
}
}
h
}
pub fn byref_out_get(&self, pos: usize) -> Value {
self.byref_out.get(pos).cloned().unwrap_or(Value::Undef)
}
pub fn byref_out_live(&self, pos: usize) -> bool {
self.byref_live.get(pos).copied().unwrap_or(false)
}
pub fn byref_out_set(&mut self, vals: Vec<Value>, live: Vec<bool>) {
self.byref_out = vals;
self.byref_live = live;
}
pub fn byref_out_put(&mut self, pos: usize, v: Value) {
if self.byref_out.len() <= pos {
self.byref_out.resize(pos + 1, Value::Undef);
self.byref_live.resize(pos + 1, false);
}
self.byref_out[pos] = v;
self.byref_live[pos] = true;
}
pub fn byref_out_clear(&mut self) {
self.byref_out.clear();
self.byref_live.clear();
}
fn init_stdio(&mut self) {
use crate::stdlib::fileres::{Stream, StreamKind};
for (name, kind) in [
("STDIN", StreamKind::Stdin),
("STDOUT", StreamKind::Stdout),
("STDERR", StreamKind::Stderr),
] {
let v = self.new_stream(Stream::stdio(kind));
self.constants.insert(name.to_string(), v);
}
self.next_resource_id = 5;
}
fn init_superglobals(&mut self) {
let env: Vec<(String, String)> = std::env::vars().collect();
let mkenv = |h: &mut PhpHost| -> Value {
let a = h.new_array();
for (k, v) in &env {
h.arr_set_key(&a, &Value::str(k.clone()), Value::str(v.clone()));
}
a
};
let e = mkenv(self);
self.set_var("_ENV", e);
let s = mkenv(self);
self.arr_set_key(&s, &Value::str("PHP_SELF"), Value::str(String::new()));
self.arr_set_key(&s, &Value::str("SCRIPT_NAME"), Value::str(String::new()));
self.arr_set_key(
&s,
&Value::str("SCRIPT_FILENAME"),
Value::str(String::new()),
);
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_secs() as i64);
self.arr_set_key(&s, &Value::str("REQUEST_TIME"), Value::int(now));
self.set_var("_SERVER", s);
for name in [
"_GET", "_POST", "_REQUEST", "_COOKIE", "_FILES", "_SESSION", "GLOBALS",
] {
let empty = self.new_array();
self.set_var(name, empty);
}
let argv = self.new_array();
self.arr_push_auto(&argv, Value::str(String::new()));
self.set_var("argv", argv);
self.set_var("argc", Value::int(1));
}
pub fn set_script_args(&mut self, file: Option<&str>, args: &[String]) {
let script = file.unwrap_or("Standard input code").to_string();
let argv = self.new_array();
self.arr_push_auto(&argv, Value::str(script.clone()));
for a in args {
self.arr_push_auto(&argv, Value::str(a.clone()));
}
let argc = Value::int(args.len() as i64 + 1);
self.set_var("argv", argv.clone());
self.set_var("argc", argc.clone());
let server = self.get_var("_SERVER");
for (k, v) in [
("argv", argv),
("argc", argc),
("PHP_SELF", Value::str(script.clone())),
("SCRIPT_NAME", Value::str(script)),
(
"SCRIPT_FILENAME",
Value::str(file.unwrap_or_default().to_string()),
),
] {
self.arr_set_key(&server, &Value::str(k.to_string()), v);
}
}
pub fn all_constants(&self) -> Vec<(String, Value)> {
self.constants
.iter()
.map(|(k, v)| (k.clone(), v.clone()))
.collect()
}
pub fn declared_names(&self, kind: TypeKind) -> Vec<String> {
let want = |k: TypeKind| match kind {
TypeKind::Class => matches!(k, TypeKind::Class | TypeKind::Enum),
other => k == other,
};
let mut out: Vec<String> = BUILTIN_TYPES
.iter()
.filter(|(_, k, ..)| want(*k))
.map(|(n, ..)| n.to_string())
.collect();
for key in &self.class_order {
let Some(def) = self.classes.get(key) else {
continue;
};
if def.name.starts_with("__") && def.name != "__PHP_Incomplete_Class" {
continue;
}
if self.type_kind(key).is_some_and(want) {
out.push(def.name.clone());
}
}
out
}
fn class_insert(&mut self, key: String, def: ClassDef) {
if !self.classes.contains_key(&key) {
self.class_order.push(key.clone());
}
self.classes.insert(key, def);
}
pub fn const_fetch(&self, name: &str) -> Option<Value> {
let name = name.strip_prefix('\\').unwrap_or(name);
self.constants
.get(name)
.or_else(|| {
let written = self.const_ns_keys.get(&const_key(name))?;
self.constants.get(written)
})
.cloned()
.or_else(|| match name.to_ascii_lowercase().as_str() {
"true" => Some(Value::bool(true)),
"false" => Some(Value::bool(false)),
"null" => Some(Value::Undef),
_ => None,
})
}
pub fn const_use(&mut self, name: &str) -> Option<Value> {
let value = self.const_fetch(name)?;
let name = name.strip_prefix('\\').unwrap_or(name);
if let Some(suffix) = deprecated_constant_suffix(name) {
self.deprecated(format!("Constant {name} is deprecated {suffix}"));
}
Some(value)
}
pub fn const_defined(&self, name: &str) -> bool {
self.const_fetch(name).is_some()
}
pub fn const_define(&mut self, name: &str, value: Value) -> bool {
let key = const_key(name);
if self.constants.contains_key(name) || self.const_ns_keys.contains_key(&key) {
self.warn(format!(
"Constant {key} already defined, this will be an error in PHP 9"
));
return false;
}
if key.contains('\\') {
self.const_ns_keys.insert(key, name.to_string());
}
self.constants.insert(name.to_string(), value);
true
}
pub fn load_program(&mut self, functions: Vec<(String, FuncDef)>) {
for (name, def) in functions {
self.functions.insert(name, def);
}
}
pub fn load_classes(&mut self, classes: Vec<(String, ClassDef)>) {
for (name, def) in classes {
self.class_insert(name, def);
}
}
pub fn record_decl_sites(
&mut self,
file: &str,
fns: Vec<(String, u32, String)>,
classes: Vec<(String, u32, String)>,
) {
let at = |line, namespace| DeclAt {
file: file.to_string(),
line,
namespace,
};
for (name, line, ns) in fns {
self.fn_sites.insert(name, at(line, ns));
}
for (name, line, ns) in classes {
self.class_sites.insert(name, at(line, ns));
}
}
pub fn fn_redeclare_msg(&self, name: &str, ns: &str) -> Option<String> {
let lname = name.to_ascii_lowercase();
match self.fn_sites.get(&lname) {
Some(at) if at.namespace == ns => Some(format!(
"Cannot redeclare function {name}() (previously declared in {}:{})",
at.file, at.line
)),
Some(_) => None,
None if ns.is_empty()
&& (self.functions.contains_key(&lname)
|| crate::stdlib::callable::is_library_function(&lname)) =>
{
Some(format!("Cannot redeclare function {name}()"))
}
None => None,
}
}
pub fn class_redeclare_msg(&self, name: &str, ns: &str) -> Option<String> {
let lname = name.to_ascii_lowercase();
if let Some(at) = self.class_sites.get(&lname) {
if at.namespace != ns {
return None;
}
let def = self.classes.get(&lname)?;
return Some(format!(
"Cannot redeclare {} {} (previously declared in {}:{})",
class_kind_word(def),
def.name,
at.file,
at.line
));
}
if !ns.is_empty() {
return None;
}
if let Some(def) = self.classes.get(&lname) {
return Some(format!(
"Cannot redeclare {} {}",
class_kind_word(def),
def.name
));
}
if let Some((spelled, kind)) = crate::prelude_type(&lname) {
return Some(format!("Cannot redeclare {kind} {spelled}"));
}
builtin_type(&lname).map(|(spelled, kind, ..)| {
format!("Cannot redeclare {} {spelled}", type_kind_word(*kind))
})
}
pub fn declare_fn_at(
&mut self,
key: &str,
name: &str,
ns: &str,
line: u32,
) -> Result<(), String> {
if let Some(msg) = self.fn_redeclare_msg(name, ns) {
return Err(msg);
}
let lname = name.to_ascii_lowercase();
if let Some(def) = self.functions.remove(key) {
self.functions.insert(lname.clone(), def);
}
let file = self.current_file().to_string();
self.fn_sites.insert(
lname,
DeclAt {
file,
line,
namespace: ns.to_string(),
},
);
Ok(())
}
pub fn final_check(&self, class: &str) -> Option<(String, Option<u32>)> {
let def = self.classes.get(&class.to_ascii_lowercase())?;
final_violation(def, |n| self.classes.get(&n.to_ascii_lowercase()))
}
pub fn final_check_with<'a>(
&'a self,
def: &ClassDef,
local: impl Fn(&str) -> Option<&'a ClassDef>,
) -> Option<(String, Option<u32>)> {
final_violation(def, |n| {
local(n).or_else(|| self.classes.get(&n.to_ascii_lowercase()))
})
}
pub fn declare_class_at(&mut self, key: &str, ns: &str, line: u32) -> Result<(), String> {
let Some(def) = self.classes.get(key) else {
return Ok(());
};
let name = def.name.clone();
if let Some(msg) = self.class_redeclare_msg(&name, ns) {
return Err(msg);
}
let lname = name.to_ascii_lowercase();
if let Some(def) = self.classes.remove(key) {
self.class_order.retain(|k| k != key);
self.class_insert(lname.clone(), def);
}
let file = self.current_file().to_string();
self.class_sites.insert(
lname,
DeclAt {
file,
line,
namespace: ns.to_string(),
},
);
Ok(())
}
pub fn load_try_defs(&mut self, defs: Vec<TryDef>) {
self.try_defs = defs;
}
pub fn catch_matches(&self, class: &str, target: &str) -> bool {
let target = target.to_ascii_lowercase();
if target == "throwable" {
return self.class_is_a(class, "exception") || self.class_is_a(class, "error");
}
self.class_is_a(class, &target)
}
pub fn class_is_a_pub(&self, class: &str, ancestor: &str) -> bool {
self.class_is_a(class, &ancestor.to_ascii_lowercase())
}
fn class_is_a(&self, class: &str, ancestor: &str) -> bool {
if ancestor == "stringable" && self.class_has_method(class, "__tostring") {
return true;
}
let mut stack = vec![class.to_ascii_lowercase()];
let mut seen: Vec<String> = Vec::new();
while let Some(c) = stack.pop() {
if c == ancestor {
return true;
}
if seen.contains(&c) || seen.len() > 1000 {
continue;
}
seen.push(c.clone());
if let Some(d) = self.classes.get(&c) {
if let Some(p) = &d.parent {
stack.push(p.to_ascii_lowercase());
}
for i in &d.interfaces {
stack.push(i.to_ascii_lowercase());
}
} else {
stack.extend(
builtin_type_parents(&c)
.iter()
.map(|p| p.to_ascii_lowercase()),
);
}
}
false
}
pub fn begin_capture(&mut self) {
self.capture = Some(String::new());
}
pub fn end_capture(&mut self) -> String {
self.capture.take().unwrap_or_default()
}
pub fn set_stdin(&mut self, input: &str) {
self.stdin_feed = Some(std::io::Cursor::new(
crate::bytes::to_bytes(input).into_owned(),
));
}
pub fn write_err(bytes: &[u8]) {
use std::io::Write;
let _ = std::io::stdout().flush();
let _ = std::io::stderr().write_all(bytes);
}
pub fn write_out(&mut self, s: &str) {
let top = self.ob.handlers.len();
self.ob_write_below(top, s);
}
pub(crate) fn ob_write_below(&mut self, n: usize, s: &str) {
if s.is_empty() {
return;
}
let running = self.ob.running.is_some();
for i in (0..n).rev() {
let h = &mut self.ob.handlers[i];
if h.is_disabled() {
continue;
}
if running {
h.flags |= crate::stdlib::output::PRODUCED_OUTPUT;
}
h.append(s);
if h.chunk_full() && !running {
self.ob.chunk_due = Some(h.id);
crate::stdlib::output::mark_chunk_due();
}
return;
}
self.write_unbuffered(s);
}
fn write_unbuffered(&mut self, s: &str) {
if let Some(buf) = &mut self.capture {
buf.push_str(s);
} else {
use std::io::Write;
let mut out = std::io::stdout();
let _ = out.write_all(&crate::bytes::to_bytes(s));
}
}
pub fn set_script_name(&mut self, name: impl Into<String>) {
self.script_name = name.into();
self.included_files = if self.script_name.starts_with('/') {
vec![self.script_name.clone()]
} else {
Vec::new()
};
}
pub fn script_name(&self) -> &str {
&self.script_name
}
fn scope_file(&self, i: usize) -> &str {
let scope = &self.scopes[i];
if scope.internal && i > 0 {
return self.scope_file(i - 1);
}
scope.file.as_deref().unwrap_or(&self.script_name)
}
pub fn current_file(&self) -> &str {
if self.unknown_site {
return "Unknown";
}
let top = self.scopes.len() - 1;
match self.includes.last() {
Some(f) if f.depth == top => &f.file,
_ => {
let mut i = top;
while self.scopes[i].internal && i > 0 {
i -= 1;
}
match self.includes.last() {
Some(f) if f.depth == i => &f.file,
_ => self.scope_file(top),
}
}
}
}
pub fn cur_frame_line(&self) -> u32 {
self.scopes.last().map(|s| s.line).unwrap_or(0)
}
pub fn suppress_push(&mut self) {
self.suppress += 1;
}
pub fn suppress_pop(&mut self) {
self.suppress = self.suppress.saturating_sub(1);
}
pub fn suppress_depth(&self) -> usize {
self.suppress
}
pub fn suppress_restore(&mut self, depth: usize) {
self.suppress = depth;
}
pub fn warn(&mut self, msg: impl std::fmt::Display) {
self.diagnose("Warning", errlevel::E_WARNING, warn_line(), msg);
}
pub fn set_strict_types(&mut self, on: bool) {
self.strict_types = on;
}
pub fn strict_types(&self) -> bool {
self.strict_types
}
pub(crate) fn type_name_for_error(&self, v: &Value) -> String {
match v {
Value::Undef => "null".to_string(),
Value::Bool(b) => if *b { "true" } else { "false" }.to_string(),
Value::Int(_) => "int".to_string(),
Value::Float(_) => "float".to_string(),
Value::Str(_) => "string".to_string(),
Value::Obj(_) => match self.as_array(v) {
Some(PhpObj::Array { .. }) => "array".to_string(),
Some(PhpObj::Resource(_)) => "resource".to_string(),
_ => self
.instance_class(v)
.map(|c| display_class(&c).to_string())
.unwrap_or_else(|| "object".to_string()),
},
_ => "mixed".to_string(),
}
}
pub fn warn_at(&mut self, msg: impl std::fmt::Display, line: u32) {
self.diagnose("Warning", errlevel::E_WARNING, line, msg);
}
pub fn deprecated(&mut self, msg: impl std::fmt::Display) {
self.diagnose("Deprecated", errlevel::E_DEPRECATED, warn_line(), msg);
}
pub fn to_int_cast(&mut self, v: &Value) -> i64 {
let Value::Float(f) = *v else {
return self.to_number(v).to_int();
};
const TWO_63: f64 = 9223372036854775808.0;
if !f.is_finite() || !(-TWO_63..TWO_63).contains(&f) {
let shown = crate::stdlib::types::serialize_float(f);
self.warn(format!(
"The float {shown} is not representable as an int, cast occurred"
));
}
dval_to_lval(f)
}
pub fn dval_to_lval_reported(&mut self, f: f64) -> i64 {
const TWO_63: f64 = 9223372036854775808.0;
let l = self.to_int_cast(&Value::Float(f));
let in_range = (-TWO_63..TWO_63).contains(&f);
if f.is_nan() || (in_range && f.fract() != 0.0) {
let shown = crate::stdlib::types::serialize_float(f);
self.deprecated(format!(
"Implicit conversion from float {shown} to int loses precision"
));
}
l
}
pub fn diagnose_offset(&mut self, key: &Value) {
const TWO_63: f64 = 9223372036854775808.0;
match key {
Value::Undef => self.deprecated(
"Using null as an array offset is deprecated, use an empty string instead",
),
Value::Float(f) => {
let (f, shown) = (*f, crate::stdlib::types::serialize_float(*f));
if !f.is_finite() || !(-TWO_63..TWO_63).contains(&f) {
self.warn(format!(
"The float {shown} is not representable as an int, cast occurred"
));
if f.is_nan() {
self.deprecated(format!(
"Implicit conversion from float {shown} to int loses precision"
));
}
} else if f.fract() != 0.0 {
self.deprecated(format!(
"Implicit conversion from float {shown} to int loses precision"
));
}
}
Value::Obj(_) => {
if let Some((id, _)) = self.resource_info(key) {
self.warn(format!(
"Resource ID#{id} used as offset, casting to integer ({id})"
));
}
}
_ => {}
}
}
pub fn bad_offset_type(&self, key: &Value) -> Option<String> {
if self.is_array(key) {
return Some("array".to_string());
}
self.instance_class(key)
.map(|c| display_class(&c).to_string())
}
pub fn diagnose_array_offset(&mut self, recv: &Value, key: &Value) {
if matches!(self.as_array(recv), Some(PhpObj::Array { .. })) {
self.diagnose_offset(key);
}
}
pub fn diagnose_quiet_offset(&mut self, recv: &Value, key: &Value) {
if matches!(recv, Value::Str(_)) {
self.diagnose_offset(key);
return;
}
self.diagnose_array_offset(recv, key);
}
pub fn array_has_key(&mut self, arr: &Value, key: &Value) -> Option<bool> {
if !matches!(self.as_array(arr), Some(PhpObj::Array { .. })) {
return None;
}
self.diagnose_offset(key);
let k = self.norm_key(key);
match self.as_array(arr) {
Some(PhpObj::Array { entries, .. }) => Some(entries.contains_key(&k)),
_ => None,
}
}
pub(crate) fn active_function_name(&self) -> String {
match self.scopes.iter().rev().find(|s| !s.internal) {
Some(scope) if scope.name.is_some() => {
format!("{}()", self.trace_frame_name(scope).replace("->", "::"))
}
_ => "Unknown".to_string(),
}
}
pub(crate) fn deprecated_at_shutdown(&mut self, msg: impl std::fmt::Display) {
self.unknown_site = true;
self.diagnose(
"Deprecated",
errlevel::E_DEPRECATED,
0,
format!("PHP Request Shutdown: {msg}"),
);
self.unknown_site = false;
}
pub fn notice(&mut self, msg: impl std::fmt::Display) {
self.diagnose("Notice", errlevel::E_NOTICE, warn_line(), msg);
}
pub fn diagnose(&mut self, severity: &str, level: i64, line: u32, msg: impl std::fmt::Display) {
let line = prelude_call_site_line(self).unwrap_or(line);
if !self.in_error_handler && level & errlevel::HANDLEABLE != 0 {
if let Some((handler, mask)) = self.error_handlers.last() {
if !matches!(handler, Value::Undef) && mask & level != 0 {
let file = self.current_file().to_string();
self.queued_errors.push((
severity.to_string(),
level,
msg.to_string(),
file,
line,
));
ERRORS_QUEUED.with(|q| q.set(true));
return;
}
}
}
self.diagnose_default(severity, level, line, msg);
}
fn diagnose_default(
&mut self,
severity: &str,
level: i64,
line: u32,
msg: impl std::fmt::Display,
) {
self.last_error = Some((
level,
msg.to_string(),
self.current_file().to_string(),
line,
));
if self.suppress > 0 || self.error_reporting & level == 0 {
return;
}
let body = format!("{msg} in {} on line {line}", self.current_file());
if self.ini_flag("log_errors") {
Self::write_err(format!("PHP {severity}: {body}\n").as_bytes());
}
if self.ini_flag("display_errors") {
self.write_out(&format!("\n{severity}: {body}\n"));
}
}
fn ini_flag(&self, name: &str) -> bool {
match self.ini.get(name).map(|s| s.trim()) {
None | Some("") | Some("0") => false,
Some(s) => {
!(s.eq_ignore_ascii_case("off")
|| s.eq_ignore_ascii_case("false")
|| s.eq_ignore_ascii_case("no"))
}
}
}
pub fn error_reporting(&self) -> i64 {
self.error_reporting
}
pub fn preg_error(&self) -> i64 {
self.preg_error
}
pub fn set_preg_error(&mut self, code: i64) {
self.preg_error = code;
}
pub fn strtok_state(&self) -> Option<(String, usize)> {
self.strtok_state.clone()
}
pub fn set_strtok_state(&mut self, state: Option<(String, usize)>) {
self.strtok_state = state;
}
pub fn error_get_last(&mut self) -> Value {
let Some((level, msg, file, line)) = self.last_error.clone() else {
return Value::Undef;
};
let arr = self.new_array();
for (k, v) in [
("type", Value::int(level)),
("message", Value::str(msg)),
("file", Value::str(file)),
("line", Value::int(line as i64)),
] {
self.arr_set_key(&arr, &Value::str(k.to_string()), v);
}
arr
}
pub fn error_clear_last(&mut self) {
self.last_error = None;
}
pub fn set_error_reporting(&mut self, level: i64) -> i64 {
self.ini
.insert("error_reporting".to_string(), level.to_string());
std::mem::replace(&mut self.error_reporting, level)
}
pub fn ini_get(&self, name: &str) -> Option<String> {
self.ini.get(name).cloned()
}
pub fn ini_set(&mut self, name: &str, value: &str) -> Option<String> {
if INI_FIXED.contains(&name) {
return None;
}
let level = (name == "error_reporting")
.then(|| self.to_number(&Value::str(value.to_string())).to_int());
let slot = self.ini.get_mut(name)?;
let old = std::mem::replace(slot, value.to_string());
if let Some(level) = level {
self.error_reporting = level;
}
Some(old)
}
fn trace_arg(&self, v: &Value) -> String {
match v {
Value::Undef => "NULL".to_string(),
Value::Bool(true) => "true".to_string(),
Value::Bool(false) => "false".to_string(),
Value::Str(s) => format!("'{}'", escape_trace_string(s)),
Value::Obj(_) if self.is_array(v) => "Array".to_string(),
Value::Obj(_) if self.is_stream(v) => self.to_str(v),
Value::Obj(_) => match self.instance_class(v) {
Some(c) => format!("Object({c})"),
None => "Object(stdClass)".to_string(),
},
Value::Float(f) => {
let s = self.to_str(v);
if f.is_finite() && !s.contains('.') && !s.contains('E') {
format!("{s}.0")
} else {
s
}
}
other => self.to_str(other),
}
}
pub fn match_error_message(&self, v: &Value) -> String {
let rendered = match v {
Value::Undef | Value::Bool(_) | Value::Int(_) | Value::Float(_) | Value::Str(_) => {
self.trace_arg(v)
}
_ if self.is_stream(v) => "of type resource".to_string(),
_ => format!("of type {}", crate::stdlib::types::debug_type(self, v)),
};
format!("Unhandled match case {rendered}")
}
fn trace_frame_parts(&self, scope: &Scope) -> (Option<(String, &'static str)>, String) {
let Some(name) = &scope.name else {
return (None, String::new());
};
let call_type = if !matches!(scope.vars.get("this"), Slot::Unset) {
"->"
} else {
"::"
};
let declared = |class: &str| {
self.classes
.get(class)
.map(|d| d.name.clone())
.unwrap_or_else(|| class.to_string())
};
if let Some(site) = &scope.closure_site {
let rendered = match site {
DeclSite::Closure(inner, line) => {
format!(
"{{closure:{}:{line}}}",
inner.render(scope.file.as_deref().unwrap_or(&self.script_name))
)
}
other => other.render(scope.file.as_deref().unwrap_or(&self.script_name)),
};
return match name.split_once("::") {
Some((class, _)) => (Some((declared(class), call_type)), rendered),
None => (None, rendered),
};
}
match name.split_once("::") {
Some((class, method)) => (Some((declared(class), call_type)), method.to_string()),
None => (None, name.clone()),
}
}
fn trace_frame_name(&self, scope: &Scope) -> String {
match self.trace_frame_parts(scope) {
(Some((class, ty)), function) => format!("{class}{ty}{function}"),
(None, function) => function,
}
}
pub fn backtrace(&self) -> String {
self.render_trace(&self.trace_entries())
}
fn trace_entries(&self) -> Vec<TraceEntry> {
struct Frame<'a> {
entry: Option<TraceEntry>,
file: &'a str,
line: u32,
internal: bool,
prelude: bool,
helper: bool,
transparent: bool,
}
let mut frames: Vec<Frame<'_>> = Vec::new();
for (i, scope) in self.scopes.iter().enumerate() {
let incs: Vec<&IncludeFrame> = self.includes.iter().filter(|f| f.depth == i).collect();
let entry = (i > 0).then(|| {
let names = self.frame_arg_names(i);
let args = self
.frame_args(i)
.unwrap_or_default()
.into_iter()
.enumerate()
.map(|(j, v)| (names.get(j).cloned().flatten(), v))
.collect();
let (class, function) = self.trace_frame_parts(scope);
let object = match scope.vars.get("this") {
Slot::Unset => None,
slot => Some(self.read_slot(&slot.clone())),
}
.filter(|_| class.is_some());
TraceEntry {
site: None,
function,
class,
args,
object,
include: false,
}
});
frames.push(Frame {
entry,
file: self.scope_file(i),
line: incs.first().map_or(scope.line, |f| f.call_line),
internal: scope.internal,
prelude: scope.name.as_deref().is_some_and(is_prelude_frame),
helper: scope.name.as_deref().is_some_and(is_prelude_frame)
&& (scope.closure_site.is_some()
|| scope.name.as_deref().is_some_and(is_prelude_helper_name)),
transparent: scope.transparent
|| scope
.name
.as_deref()
.is_some_and(|n| is_prelude_frame(n) && n.ends_with("::__call")),
});
for (k, inc) in incs.iter().enumerate() {
frames.push(Frame {
entry: Some(TraceEntry {
site: None,
function: inc.construct.to_string(),
class: None,
args: inc
.arg
.clone()
.map(|p| (None, Value::str(p)))
.into_iter()
.collect(),
object: None,
include: true,
}),
file: &inc.file,
line: incs.get(k + 1).map_or(scope.line, |f| f.call_line),
internal: false,
prelude: false,
helper: false,
transparent: false,
});
}
}
let visible: Vec<bool> = (0..frames.len())
.map(|j| {
j == 0
|| !(frames[j].transparent
|| frames[j - 1].prelude && (frames[j].helper || frames[j].internal))
})
.collect();
let mut out = Vec::new();
for j in (1..frames.len()).rev() {
if !visible[j] {
continue;
}
let mut k = j - 1;
while !visible[k] {
k -= 1;
}
let caller = &frames[k];
let Some(mut entry) = frames[j].entry.clone() else {
continue;
};
if !(caller.internal || caller.prelude) {
entry.site = Some((caller.file.to_string(), caller.line));
}
out.push(entry);
}
out
}
fn trace_args_string(&self, args: &[(Option<String>, Value)]) -> String {
args.iter()
.map(|(name, v)| match name {
Some(n) => format!("{n}: {}", self.trace_arg(v)),
None => self.trace_arg(v),
})
.collect::<Vec<_>>()
.join(", ")
}
fn render_trace(&self, entries: &[TraceEntry]) -> String {
let mut out = String::new();
for (n, e) in entries.iter().enumerate() {
let site = match &e.site {
Some((file, line)) => format!("{file}({line})"),
None => "[internal function]".to_string(),
};
let name = match &e.class {
Some((class, ty)) => format!("{class}{ty}{}", e.function),
None => e.function.clone(),
};
let args = self.trace_args_string(&e.args);
out.push_str(&format!("#{n} {site}: {name}({args})\n"));
}
out.push_str(&format!("#{} {{main}}", entries.len()));
out
}
pub fn trace_array(&mut self, provide_object: bool, ignore_args: bool, limit: usize) -> Value {
let mut entries = self.trace_entries();
if limit > 0 {
entries.truncate(limit);
}
let out = self.new_array();
for e in entries {
let frame = self.new_array();
if let Some((file, line)) = &e.site {
self.arr_set_key(&frame, &Value::str("file"), Value::str(file.clone()));
self.arr_set_key(&frame, &Value::str("line"), Value::int(*line as i64));
}
let args_arr = (!ignore_args).then(|| {
let a = self.new_array();
for (name, v) in &e.args {
match name {
Some(n) => self.arr_set_key(&a, &Value::str(n.clone()), v.clone()),
None => self.arr_push_auto(&a, v.clone()),
}
}
a
});
if e.include {
if let Some(a) = args_arr.filter(|_| !e.args.is_empty()) {
self.arr_set_key(&frame, &Value::str("args"), a);
}
self.arr_set_key(
&frame,
&Value::str("function"),
Value::str(e.function.clone()),
);
} else {
self.arr_set_key(
&frame,
&Value::str("function"),
Value::str(e.function.clone()),
);
if let Some((class, ty)) = &e.class {
self.arr_set_key(&frame, &Value::str("class"), Value::str(class.clone()));
if let (true, Some(obj)) = (provide_object, &e.object) {
self.arr_set_key(&frame, &Value::str("object"), obj.clone());
}
self.arr_set_key(&frame, &Value::str("type"), Value::str(*ty));
}
if let Some(a) = args_arr {
self.arr_set_key(&frame, &Value::str("args"), a);
}
}
self.arr_push_auto(&out, frame);
}
out
}
pub fn render_trace_array(&self, trace: &Value) -> String {
let key = |f: &Value, k: &str| self.index_get(f, &Value::str(k.to_string()));
let entries: Vec<TraceEntry> = self
.array_pairs(trace)
.unwrap_or_default()
.into_iter()
.map(|(_, f)| {
let file = key(&f, "file");
let site = match file {
Value::Undef => None,
file => Some((self.to_str(&file), key(&f, "line").to_int() as u32)),
};
let class = match key(&f, "class") {
Value::Undef => None,
c => Some((
self.to_str(&c),
if self.to_str(&key(&f, "type")) == "::" {
"::"
} else {
"->"
},
)),
};
let args = match key(&f, "args") {
a if self.is_array(&a) => self
.array_pairs(&a)
.unwrap_or_default()
.into_iter()
.map(|(k, v)| match k {
Value::Str(s) => (Some(s.to_string()), v),
_ => (None, v),
})
.collect(),
_ => Vec::new(),
};
TraceEntry {
site,
function: self.to_str(&key(&f, "function")),
class,
args,
object: None,
include: false,
}
})
.collect();
self.render_trace(&entries)
}
pub fn push_internal_frame(&mut self, func: &str, line: u32, args: Value) {
self.scopes.push(Scope {
name: Some(func.to_string()),
line,
internal: true,
..Scope::default()
});
self.set_var("@args", args);
}
pub fn pop_internal_frame(&mut self) {
self.scopes.pop();
}
pub fn enter_clone_frame(&mut self, line: u32, args: Value) -> bool {
let ctx = self.current_class_ctx();
self.push_internal_frame("clone", line, args);
match ctx {
Some(c) => {
self.init_class_scope.push(c);
true
}
None => false,
}
}
pub fn leave_clone_frame(&mut self, scoped: bool) {
if scoped {
self.init_class_scope.pop();
}
self.pop_internal_frame();
}
pub(crate) fn frame_arg_names(&self, idx: usize) -> Vec<Option<String>> {
let args = self.get_var_in(idx, "@args");
if !self.is_array(&args) {
return Vec::new();
}
self.array_pairs(&args)
.unwrap_or_default()
.iter()
.map(|(k, _)| match k {
Value::Str(s) => Some(s.to_string()),
_ => None,
})
.collect()
}
pub(crate) fn frame_args(&self, idx: usize) -> Option<Vec<Value>> {
let args = self.get_var_in(idx, "@args");
if !self.is_array(&args) {
return None;
}
let names = self.get_var_in(idx, "@argnames");
Some(
self.array_pairs(&args)
.unwrap_or_default()
.iter()
.enumerate()
.map(
|(pos, (_, v))| match self.index_get(&names, &Value::int(pos as i64)) {
Value::Undef => v.clone(),
n => self.get_var_in(idx, &self.to_str(&n)),
},
)
.collect(),
)
}
pub(crate) fn current_frame_args(&self) -> Option<Vec<Value>> {
self.frame_args(self.scopes.len().checked_sub(1)?)
}
fn get_var_in(&self, idx: usize, name: &str) -> Value {
self.scopes
.get(idx)
.map(|s| s.vars.get(name).clone())
.map(|s| self.read_slot(&s))
.unwrap_or(Value::Undef)
}
pub fn fatal(&mut self, severity: &str, body: &str) {
let level = if severity == "Parse error" {
errlevel::E_PARSE
} else {
errlevel::E_ERROR
};
if self.error_reporting & level == 0 {
self.fatal_reported = true;
return;
}
if self.ini_flag("log_errors") {
Self::write_err(format!("PHP {severity}: {body}\n").as_bytes());
}
if self.ini_flag("display_errors") {
self.write_out(&format!("\n{severity}: {body}\n"));
}
self.fatal_reported = true;
}
pub fn fatal_reported(&self) -> bool {
self.fatal_reported
}
pub fn diag_type(&self, v: &Value) -> &'static str {
match v {
Value::Undef => "null",
Value::Bool(_) => "bool",
Value::Int(_) => "int",
Value::Float(_) => "float",
Value::Str(_) => "string",
Value::Obj(_) => {
if self.is_array(v) {
"array"
} else {
"object"
}
}
_ => "null",
}
}
fn diag_offset_type(&self, v: &Value) -> &'static str {
match v {
Value::Bool(true) => "true",
Value::Bool(false) => "false",
other => self.diag_type(other),
}
}
pub fn diag_key(&self, key: &Value) -> String {
match self.norm_key(key) {
ArrayKey::Int(n) => n.to_string(),
ArrayKey::Str(s) => format!("\"{s}\""),
}
}
pub fn set_error(&mut self, msg: impl Into<String>) {
if self.error.is_none() {
self.error = Some(msg.into());
}
}
pub fn take_error(&mut self) -> Option<String> {
self.error.take()
}
fn scope_idx(&self, name: &str) -> usize {
if is_superglobal(name) {
0
} else {
self.scopes.len().saturating_sub(1)
}
}
pub fn get_var(&self, name: &str) -> Value {
let idx = self.scope_idx(name);
let Some(scope) = self.scopes.get(idx) else {
return Value::Undef;
};
self.read_slot(scope.vars.get(name))
}
fn read_slot(&self, s: &Slot) -> Value {
match s {
Slot::Val(v) => v.clone(),
Slot::Ref(c) => self.ref_cells.get(*c).cloned().unwrap_or(Value::Undef),
Slot::Unset => Value::Undef,
}
}
pub fn var_defined(&self, name: &str) -> bool {
let idx = self.scope_idx(name);
let Some(scope) = self.scopes.get(idx) else {
return false;
};
!matches!(scope.vars.get(name), Slot::Unset)
}
pub fn var_has_slot(&self, name: &str) -> bool {
let idx = self.scope_idx(name);
self.scopes
.get(idx)
.is_some_and(|s| s.vars.slot_of(name).is_some())
}
pub fn set_var(&mut self, name: &str, val: Value) {
let idx = self.scope_idx(name);
let Some(scope) = self.scopes.get_mut(idx) else {
return;
};
let i = scope.vars.ensure_slot(name);
self.write_slot(idx, i, val);
}
pub fn is_plain_foreach_object(&self, v: &Value) -> bool {
!self.is_array(v)
&& !self.is_generator_val(v)
&& self.object_class(v).is_some_and(|c| {
!self.class_has_method(&c, "getIterator")
&& !(self.class_has_method(&c, "valid") && self.class_has_method(&c, "current"))
})
}
fn bound_value_mut(&mut self, scope_idx: usize, i: u32) -> Option<&mut Value> {
let cell = match self.scopes.get(scope_idx)?.vars.slots.get(i as usize)? {
Slot::Ref(c) => Some(*c),
Slot::Val(_) => None,
Slot::Unset => return None,
};
match cell {
Some(c) => self.ref_cells.get_mut(c),
None => match self.scopes[scope_idx].vars.slots.get_mut(i as usize)? {
Slot::Val(v) => Some(v),
_ => None,
},
}
}
fn append_bound(&mut self, scope_idx: usize, i: u32, y: &str) -> Option<Value> {
match self.bound_value_mut(scope_idx, i)? {
Value::Str(s) => {
crate::bytes::append(std::sync::Arc::make_mut(s), y);
Some(Value::Str(s.clone()))
}
_ => None,
}
}
pub fn slot_append_str(&mut self, i: u32, y: &str) -> Option<Value> {
let idx = self.scopes.len().checked_sub(1)?;
self.append_bound(idx, i, y)
}
pub fn var_append_str(&mut self, name: &str, y: &str) -> Option<Value> {
let idx = self.scope_idx(name);
let i = self.scopes.get(idx)?.vars.slot_of(name)?;
self.append_bound(idx, i, y)
}
fn write_slot(&mut self, scope_idx: usize, i: u32, val: Value) {
let cell = match self.scopes.get(scope_idx).map(|s| s.vars.at(i)) {
Some(Slot::Ref(c)) => Some(*c),
_ => None,
};
match cell {
Some(c) => {
if let Some(slot) = self.ref_cells.get_mut(c) {
*slot = val;
}
}
None => {
if let Some(scope) = self.scopes.get_mut(scope_idx) {
scope.vars.put(i, Slot::Val(val));
}
}
}
}
pub fn defined_vars(&self) -> Vec<(String, Value)> {
let idx = self.scopes.len().saturating_sub(1);
if idx == 0 {
return self.global_vars_ordered();
}
self.frame_vars(idx)
}
fn frame_vars(&self, idx: usize) -> Vec<(String, Value)> {
let Some(scope) = self.scopes.get(idx) else {
return Vec::new();
};
let mut by_slot: Vec<(u32, &String)> = scope
.vars
.index
.iter()
.map(|(name, &i)| (i, name))
.collect();
by_slot.sort_unstable_by_key(|(i, _)| *i);
by_slot
.into_iter()
.filter(|(_, name)| {
!name.starts_with('@') && !matches!(name.as_str(), "this" | "GLOBALS")
})
.filter_map(|(i, name)| match scope.vars.at(i) {
Slot::Unset => None,
slot => Some((name.clone(), self.read_slot(slot))),
})
.collect()
}
pub fn slot_get(&mut self, i: u32) -> Value {
let s = match self.scopes.last() {
Some(sc) => sc.vars.at(i).clone(),
None => Slot::Unset,
};
if matches!(s, Slot::Unset) {
if let Some(n) = self.slot_name(i) {
if !n.starts_with('@') {
self.warn(format_args!("Undefined variable ${n}"));
}
}
return Value::Undef;
}
self.read_slot(&s)
}
pub fn slot_get_quiet(&self, i: u32) -> Value {
match self.scopes.last() {
Some(sc) => self.read_slot(sc.vars.at(i)),
None => Value::Undef,
}
}
pub fn slot_set(&mut self, i: u32, val: Value) {
let idx = self.scopes.len().saturating_sub(1);
self.write_slot(idx, i, val);
}
fn slot_name(&self, i: u32) -> Option<String> {
self.scopes
.last()?
.vars
.index
.iter()
.find(|(_, &v)| v == i)
.map(|(k, _)| k.clone())
}
pub fn seed_global_slots(&mut self, names: &[String]) {
if let Some(scope) = self.scopes.first_mut() {
scope.vars.renumber(names);
}
}
fn seed_slots(&mut self, names: &[String]) {
if let Some(scope) = self.scopes.last_mut() {
for n in names {
scope.vars.ensure_slot(n);
}
}
}
pub fn ref_cell_of(&mut self, name: &str) -> Value {
let slot = self.ref_slot_of(name);
self.objs.push(PhpObj::Ref { slot });
Value::Obj((self.objs.len() - 1) as u32)
}
pub fn bind_ref_slot(&mut self, name: &str, slot: usize) {
let idx = self.scope_idx(name);
if let Some(scope) = self.scopes.get_mut(idx) {
let i = scope.vars.ensure_slot(name);
scope.vars.put(i, Slot::Ref(slot));
}
}
pub fn new_ref_cell(&mut self, val: Value) -> (Value, usize) {
self.ref_cells.push(val);
let slot = self.ref_cells.len() - 1;
self.objs.push(PhpObj::Ref { slot });
(Value::Obj((self.objs.len() - 1) as u32), slot)
}
pub fn ref_cell_value(&self, slot: usize) -> Value {
self.ref_cells.get(slot).cloned().unwrap_or(Value::Undef)
}
pub fn ref_slot_of_value(&self, v: &Value) -> Option<usize> {
match v {
Value::Obj(h) => match self.objs.get(*h as usize) {
Some(PhpObj::Ref { slot }) => Some(*slot),
_ => None,
},
_ => None,
}
}
fn deref(&self, v: Value) -> Value {
match self.ref_slot_of_value(&v) {
Some(slot) => self.ref_cells.get(slot).cloned().unwrap_or(Value::Undef),
None => v,
}
}
fn ref_cell_set(&mut self, slot: usize, val: Value) {
if let Some(cell) = self.ref_cells.get_mut(slot) {
*cell = val;
}
}
fn ref_slot_of(&mut self, name: &str) -> usize {
let idx = self.scope_idx(name);
if let Some(Slot::Ref(c)) = self.scopes.get(idx).map(|s| s.vars.get(name)) {
return *c;
}
let cur = self
.scopes
.get(idx)
.map(|s| s.vars.get(name).clone())
.map(|s| self.read_slot(&s))
.unwrap_or(Value::Undef);
self.ref_cells.push(cur);
let slot = self.ref_cells.len() - 1;
if let Some(scope) = self.scopes.get_mut(idx) {
let i = scope.vars.ensure_slot(name);
scope.vars.put(i, Slot::Ref(slot));
}
slot
}
pub fn elem_ref_slot(&mut self, name: &str, keys: &[Value]) -> usize {
let Some((last, inter)) = keys.split_last() else {
return self.ref_slot_of(name);
};
let arr = self.ensure_path_array(name, inter);
self.arr_elem_ref_slot(&arr, last)
}
pub fn arr_elem_ref_slot(&mut self, arr: &Value, key: &Value) -> usize {
let k = self.norm_key(key);
if let Some(slot) = self.entry_ref_slot(arr, &k) {
return slot;
}
let cur = match self.as_array(arr) {
Some(PhpObj::Array { entries, .. }) => entries.get(&k).cloned().unwrap_or(Value::Undef),
_ => Value::Undef,
};
self.ref_cells.push(cur);
let slot = self.ref_cells.len() - 1;
self.objs.push(PhpObj::Ref { slot });
let handle = Value::Obj((self.objs.len() - 1) as u32);
if let Some(PhpObj::Array {
entries,
next_index,
}) = self.as_array_mut(arr)
{
if let ArrayKey::Int(n) = k {
if n >= *next_index {
*next_index = n.saturating_add(1);
}
}
entries.insert(k, handle);
}
slot
}
pub fn prop_ref_slot_ensure(&mut self, recv: &Value, name: &str) -> usize {
if let Some(slot) = self.prop_ref_slot(recv, name) {
return slot;
}
let cur = match self.as_array(recv) {
Some(PhpObj::Object { props, .. }) => props.get(name).cloned().unwrap_or(Value::Undef),
_ => Value::Undef,
};
self.ref_cells.push(cur);
let slot = self.ref_cells.len() - 1;
self.objs.push(PhpObj::Ref { slot });
let handle = Value::Obj((self.objs.len() - 1) as u32);
self.obj_put_prop(recv, name, handle);
slot
}
pub fn bind_elem_to_slot(&mut self, name: &str, keys: &[Value], slot: usize) {
let Some((last, inter)) = keys.split_last() else {
self.bind_ref_slot(name, slot);
return;
};
let arr = self.ensure_path_array(name, inter);
self.objs.push(PhpObj::Ref { slot });
let handle = Value::Obj((self.objs.len() - 1) as u32);
let k = self.norm_key(last);
if let Some(PhpObj::Array {
entries,
next_index,
}) = self.as_array_mut(&arr)
{
if let ArrayKey::Int(n) = k {
if n >= *next_index {
*next_index = n.saturating_add(1);
}
}
entries.insert(k, handle);
}
}
pub fn append_elem_to_slot(
&mut self,
name: &str,
keys: &[Value],
slot: usize,
) -> Result<(), String> {
let arr = self.ensure_path_array(name, keys);
if self.append_slot_taken(&arr) {
return Err(NEXT_ELEMENT_OCCUPIED.to_string());
}
self.objs.push(PhpObj::Ref { slot });
let handle = Value::Obj((self.objs.len() - 1) as u32);
if let Some(PhpObj::Array {
entries,
next_index,
}) = self.as_array_mut(&arr)
{
let k = ArrayKey::Int(take_next_index(next_index));
entries.insert(k, handle);
}
Ok(())
}
pub fn bind_prop_to_slot(&mut self, recv: &Value, name: &str, slot: usize) {
self.objs.push(PhpObj::Ref { slot });
let handle = Value::Obj((self.objs.len() - 1) as u32);
self.obj_put_prop(recv, name, handle);
}
pub fn lsb_class(&self, fallback: &str) -> String {
self.scopes
.last()
.and_then(|s| s.static_class.clone())
.unwrap_or_else(|| fallback.to_string())
}
pub fn lsb_forward(&mut self) {
self.pending_lsb = self.scopes.last().and_then(|s| s.static_class.clone());
}
pub fn lsb_set_for_next_call(&mut self, class: &str) {
if self.pending_lsb.is_none() {
self.pending_lsb = Some(class.to_string());
}
}
fn lsb_take(&mut self) -> Option<String> {
self.pending_lsb.take()
}
pub fn closure_site_for_next_call(&mut self, site: Option<DeclSite>) {
self.pending_closure_site = site;
}
fn closure_site_take(&mut self) -> Option<DeclSite> {
self.pending_closure_site.take()
}
pub fn set_ret_ref_slot(&mut self, slot: usize) {
self.ret_ref_slot = Some(slot);
}
pub fn take_published_ret_ref(&mut self) -> Option<usize> {
self.ret_ref_slot.take()
}
pub fn has_published_ret_ref(&self) -> bool {
self.ret_ref_slot.is_some()
}
pub fn ref_cell_ensure_array(&mut self, slot: usize) -> Value {
let cur = self.ref_cell_value(slot);
if !matches!(cur, Value::Undef) {
return cur;
}
let arr = self.new_array();
if let Some(cell) = self.ref_cells.get_mut(slot) {
*cell = arr.clone();
}
arr
}
pub fn take_ret_ref_slot(&mut self, fallback: Value) -> usize {
match self.ret_ref_slot.take() {
Some(slot) => slot,
None => {
self.ref_cells.push(fallback);
self.ref_cells.len() - 1
}
}
}
fn global_vars_ordered(&self) -> Vec<(String, Value)> {
const FIXED: [&str; 7] = [
"argv", "argc", "_GET", "_POST", "_COOKIE", "_FILES", "_SERVER",
];
let all = self.frame_vars(0);
let mut ordered: Vec<(String, Value)> = Vec::with_capacity(all.len());
for name in FIXED {
if let Some(pair) = all.iter().find(|(n, _)| n == name) {
ordered.push(pair.clone());
}
}
ordered.extend(
all.into_iter()
.filter(|(n, _)| !FIXED.contains(&n.as_str()) && !is_superglobal(n)),
);
ordered
}
pub fn globals_array(&mut self) -> Value {
let ordered = self.global_vars_ordered();
let arr = self.new_array();
for (name, value) in ordered {
self.arr_set_key(&arr, &Value::str(name), value);
}
arr
}
pub fn global_value(&self, name: &str) -> Option<Value> {
if name == "GLOBALS" {
return None;
}
let scope = self.scopes.first()?;
match scope.vars.get(name) {
Slot::Unset => None,
slot => Some(self.read_slot(slot)),
}
}
pub fn globals_bind(&mut self, local: &str, name: &str) {
const GLOBAL_FRAME: usize = 0;
let cur = self.scopes.len().saturating_sub(1);
let slot = match self.scopes.get(GLOBAL_FRAME).map(|s| s.vars.get(name)) {
Some(Slot::Ref(c)) => *c,
_ => {
let cur_val = self
.scopes
.get(GLOBAL_FRAME)
.map(|s| s.vars.get(name).clone())
.map(|s| self.read_slot(&s))
.unwrap_or(Value::Undef);
self.ref_cells.push(cur_val);
let slot = self.ref_cells.len() - 1;
if let Some(scope) = self.scopes.get_mut(GLOBAL_FRAME) {
let i = scope.vars.ensure_slot(name);
scope.vars.put(i, Slot::Ref(slot));
}
slot
}
};
if let Some(scope) = self.scopes.get_mut(cur) {
let i = scope.vars.ensure_slot(local);
scope.vars.put(i, Slot::Ref(slot));
}
}
pub fn globals_unset(&mut self, name: &str) {
if let Some(scope) = self.scopes.first_mut() {
if let Some(i) = scope.vars.slot_of(name) {
scope.vars.put(i, Slot::Unset);
}
}
}
pub fn bind_global(&mut self, name: &str) {
const GLOBAL_FRAME: usize = 0;
let cur = self.scopes.len().saturating_sub(1);
if cur == GLOBAL_FRAME {
return;
}
let slot = match self.scopes.get(GLOBAL_FRAME).map(|s| s.vars.get(name)) {
Some(Slot::Ref(c)) => *c,
_ => {
let cur_val = self
.scopes
.get(GLOBAL_FRAME)
.map(|s| s.vars.get(name).clone())
.map(|s| self.read_slot(&s))
.unwrap_or(Value::Undef);
self.ref_cells.push(cur_val);
let slot = self.ref_cells.len() - 1;
if let Some(scope) = self.scopes.get_mut(GLOBAL_FRAME) {
let i = scope.vars.ensure_slot(name);
scope.vars.put(i, Slot::Ref(slot));
}
slot
}
};
if let Some(scope) = self.scopes.get_mut(cur) {
let i = scope.vars.ensure_slot(name);
scope.vars.put(i, Slot::Ref(slot));
}
}
pub fn ref_bind(&mut self, target: &str, source: &str) {
let idx = self.scope_idx(source);
let slot = self.ref_slot_of(source);
let _ = idx;
let tidx = self.scope_idx(target);
if let Some(scope) = self.scopes.get_mut(tidx) {
let i = scope.vars.ensure_slot(target);
scope.vars.put(i, Slot::Ref(slot));
}
}
pub fn unset_var(&mut self, name: &str) {
let idx = self.scope_idx(name);
if let Some(scope) = self.scopes.get_mut(idx) {
if let Some(i) = scope.vars.slot_of(name) {
scope.vars.put(i, Slot::Unset);
}
}
}
pub fn unset_path(&mut self, name: &str, keys: &[Value]) {
let Some((last, inter)) = keys.split_last() else {
return;
};
let mut arr = self.get_var(name);
for k in inter {
arr = self.index_get(&arr, k);
}
self.diagnose_array_offset(&arr, last);
let nk = self.norm_key(last);
if let Some(PhpObj::Array { entries, .. }) = self.as_array_mut(&arr) {
entries.shift_remove(&nk);
}
}
pub fn frame_depth(&self) -> usize {
self.scopes.len()
}
pub fn set_cur_line(&mut self, line: u32) {
if let Some(s) = self.scopes.last_mut() {
s.line = line;
}
}
pub fn dbg_stack(&self) -> Vec<(String, u32)> {
self.scopes
.iter()
.rev()
.map(|s| {
let name = s.name.clone().unwrap_or_else(|| "{main}".to_string());
(name, s.line)
})
.collect()
}
pub fn dbg_locals(&self) -> Vec<(String, String)> {
let pairs: Vec<(String, Slot)> = self
.scopes
.last()
.map(|s| {
s.vars
.iter()
.filter(|(k, _)| !k.starts_with('@'))
.map(|(k, v)| (k.clone(), v.clone()))
.collect()
})
.unwrap_or_default();
let vars: Vec<(String, Value)> = pairs
.into_iter()
.map(|(k, s)| {
let v = self.read_slot(&s);
(k, v)
})
.collect();
vars.into_iter()
.map(|(n, v)| (format!("${n}"), self.to_str(&v)))
.collect()
}
pub fn new_transient_object(&mut self, props: Vec<(String, Value)>) -> Value {
let v = self.new_object_bare("stdClass", props);
if let Value::Obj(id) = v {
self.transient_objs.insert(id);
}
v
}
pub fn new_object_bare(&mut self, class: &str, props: Vec<(String, Value)>) -> Value {
self.objs.push(PhpObj::Object {
class: class.to_string(),
props: props.into_iter().collect(),
});
Value::Obj((self.objs.len() - 1) as u32)
}
pub fn new_array(&mut self) -> Value {
self.objs.push(PhpObj::Array {
entries: IndexMap::new(),
next_index: NO_INDEX,
});
Value::Obj((self.objs.len() - 1) as u32)
}
pub fn copy_on_assign(&mut self, v: Value) -> Value {
let Value::Obj(id) = v else { return v };
let Some(PhpObj::Array {
entries,
next_index,
}) = self.objs.get(id as usize)
else {
return v;
};
let next_index = *next_index;
let pairs: Vec<(ArrayKey, Value)> = entries
.iter()
.map(|(k, v)| (k.clone(), v.clone()))
.collect();
let copied: IndexMap<ArrayKey, Value> = pairs
.into_iter()
.map(|(k, v)| (k, self.copy_on_assign(v)))
.collect();
self.objs.push(PhpObj::Array {
entries: copied,
next_index,
});
Value::Obj((self.objs.len() - 1) as u32)
}
pub fn clone_obj(&mut self, v: &Value) -> Option<Value> {
let Value::Obj(id) = v else { return None };
match self.objs.get(*id as usize)? {
PhpObj::Object { class, props } => {
let class = class.clone();
let pairs: Vec<(String, Value)> =
props.iter().map(|(k, v)| (k.clone(), v.clone())).collect();
let props: IndexMap<String, Value> = pairs
.into_iter()
.map(|(k, v)| (k, self.copy_on_assign(v)))
.collect();
self.objs.push(PhpObj::Object { class, props });
let copy = (self.objs.len() - 1) as u32;
if let Some(init) = self.readonly_init.get(id).cloned() {
self.readonly_init.insert(copy, init);
}
Some(Value::Obj(copy))
}
dup @ PhpObj::Closure { .. } => {
let mut dup = dup.clone();
if let PhpObj::Closure { captured, .. } = &mut dup {
self.fork_closure_statics(captured);
}
self.objs.push(dup);
Some(Value::Obj((self.objs.len() - 1) as u32))
}
_ => None,
}
}
pub fn make_closure(&mut self, def_name: &str, mut captured: Vec<(String, Value)>) -> Value {
let Some(def) = self.functions.get(def_name).cloned() else {
return Value::Undef;
};
let is_static = {
let n = captured.len();
captured.retain(|(k, _)| k != STATIC_CLOSURE_CAPTURE);
captured.len() != n
};
for (k, v) in captured.iter_mut() {
let uninit = k.starts_with("?@static#");
if !uninit && !k.starts_with("@static#") {
continue;
}
if uninit {
k.remove(0);
}
self.ref_cells.push(std::mem::take(v));
let slot = self.ref_cells.len() - 1;
if uninit {
self.static_uninit.insert(slot);
}
self.objs.push(PhpObj::Ref { slot });
*v = Value::Obj((self.objs.len() - 1) as u32);
}
let bound_this = match self.get_var("this") {
_ if is_static => None,
t @ Value::Obj(_) => Some(t),
_ => None,
};
let scope = self.current_class_ctx();
let called_scope = match self.get_var("this") {
t @ Value::Obj(_) => self.object_class(&t),
_ => self.scopes.last().and_then(|s| s.static_class.clone()),
};
self.objs.push(PhpObj::Closure {
params: def.params,
chunk: Box::new(def.chunk),
captured,
bound_this,
scope,
called_scope,
is_generator: def.is_generator,
ret: def.ret,
is_static,
site: def.closure_site,
doc: def.doc,
attrs: def.attrs,
span: def.span,
});
Value::Obj((self.objs.len() - 1) as u32)
}
fn closure_of(&self, v: &Value) -> Option<ClosureCall> {
match self.as_array(v) {
Some(PhpObj::Closure {
params,
chunk,
captured,
bound_this,
scope,
called_scope,
is_generator,
ret,
site,
..
}) => Some(ClosureCall {
params: params.clone(),
chunk: (**chunk).clone(),
captured: captured.clone(),
bound_this: bound_this.clone(),
scope: scope.clone(),
called_scope: called_scope.clone(),
is_generator: *is_generator,
ret: ret.clone(),
site: site.clone(),
}),
_ => None,
}
}
pub fn rebind_closure(
&mut self,
v: &Value,
this: Option<Value>,
scope: Option<String>,
) -> Option<Value> {
let mut dup = match self.as_array(v) {
Some(c @ PhpObj::Closure { .. }) => c.clone(),
_ => return None,
};
let new_called = match &this {
Some(t) => self.object_class(t),
None => scope.as_ref().map(|s| {
self.classes
.get(&s.to_ascii_lowercase())
.map_or_else(|| s.clone(), |d| d.name.clone())
}),
};
if let PhpObj::Closure {
captured,
bound_this,
scope: s,
called_scope,
..
} = &mut dup
{
self.fork_closure_statics(captured);
*bound_this = this;
*s = scope;
*called_scope = new_called;
}
self.objs.push(dup);
Some(Value::Obj((self.objs.len() - 1) as u32))
}
pub fn closure_callable_name(&self, v: &Value) -> Option<String> {
let cc = self.closure_of(v)?;
Some(
cc.site
.map_or_else(|| "{closure}".to_string(), |s| s.render(&self.script_name)),
)
}
pub fn is_closure(&self, v: &Value) -> bool {
matches!(self.as_array(v), Some(PhpObj::Closure { .. }))
}
fn closure_scope(&self, v: &Value) -> Option<String> {
match self.as_array(v) {
Some(PhpObj::Closure { scope, .. }) => scope.clone(),
_ => None,
}
}
pub fn closure_is_fake(&self, v: &Value) -> bool {
matches!(
self.as_array(v),
Some(PhpObj::Closure { params, .. }) if params.first().is_some_and(|p| p.name == FCC_PARAM)
)
}
fn closure_is_static(&self, v: &Value) -> bool {
matches!(
self.as_array(v),
Some(PhpObj::Closure {
is_static: true,
..
})
)
}
fn is_internal_class(&self, lower: &str) -> bool {
crate::prelude_type(lower).is_some() || !self.classes.contains_key(lower)
}
pub fn is_object(&self, v: &Value) -> bool {
matches!(self.as_array(v), Some(PhpObj::Object { .. }))
}
pub fn object_id(&self, v: &Value) -> Option<i64> {
match v {
Value::Obj(_) if self.is_object_value(v) => Some(self.object_ordinal(v) as i64),
Value::Obj(h) => Some(*h as i64),
_ => None,
}
}
pub fn object_ordinal(&self, v: &Value) -> usize {
let Value::Obj(h) = v else { return 0 };
self.objs
.iter()
.enumerate()
.take(*h as usize + 1)
.filter(|(i, o)| {
matches!(
o,
PhpObj::Object { .. } | PhpObj::Closure { .. } | PhpObj::Generator { .. }
) && !self.transient_objs.contains(&(*i as u32))
})
.count()
}
pub fn object_class(&self, v: &Value) -> Option<String> {
match self.as_array(v) {
Some(PhpObj::Object { class, .. }) => Some(class.clone()),
_ => None,
}
}
pub fn instance_class(&self, v: &Value) -> Option<String> {
match self.as_array(v) {
Some(PhpObj::Object { class, .. }) => Some(class.clone()),
Some(PhpObj::Closure { .. }) => Some("Closure".to_string()),
Some(PhpObj::Generator { .. }) => Some("Generator".to_string()),
_ => None,
}
}
pub fn is_object_value(&self, v: &Value) -> bool {
matches!(
self.as_array(v),
Some(PhpObj::Object { .. } | PhpObj::Closure { .. } | PhpObj::Generator { .. })
)
}
pub fn class_exists(&self, name: &str) -> bool {
let lower = unanchored(name).to_ascii_lowercase();
self.classes.contains_key(&lower) || builtin_type_kind(&lower).is_some()
}
pub fn type_kind(&self, name: &str) -> Option<TypeKind> {
let lower = unanchored(name).to_ascii_lowercase();
match self.classes.get(&lower) {
Some(d) if d.is_trait => Some(TypeKind::Trait),
Some(d) if d.is_interface => Some(TypeKind::Interface),
Some(d) if d.is_enum => Some(TypeKind::Enum),
Some(_) => Some(TypeKind::Class),
None => builtin_type_kind(&lower),
}
}
pub fn class_interface_names(&self, class: &str) -> Vec<String> {
self.interface_list(&class.to_ascii_lowercase(), 0)
}
fn interface_list(&self, c: &str, depth: usize) -> Vec<String> {
let Some(def) = self.classes.get(c) else {
return builtin_type_parents(c)
.iter()
.map(|p| (*p).to_string())
.collect();
};
if depth > 64 {
return Vec::new();
}
let mut out = match &def.parent {
Some(p) => self.interface_list(&p.to_ascii_lowercase(), depth + 1),
None => Vec::new(),
};
let mut declared: Vec<String> = def
.interfaces
.iter()
.map(|i| i.to_ascii_lowercase())
.collect();
if def.methods.contains_key("__tostring") && !declared.iter().any(|d| d == "stringable") {
declared.push("stringable".to_string());
}
if declared.is_empty() && def.parent.is_some() {
out.reverse();
}
let spell = |lower: &str| {
self.classes
.get(lower)
.map(|d| d.name.clone())
.unwrap_or_else(|| {
builtin_type(lower)
.map_or_else(|| lower.to_string(), |(n, ..)| (*n).to_string())
})
};
let push = |out: &mut Vec<String>, name: String| {
if !out.iter().any(|o| o.eq_ignore_ascii_case(&name)) {
out.push(name);
}
};
for d in &declared {
push(&mut out, spell(d));
}
for d in &declared {
for inherited in self.interface_list(d, depth + 1).into_iter().rev() {
push(&mut out, inherited);
}
}
if crate::prelude_type(c).is_some() {
use crate::internal_interfaces::INTERNAL_INTERFACES as TABLE;
if let Ok(i) = TABLE.binary_search_by(|&(k, _)| k.cmp(c)) {
let order = TABLE[i].1;
out.sort_by_key(|n| {
order
.iter()
.position(|o| o.eq_ignore_ascii_case(n))
.unwrap_or(order.len())
});
}
}
out
}
pub fn class_trait_names(&self, class: &str) -> Vec<String> {
self.classes
.get(&class.to_ascii_lowercase())
.map(|d| d.uses.clone())
.unwrap_or_default()
}
fn class_instantiation_error(&self, class: &str) -> Option<String> {
let def = self.classes.get(&class.to_ascii_lowercase())?;
let kind = if def.is_interface {
"interface"
} else if def.is_trait {
"trait"
} else if def.is_enum {
"enum"
} else if def.is_abstract {
"abstract class"
} else {
return None;
};
Some(format!(
"Cannot instantiate {kind} {}",
display_class(class)
))
}
pub fn function_defined(&self, name: &str) -> bool {
let name = name.strip_prefix('\\').unwrap_or(name);
self.functions.contains_key(&name.to_ascii_lowercase())
}
pub fn prop_type(&self, class: &str, name: &str) -> Option<(String, TypeHint)> {
let mut cur = Some(class.to_ascii_lowercase());
while let Some(c) = cur {
let def = self.classes.get(&c)?;
if let Some(ty) = def.prop_types.get(name) {
return Some((def.name.clone(), ty.clone()));
}
if def.prop_vis.contains_key(name) {
return None;
}
cur = def.parent.as_ref().map(|p| p.to_ascii_lowercase());
}
None
}
pub fn class_parent(&self, name: &str) -> Option<String> {
self.classes
.get(&name.to_ascii_lowercase())
.and_then(|d| d.parent.clone())
}
pub fn is_a_class(&self, class: &str, target: &str) -> bool {
self.catch_matches(class, unanchored(target))
}
pub fn class_methods_visible(&self, class: &str) -> Vec<String> {
let scope = self.current_class_ctx().map(|s| s.to_ascii_lowercase());
let mut seen: Vec<String> = Vec::new();
let mut out = Vec::new();
let mut cur = Some(class.to_ascii_lowercase());
while let Some(c) = cur {
let Some(def) = self.classes.get(&c) else {
out.extend(builtin_type_methods(&c).iter().map(|m| m.to_string()));
break;
};
let mut names: Vec<String> = def.method_sites.iter().map(|(n, _)| n.clone()).collect();
if def.is_enum {
names.push("cases".to_string());
if def
.interfaces
.iter()
.any(|i| i.eq_ignore_ascii_case("BackedEnum"))
{
names.push("from".to_string());
names.push("tryFrom".to_string());
}
}
for name in names {
let lname = name.to_ascii_lowercase();
if seen.contains(&lname) {
continue;
}
seen.push(lname.clone());
if crate::prelude_type(&c).is_some()
&& (is_prelude_helper_name(&format!("{c}::{name}"))
|| self.spl_array_forwarder(&c, &lname))
{
continue;
}
let accessible = match def.method_vis.get(&lname) {
Some(Visibility::Private) => scope.as_deref() == Some(c.as_str()),
Some(Visibility::Protected) => scope
.as_deref()
.is_some_and(|s| self.class_is_a(s, &c) || self.class_is_a(&c, s)),
_ => true,
};
if accessible {
out.push(lname);
}
}
cur = def.parent.as_ref().map(|p| p.to_ascii_lowercase());
}
out
}
pub fn class_method_names(&self, class: &str) -> Vec<String> {
let mut out = Vec::new();
let mut cur = Some(class.to_ascii_lowercase());
while let Some(c) = cur {
let Some(def) = self.classes.get(&c) else {
out.extend(builtin_type_methods(&c).iter().map(|m| m.to_string()));
break;
};
for m in def.methods.keys() {
if !out.contains(m) {
out.push(m.clone());
}
}
cur = def.parent.as_ref().map(|p| p.to_ascii_lowercase());
}
out
}
pub fn class_has_method(&self, class: &str, method: &str) -> bool {
if self.method_declared(class, &method.to_ascii_lowercase()) {
return true;
}
builtin_type_methods(&class.to_ascii_lowercase())
.iter()
.any(|m| m.eq_ignore_ascii_case(method))
}
pub fn property_exists(&self, target: &Value, name: &str) -> bool {
let is_obj = self.is_object(target);
let class = if is_obj {
self.object_class(target).unwrap_or_default()
} else {
let written = self.to_str(target);
written
.strip_prefix('\\')
.map_or_else(|| written.clone(), str::to_string)
};
let decl = self.resolve_prop_vis(&class, name);
if let Some((declaring, vis)) = &decl {
if *vis != Visibility::Private || declaring.eq_ignore_ascii_case(&class) {
return true;
}
}
is_obj
&& self.object_props(target).iter().any(|(n, _)| n == name)
&& decl.is_none_or(|(declaring, vis)| self.visibility_allows(vis, &declaring))
}
pub fn prop_visibility(&self, class: &str, name: &str) -> Option<(String, Visibility)> {
let (declaring, vis) = self.resolve_prop_vis(class, name)?;
if matches!(vis, Visibility::Public) {
return None;
}
let spelled = self
.classes
.get(&declaring)
.map(|d| d.name.clone())
.unwrap_or(declaring);
Some((spelled, vis))
}
pub fn enum_case_of(&self, v: &Value) -> Option<(String, Option<Value>)> {
let Some(PhpObj::Object { class, props }) = self.as_array(v) else {
return None;
};
if !self.is_enum_class(class) {
return None;
}
let name = props.get("name").map(|n| self.to_str(n))?;
Some((name, props.get("value").map(|x| self.deref(x.clone()))))
}
pub fn object_props(&self, v: &Value) -> Vec<(String, Value)> {
match self.as_array(v) {
Some(PhpObj::Object { props, .. }) => props
.iter()
.map(|(k, v)| (k.clone(), self.deref(v.clone())))
.collect(),
_ => Vec::new(),
}
}
pub fn object_props_visible(&self, v: &Value) -> Vec<(String, Value)> {
let Some(class) = self.object_class(v) else {
return Vec::new();
};
self.object_props(v)
.into_iter()
.filter(|(name, _)| match self.resolve_prop_vis(&class, name) {
Some((declaring, vis)) => self.visibility_allows(vis, &declaring),
None => true,
})
.collect()
}
pub fn object_props_mangled(&self, v: &Value) -> Vec<(String, Value)> {
let class = self.object_class(v).unwrap_or_default();
self.object_props(v)
.into_iter()
.map(|(name, val)| {
let key = match self.declaring_class_of_prop(&class, &name) {
Some((declaring, Visibility::Private)) => format!("\0{declaring}\0{name}"),
Some((_, Visibility::Protected)) => format!("\0*\0{name}"),
_ => name,
};
(key, val)
})
.collect()
}
fn declaring_class_of_prop(&self, class: &str, name: &str) -> Option<(String, Visibility)> {
let mut cur = Some(class.to_string());
while let Some(c) = cur {
let def = self.classes.get(&c.to_ascii_lowercase())?;
if let Some(v) = def.prop_vis.get(name) {
return Some((c, *v));
}
cur = def.parent.clone();
}
None
}
pub fn object_props_marked(&self, v: &Value) -> Vec<(String, Value, bool)> {
match self.as_array(v) {
Some(PhpObj::Object { props, .. }) => props
.iter()
.map(|(k, v)| {
let is_ref = self.ref_slot_of_value(v).is_some();
(k.clone(), self.deref(v.clone()), is_ref)
})
.collect(),
_ => Vec::new(),
}
}
pub fn new_stream(&mut self, mut s: crate::stdlib::fileres::Stream) -> Value {
s.id = self.next_resource_id;
self.next_resource_id += if s.kind == crate::stdlib::fileres::StreamKind::Temp {
2
} else {
1
};
self.objs.push(PhpObj::Resource(Box::new(s)));
Value::Obj((self.objs.len() - 1) as u32)
}
pub fn stream_any(&self, v: &Value) -> Option<&crate::stdlib::fileres::Stream> {
match self.as_array(v) {
Some(PhpObj::Resource(s)) => Some(s),
_ => None,
}
}
pub fn stream(&self, v: &Value) -> Option<&crate::stdlib::fileres::Stream> {
self.stream_any(v).filter(|s| !s.closed)
}
pub fn stream_mut(&mut self, v: &Value) -> Option<&mut crate::stdlib::fileres::Stream> {
match self.as_array_mut(v) {
Some(PhpObj::Resource(s)) if !s.closed => Some(s),
_ => None,
}
}
pub fn stream_write(&mut self, v: &Value, bytes: &[u8]) {
let mut spilled = false;
if let Some(s) = self.stream_mut(v) {
if let Some(limit) = s.spill_at {
if s.buf.len() + bytes.len() >= limit {
s.spill_at = None;
spilled = true;
}
}
s.write_at_cursor(bytes);
}
if spilled {
self.next_resource_id += 1;
}
}
pub fn consume_resource_id(&mut self) {
self.next_resource_id += 1;
}
pub fn resource_info(&self, v: &Value) -> Option<(i64, bool)> {
self.stream_any(v).map(|s| (s.id, s.closed))
}
pub fn is_resource(&self, v: &Value) -> bool {
self.stream(v).is_some()
}
pub fn is_stream(&self, v: &Value) -> bool {
self.stream_any(v).is_some()
}
pub fn write_stdout_direct(&mut self, s: &str) {
if let Some(buf) = &mut self.capture {
buf.push_str(s);
} else {
use std::io::Write;
let _ = std::io::stdout().write_all(&crate::bytes::to_bytes(s));
}
}
pub fn obj_has_prop(&self, recv: &Value, name: &str) -> bool {
matches!(self.as_array(recv), Some(PhpObj::Object { props, .. }) if props.contains_key(name))
}
pub fn prop_get(&self, recv: &Value, name: &str) -> Value {
match self.as_array(recv) {
Some(PhpObj::Object { props, .. }) => {
let raw = props.get(name).cloned().unwrap_or(Value::Undef);
self.deref(raw)
}
_ => Value::Undef,
}
}
pub fn prop_set(&mut self, recv: &Value, name: &str, val: Value) {
if let Some(slot) = self.prop_ref_slot(recv, name) {
self.ref_cell_set(slot, val);
return;
}
self.obj_put_prop(recv, name, val);
}
pub fn prop_write_refusal(&self, recv: &Value, name: &str, verb: &str) -> Option<String> {
let ty = match recv {
Value::Bool(true) => "true",
Value::Bool(false) => "false",
Value::Obj(_) => match self.as_array(recv) {
Some(PhpObj::Object { class, props }) if self.is_enum_class(class) => {
let shown = self.class_display_name(&class.to_ascii_lowercase());
return Some(if props.contains_key(name) {
let how = if verb == "modify" {
"indirectly modify"
} else {
"modify"
};
format!("Cannot {how} readonly property {shown}::${name}")
} else {
format!("Cannot create dynamic property {shown}::${name}")
});
}
Some(PhpObj::Object { class, .. })
if matches!(
class.to_ascii_lowercase().as_str(),
"weakmap" | "weakreference"
) && self.resolve_prop_vis(class, name).is_none() =>
{
return Some(format!(
"Cannot create dynamic property {}::${name}",
self.class_display_name(&class.to_ascii_lowercase())
));
}
Some(PhpObj::Object { .. } | PhpObj::Ref { .. }) | None => return None,
Some(PhpObj::Closure { .. }) => {
return Some(format!("Cannot create dynamic property Closure::${name}"));
}
Some(PhpObj::Generator { .. }) => {
return Some(format!("Cannot create dynamic property Generator::${name}"));
}
Some(PhpObj::Resource(_)) => "resource",
Some(PhpObj::Array { .. }) => "array",
},
other => self.diag_type(other),
};
Some(format!("Attempt to {verb} property \"{name}\" on {ty}"))
}
pub fn prop_set_checked(&mut self, recv: &Value, name: &str, val: Value) {
self.warn_dynamic_prop(recv, name);
self.prop_set(recv, name, val);
}
pub fn warn_dynamic_prop(&mut self, recv: &Value, name: &str) {
let Some(PhpObj::Object { class, props }) = self.as_array(recv) else {
return;
};
if props.contains_key(name) || class.eq_ignore_ascii_case("stdClass") {
return;
}
let class = class.clone();
if self.prop_is_declared(&class, name) || self.allows_dynamic_props(&class) {
return;
}
self.deprecated(format_args!(
"Creation of dynamic property {class}::${name} is deprecated"
));
}
pub(crate) fn prop_is_declared(&self, class: &str, name: &str) -> bool {
self.class_chain(class).any(|d| {
d.prop_vis.contains_key(name) || d.prop_defaults.iter().any(|(p, _)| p == name)
})
}
fn allows_dynamic_props(&self, class: &str) -> bool {
self.class_chain(class).any(|d| d.allow_dynamic_props)
}
fn class_chain<'a>(&'a self, class: &str) -> impl Iterator<Item = &'a ClassDef> + 'a {
let mut cur = Some(class.to_ascii_lowercase());
std::iter::from_fn(move || {
let def = self.classes.get(&cur.take()?)?;
cur = def.parent.as_ref().map(|p| p.to_ascii_lowercase());
Some(def)
})
}
fn prop_ref_slot(&self, recv: &Value, name: &str) -> Option<usize> {
let Some(PhpObj::Object { props, .. }) = self.as_array(recv) else {
return None;
};
self.ref_slot_of_value(props.get(name)?)
}
pub fn dim_container_kept(&mut self, cur: &Value) -> Option<Value> {
match cur {
Value::Undef => None,
Value::Bool(false) => {
self.deprecated("Automatic conversion of false to array is deprecated");
None
}
_ => Some(cur.clone()),
}
}
pub fn prop_ensure_array(&mut self, recv: &Value, name: &str) -> Value {
let cur = self.prop_get(recv, name);
if let Some(kept) = self.dim_container_kept(&cur) {
return kept;
}
let arr = self.new_array();
self.prop_set(recv, name, arr.clone());
arr
}
pub fn spl_array_dim_for_write(&mut self, recv: &Value, name: &str) -> Option<Value> {
let class = self.instance_class(recv)?;
let native_get = matches!(
self.method_owner_key(&class, "offsetget").as_deref(),
Some("arrayobject" | "arrayiterator")
);
if !self.spl_array_forwarder(&class, "__get") || !native_get {
return None;
}
let storage = self.prop_get(recv, "storage");
if !self.is_array(&storage) {
return None;
}
let key = Value::str(name);
let cur = self.index_get(&storage, &key);
if !matches!(cur, Value::Undef) {
return Some(cur);
}
let arr = self.new_array();
self.arr_set_key(&storage, &key, arr.clone());
Some(arr)
}
fn method_declared(&self, class: &str, method: &str) -> bool {
let mut cur = Some(class.to_ascii_lowercase());
while let Some(c) = cur {
let Some(def) = self.classes.get(&c) else {
return false;
};
if def.methods.contains_key(method) {
return true;
}
cur = def.parent.as_ref().map(|p| p.to_ascii_lowercase());
}
false
}
pub fn method_byref_param(
&self,
recv: &Value,
method: &str,
argno: usize,
) -> Option<(String, String)> {
let class = match recv {
Value::Obj(_) => self.object_class(recv)?,
other => self.to_str(other),
};
let (decl, def) = self.resolve_method(&class, &method.to_ascii_lowercase())?;
let p = def.params.get(argno.checked_sub(1)?)?;
(p.by_ref && !p.variadic).then(|| {
(
format!("{}::{method}", self.class_display_name(&decl)),
p.name.clone(),
)
})
}
pub(crate) fn method_owner(&self, obj: &Value, lname: &str) -> Option<String> {
let class = self.instance_class(obj)?;
self.resolve_method(&class, &lname.to_ascii_lowercase())
.map(|(c, _)| c)
}
fn resolve_method(&self, class: &str, method: &str) -> Option<(String, FuncDef)> {
let mut cur = Some(class.to_ascii_lowercase());
while let Some(c) = cur {
let def = self.classes.get(&c)?;
if let Some(m) = def.methods.get(method) {
return Some((c, m.clone()));
}
cur = def.parent.as_ref().map(|p| p.to_ascii_lowercase());
}
None
}
fn current_class_ctx(&self) -> Option<String> {
if let Some(c) = self.init_class_scope.last() {
return Some(c.clone());
}
let name = self.scopes.last()?.name.as_ref()?;
name.rsplit_once("::").map(|(cls, _)| cls.to_string())
}
pub fn magic_class(&self) -> String {
let Some(cls) = self.current_class_ctx() else {
return String::new();
};
self.classes.get(&cls).map_or(cls, |d| d.name.clone())
}
pub fn magic_parent_class(&self) -> String {
let Some(cls) = self.current_class_ctx() else {
return String::new();
};
let Some(parent) = self
.classes
.get(&cls.to_ascii_lowercase())
.and_then(|d| d.parent.clone())
else {
return String::new();
};
self.classes
.get(&parent.to_ascii_lowercase())
.map_or(parent, |d| d.name.clone())
}
pub fn magic_dir(&self) -> String {
let name = self.current_file();
if name.starts_with('/') {
if let Some(parent) = std::path::Path::new(name).parent() {
return parent.display().to_string();
}
}
std::env::current_dir().map_or_else(|_| String::new(), |p| p.display().to_string())
}
fn readonly_owner(&self, class: &str, name: &str) -> Option<String> {
let mut cur = Some(class.to_ascii_lowercase());
while let Some(c) = cur {
let def = self.classes.get(&c)?;
if def.readonly_props.contains(name) {
return Some(c);
}
cur = def.parent.as_ref().map(|p| p.to_ascii_lowercase());
}
None
}
pub fn readonly_write_error(&self, recv: &Value, name: &str) -> Option<String> {
let Some(PhpObj::Object { class, .. }) = self.as_array(recv) else {
return None;
};
let owner = self.readonly_owner(class, name)?;
if let (Value::Obj(id), Some(c)) = (recv, self.cloning) {
if *id == c {
return None;
}
}
let display = self.class_display_name(&owner);
let reinit = matches!((recv, self.cloning_with), (Value::Obj(id), Some(c)) if *id == c);
if self.readonly_is_init(recv, name) && !reinit {
return Some(format!(
"Cannot modify readonly property {display}::${name}"
));
}
let scope = self.current_class_ctx();
if scope
.as_deref()
.is_some_and(|s| self.class_is_a(&s.to_ascii_lowercase(), &owner))
{
return None;
}
let from = match &scope {
Some(s) => format!("scope {}", self.class_display_name(&s.to_ascii_lowercase())),
None => "global scope".to_string(),
};
Some(format!(
"Cannot modify protected(set) readonly property {display}::${name} from {from}"
))
}
pub fn set_visibility_error(&self, recv: &Value, name: &str, verb: &str) -> Option<String> {
let Some(PhpObj::Object { class, .. }) = self.as_array(recv) else {
return None;
};
let decl = self
.class_chain(class)
.find(|d| d.prop_vis.contains_key(name))?;
self.set_visibility_refusal(decl, name, verb)
}
fn set_visibility_refusal(&self, decl: &ClassDef, name: &str, verb: &str) -> Option<String> {
let set = *decl.prop_set_vis.get(name)?;
let decl_lc = decl.name.to_ascii_lowercase();
let scope = self.current_class_ctx().map(|s| s.to_ascii_lowercase());
let allowed = match set {
Visibility::Public => true,
Visibility::Private => scope.as_deref() == Some(decl_lc.as_str()),
Visibility::Protected => scope
.as_deref()
.is_some_and(|s| self.class_is_a(s, &decl_lc) || self.class_is_a(&decl_lc, s)),
};
if allowed {
return None;
}
let word = match set {
Visibility::Public => "public",
Visibility::Protected => "protected",
Visibility::Private => "private",
};
let from = match &scope {
Some(s) => format!("scope {}", self.class_display_name(s)),
None => "global scope".to_string(),
};
Some(format!(
"Cannot {verb} {word}(set) property {}::${name} from {from}",
decl.name
))
}
pub fn static_set_visibility_error(&self, class: &str, name: &str) -> Option<String> {
let owner = self.resolve_static_owner(class, name)?;
let decl = self.classes.get(&owner)?;
self.set_visibility_refusal(decl, name, "modify")
}
pub fn readonly_unset_error(&self, recv: &Value, name: &str) -> Option<String> {
let Some(PhpObj::Object { class, props }) = self.as_array(recv) else {
return None;
};
if self.is_enum_class(class) && props.contains_key(name) {
let shown = self.class_display_name(&class.to_ascii_lowercase());
return Some(format!("Cannot unset readonly property {shown}::${name}"));
}
let owner = self.readonly_owner(class, name)?;
self.readonly_is_init(recv, name).then(|| {
let display = self.class_display_name(&owner);
format!("Cannot unset readonly property {display}::${name}")
})
}
pub fn readonly_indirect_error(&self, recv: &Value, name: &str) -> Option<String> {
let Some(PhpObj::Object { class, .. }) = self.as_array(recv) else {
return None;
};
if let (Value::Obj(id), Some(c)) = (recv, self.cloning) {
if *id == c {
return None;
}
}
let owner = self.readonly_owner(class, name)?;
if !self.readonly_is_init(recv, name) {
return None;
}
let display = self.class_display_name(&owner);
Some(format!(
"Cannot indirectly modify readonly property {display}::${name}"
))
}
fn readonly_is_init(&self, recv: &Value, name: &str) -> bool {
let Value::Obj(id) = recv else { return false };
self.readonly_init
.get(id)
.is_some_and(|set| set.contains(name))
}
pub fn readonly_note_init(&mut self, recv: &Value, name: &str) {
let Value::Obj(id) = recv else { return };
let Some(PhpObj::Object { class, .. }) = self.as_array(recv) else {
return;
};
if self.readonly_owner(class, name).is_none() {
return;
}
self.readonly_init
.entry(*id)
.or_default()
.insert(name.to_string());
}
fn resolve_prop_vis(&self, class: &str, name: &str) -> Option<(String, Visibility)> {
let mut cur = Some(class.to_ascii_lowercase());
while let Some(c) = cur {
let def = self.classes.get(&c)?;
if let Some(v) = def.prop_vis.get(name) {
return Some((c, *v));
}
cur = def.parent.as_ref().map(|p| p.to_ascii_lowercase());
}
None
}
fn visibility_allows(&self, vis: Visibility, declaring: &str) -> bool {
match vis {
Visibility::Public => true,
Visibility::Private => {
matches!(self.current_class_ctx(), Some(c) if c.eq_ignore_ascii_case(declaring))
}
Visibility::Protected => match self.current_class_ctx() {
Some(c) => self.class_is_a(&c, declaring) || self.class_is_a(declaring, &c),
None => false,
},
}
}
pub fn prop_access(&self, recv: &Value, name: &str, magic: &'static str) -> PropAccess {
let Some(PhpObj::Object { class, props }) = self.as_array(recv) else {
return PropAccess::Absent;
};
let declared = self.resolve_prop_vis(class, name);
let reachable = match &declared {
Some((declaring, vis)) => self.visibility_allows(*vis, declaring),
None => true,
};
if reachable && props.contains_key(name) {
return PropAccess::Direct;
}
let handle = match recv {
Value::Obj(h) => *h,
_ => return PropAccess::Absent,
};
let guarded = self
.magic_in_progress
.iter()
.any(|(h, p, m)| *h == handle && p == name && *m == magic);
if !guarded
&& self.class_has_method(class, magic)
&& !self.spl_array_props_off(recv, class, magic)
{
return PropAccess::Magic;
}
match declared {
Some((declaring, vis)) if !reachable => {
let vname = match vis {
Visibility::Private => "private",
Visibility::Protected => "protected",
Visibility::Public => unreachable!("public is always reachable"),
};
let class = self.class_display_name(&declaring);
PropAccess::Denied(format!("Cannot access {vname} property {class}::${name}"))
}
_ => PropAccess::Absent,
}
}
pub fn spl_array_flags(&self, v: &Value) -> Option<i64> {
let class = self.instance_class(v)?;
let (key, in_pair) = if self.class_is_a(&class, "arrayobject") {
("arrayobject::__state", true)
} else if self.class_is_a(&class, "arrayiterator") {
("arrayiterator::__flags", false)
} else {
return None;
};
let id = Value::Int(self.object_id(v)?);
let entry = self
.get_static_stored(key)
.and_then(|t| self.array_pairs(&t))
.and_then(|pairs| pairs.into_iter().find(|(k, _)| *k == id))
.map(|(_, e)| self.deref(e));
let flags = match entry {
Some(e) if in_pair => self
.array_pairs(&e)
.and_then(|p| p.into_iter().next())
.map(|(_, f)| self.deref(f)),
other => other,
};
Some(match flags {
Some(Value::Int(n)) => n,
_ => 0,
})
}
fn spl_array_props_off(&self, recv: &Value, class: &str, method: &str) -> bool {
self.spl_array_forwarder(class, method)
&& self.spl_array_flags(recv).is_some_and(|f| f & 2 == 0)
}
pub fn spl_array_forwarder(&self, class: &str, method: &str) -> bool {
matches!(method, "__get" | "__set" | "__isset" | "__unset")
&& matches!(
self.method_owner_key(class, method).as_deref(),
Some("arrayobject" | "arrayiterator")
)
}
fn method_owner_key(&self, class: &str, method: &str) -> Option<String> {
let mut cur = Some(class.to_ascii_lowercase());
while let Some(c) = cur {
let def = self.classes.get(&c)?;
if def.methods.contains_key(method) {
return Some(c);
}
cur = def.parent.as_ref().map(|p| p.to_ascii_lowercase());
}
None
}
pub fn magic_enter(&mut self, recv: &Value, name: &str, magic: &'static str) {
if let Value::Obj(h) = recv {
self.magic_in_progress.push((*h, name.to_string(), magic));
}
}
pub fn magic_leave(&mut self) {
self.magic_in_progress.pop();
}
pub fn magic_depth(&self) -> usize {
self.magic_in_progress.len()
}
pub fn magic_restore(&mut self, depth: usize) {
self.magic_in_progress.truncate(depth);
}
pub fn class_display_name(&self, lowered: &str) -> String {
let name = self
.classes
.get(lowered)
.map_or(lowered, |d| d.name.as_str());
display_class(name).to_string()
}
pub fn prop_remove(&mut self, recv: &Value, name: &str) {
self.note_unset(recv, name);
if let Some(PhpObj::Object { props, .. }) = self.as_array_mut(recv) {
props.shift_remove(name);
}
}
pub fn check_method_access(&self, class: &str, method: &str) -> Result<(), String> {
let Some((declaring, vis)) = self.declaring_method_vis(class, method) else {
return Ok(());
};
if self.visibility_allows(vis, &declaring) {
return Ok(());
}
let vname = match vis {
Visibility::Private => "private",
Visibility::Protected => "protected",
Visibility::Public => unreachable!(),
};
Err(format!(
"Call to {vname} method {class}::{method}() from {}",
self.scope_display()
))
}
fn scope_display(&self) -> String {
match self.current_class_ctx() {
Some(c) => format!("scope {}", self.class_display_name(&c.to_ascii_lowercase())),
None => "global scope".to_string(),
}
}
pub fn constructor_access_error(&self, class: &str) -> Option<String> {
let (declaring, vis) = self.declaring_method_vis(class, "__construct")?;
if self.visibility_allows(vis, &declaring) {
return None;
}
let vname = match vis {
Visibility::Private => "private",
Visibility::Protected => "protected",
Visibility::Public => unreachable!(),
};
Some(format!(
"Call to {vname} {}::__construct() from {}",
self.class_display_name(&declaring),
self.scope_display()
))
}
fn declaring_method_vis(&self, class: &str, method: &str) -> Option<(String, Visibility)> {
let method_l = method.to_ascii_lowercase();
let mut cur = Some(class.to_ascii_lowercase());
while let Some(c) = cur {
let def = self.classes.get(&c)?;
if let Some(v) = def.method_vis.get(&method_l) {
return Some((c, *v));
}
cur = def.parent.as_ref().map(|p| p.to_ascii_lowercase());
}
None
}
pub fn method_visibility_name(&self, class: &str, method: &str) -> Option<&'static str> {
match self.declaring_method_vis(class, method) {
Some((_, Visibility::Private)) => Some("private"),
Some((_, Visibility::Protected)) => Some("protected"),
_ => None,
}
}
pub fn method_is_static(&self, class: &str, method: &str) -> bool {
let method_l = method.to_ascii_lowercase();
let mut cur = Some(class.to_ascii_lowercase());
while let Some(c) = cur {
let Some(def) = self.classes.get(&c) else {
return false;
};
if def.methods.contains_key(&method_l) {
return def.static_methods.contains(&method_l);
}
cur = def.parent.as_ref().map(|p| p.to_ascii_lowercase());
}
false
}
fn magic_call_name(&self, class: &str, has_this: bool) -> Option<&'static str> {
let magic = if has_this { "__call" } else { "__callstatic" };
self.method_declared(class, magic).then_some(if has_this {
"__call"
} else {
"__callStatic"
})
}
pub fn method_dispatch(&self, class: &str, method: &str, has_this: bool) -> MethodDispatch {
let method_l = method.to_ascii_lowercase();
if !self.method_declared(class, &method_l) {
return match self.magic_call_name(class, has_this) {
Some(_) => MethodDispatch::Magic,
None => MethodDispatch::Undefined,
};
}
match self.check_method_access(class, method) {
Ok(()) => MethodDispatch::Direct,
Err(msg) => match self.magic_call_name(class, has_this) {
Some(_) => MethodDispatch::Magic,
None => MethodDispatch::Denied(msg),
},
}
}
#[allow(clippy::type_complexity)]
fn class_prop_default_chunks(
&self,
class: &str,
) -> Option<Vec<(String, (String, Chunk, bool))>> {
let cl = class.to_ascii_lowercase();
if !self.classes.contains_key(&cl) {
return None;
}
let mut chain: Vec<(String, &ClassDef)> = Vec::new();
let mut cur = Some(cl);
while let Some(c) = cur {
let Some(def) = self.classes.get(&c) else {
break;
};
chain.push((c, def));
cur = def.parent.as_ref().map(|p| p.to_ascii_lowercase());
}
let mut map: IndexMap<String, (String, Chunk, bool)> = IndexMap::new();
for (c, def) in chain.into_iter().rev() {
for (name, chunk) in &def.prop_defaults {
let uninit = def.uninit_props.contains_key(name);
map.insert(name.clone(), (c.clone(), chunk.clone(), uninit));
}
}
Some(map.into_iter().collect())
}
pub(crate) fn declared_prop_order(&self, class: &str) -> Vec<String> {
let mut chain: Vec<&ClassDef> = Vec::new();
let mut cur = Some(class.to_ascii_lowercase());
while let Some(c) = cur {
let Some(def) = self.classes.get(&c) else {
break;
};
chain.push(def);
cur = def.parent.as_ref().map(|p| p.to_ascii_lowercase());
}
let mut order: IndexMap<String, ()> = IndexMap::new();
for def in chain.into_iter().rev() {
for (name, _) in &def.prop_defaults {
order.insert(name.clone(), ());
}
}
order.into_keys().collect()
}
fn uninit_prop_decl(&self, class: &str, name: &str) -> Option<(String, String)> {
let mut cur = Some(class.to_ascii_lowercase());
while let Some(c) = cur {
let def = self.classes.get(&c)?;
if def.prop_defaults.iter().any(|(n, _)| n == name) {
return def
.uninit_props
.get(name)
.map(|ty| (self.class_display_name(&c), ty.clone()));
}
cur = def.parent.as_ref().map(|p| p.to_ascii_lowercase());
}
None
}
pub fn uninit_read_error(&self, recv: &Value, name: &str) -> Option<String> {
let Some(PhpObj::Object { class, props }) = self.as_array(recv) else {
return None;
};
if props.contains_key(name) {
return None;
}
let (declaring, _) = self.uninit_prop_decl(class, name)?;
Some(format!(
"Typed property {declaring}::${name} must not be accessed before initialization"
))
}
pub fn note_unset(&mut self, recv: &Value, name: &str) {
if let (Value::Obj(id), Some(PhpObj::Object { class, .. })) = (recv, self.as_array(recv)) {
if self.uninit_prop_decl(class, name).is_some() {
self.unset_typed
.entry(*id)
.or_default()
.insert(name.to_string());
}
}
}
pub fn uninit_magic_blocked(&self, recv: &Value, name: &str) -> Option<String> {
let Value::Obj(id) = recv else { return None };
if self.unset_typed.get(id).is_some_and(|s| s.contains(name)) {
return None;
}
self.uninit_read_error(recv, name)
}
pub fn uninit_slots(&self, recv: &Value) -> Vec<(usize, String, String)> {
let Some(PhpObj::Object { class, props }) = self.as_array(recv) else {
return Vec::new();
};
let mut out = Vec::new();
let mut present = 0;
for name in self.declared_prop_order(class) {
if props.contains_key(&name) {
present += 1;
} else if let Some((_, ty)) = self.uninit_prop_decl(class, &name) {
out.push((present, name, ty));
}
}
out
}
fn obj_put_prop(&mut self, recv: &Value, name: &str, val: Value) {
let at = match self.as_array(recv) {
Some(PhpObj::Object { props, .. }) if props.contains_key(name) => None,
Some(PhpObj::Object { class, props }) => {
let order = self.declared_prop_order(class);
order.iter().position(|n| n == name).map(|mine| {
props
.keys()
.filter(|k| order[..mine].iter().any(|d| d == *k))
.count()
})
}
_ => return,
};
if let Some(PhpObj::Object { props, .. }) = self.as_array_mut(recv) {
match at {
Some(i) => {
props.shift_insert(i, name.to_string(), val);
}
None => {
props.insert(name.to_string(), val);
}
}
}
}
pub fn resolve_static_owner(&self, class: &str, name: &str) -> Option<String> {
self.resolve_static_key(class, name)
.and_then(|(key, _)| key.split_once("::").map(|(c, _)| c.to_string()))
}
fn resolve_static_key(&self, class: &str, name: &str) -> Option<(String, Chunk)> {
let mut cur = Some(class.to_ascii_lowercase());
while let Some(c) = cur {
let def = self.classes.get(&c)?;
if let Some((_, chunk)) = def.static_prop_defaults.iter().find(|(n, _)| n == name) {
return Some((format!("{c}::{name}"), chunk.clone()));
}
cur = def.parent.as_ref().map(|p| p.to_ascii_lowercase());
}
None
}
fn property_names_inheritance_order(&self, class: &str, statics: bool) -> Vec<String> {
let mut out: Vec<String> = Vec::new();
let mut cur = Some(class.to_ascii_lowercase());
while let Some(c) = cur {
let Some(def) = self.classes.get(&c) else {
break;
};
let own = if statics {
&def.static_prop_defaults
} else {
&def.prop_defaults
};
for (name, _) in own {
if !out.contains(name) {
out.push(name.clone());
}
}
cur = def.parent.as_ref().map(|p| p.to_ascii_lowercase());
}
out
}
fn get_static_stored(&self, key: &str) -> Option<Value> {
let v = self.static_props.get(key)?;
Some(match self.ref_slot_of_value(v) {
Some(slot) => self.ref_cells[slot].clone(),
None => v.clone(),
})
}
fn set_static_stored(&mut self, key: &str, val: Value) {
match self
.static_props
.get(key)
.and_then(|v| self.ref_slot_of_value(v))
{
Some(slot) => self.ref_cells[slot] = val,
None => {
self.static_props.insert(key.to_string(), val);
}
}
}
fn static_ref_slot_ensure(&mut self, key: &str) -> usize {
let cur = self.static_props.get(key).cloned().unwrap_or(Value::Undef);
if let Some(slot) = self.ref_slot_of_value(&cur) {
return slot;
}
self.ref_cells.push(cur);
let slot = self.ref_cells.len() - 1;
self.bind_static_to_slot(key, slot);
slot
}
fn bind_static_to_slot(&mut self, key: &str, slot: usize) {
self.objs.push(PhpObj::Ref { slot });
let handle = Value::Obj((self.objs.len() - 1) as u32);
self.static_props.insert(key.to_string(), handle);
}
pub fn bind_static_local(&mut self, name: &str, slot_key: &str, init: Value) {
let slot = match self.closure_static_slot(slot_key) {
Some(s) => {
if self.static_uninit.remove(&s) {
self.ref_cells[s] = init;
}
s
}
None => match self.static_slots.get(slot_key) {
Some(&s) => s,
None => {
self.ref_cells.push(init);
let s = self.ref_cells.len() - 1;
self.static_slots.insert(slot_key.to_string(), s);
s
}
},
};
let idx = self.scope_idx(name);
if let Some(scope) = self.scopes.get_mut(idx) {
let i = scope.vars.ensure_slot(name);
scope.vars.put(i, Slot::Ref(slot));
}
}
fn closure_static_slot(&self, slot_key: &str) -> Option<usize> {
let idx = self.scope_idx(slot_key);
match self.scopes.get(idx).map(|s| s.vars.get(slot_key)) {
Some(Slot::Ref(c)) => Some(*c),
_ => None,
}
}
pub fn static_initialized(&self, slot_key: &str) -> bool {
match self.closure_static_slot(slot_key) {
Some(s) => !self.static_uninit.contains(&s),
None => self.static_slots.contains_key(slot_key),
}
}
fn fork_closure_statics(&mut self, captured: &mut [(String, Value)]) {
for (name, v) in captured.iter_mut() {
if !name.starts_with("@static#") {
continue;
}
let Some(slot) = self.ref_slot_of_value(v) else {
continue;
};
self.ref_cells.push(self.ref_cells[slot].clone());
let fresh = self.ref_cells.len() - 1;
if self.static_uninit.contains(&slot) {
self.static_uninit.insert(fresh);
}
self.objs.push(PhpObj::Ref { slot: fresh });
*v = Value::Obj((self.objs.len() - 1) as u32);
}
}
pub fn declared_class_name(&self, class: &str) -> String {
self.classes
.get(&class.to_ascii_lowercase())
.map_or_else(|| class.to_string(), |d| d.name.clone())
}
pub fn is_enum_class(&self, class: &str) -> bool {
self.classes
.get(&class.to_ascii_lowercase())
.map(|d| d.is_enum)
.unwrap_or(false)
}
fn enum_case_chunk(&self, class: &str, case: &str) -> Option<Option<Chunk>> {
let d = self.classes.get(&class.to_ascii_lowercase())?;
d.enum_cases
.iter()
.find(|(n, _)| n == case)
.map(|(_, c)| c.clone())
}
fn enum_case_names(&self, class: &str) -> Vec<String> {
self.classes
.get(&class.to_ascii_lowercase())
.map(|d| d.enum_cases.iter().map(|(n, _)| n.clone()).collect())
.unwrap_or_default()
}
fn enum_case_cached(&self, key: &str) -> Option<Value> {
self.enum_case_cache.get(key).cloned()
}
fn enum_case_store(&mut self, key: &str, v: Value) {
self.enum_case_cache.insert(key.to_string(), v);
}
fn new_enum_object(&mut self, class: &str, name: &str, value: Option<Value>) -> Value {
let mut props: IndexMap<String, Value> = IndexMap::new();
props.insert("name".to_string(), Value::str(name.to_string()));
if let Some(v) = value {
props.insert("value".to_string(), v);
}
self.objs.push(PhpObj::Object {
class: class.to_string(),
props,
});
Value::Obj((self.objs.len() - 1) as u32)
}
fn const_access_denied(&self, class: &str, name: &str) -> Option<String> {
let mut cur = Some(class.to_ascii_lowercase());
while let Some(c) = cur {
let def = self.classes.get(&c)?;
if def.consts.iter().any(|(n, _)| n == name) {
let vis = *def.const_vis.get(name)?;
if self.visibility_allows(vis, &c) {
return None;
}
let vname = match vis {
Visibility::Private => "private",
Visibility::Protected => "protected",
Visibility::Public => return None,
};
let shown = self.class_display_name(&class.to_ascii_lowercase());
return Some(format!("Cannot access {vname} constant {shown}::{name}"));
}
cur = def.parent.as_ref().map(|p| p.to_ascii_lowercase());
}
None
}
fn resolve_const_chunk(&self, class: &str, name: &str) -> Option<(String, Chunk)> {
let mut ifaces: Vec<String> = Vec::new();
let mut cur = Some(class.to_ascii_lowercase());
while let Some(c) = cur {
let Some(def) = self.classes.get(&c) else {
break;
};
if let Some((_, chunk)) = def.consts.iter().find(|(n, _)| n == name) {
return Some((c, chunk.clone()));
}
ifaces.extend(def.interfaces.iter().map(|i| i.to_ascii_lowercase()));
cur = def.parent.as_ref().map(|p| p.to_ascii_lowercase());
}
let mut seen: Vec<String> = Vec::new();
while let Some(i) = ifaces.pop() {
if seen.contains(&i) || seen.len() > 1000 {
continue;
}
seen.push(i.clone());
if let Some(def) = self.classes.get(&i) {
if let Some((_, chunk)) = def.consts.iter().find(|(n, _)| n == name) {
return Some((i.clone(), chunk.clone()));
}
ifaces.extend(def.interfaces.iter().map(|x| x.to_ascii_lowercase()));
if let Some(p) = &def.parent {
ifaces.push(p.to_ascii_lowercase());
}
}
}
None
}
fn as_array_mut(&mut self, v: &Value) -> Option<&mut PhpObj> {
match v {
Value::Obj(h) => self.objs.get_mut(*h as usize),
_ => None,
}
}
fn as_array(&self, v: &Value) -> Option<&PhpObj> {
match v {
Value::Obj(h) => self.objs.get(*h as usize),
_ => None,
}
}
fn norm_key(&self, key: &Value) -> ArrayKey {
match key {
Value::Int(n) => ArrayKey::Int(*n),
Value::Bool(b) => ArrayKey::Int(*b as i64),
Value::Float(f) => ArrayKey::Int(dval_to_lval(*f)),
Value::Undef => ArrayKey::Str(String::new()),
Value::Str(s) => match canonical_int_key(s) {
Some(n) => ArrayKey::Int(n),
None => ArrayKey::Str(String::clone(s)),
},
Value::Obj(_) if self.is_stream(key) => {
ArrayKey::Int(self.resource_info(key).map_or(0, |(id, _)| id))
}
Value::Obj(_) => ArrayKey::Str("Array".into()),
_ => ArrayKey::Str(self.to_str(key)),
}
}
fn entry_ref_slot(&self, arr: &Value, k: &ArrayKey) -> Option<usize> {
let Some(PhpObj::Array { entries, .. }) = self.as_array(arr) else {
return None;
};
self.ref_slot_of_value(entries.get(k)?)
}
pub fn array_access_class(&self, recv: &Value) -> Option<String> {
let class = self.object_class(recv)?;
self.class_is_a_pub(&class, "ArrayAccess").then_some(class)
}
pub fn index_get(&self, recv: &Value, key: &Value) -> Value {
if let Some(PhpObj::Array { entries, .. }) = self.as_array(recv) {
let k = self.norm_key(key);
let raw = entries.get(&k).cloned().unwrap_or(Value::Undef);
return self.deref(raw);
}
if let Value::Str(s) = recv {
let bytes = &*crate::bytes::to_bytes(s);
let len = bytes.len() as i64;
let StrOffset::At(mut i, _) = classify_string_offset(key) else {
return Value::Undef;
};
if i < 0 {
i += len;
}
if i >= 0 && i < len {
let b = i as usize;
return Value::str(crate::bytes::from_bytes(&bytes[b..b + 1]));
}
}
Value::Undef
}
pub fn index_get_warn(&mut self, recv: &Value, key: &Value) -> Value {
self.diagnose_array_offset(recv, key);
if let Some(PhpObj::Array { entries, .. }) = self.as_array(recv) {
let k = self.norm_key(key);
match entries.get(&k).cloned() {
Some(v) => return self.deref(v),
None => {
let k = self.diag_key(key);
self.warn(format_args!("Undefined array key {k}"));
return Value::Undef;
}
}
}
if let Value::Str(s) = recv {
let len = s.len() as i64;
let StrOffset::At(off, cast) = classify_string_offset(key) else {
return Value::Undef;
};
if cast {
self.warn("String offset cast occurred");
}
let i = if off < 0 { off + len } else { off };
if i >= 0 && i < len {
return self.index_get(recv, key);
}
self.warn(format_args!("Uninitialized string offset {off}"));
return Value::Undef;
}
if !matches!(recv, Value::Obj(_)) {
let t = self.diag_offset_type(recv);
self.warn(format_args!("Trying to access array offset on {t}"));
}
Value::Undef
}
pub fn get_var_warn(&mut self, name: &str) -> Value {
let idx = self.scope_idx(name);
if let Some(scope) = self.scopes.get(idx) {
let s = scope.vars.get(name).clone();
if !matches!(s, Slot::Unset) {
return self.read_slot(&s);
}
}
if !name.starts_with('@') {
self.warn(format_args!("Undefined variable ${name}"));
}
Value::Undef
}
pub fn prop_get_warn(&mut self, recv: &Value, name: &str) -> Value {
match self.as_array(recv) {
Some(PhpObj::Object { class, props }) => match props.get(name).cloned() {
Some(v) => self.deref(v),
None => {
let class = display_class(class).to_string();
self.warn(format_args!("Undefined property: {class}::${name}"));
Value::Undef
}
},
_ => {
let t = self.diag_type(recv);
self.warn(format_args!("Attempt to read property \"{name}\" on {t}"));
Value::Undef
}
}
}
pub fn index_set_var(&mut self, name: &str, key: &Value, val: Value) -> Result<(), String> {
if let Value::Str(cur) = self.get_var(name) {
let updated = self.string_offset_set(&cur, key, &val)?;
if let Some(updated) = updated {
self.set_var(name, Value::str(updated));
}
return Ok(());
}
let arr = self.ensure_array_var(name);
self.arr_set_key(&arr, key, val);
Ok(())
}
fn string_offset_set(
&mut self,
cur: &str,
key: &Value,
val: &Value,
) -> Result<Option<String>, String> {
let off = match key {
Value::Int(n) => *n,
Value::Str(k) => match parse_php_number_full(k) {
Some(Value::Int(n)) => n,
_ => {
return Err(crate::builtins::throws_bare(
"TypeError",
format!(
"Cannot access offset of type {} on string",
self.type_name_for_error(key)
),
))
}
},
Value::Float(_) | Value::Bool(_) | Value::Undef => {
self.warn("String offset cast occurred");
self.to_number(key).to_int()
}
other => {
return Err(crate::builtins::throws_bare(
"TypeError",
format!(
"Cannot access offset of type {} on string",
self.type_name_for_error(other)
),
))
}
};
let replacement = self.to_str(val);
if replacement.is_empty() {
return Err(crate::builtins::throws_bare(
"Error",
"Cannot assign an empty string to a string offset",
));
}
if replacement.len() > 1 {
self.warn("Only the first byte will be assigned to the string offset");
}
let byte = (&*crate::bytes::to_bytes(&replacement))[0];
let len = cur.len() as i64;
let idx = if off < 0 {
let from_end = len + off;
if from_end < 0 {
self.warn(format_args!("Illegal string offset {off}"));
return Ok(None);
}
from_end as usize
} else {
off as usize
};
let mut bytes = (*crate::bytes::to_bytes(cur)).to_vec();
if idx >= bytes.len() {
bytes.resize(idx + 1, b' ');
}
bytes[idx] = byte;
Ok(Some(crate::bytes::from_bytes(&bytes)))
}
pub fn append_var(&mut self, name: &str, val: Value) -> Result<(), String> {
let arr = self.ensure_array_var(name);
if self.append_slot_taken(&arr) {
return Err(NEXT_ELEMENT_OCCUPIED.to_string());
}
if let Some(PhpObj::Array {
entries,
next_index,
}) = self.as_array_mut(&arr)
{
let k = ArrayKey::Int(take_next_index(next_index));
entries.insert(k, val);
}
Ok(())
}
fn ensure_array_var(&mut self, name: &str) -> Value {
let cur = self.get_var(name);
if matches!(self.as_array(&cur), Some(PhpObj::Array { .. })) {
return cur;
}
let arr = self.new_array();
self.set_var(name, arr.clone());
arr
}
fn ensure_path_from(&mut self, mut arr: Value, keys: &[Value]) -> Value {
for key in keys {
let k = self.norm_key(key);
let child = match self.as_array(&arr) {
Some(PhpObj::Array { entries, .. }) => {
entries.get(&k).cloned().map(|v| self.deref(v))
}
_ => None,
};
arr = match child {
Some(v) if self.is_array(&v) => v,
_ => {
let new = self.new_array();
self.arr_set_key(&arr, key, new.clone());
new
}
};
}
arr
}
fn ensure_path_array(&mut self, name: &str, keys: &[Value]) -> Value {
let root = self.ensure_array_var(name);
self.ensure_path_from(root, keys)
}
pub fn index_set_path(&mut self, name: &str, keys: &[Value], val: Value) -> Result<(), String> {
let Some((last, inter)) = keys.split_last() else {
return Ok(());
};
if let Value::Str(cur) = self.index_get_path(name, inter) {
if let Some(updated) = self.string_offset_set(&cur, last, &val)? {
if inter.is_empty() {
self.set_var(name, Value::str(updated));
} else {
self.index_set_path(name, inter, Value::str(updated))?;
}
}
return Ok(());
}
let arr = self.ensure_path_array(name, inter);
self.arr_set_key(&arr, last, val);
Ok(())
}
pub fn append_path(&mut self, name: &str, keys: &[Value], val: Value) {
let arr = self.ensure_path_array(name, keys);
self.arr_push_auto(&arr, val);
}
pub fn index_get_path(&self, name: &str, keys: &[Value]) -> Value {
let mut cur = self.get_var(name);
for key in keys {
cur = self.index_get(&cur, key);
}
cur
}
pub fn object_as_array_refusal(&self, obj: &Value) -> ContainerIssue {
let class = self.instance_class(obj).unwrap_or_default();
ContainerIssue::Refused(format!(
"Cannot use object of type {} as array",
display_class(&class)
))
}
pub fn spl_native_storage(&self, recv: &Value) -> Option<Value> {
let class = self.instance_class(recv)?;
let native_get = matches!(
self.method_owner_key(&class, "offsetget").as_deref(),
Some("arrayobject" | "arrayiterator")
);
let storage = self.prop_get(recv, "storage");
(native_get && self.is_array(&storage)).then_some(storage)
}
pub fn write_container_issue(
&self,
name: &str,
keys: &[Value],
tail: WriteTail,
) -> Option<ContainerIssue> {
let mut cur = self.get_var(name);
for i in 0..=keys.len() {
match cur {
Value::Int(_) | Value::Float(_) | Value::Bool(true) => {
return Some(ContainerIssue::Scalar)
}
Value::Bool(false) => return Some(ContainerIssue::FalseToArray),
Value::Str(_) if i < keys.len() => {
return Some(ContainerIssue::Refused(STRING_OFFSET_AS_ARRAY.into()))
}
Value::Str(_) => {
return tail
.string_refusal()
.map(|m| ContainerIssue::Refused(m.into()))
}
Value::Obj(_) if self.array_access_class(&cur).is_some() => return None,
Value::Obj(_) if self.is_object_value(&cur) => {
return Some(self.object_as_array_refusal(&cur))
}
_ => {}
}
let Some(key) = keys.get(i) else { break };
cur = self.index_get(&cur, key);
}
None
}
pub fn unset_container_issue(&self, name: &str, keys: &[Value]) -> Option<ContainerIssue> {
let mut cur = self.get_var(name);
let last = keys.len().saturating_sub(1);
for (i, key) in keys.iter().enumerate() {
match cur {
Value::Int(_) | Value::Float(_) | Value::Bool(true) => {
return Some(ContainerIssue::Refused(
"Cannot unset offset in a non-array variable".into(),
))
}
Value::Bool(false) => return Some(ContainerIssue::FalseToArray),
Value::Str(_) if i < last => {
return Some(ContainerIssue::Refused(STRING_OFFSET_AS_ARRAY.into()))
}
Value::Str(_) => {
return Some(ContainerIssue::Refused(
"Cannot unset string offsets".into(),
))
}
_ if self.is_array(&cur) => cur = self.index_get(&cur, key),
Value::Obj(_)
if self.is_object_value(&cur) && self.array_access_class(&cur).is_none() =>
{
return Some(self.object_as_array_refusal(&cur))
}
_ => return None,
}
}
None
}
pub fn index_get_path_warn(&mut self, name: &str, keys: &[Value]) -> Value {
let mut cur = self.get_var_warn(name);
for key in keys {
if matches!(cur, Value::Undef) {
let k = self.diag_key(key);
self.warn(format_args!("Undefined array key {k}"));
continue;
}
cur = self.index_get_warn(&cur, key);
}
cur
}
pub fn path_append_child(&mut self, name: &str, keys: &[Value]) -> Value {
let arr = self.ensure_path_array(name, keys);
let new = self.new_array();
self.arr_push_auto(&arr, new.clone());
new
}
pub fn append_slot_taken(&self, arr: &Value) -> bool {
matches!(
self.as_array(arr),
Some(PhpObj::Array { entries, next_index })
if entries.contains_key(&ArrayKey::Int(next_key(*next_index)))
)
}
pub fn arr_push_auto(&mut self, arr: &Value, v: Value) {
if let Some(PhpObj::Array {
entries,
next_index,
}) = self.as_array_mut(arr)
{
let k = ArrayKey::Int(take_next_index(next_index));
entries.insert(k, v);
}
}
pub fn arr_set_key(&mut self, arr: &Value, key: &Value, v: Value) {
self.diagnose_array_offset(arr, key);
let k = self.norm_key(key);
if let Some(slot) = self.entry_ref_slot(arr, &k) {
self.ref_cell_set(slot, v);
return;
}
if let Some(PhpObj::Array {
entries,
next_index,
}) = self.as_array_mut(arr)
{
if let ArrayKey::Int(n) = k {
if n >= *next_index {
*next_index = n.saturating_add(1);
}
}
entries.insert(k, v);
}
}
pub fn arr_replace_all(&mut self, arr: &Value, src: &Value) {
let Some(PhpObj::Array {
entries,
next_index,
}) = self.as_array(src)
else {
return;
};
let (entries, next_index) = (entries.clone(), *next_index);
if let Some(PhpObj::Array {
entries: dst,
next_index: dst_next,
}) = self.as_array_mut(arr)
{
*dst = entries;
*dst_next = next_index;
}
}
pub fn arr_set_reindexed(&mut self, arr: &Value, vals: Vec<Value>) {
if let Some(PhpObj::Array {
entries,
next_index,
}) = self.as_array_mut(arr)
{
entries.clear();
*next_index = 0;
for v in vals {
let k = ArrayKey::Int(*next_index);
*next_index = next_index.saturating_add(1);
entries.insert(k, v);
}
}
}
pub fn arr_set_pairs(&mut self, arr: &Value, pairs: Vec<(Value, Value)>) {
let normed: Vec<(ArrayKey, Value)> = pairs
.into_iter()
.map(|(k, v)| (self.norm_key(&k), v))
.collect();
if let Some(PhpObj::Array {
entries,
next_index,
}) = self.as_array_mut(arr)
{
entries.clear();
*next_index = NO_INDEX;
for (k, v) in normed {
if let ArrayKey::Int(n) = k {
if n >= *next_index {
*next_index = n.saturating_add(1);
}
}
entries.insert(k, v);
}
}
}
fn arr_rebuild_reindexed(&mut self, arr: &Value, pairs: Vec<(Value, Value)>) {
let normed: Vec<(ArrayKey, Value)> = pairs
.into_iter()
.map(|(k, v)| (self.norm_key(&k), v))
.collect();
if let Some(PhpObj::Array {
entries,
next_index,
}) = self.as_array_mut(arr)
{
entries.clear();
*next_index = 0;
for (k, v) in normed {
match k {
ArrayKey::Int(_) => {
let nk = ArrayKey::Int(*next_index);
*next_index = next_index.saturating_add(1);
entries.insert(nk, v);
}
ArrayKey::Str(_) => {
entries.insert(k, v);
}
}
}
}
}
pub fn arr_pop_var(&mut self, name: &str) -> Value {
let arr = self.get_var(name);
if let Some(PhpObj::Array {
entries,
next_index,
}) = self.as_array_mut(&arr)
{
let before = *next_index;
let popped = entries.pop();
if let Some((ArrayKey::Int(n), _)) = &popped {
if before.checked_sub(1) == Some(*n) {
*next_index = *n;
}
}
return popped.map(|(_, v)| v).unwrap_or(Value::Undef);
}
Value::Undef
}
pub fn arr_shift_var(&mut self, name: &str) -> Value {
let arr = self.get_var(name);
let Some(mut pairs) = self.array_pairs(&arr) else {
return Value::Undef;
};
if pairs.is_empty() {
return Value::Undef;
}
let (_, first) = pairs.remove(0);
self.arr_rebuild_reindexed(&arr, pairs);
first
}
pub fn arr_push_var(&mut self, name: &str, vals: Vec<Value>) -> Result<Value, String> {
let arr = self.ensure_array_var(name);
for v in vals {
if self.append_slot_taken(&arr) {
return Err(NEXT_ELEMENT_OCCUPIED.to_string());
}
self.arr_push_auto(&arr, v);
}
Ok(Value::int(self.array_len(&arr)))
}
pub fn arr_unshift_var(&mut self, name: &str, vals: Vec<Value>) -> Value {
let arr = self.ensure_array_var(name);
let existing = self.array_pairs(&arr).unwrap_or_default();
let mut combined: Vec<(Value, Value)> = Vec::with_capacity(vals.len() + existing.len());
for v in vals {
combined.push((Value::int(0), v));
}
combined.extend(existing);
self.arr_rebuild_reindexed(&arr, combined);
Value::int(self.array_len(&arr))
}
pub fn arr_splice_var(&mut self, name: &str, args: &[Value]) -> Value {
let arr = self.ensure_array_var(name);
let pairs = self.array_pairs(&arr).unwrap_or_default();
let n = pairs.len() as i64;
let mut off = args.first().map(|v| v.to_int()).unwrap_or(0);
if off < 0 {
off = (n + off).max(0);
}
let off = off.min(n).max(0) as usize;
let len = match args.get(1) {
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).min(pairs.len() - off)
}
}
_ => pairs.len() - off,
};
let end = (off + len).min(pairs.len());
let replacement: Vec<Value> = match args.get(2) {
Some(v) if self.is_array(v) => self
.array_pairs(v)
.unwrap_or_default()
.into_iter()
.map(|(_, x)| x)
.collect(),
Some(v) if !matches!(v, Value::Undef) => vec![v.clone()],
_ => Vec::new(),
};
let removed: Vec<(Value, Value)> = pairs[off..end].to_vec();
let mut rebuilt: Vec<(Value, Value)> = Vec::with_capacity(pairs.len());
rebuilt.extend(pairs[..off].iter().cloned());
for v in replacement {
rebuilt.push((Value::int(0), v));
}
rebuilt.extend(pairs[end..].iter().cloned());
self.arr_rebuild_reindexed(&arr, rebuilt);
let out = self.new_array();
self.arr_rebuild_reindexed(&out, removed);
out
}
pub fn array_keys(&mut self, recv: &Value) -> Value {
let keys: Vec<Value> = match self.as_array(recv) {
Some(PhpObj::Array { entries, .. }) => entries.keys().map(|k| k.to_value()).collect(),
_ => Vec::new(),
};
let arr = self.new_array();
if let Some(PhpObj::Array {
entries,
next_index,
}) = self.as_array_mut(&arr)
{
for (i, k) in keys.into_iter().enumerate() {
entries.insert(ArrayKey::Int(i as i64), k);
*next_index = (i + 1) as i64;
}
}
arr
}
pub fn array_len(&self, recv: &Value) -> i64 {
match self.as_array(recv) {
Some(PhpObj::Array { entries, .. }) => entries.len() as i64,
_ => 0,
}
}
pub fn array_pairs(&self, recv: &Value) -> Option<Vec<(Value, Value)>> {
match self.as_array(recv) {
Some(PhpObj::Array { entries, .. }) => {
let raw: Vec<(Value, Value)> = entries
.iter()
.map(|(k, v)| (k.to_value(), v.clone()))
.collect();
Some(raw.into_iter().map(|(k, v)| (k, self.deref(v))).collect())
}
_ => None,
}
}
pub fn array_pairs_marked(&self, recv: &Value) -> Option<Vec<(Value, Value, bool)>> {
let Some(PhpObj::Array { entries, .. }) = self.as_array(recv) else {
return None;
};
let raw: Vec<(Value, Value)> = entries
.iter()
.map(|(k, v)| (k.to_value(), v.clone()))
.collect();
Some(
raw.into_iter()
.map(|(k, v)| {
let is_ref = self.ref_slot_of_value(&v).is_some();
(k, self.deref(v), is_ref)
})
.collect(),
)
}
pub fn is_array(&self, v: &Value) -> bool {
matches!(self.as_array(v), Some(PhpObj::Array { .. }))
}
pub fn is_truthy(&self, v: &Value) -> bool {
match v {
Value::Undef => false,
Value::Bool(b) => *b,
Value::Int(n) => *n != 0,
Value::Float(f) => *f != 0.0,
Value::Str(s) => !(s.is_empty() || s.as_str() == "0"),
Value::Obj(_) => !self.is_array(v) || self.array_len(v) != 0,
_ => true,
}
}
pub fn to_str_diag(&mut self, v: &Value) -> String {
match v {
Value::Obj(_) if self.is_array(v) => self.warn("Array to string conversion"),
Value::Float(f) if f.is_nan() => {
self.warn("unexpected NAN value was coerced to string");
}
_ => {}
}
self.to_str(v)
}
pub fn to_str(&self, v: &Value) -> String {
match v {
Value::Undef => String::new(),
Value::Bool(b) => if *b { "1" } else { "" }.to_string(),
Value::Int(n) => n.to_string(),
Value::Float(f) => float_to_php_string(*f),
Value::Str(s) => String::clone(s),
Value::Obj(_) => match self.resource_info(v) {
Some((id, _)) => format!("Resource id #{id}"),
None => "Array".to_string(),
},
_ => String::new(),
}
}
fn int_step_impl(n: i64, delta: i64) -> Value {
match n.checked_add(delta) {
Some(v) => Value::int(v),
None => Value::float(n as f64 + delta as f64),
}
}
pub fn incdec_value(&mut self, old: &Value, inc: bool) -> Value {
let delta = if inc { 1 } else { -1 };
match old {
Value::Undef => {
if inc {
Value::int(1)
} else {
self.warn(
"Decrement on type null has no effect, this will change in the next \
major version of PHP",
);
Value::Undef
}
}
Value::Bool(_) => {
let word = if inc { "Increment" } else { "Decrement" };
self.warn(format_args!(
"{word} on type bool has no effect, this will change in the next major \
version of PHP"
));
old.clone()
}
Value::Int(n) => Self::int_step_impl(*n, delta),
Value::Float(f) => Value::float(f + delta as f64),
Value::Str(s) if is_numeric_string(s) => match parse_php_number(s) {
Value::Float(f) => Value::float(f + delta as f64),
Value::Int(n) => Self::int_step_impl(n, delta),
other => other,
},
Value::Str(s) if s.is_empty() => {
if inc {
self.deprecated(
"Increment on non-numeric string is deprecated, use str_increment() \
instead",
);
Value::str("1")
} else {
self.deprecated("Decrement on empty string is deprecated as non-numeric");
Value::int(-1)
}
}
Value::Str(s) => {
if inc {
self.deprecated(
"Increment on non-numeric string is deprecated, use str_increment() \
instead",
);
Value::str(increment_alnum_string(s))
} else {
self.deprecated(
"Decrement on non-numeric string has no effect and is deprecated",
);
old.clone()
}
}
other => other.clone(),
}
}
pub fn to_number(&self, v: &Value) -> Value {
match v {
Value::Int(_) | Value::Float(_) => v.clone(),
Value::Bool(b) => Value::int(*b as i64),
Value::Undef => Value::int(0),
Value::Str(s) => parse_php_number(s),
Value::Obj(_) if self.is_stream(v) => {
Value::int(self.resource_info(v).map_or(0, |(id, _)| id))
}
Value::Obj(_) => Value::int(if self.is_array(v) && self.array_len(v) == 0 {
0
} else {
1
}),
_ => Value::int(0),
}
}
pub fn type_name(&self, v: &Value) -> &'static str {
match v {
Value::Undef => "NULL",
Value::Bool(_) => "boolean",
Value::Int(_) => "integer",
Value::Float(_) => "double",
Value::Str(_) => "string",
Value::Obj(_) => {
if self.is_array(v) {
"array"
} else if let Some((_, closed)) = self.resource_info(v) {
if closed {
"resource (closed)"
} else {
"resource"
}
} else {
"object"
}
}
_ => "unknown type",
}
}
}
pub fn is_superglobal(name: &str) -> bool {
if !matches!(
(*crate::bytes::to_bytes(name)).first(),
Some(b'_' | b'G' | b'a')
) {
return false;
}
matches!(
name,
"_SERVER"
| "_GET"
| "_POST"
| "_REQUEST"
| "_COOKIE"
| "_FILES"
| "_ENV"
| "_SESSION"
| "GLOBALS"
| "argv"
| "argc"
)
}
pub const PHP_VERSION: &str = "8.5.11";
fn php_version_parts() -> (i64, i64, i64) {
let mut it = PHP_VERSION.split('.').map(|p| p.parse().unwrap_or(0));
let mut next = || it.next().unwrap_or(0);
(next(), next(), next())
}
#[cfg(unix)]
fn php_binary() -> String {
use std::ffi::CString;
use std::os::unix::ffi::OsStrExt;
use std::path::{Path, PathBuf};
let executable = |p: &Path| {
CString::new(p.as_os_str().as_bytes())
.is_ok_and(|c| unsafe { libc::access(c.as_ptr(), libc::X_OK) } == 0)
};
let Some(argv0) = std::env::args_os().next() else {
return String::new();
};
let found: Option<PathBuf> = if argv0.as_bytes().contains(&b'/') {
std::fs::canonicalize(&argv0)
.ok()
.filter(|real| executable(real))
} else {
let path = std::env::var_os("PATH").unwrap_or_default();
path.as_bytes()
.split(|&b| b == b':')
.filter(|dir| !dir.is_empty())
.find_map(|dir| {
let mut candidate = dir.to_vec();
candidate.push(b'/');
candidate.extend_from_slice(argv0.as_bytes());
let real = std::fs::canonicalize(std::ffi::OsStr::from_bytes(&candidate)).ok()?;
(executable(&real) && real.is_file()).then_some(real)
})
};
found
.map(|p| p.to_string_lossy().into_owned())
.unwrap_or_default()
}
#[cfg(not(unix))]
fn php_binary() -> String {
std::env::current_exe()
.map(|p| p.to_string_lossy().into_owned())
.unwrap_or_default()
}
fn deprecated_constant_suffix(name: &str) -> Option<&'static str> {
Some(match name {
"E_STRICT" => "since 8.4, the error level was removed",
"DATE_RFC7231" => {
"since 8.5, as this format ignores the associated timezone and always uses GMT"
}
"SUNFUNCS_RET_TIMESTAMP" | "SUNFUNCS_RET_STRING" | "SUNFUNCS_RET_DOUBLE" => {
"since 8.4, as date_sunrise() and date_sunset() were deprecated in 8.1"
}
"FILTER_SANITIZE_STRING" | "FILTER_SANITIZE_STRIPPED" => {
"since 8.1, use htmlspecialchars() instead"
}
_ => return None,
})
}
pub fn is_predefined_constant(name: &str) -> bool {
thread_local! {
static NAMES: FxHashSet<String> = predefined_constants().into_keys().collect();
}
NAMES.with(|n| n.contains(name))
}
fn predefined_constants() -> FxHashMap<String, Value> {
let mut m = FxHashMap::default();
let mut si = |k: &str, v: i64| {
m.insert(k.to_string(), Value::int(v));
};
si("PHP_INT_MAX", i64::MAX);
si("PHP_INT_MIN", i64::MIN);
si("PHP_INT_SIZE", 8);
si("PHP_FLOAT_DIG", 15);
let (major, minor, release) = php_version_parts();
si("PHP_MAJOR_VERSION", major);
si("PHP_MINOR_VERSION", minor);
si("PHP_RELEASE_VERSION", release);
si("PHP_VERSION_ID", major * 10000 + minor * 100 + release);
si("PHP_MAXPATHLEN", 1024);
si("PHP_FD_SETSIZE", 1024);
si("INI_USER", 1);
si("INI_PERDIR", 2);
si("INI_SYSTEM", 4);
si("INI_ALL", 7);
si("CONNECTION_ABORTED", 1);
si("CONNECTION_NORMAL", 0);
si("CONNECTION_TIMEOUT", 2);
si("PHP_QUERY_RFC1738", 1);
si("PHP_QUERY_RFC3986", 2);
for (i, k) in [
"UPLOAD_ERR_OK",
"UPLOAD_ERR_INI_SIZE",
"UPLOAD_ERR_FORM_SIZE",
"UPLOAD_ERR_PARTIAL",
"UPLOAD_ERR_NO_FILE",
]
.into_iter()
.enumerate()
{
si(k, i as i64);
}
si("UPLOAD_ERR_NO_TMP_DIR", 6);
si("UPLOAD_ERR_CANT_WRITE", 7);
si("UPLOAD_ERR_EXTENSION", 8);
si("PHP_ROUND_HALF_UP", 1);
si("PHP_ROUND_HALF_DOWN", 2);
si("PHP_ROUND_HALF_EVEN", 3);
si("PHP_ROUND_HALF_ODD", 4);
si("E_ERROR", errlevel::E_ERROR);
si("E_WARNING", errlevel::E_WARNING);
si("E_PARSE", errlevel::E_PARSE);
si("E_NOTICE", errlevel::E_NOTICE);
si("E_CORE_ERROR", errlevel::E_CORE_ERROR);
si("E_CORE_WARNING", errlevel::E_CORE_WARNING);
si("E_COMPILE_ERROR", errlevel::E_COMPILE_ERROR);
si("E_COMPILE_WARNING", errlevel::E_COMPILE_WARNING);
si("E_STRICT", errlevel::E_STRICT);
si("E_RECOVERABLE_ERROR", errlevel::E_RECOVERABLE_ERROR);
si("E_DEPRECATED", errlevel::E_DEPRECATED);
si("E_ALL", errlevel::E_ALL);
si("E_USER_ERROR", errlevel::E_USER_ERROR);
si("E_USER_WARNING", errlevel::E_USER_WARNING);
si("E_USER_NOTICE", errlevel::E_USER_NOTICE);
si("E_USER_DEPRECATED", errlevel::E_USER_DEPRECATED);
si("SORT_REGULAR", 0);
si("SORT_NUMERIC", 1);
si("SORT_STRING", 2);
si("SORT_DESC", 3);
si("SORT_ASC", 4);
si("SORT_LOCALE_STRING", 5);
si("SORT_NATURAL", 6);
si("SORT_FLAG_CASE", 8);
si("PHP_OUTPUT_HANDLER_START", 1);
si("PHP_OUTPUT_HANDLER_WRITE", 0);
si("PHP_OUTPUT_HANDLER_FLUSH", 4);
si("PHP_OUTPUT_HANDLER_CLEAN", 2);
si("PHP_OUTPUT_HANDLER_FINAL", 8);
si("PHP_OUTPUT_HANDLER_CONT", 0);
si("PHP_OUTPUT_HANDLER_END", 8);
si("PHP_OUTPUT_HANDLER_CLEANABLE", 16);
si("PHP_OUTPUT_HANDLER_FLUSHABLE", 32);
si("PHP_OUTPUT_HANDLER_REMOVABLE", 64);
si("PHP_OUTPUT_HANDLER_STDFLAGS", 112);
si("PHP_OUTPUT_HANDLER_STARTED", 4096);
si("PHP_OUTPUT_HANDLER_DISABLED", 8192);
si("PHP_OUTPUT_HANDLER_PROCESSED", 16384);
si("COUNT_NORMAL", 0);
si("COUNT_RECURSIVE", 1);
si("STR_PAD_RIGHT", 1);
si("STR_PAD_LEFT", 0);
si("STR_PAD_BOTH", 2);
si("ARRAY_FILTER_USE_KEY", ARRAY_FILTER_USE_KEY);
si("ARRAY_FILTER_USE_BOTH", ARRAY_FILTER_USE_BOTH);
si("EXTR_OVERWRITE", 0);
si("EXTR_SKIP", 1);
si("EXTR_PREFIX_SAME", 2);
si("EXTR_PREFIX_ALL", 3);
si("EXTR_PREFIX_INVALID", 4);
si("EXTR_PREFIX_IF_EXISTS", 5);
si("EXTR_IF_EXISTS", 6);
si("EXTR_REFS", 256);
si("LC_CTYPE", i64::from(libc::LC_CTYPE));
si("LC_NUMERIC", i64::from(libc::LC_NUMERIC));
si("LC_TIME", i64::from(libc::LC_TIME));
si("LC_COLLATE", i64::from(libc::LC_COLLATE));
si("LC_MONETARY", i64::from(libc::LC_MONETARY));
si("LC_MESSAGES", i64::from(libc::LC_MESSAGES));
si("LC_ALL", i64::from(libc::LC_ALL));
si("PREG_PATTERN_ORDER", 1);
si("PREG_SET_ORDER", 2);
si("PREG_OFFSET_CAPTURE", 256);
si("PREG_UNMATCHED_AS_NULL", 512);
si("PREG_SPLIT_NO_EMPTY", 1);
si("PREG_SPLIT_DELIM_CAPTURE", 2);
si("PREG_SPLIT_OFFSET_CAPTURE", 4);
si("PREG_GREP_INVERT", 1);
si("PREG_NO_ERROR", 0);
si("PREG_INTERNAL_ERROR", 1);
si("PREG_BACKTRACK_LIMIT_ERROR", 2);
si("PREG_RECURSION_LIMIT_ERROR", 3);
si("PREG_BAD_UTF8_ERROR", 4);
si("PREG_BAD_UTF8_OFFSET_ERROR", 5);
si("PREG_JIT_STACKLIMIT_ERROR", 6);
si("JSON_HEX_TAG", 1);
si("JSON_HEX_AMP", 2);
si("JSON_HEX_APOS", 4);
si("JSON_HEX_QUOT", 8);
si("JSON_FORCE_OBJECT", 16);
si("JSON_NUMERIC_CHECK", 32);
si("JSON_UNESCAPED_SLASHES", 64);
si("JSON_PRETTY_PRINT", 128);
si("JSON_UNESCAPED_UNICODE", 256);
si("JSON_PARTIAL_OUTPUT_ON_ERROR", 512);
si("JSON_PRESERVE_ZERO_FRACTION", 1024);
si("JSON_UNESCAPED_LINE_TERMINATORS", 2048);
si("JSON_THROW_ON_ERROR", 4194304);
si("JSON_OBJECT_AS_ARRAY", 1);
si("JSON_BIGINT_AS_STRING", 2);
si("JSON_ERROR_NONE", 0);
si("JSON_ERROR_DEPTH", 1);
si("JSON_ERROR_STATE_MISMATCH", 2);
si("JSON_ERROR_CTRL_CHAR", 3);
si("JSON_ERROR_SYNTAX", 4);
si("JSON_ERROR_UTF8", 5);
si("JSON_INVALID_UTF8_IGNORE", 1_048_576);
si("JSON_INVALID_UTF8_SUBSTITUTE", 2_097_152);
si("JSON_ERROR_RECURSION", 6);
si("JSON_ERROR_INF_OR_NAN", 7);
si("JSON_ERROR_UNSUPPORTED_TYPE", 8);
si("JSON_ERROR_INVALID_PROPERTY_NAME", 9);
si("JSON_ERROR_UTF16", 10);
si("JSON_ERROR_NON_BACKED_ENUM", 11);
si("PHP_URL_SCHEME", 0);
si("PHP_URL_HOST", 1);
si("PHP_URL_PORT", 2);
si("PHP_URL_USER", 3);
si("PHP_URL_PASS", 4);
si("PHP_URL_PATH", 5);
si("PHP_URL_QUERY", 6);
si("PHP_URL_FRAGMENT", 7);
si("INPUT_GET", 1);
si("INPUT_POST", 0);
si("FILTER_DEFAULT", 516);
si("FILTER_UNSAFE_RAW", 516);
si("FILTER_VALIDATE_INT", 257);
si("FILTER_VALIDATE_BOOLEAN", 258);
si("FILTER_VALIDATE_BOOL", 258);
si("FILTER_VALIDATE_FLOAT", 259);
si("FILTER_VALIDATE_REGEXP", 272);
si("FILTER_VALIDATE_DOMAIN", 277);
si("FILTER_VALIDATE_URL", 273);
si("FILTER_VALIDATE_EMAIL", 274);
si("FILTER_VALIDATE_IP", 275);
si("FILTER_VALIDATE_MAC", 276);
si("FILTER_SANITIZE_STRING", 513);
si("FILTER_SANITIZE_STRIPPED", 513);
si("FILTER_SANITIZE_ENCODED", 514);
si("FILTER_SANITIZE_SPECIAL_CHARS", 515);
si("FILTER_SANITIZE_FULL_SPECIAL_CHARS", 522);
si("FILTER_SANITIZE_EMAIL", 517);
si("FILTER_SANITIZE_URL", 518);
si("FILTER_SANITIZE_NUMBER_INT", 519);
si("FILTER_SANITIZE_NUMBER_FLOAT", 520);
si("FILTER_SANITIZE_ADD_SLASHES", 523);
si("FILTER_FLAG_ALLOW_OCTAL", 1);
si("FILTER_FLAG_ALLOW_HEX", 2);
si("FILTER_FLAG_STRIP_LOW", 4);
si("FILTER_FLAG_STRIP_HIGH", 8);
si("FILTER_FLAG_ALLOW_FRACTION", 4096);
si("FILTER_FLAG_ALLOW_THOUSAND", 8192);
si("FILTER_FLAG_ALLOW_SCIENTIFIC", 16384);
si("FILTER_FLAG_IPV4", 1048576);
si("FILTER_FLAG_IPV6", 2097152);
si("FILTER_FLAG_HOSTNAME", 1048576);
si("FILTER_NULL_ON_FAILURE", 134217728);
si("FILTER_REQUIRE_SCALAR", 33554432);
si("FILTER_REQUIRE_ARRAY", 16777216);
si("FILTER_FORCE_ARRAY", 67108864);
si("MB_CASE_UPPER", 0);
si("MB_CASE_LOWER", 1);
si("MB_CASE_TITLE", 2);
si("FILE_USE_INCLUDE_PATH", 1);
si("FILE_APPEND", 8);
si("FILE_IGNORE_NEW_LINES", 2);
si("FILE_SKIP_EMPTY_LINES", 4);
si("FILE_NO_DEFAULT_CONTEXT", 16);
si("LOCK_SH", 1);
si("LOCK_EX", 2);
si("LOCK_UN", 3);
si("LOCK_NB", 4);
si("SEEK_SET", 0);
si("SEEK_CUR", 1);
si("SEEK_END", 2);
si("SCANDIR_SORT_ASCENDING", 0);
si("SCANDIR_SORT_DESCENDING", 1);
si("SCANDIR_SORT_NONE", 2);
si("GLOB_ERR", crate::stdlib::fileio::GLOB_ERR);
si("GLOB_MARK", crate::stdlib::fileio::GLOB_MARK);
si("GLOB_NOCHECK", crate::stdlib::fileio::GLOB_NOCHECK);
si("GLOB_NOSORT", crate::stdlib::fileio::GLOB_NOSORT);
si("GLOB_BRACE", crate::stdlib::fileio::GLOB_BRACE);
si("GLOB_NOESCAPE", crate::stdlib::fileio::GLOB_NOESCAPE);
si("GLOB_ONLYDIR", crate::stdlib::fileio::GLOB_ONLYDIR);
si(
"GLOB_AVAILABLE_FLAGS",
crate::stdlib::fileio::GLOB_AVAILABLE_FLAGS,
);
si("FNM_NOESCAPE", crate::stdlib::fileio::FNM_NOESCAPE);
si("FNM_PATHNAME", crate::stdlib::fileio::FNM_PATHNAME);
si("FNM_PERIOD", crate::stdlib::fileio::FNM_PERIOD);
si("FNM_CASEFOLD", crate::stdlib::fileio::FNM_CASEFOLD);
si("GMP_ROUND_ZERO", crate::stdlib::gmp::GMP_ROUND_ZERO);
si("GMP_ROUND_PLUSINF", crate::stdlib::gmp::GMP_ROUND_PLUSINF);
si("GMP_ROUND_MINUSINF", crate::stdlib::gmp::GMP_ROUND_MINUSINF);
si("HASH_HMAC", crate::stdlib::hashext::HASH_HMAC);
si("DEBUG_BACKTRACE_PROVIDE_OBJECT", 1);
si("DEBUG_BACKTRACE_IGNORE_ARGS", 2);
si("PATHINFO_DIRNAME", 1);
si("PATHINFO_BASENAME", 2);
si("PATHINFO_EXTENSION", 4);
si("PATHINFO_FILENAME", 8);
si("PATHINFO_ALL", 15);
si("CASE_LOWER", 0);
si("CASE_UPPER", 1);
si("HTML_SPECIALCHARS", 0);
si("HTML_ENTITIES", 1);
si("ENT_NOQUOTES", 0);
si("ENT_COMPAT", 2);
si("ENT_QUOTES", 3);
si("ENT_HTML401", 0);
si("ENT_HTML5", 48);
si("ENT_XML1", 16);
si("ENT_XHTML", 32);
si("ENT_SUBSTITUTE", 8);
si("ENT_IGNORE", 4);
si("SUNFUNCS_RET_TIMESTAMP", 0);
si("SUNFUNCS_RET_STRING", 1);
si("SUNFUNCS_RET_DOUBLE", 2);
let mut ss = |k: &str, v: &str| {
m.insert(k.to_string(), Value::str(v.to_string()));
};
ss("PHP_EOL", "\n");
ss("ICONV_IMPL", "libiconv");
ss("ICONV_VERSION", "1.11");
for (k, v) in [
("DATE_ATOM", r"Y-m-d\TH:i:sP"),
("DATE_COOKIE", "l, d-M-Y H:i:s T"),
("DATE_ISO8601", r"Y-m-d\TH:i:sO"),
("DATE_ISO8601_EXPANDED", r"X-m-d\TH:i:sP"),
("DATE_RFC822", "D, d M y H:i:s O"),
("DATE_RFC850", "l, d-M-y H:i:s T"),
("DATE_RFC1036", "D, d M y H:i:s O"),
("DATE_RFC1123", "D, d M Y H:i:s O"),
("DATE_RFC7231", r"D, d M Y H:i:s \G\M\T"),
("DATE_RFC2822", "D, d M Y H:i:s O"),
("DATE_RFC3339", r"Y-m-d\TH:i:sP"),
("DATE_RFC3339_EXTENDED", r"Y-m-d\TH:i:s.vP"),
("DATE_RSS", "D, d M Y H:i:s O"),
("DATE_W3C", r"Y-m-d\TH:i:sP"),
] {
ss(k, v);
}
ss("PHP_VERSION", PHP_VERSION);
ss("PHP_EXTRA_VERSION", "");
ss("PHP_SAPI", "cli");
ss("PHP_BINARY", &php_binary());
ss("PHP_SHLIB_SUFFIX", "so");
ss(
"PHP_OS",
if cfg!(target_os = "macos") {
"Darwin"
} else if cfg!(target_os = "windows") {
"WINNT"
} else {
"Linux"
},
);
ss(
"PHP_OS_FAMILY",
if cfg!(target_os = "windows") {
"Windows"
} else if cfg!(target_os = "macos") {
"Darwin"
} else {
"Linux"
},
);
ss(
"DIRECTORY_SEPARATOR",
if cfg!(windows) { "\\" } else { "/" },
);
ss("PATH_SEPARATOR", if cfg!(windows) { ";" } else { ":" });
let mut sf = |k: &str, v: f64| {
m.insert(k.to_string(), Value::float(v));
};
sf("M_PI", std::f64::consts::PI);
sf("M_E", std::f64::consts::E);
sf("M_SQRT2", std::f64::consts::SQRT_2);
sf("M_SQRT1_2", std::f64::consts::FRAC_1_SQRT_2);
sf("M_SQRT3", 1.7320508075688772);
sf("M_2_SQRTPI", std::f64::consts::FRAC_2_SQRT_PI);
sf("M_PI_2", std::f64::consts::FRAC_PI_2);
sf("M_PI_4", std::f64::consts::FRAC_PI_4);
sf("M_1_PI", std::f64::consts::FRAC_1_PI);
sf("M_2_PI", std::f64::consts::FRAC_2_PI);
sf("M_LN2", std::f64::consts::LN_2);
sf("M_LN10", std::f64::consts::LN_10);
sf("M_LOG2E", std::f64::consts::LOG2_E);
sf("M_LOG10E", std::f64::consts::LOG10_E);
sf("M_EULER", 0.5772156649015329);
sf("M_SQRTPI", 1.7724538509055159);
sf("M_LNPI", 1.1447298858494002);
sf("PHP_FLOAT_EPSILON", f64::EPSILON);
sf("PHP_FLOAT_MAX", f64::MAX);
sf("PHP_FLOAT_MIN", f64::MIN_POSITIVE);
sf("INF", f64::INFINITY);
sf("NAN", f64::NAN);
for k in [
"ZEND_THREAD_SAFE",
"ZEND_DEBUG_BUILD",
"PHP_DEBUG",
"PHP_ZTS",
] {
m.insert(k.to_string(), Value::bool(false));
}
m
}
thread_local! {
static HOST: RefCell<PhpHost> = RefCell::new(PhpHost::new());
static WARN_LINE: Cell<u32> = const { Cell::new(0) };
}
pub fn set_warn_line(line: u32) {
WARN_LINE.with(|c| c.set(line));
}
pub fn warn_line() -> u32 {
WARN_LINE.with(Cell::get)
}
pub fn with_host<R>(f: impl FnOnce(&mut PhpHost) -> R) -> R {
HOST.with(|h| f(&mut h.borrow_mut()))
}
pub fn reset_host() {
CUR_GEN.with(|c| c.set(None));
crate::stdlib::system::reset_lc_ctype();
crate::stdlib::strings::reset_mblen_state();
set_warn_line(0);
HOST.with(|h| *h.borrow_mut() = PhpHost::new());
}
type GenCoro = corosensei::Coroutine<Value, (), Result<Value, String>>;
type GenYielder = corosensei::Yielder<Value, ()>;
thread_local! {
static CUR_GEN: std::cell::Cell<Option<u32>> = const { std::cell::Cell::new(None) };
}
enum GenInject {
Throw(Value),
Destroy,
}
pub const GEN_DESTROY: &str = "__generator_destroy__";
#[derive(Default)]
struct GenContext {
frames: Vec<Scope>,
signal: Option<Signal>,
pending_throw: Option<Value>,
error: Option<String>,
}
struct GenCell {
function: String,
coro: Option<GenCoro>,
yielder: *const GenYielder,
ctx: GenContext,
cur_key: Value,
cur_val: Value,
auto_key: i64,
ret: Value,
started: bool,
at_first_yield: bool,
done: bool,
inject: Option<GenInject>,
destroying: bool,
}
impl PhpHost {
pub fn is_generator_val(&self, v: &Value) -> bool {
matches!(self.as_array(v), Some(PhpObj::Generator { .. }))
}
fn gen_id(&self, v: &Value) -> Option<u32> {
match self.as_array(v) {
Some(PhpObj::Generator { id }) => Some(*id),
_ => None,
}
}
fn install_gen_ctx(&mut self, mut c: GenContext) -> GenContext {
let caller_frames = self.scopes.split_off(1);
self.scopes.append(&mut c.frames); std::mem::swap(&mut self.signal, &mut c.signal);
std::mem::swap(&mut self.pending_throw, &mut c.pending_throw);
std::mem::swap(&mut self.error, &mut c.error);
c.frames = caller_frames;
c
}
}
fn make_generator(body: Chunk, frame: Scope) -> Value {
let id = with_host(|h| {
let id = h.generators.len() as u32;
let function = match h.trace_frame_parts(&frame) {
(Some((class, _)), function) => format!("{class}::{function}"),
(None, function) => function,
};
h.generators.push(GenCell {
function,
coro: None,
yielder: std::ptr::null(),
ctx: GenContext {
frames: vec![frame],
..GenContext::default()
},
cur_key: Value::Undef,
cur_val: Value::Undef,
auto_key: 0,
ret: Value::Undef,
started: false,
at_first_yield: false,
done: false,
inject: None,
destroying: false,
});
id
});
let coro = GenCoro::new(move |yielder: &GenYielder, _first: Value| {
with_host(|h| h.generators[id as usize].yielder = yielder as *const _);
let r = run_chunk_on(body);
let ret = with_host(|h| match h.signal.take() {
Some(Signal::Return(v)) => v,
_ => Value::Undef,
});
r.map(|_| ret)
});
with_host(|h| h.generators[id as usize].coro = Some(coro));
with_host(|h| {
h.objs.push(PhpObj::Generator { id });
Value::Obj((h.objs.len() - 1) as u32)
})
}
enum YieldKey {
Auto,
Explicit(Value),
Passthrough(Value),
}
fn gen_yield(key: YieldKey, val: Value) -> Result<Value, String> {
let id = match CUR_GEN.with(|c| c.get()) {
Some(id) => id,
None => return Err("cannot yield outside a generator".to_string()),
};
if with_host(|h| h.generators[id as usize].destroying) {
return Err(crate::builtins::throws_bare(
"Error",
"Cannot yield from finally in a force-closed generator",
));
}
let yp = with_host(|h| {
let g = &mut h.generators[id as usize];
let k = match key {
YieldKey::Auto => {
let k = g.auto_key;
g.auto_key += 1;
Value::int(k)
}
YieldKey::Explicit(Value::Int(i)) => {
if i >= g.auto_key {
g.auto_key = i + 1;
}
Value::int(i)
}
YieldKey::Explicit(other) => other,
YieldKey::Passthrough(k) => k,
};
g.cur_key = k;
g.cur_val = val;
g.yielder
});
let yielder = unsafe { &*yp };
let sent = yielder.suspend(());
match with_host(|h| h.generators[id as usize].inject.take()) {
Some(GenInject::Throw(e)) => {
set_pending_throw(e);
return Err("__generator_throw__".to_string());
}
Some(GenInject::Destroy) => {
set_return(Value::Undef);
return Err(GEN_DESTROY.to_string());
}
None => {}
}
Ok(sent)
}
pub fn yield_value(val: Value) -> Result<Value, String> {
gen_yield(YieldKey::Auto, val)
}
pub fn yield_kv(key: Value, val: Value) -> Result<Value, String> {
gen_yield(YieldKey::Explicit(key), val)
}
pub fn yield_from(src: Value) -> Result<Value, String> {
gen_yield_from(src)
}
fn gen_yield_from(src: Value) -> Result<Value, String> {
if with_host(|h| h.is_generator_val(&src)) {
gen_ensure_init(&src)?;
loop {
if !gen_valid(&src)? {
break;
}
let k = with_host(|h| {
h.generators[h.gen_id(&src).unwrap() as usize]
.cur_key
.clone()
});
let v = with_host(|h| {
h.generators[h.gen_id(&src).unwrap() as usize]
.cur_val
.clone()
});
let sent = gen_yield(YieldKey::Passthrough(k), v)?;
gen_send_raw(&src, sent)?;
}
return Ok(with_host(|h| {
h.generators[h.gen_id(&src).unwrap() as usize].ret.clone()
}));
}
let arr = foreach_prep(src)?;
let pairs: Vec<(Value, Value)> = with_host(|h| match h.as_array(&arr) {
Some(PhpObj::Array { entries, .. }) => entries
.iter()
.map(|(k, v)| (k.to_value(), v.clone()))
.collect(),
_ => Vec::new(),
});
for (k, v) in pairs {
gen_yield(YieldKey::Passthrough(k), v)?;
}
Ok(Value::Undef)
}
fn gen_resume(id: u32, send: Value) -> Result<(), String> {
if with_host(|h| h.generators[id as usize].done) {
return Ok(());
}
let mut coro = match with_host(|h| h.generators[id as usize].coro.take()) {
Some(c) => c,
None => return Err("cannot resume an already-running generator".to_string()),
};
with_host(|h| {
let g = &mut h.generators[id as usize];
if g.started {
g.at_first_yield = false;
}
g.started = true;
});
let gen_ctx = with_host(|h| std::mem::take(&mut h.generators[id as usize].ctx));
let caller_ctx = with_host(|h| h.install_gen_ctx(gen_ctx));
let prev = CUR_GEN.with(|c| c.replace(Some(id)));
let out = coro.resume(send);
CUR_GEN.with(|c| c.set(prev));
let body_throw = with_host(|h| h.pending_throw.take());
let gen_ctx = with_host(|h| h.install_gen_ctx(caller_ctx));
with_host(|h| {
h.generators[id as usize].ctx = gen_ctx;
h.generators[id as usize].coro = Some(coro);
});
let result = match out {
corosensei::CoroutineResult::Yield(()) => Ok(()),
corosensei::CoroutineResult::Return(r) => {
with_host(|h| {
let g = &mut h.generators[id as usize];
g.done = true;
g.cur_key = Value::Undef;
g.cur_val = Value::Undef;
});
match r {
Ok(v) => {
with_host(|h| h.generators[id as usize].ret = v);
Ok(())
}
Err(e) => Err(e),
}
}
};
if let Some(e) = body_throw {
set_pending_throw(e);
return Err("__generator_throw__".to_string());
}
result
}
pub fn gen_ensure_init(gen: &Value) -> Result<(), String> {
let id = with_host(|h| h.gen_id(gen)).ok_or("not a generator")?;
if !with_host(|h| h.generators[id as usize].started) {
gen_resume(id, Value::Undef)?;
with_host(|h| h.generators[id as usize].at_first_yield = true);
}
Ok(())
}
pub fn gen_rewind(gen: &Value) -> Result<(), String> {
gen_ensure_init(gen)?;
if with_host(|h| h.pending_throw.is_some()) {
return Ok(());
}
let id = with_host(|h| h.gen_id(gen)).ok_or("not a generator")?;
if !with_host(|h| h.generators[id as usize].at_first_yield) {
let exc = new_object(
"Exception",
vec![Value::str("Cannot rewind a generator that was already run")],
)?;
set_pending_throw(exc);
}
Ok(())
}
pub fn gen_foreach_rewind(gen: &Value) -> Result<(), String> {
let id = with_host(|h| h.gen_id(gen)).ok_or("not a generator")?;
if with_host(|h| h.generators[id as usize].done) {
let exc = new_object(
"Exception",
vec![Value::str("Cannot traverse an already closed generator")],
)?;
set_pending_throw(exc);
return Ok(());
}
gen_rewind(gen)
}
pub fn gen_valid(gen: &Value) -> Result<bool, String> {
gen_ensure_init(gen)?;
let id = with_host(|h| h.gen_id(gen)).ok_or("not a generator")?;
Ok(with_host(|h| !h.generators[id as usize].done))
}
pub fn gen_current(gen: &Value) -> Result<Value, String> {
gen_ensure_init(gen)?;
let id = with_host(|h| h.gen_id(gen)).ok_or("not a generator")?;
Ok(with_host(|h| h.generators[id as usize].cur_val.clone()))
}
pub fn gen_key(gen: &Value) -> Result<Value, String> {
gen_ensure_init(gen)?;
let id = with_host(|h| h.gen_id(gen)).ok_or("not a generator")?;
Ok(with_host(|h| h.generators[id as usize].cur_key.clone()))
}
pub fn gen_next(gen: &Value) -> Result<Value, String> {
gen_ensure_init(gen)?;
let id = with_host(|h| h.gen_id(gen)).ok_or("not a generator")?;
if !with_host(|h| h.generators[id as usize].done) {
gen_resume(id, Value::Undef)?;
}
Ok(Value::Undef)
}
fn gen_send_raw(gen: &Value, sent: Value) -> Result<(), String> {
let id = with_host(|h| h.gen_id(gen)).ok_or("not a generator")?;
if !with_host(|h| h.generators[id as usize].done) {
gen_resume(id, sent)?;
}
Ok(())
}
pub fn gen_send(gen: &Value, sent: Value) -> Result<Value, String> {
let id = with_host(|h| h.gen_id(gen)).ok_or("not a generator")?;
if !with_host(|h| h.generators[id as usize].started) {
gen_resume(id, Value::Undef)?;
}
if !with_host(|h| h.generators[id as usize].done) {
gen_resume(id, sent)?;
}
Ok(with_host(|h| h.generators[id as usize].cur_val.clone()))
}
pub fn gen_throw(gen: &Value, e: Value) -> Result<Value, String> {
let id = with_host(|h| h.gen_id(gen)).ok_or("not a generator")?;
gen_ensure_init(gen)?;
if with_host(|h| h.generators[id as usize].done) {
set_pending_throw(e);
return Ok(Value::Undef);
}
with_host(|h| h.generators[id as usize].inject = Some(GenInject::Throw(e)));
gen_resume(id, Value::Undef)?;
Ok(with_host(|h| h.generators[id as usize].cur_val.clone()))
}
pub fn shutdown_generators() {
let exit = with_host(|h| h.pending_exit.take());
let count = with_host(|h| h.generators.len());
for id in 0..count as u32 {
if gen_destroy(id).is_err() || unwinding() {
break;
}
}
with_host(|h| {
if h.pending_exit.is_none() {
h.pending_exit = exit;
}
});
crate::stdlib::output::end_all();
}
pub fn gen_mark() -> i64 {
with_host(|h| h.generators.len() as i64)
}
fn gen_destroy(id: u32) -> Result<(), String> {
let live = with_host(|h| {
let g = &h.generators[id as usize];
g.started && !g.done && g.coro.is_some()
});
let r = if live {
with_host(|h| {
let g = &mut h.generators[id as usize];
g.destroying = true;
g.inject = Some(GenInject::Destroy);
});
gen_resume(id, Value::Undef)
} else {
Ok(())
};
with_host(|h| {
let g = &mut h.generators[id as usize];
g.done = true;
g.cur_key = Value::Undef;
g.cur_val = Value::Undef;
});
r
}
pub fn gen_release(v: &Value, mark: i64) -> Result<(), String> {
let Some((id, handle)) = with_host(|h| match v {
Value::Obj(o) => h.gen_id(v).map(|id| (id, *o)),
_ => None,
}) else {
return Ok(());
};
let pending = with_host(|h| {
let g = &h.generators[id as usize];
i64::from(id) >= mark && g.started && !g.done
});
if !pending || with_host(|h| h.handle_held(handle)) {
return Ok(());
}
gen_destroy(id)
}
impl PhpHost {
fn handle_held(&self, handle: u32) -> bool {
let is = |v: &Value| matches!(v, Value::Obj(o) if *o == handle);
let frame_holds = |s: &Scope| {
s.vars
.slots
.iter()
.any(|slot| matches!(slot, Slot::Val(v) if is(v)))
};
self.scopes.iter().any(frame_holds)
|| self
.generators
.iter()
.any(|g| g.ctx.frames.iter().any(frame_holds))
|| self.ref_cells.iter().any(is)
|| self.static_props.values().any(is)
|| self.constants.values().any(is)
|| self.objs.iter().any(|o| match o {
PhpObj::Array { entries, .. } => entries.values().any(is),
PhpObj::Object { props, .. } => props.values().any(is),
PhpObj::Closure {
captured,
bound_this,
..
} => captured.iter().any(|(_, v)| is(v)) || bound_this.as_ref().is_some_and(is),
_ => false,
})
}
}
pub fn gen_get_return(gen: &Value) -> Result<Value, String> {
let id = with_host(|h| h.gen_id(gen)).ok_or("not a generator")?;
let (done, ret) = with_host(|h| {
let g = &h.generators[id as usize];
(g.done, g.ret.clone())
});
if !done {
return throw_from_internal(
"Generator->getReturn",
&[],
"Exception",
"Cannot get return value of a generator that hasn't returned",
);
}
Ok(ret)
}
pub fn call_generator_method(gen: &Value, method: &str, args: Vec<Value>) -> Result<Value, String> {
let mut args = args;
match method.to_ascii_lowercase().as_str() {
"current" => gen_current(gen),
"key" => gen_key(gen),
"next" => gen_next(gen),
"valid" => gen_valid(gen).map(Value::bool),
"rewind" => gen_rewind(gen).map(|_| Value::Undef),
"send" => gen_send(gen, args.into_iter().next().unwrap_or(Value::Undef)),
"throw" => gen_throw(gen, args.into_iter().next().unwrap_or(Value::Undef)),
"getreturn" => gen_get_return(gen),
other => {
let _ = args.pop();
Err(crate::builtins::throws_bare(
"Error",
format!("Call to undefined method Generator::{other}()"),
))
}
}
}
thread_local! {
static DEBUG_MODE: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
static VM_POOL: RefCell<fusevm::VMPool> = RefCell::new(fusevm::VMPool::new());
}
pub fn set_debug_mode(on: bool) {
DEBUG_MODE.with(|d| d.set(on));
VM_POOL.with(|p| *p.borrow_mut() = fusevm::VMPool::new());
}
fn run_chunk_on(chunk: Chunk) -> Result<Value, String> {
run_chunk_capturing(chunk, false)
}
fn run_chunk_capturing(chunk: Chunk, capture: bool) -> Result<Value, String> {
let lines: std::sync::Arc<[u32]> = chunk.lines.as_slice().into();
let (mut vm, fresh) = VM_POOL.with(|p| {
let mut pool = p.borrow_mut();
let fresh = pool.is_empty();
(pool.acquire(chunk), fresh)
});
if fresh {
crate::builtins::install(&mut vm);
if DEBUG_MODE.with(|d| d.get()) {
vm.set_extension_handler(Box::new(|vm, id, _| {
crate::dap::on_ext(vm, id);
}));
} else {
vm.enable_tracing_jit();
}
}
vm.set_sited_numeric_hook(std::sync::Arc::new(move |call| {
crate::builtins::numeric_hook_sited(call, &lines)
}));
let outcome = vm.run();
let err = with_host(|h| h.take_error());
let result = match (&err, &outcome) {
(Some(_), _) => None,
(None, VMResult::Ok(v)) => Some(Ok(v.clone())),
(None, VMResult::Halted) => Some(Ok(vm.stack.last().cloned().unwrap_or(Value::Undef))),
(None, VMResult::Error(_)) if unwinding() => Some(Ok(Value::Undef)),
(None, VMResult::Error(e)) => Some(Err(e.clone())),
};
if capture {
let slots = vm
.frames
.first()
.map(|f| f.slots.clone())
.unwrap_or_default();
with_host(|h| h.main_frame_slots = slots);
}
VM_POOL.with(|p| p.borrow_mut().release(vm));
match (err, result) {
(Some(e), _) => Err(e),
(None, Some(r)) => r,
(None, None) => unreachable!("result is set whenever there is no host error"),
}
}
pub fn run_main(chunk: Chunk) -> Result<Value, String> {
let r = run_chunk_capturing(chunk, true);
drain_error_handlers();
with_host(|h| h.signal.take());
if let Some(mut exc) = with_host(|h| h.pending_throw.take()) {
if let Some(handler) = with_host(|h| h.user_exception_handler()) {
with_host(|h| {
if let Some(g) = h.scopes.first_mut() {
g.internal = true;
}
});
let _ = call_value(handler, vec![exc.clone()]);
with_host(|h| h.signal.take());
match with_host(|h| h.pending_throw.take()) {
Some(next) => exc = next,
None => {
return Ok(Value::Undef);
}
}
}
return Err(report_uncaught(exc));
}
r
}
pub fn throwable_string(this: &Value) -> Result<Value, String> {
let mut out = String::new();
let mut exc = this.clone();
while let Some(class) = with_host(|h| {
h.object_class(&exc)
.filter(|c| h.class_is_a_pub(c, "Exception") || h.class_is_a_pub(c, "Error"))
}) {
let (message, file, line) = with_host(|h| {
(
h.to_str(&h.prop_get(&exc, "message")),
h.to_str(&h.prop_get(&exc, "file")),
h.prop_get(&exc, "line").to_int(),
)
});
let trace = call_method(&class, "getTraceAsString", Some(exc.clone()), Vec::new())?;
let trace = match trace {
Value::Str(s) if !s.is_empty() => s.to_string(),
_ => "#0 {main}\n".to_string(),
};
let message = if (class.eq_ignore_ascii_case("TypeError")
|| class.eq_ignore_ascii_case("ArgumentCountError"))
&& message.contains(", called in ")
{
format!("{message} and defined")
} else {
message
};
let name = display_class(&class).to_string();
let next = if out.is_empty() { "" } else { "\n\nNext " };
out = if message.is_empty() {
format!("{name} in {file}:{line}\nStack trace:\n{trace}{next}{out}")
} else {
format!("{name}: {message} in {file}:{line}\nStack trace:\n{trace}{next}{out}")
};
exc = with_host(|h| h.prop_get(&exc, "previous"));
}
Ok(Value::str(out))
}
fn report_uncaught(exc: Value) -> String {
{
let parse = with_host(|h| {
h.object_class(&exc)
.is_some_and(|c| c.eq_ignore_ascii_case("ParseError"))
.then(|| {
format!(
"{} in {} on line {}",
h.to_str(&h.prop_get(&exc, "message")),
h.to_str(&h.prop_get(&exc, "file")),
h.prop_get(&exc, "line").to_int()
)
})
});
if let Some(body) = parse {
with_host(|h| h.fatal("Parse error", &body));
return format!("Parse error: {body}");
}
let class = with_host(|h| h.object_class(&exc)).unwrap_or_else(|| "Exception".to_string());
with_host(|h| {
if let Some(g) = h.scopes.first_mut() {
g.internal = true;
}
});
let r = call_method(&class, "__toString", Some(exc.clone()), Vec::new());
if let Some(inner) = with_host(|h| h.pending_throw.take()) {
return report_uncaught(inner);
}
let str = r.map(|v| with_host(|h| h.to_str(&v))).unwrap_or_default();
let body = with_host(|h| {
let file = h.to_str(&h.prop_get(&exc, "file"));
let line = h.prop_get(&exc, "line").to_int();
format!("Uncaught {str}\n thrown in {file} on line {line}")
});
with_host(|h| h.fatal("Fatal error", &body));
format!("Fatal error: {body}")
}
}
pub fn to_str_ext(v: &Value) -> String {
let class = with_host(|h| {
h.object_class(v)
.filter(|c| h.class_has_method(c, "__tostring"))
});
let Some(class) = class else {
if let Some(class) = with_host(|h| h.instance_class(v)) {
let msg = format!("Object of class {class} could not be converted to string");
if let Ok(exc) = new_object("Error", vec![Value::str(msg)]) {
set_pending_throw(exc);
}
return String::new();
}
return with_host(|h| h.to_str_diag(v));
};
match call_method(&class, "__toString", Some(v.clone()), Vec::new()) {
Ok(r) => with_host(|h| h.to_str(&r)),
Err(_) => String::new(),
}
}
pub fn call_function(name: &str, args: Vec<Value>) -> Result<Value, String> {
call_function_dispatched(name, args, Dispatch::Compiled)
}
#[derive(Clone, Copy, PartialEq)]
pub enum Dispatch {
Compiled,
Indirect,
CompiledInNamespace,
}
fn call_function_dispatched(name: &str, args: Vec<Value>, how: Dispatch) -> Result<Value, String> {
let how = if how == Dispatch::Compiled && name.starts_with('\\') {
Dispatch::CompiledInNamespace
} else {
how
};
let name = name.strip_prefix('\\').unwrap_or(name);
if name == "__rust_compile" {
let b64 = args.first().map(|v| v.to_str()).unwrap_or_default();
return fusevm::ffi::compile_and_register(&b64).map(|_| Value::Undef);
}
let def = with_host(|h| h.functions.get(&name.to_ascii_lowercase()).cloned());
if def.is_none() && fusevm::ffi::is_registered(name) {
if let Some(r) = fusevm::ffi::try_call(name, &args) {
return r;
}
}
if let Some(def) = def {
return invoke_with_locals(
def.declared.as_deref().unwrap_or(name),
Signature {
params: &def.params,
ret: def.ret.as_ref(),
deprecated: def.deprecated.as_ref(),
},
def.chunk,
Vec::new(),
args,
Vec::new(),
def.is_generator,
&def.locals,
);
}
if !name.starts_with("__") && !crate::stdlib::callable::dispatches(name) {
let message = format!("Call to undefined function {name}()");
set_pending_throw(new_object("Error", vec![Value::str(message)])?);
return Ok(Value::Undef);
}
match call_library_throwing(&crate::argsig::lower_name(name), args, how) {
Ok(Value::Str(s)) if crate::bytes::has_raw(&s) => {
Ok(Value::str(crate::bytes::canonical(s.as_str().to_string())))
}
other => other,
}
}
fn throw_from_internal_typed(name: &str, args: &[Value], e: String) -> Result<Value, String> {
match crate::builtins::untag_throw(&e) {
Some((class, message)) => throw_from_internal(name, args, class, message),
None => Err(e),
}
}
fn compiles_to_an_opcode(name: &str, argc: usize) -> bool {
match name {
"strlen" | "count" | "sizeof" | "get_class" => argc == 1,
"array_key_exists" | "call_user_func_array" => argc == 2,
"call_user_func" => argc >= 1,
_ => false,
}
}
fn throw_frameless_typed(e: &str) -> Result<Value, String> {
match crate::builtins::untag_throw(e) {
Some((class, message)) => {
let exc = new_object(class, vec![Value::str(message.to_string())])?;
set_pending_throw(exc);
Ok(Value::Undef)
}
None => Err(e.to_string()),
}
}
pub(crate) const CALLS_BACK: &[&str] = &[
"array_map",
"array_filter",
"array_reduce",
"array_walk",
"array_walk_recursive",
"array_find",
"array_find_key",
"array_any",
"array_all",
"array_udiff",
"array_uintersect",
"array_diff_ukey",
"array_intersect_ukey",
"array_diff_uassoc",
"array_intersect_uassoc",
"array_udiff_assoc",
"array_uintersect_assoc",
"array_udiff_uassoc",
"array_uintersect_uassoc",
"ob_flush",
"ob_clean",
"ob_end_flush",
"ob_end_clean",
"ob_get_flush",
"ob_get_clean",
"usort",
"uasort",
"uksort",
"preg_replace_callback",
"preg_replace_callback_array",
"iterator_apply",
"iterator_to_array",
"iterator_count",
];
fn calls_back(name: &str) -> bool {
CALLS_BACK.contains(&name)
}
fn call_library_throwing(name: &str, args: Vec<Value>, how: Dispatch) -> Result<Value, String> {
let opcode = how == Dispatch::Compiled && compiles_to_an_opcode(name, args.len());
static NOCHECK: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
let nocheck = *NOCHECK.get_or_init(|| std::env::var_os("PHPLANG_NOCHECK").is_some());
let checked = if nocheck {
Ok(())
} else {
crate::argsig::check_args(
name,
&args,
how != Dispatch::Indirect && with_host(|h| h.strict_types()),
)
};
if let Err(e) = checked {
return if opcode {
throw_frameless_typed(&e)
} else {
let arity = crate::builtins::untag_throw(&e)
.is_some_and(|(class, _)| class == "ArgumentCountError");
let targs = if arity {
std::borrow::Cow::Borrowed(&args[..])
} else {
crate::argtypes::trace_args(name, &args)
};
throw_from_internal_typed(name, &targs, e)
};
}
let framed = calls_back(name);
if framed {
with_host(|h| {
let line = h.cur_frame_line();
let argsarr = h.new_array();
for a in &args {
h.arr_push_auto(&argsarr, a.clone());
}
h.push_internal_frame(name, line, argsarr);
});
}
let out = crate::builtins::call_library(name, &args);
if framed {
with_host(PhpHost::pop_internal_frame);
}
match out {
Err(e) => {
let targs = crate::argtypes::trace_args(name, &args);
if let Some((class, message)) = crate::builtins::untag_bare_throw(&e) {
let exc = new_object(class, vec![Value::str(message.to_string())])?;
set_pending_throw(exc);
return Ok(Value::Undef);
}
if let Some(message) = crate::builtins::untag_fatal(&e) {
return Err(fatal_from_internal(name, &targs, message));
}
if let Some((class, code, message)) = crate::builtins::untag_throw_code(&e) {
return throw_from_internal_args(
name,
&targs,
class,
vec![Value::str(message.to_string()), Value::int(code)],
);
}
if opcode {
return throw_frameless_typed(&e);
}
match crate::builtins::untag_throw(&e) {
Some((class, message)) => throw_from_internal(name, &targs, class, message),
None => Err(e),
}
}
ok => ok,
}
}
pub fn call_function_named(
name: &str,
args: Vec<Value>,
named: Vec<(String, Value)>,
) -> Result<Value, String> {
let name = name.strip_prefix('\\').unwrap_or(name);
let def = with_host(|h| h.functions.get(&name.to_ascii_lowercase()).cloned());
if let Some(def) = def {
return invoke_with_locals(
def.declared.as_deref().unwrap_or(name),
Signature {
params: &def.params,
ret: def.ret.as_ref(),
deprecated: def.deprecated.as_ref(),
},
def.chunk,
Vec::new(),
args,
named,
def.is_generator,
&def.locals,
);
}
let lname = crate::argsig::lower_name(name);
let name = lname.as_ref();
if crate::argsig::sig_of(name).is_some() {
return match crate::argsig::bind_named(name, args, named) {
Err(e) => match crate::builtins::untag_bare_throw(&e) {
Some((class, message)) => {
let exc = new_object(class, vec![Value::str(message.to_string())])?;
set_pending_throw(exc);
Ok(Value::Undef)
}
None => Err(e),
},
Ok(bound) => {
let mut shown = bound.shown;
let refusal = bound.refusal.or_else(|| {
bound.unplaced_name.then(|| {
let head = crate::argsig::zpp_head_len(name).min(bound.args.len());
let conv = crate::argtypes::trace_args(name, &bound.args[..head]);
for (slot, v) in shown.iter_mut().zip(conv.iter()) {
slot.1 = v.clone();
}
crate::argsig::refuse_unplaced(name, &bound.args)
})
});
match refusal {
Some(e) => throw_from_internal_named(name, &shown, e),
None => call_function(name, bound.args),
}
}
};
}
let mut all = args;
all.extend(named.into_iter().map(|(_, v)| v));
call_function(name, all)
}
fn throw_from_internal_named(
func: &str,
shown: &[(Option<String>, Value)],
e: String,
) -> Result<Value, String> {
let Some((class, message)) = crate::builtins::untag_throw(&e) else {
return Err(e);
};
let (class, message) = (class.to_string(), message.to_string());
with_host(|h| {
let line = h.cur_frame_line();
h.scopes.push(Scope {
name: Some(func.to_string()),
line,
internal: true,
..Scope::default()
});
let argsarr = h.new_array();
for (name, v) in shown {
match name {
Some(n) => h.arr_set_key(&argsarr, &Value::str(n.clone()), v.clone()),
None => h.arr_push_auto(&argsarr, v.clone()),
}
}
h.set_var("@args", argsarr);
});
let exc = new_object(&class, vec![Value::str(message)])?;
with_host(|h| {
h.scopes.pop();
});
set_pending_throw(exc);
Ok(Value::Undef)
}
#[allow(clippy::too_many_arguments)]
fn display_frame(frame: &str) -> String {
match frame.split_once("::") {
Some((cls, rest)) => {
let shown = with_host(|h| h.class_display_name(&cls.to_ascii_lowercase()));
format!("{shown}::{rest}")
}
None => frame.to_string(),
}
}
type ArgCheck = Result<Option<(Vec<Value>, Vec<(String, Value)>)>, String>;
fn check_call_shape(
frame: &str,
params: &[Param],
args: &[Value],
named: &[(String, Value)],
) -> Result<bool, String> {
let called_with: Vec<Value> = args.to_vec();
let has_variadic = params.iter().any(|p| p.variadic);
for (n, _) in named {
match params.iter().position(|p| !p.variadic && p.name == *n) {
Some(i) if i < args.len() => {
throw_from_internal(
frame,
&called_with,
"Error",
&format!("Named parameter ${n} overwrites previous argument"),
)?;
return Ok(false);
}
Some(_) => {}
None if !has_variadic => {
throw_from_internal(
frame,
&called_with,
"Error",
&format!("Unknown named parameter ${n}"),
)?;
return Ok(false);
}
None => {}
}
}
let required = params
.iter()
.filter(|p| !p.variadic && p.default.is_none())
.count();
if named.is_empty() && is_prelude_frame(frame) {
let declared = params.iter().filter(|p| !p.variadic).count();
let passed = args.len();
if passed < required || (!has_variadic && passed > declared) {
let (bound, n) = if required == declared && !has_variadic {
("exactly", required)
} else if passed < required {
("at least", required)
} else {
("at most", declared)
};
let s = if n == 1 { "" } else { "s" };
throw_from_callee(
frame,
&called_with,
"ArgumentCountError",
&format!(
"{}() expects {bound} {n} argument{s}, {passed} given",
callee_shown(frame)
),
)?;
return Ok(false);
}
}
let unfilled = params.iter().enumerate().find(|(i, p)| {
!p.variadic
&& p.default.is_none()
&& *i >= args.len()
&& !named.iter().any(|(n, _)| *n == p.name)
});
let Some((i, p)) = unfilled else {
return Ok(true);
};
let shown = callee_shown(frame);
let reached = params
.iter()
.enumerate()
.filter(|(_, p)| named.iter().any(|(n, _)| *n == p.name))
.map(|(j, _)| j + 1)
.chain(std::iter::once(args.len()))
.max()
.unwrap_or(0);
let placed: Vec<Value> = (0..reached)
.map(|j| match args.get(j) {
Some(v) => v.clone(),
None => named
.iter()
.find(|(n, _)| *n == params[j].name)
.map_or(Value::Undef, |(_, v)| v.clone()),
})
.collect();
if i < reached {
let argno = i + 1;
throw_at_param(
frame,
&placed,
"ArgumentCountError",
&format!("{shown}(): Argument #{argno} (${}) not passed", p.name),
p.line,
)?;
return Ok(false);
}
let declared = params.iter().filter(|p| !p.variadic).count();
let bound = if required == declared {
"exactly"
} else {
"at least"
};
let passed = args.len() + named.len();
let (file, line) = with_host(|h| (h.current_file().to_string(), h.cur_frame_line()));
throw_at_param(
frame,
&placed,
"ArgumentCountError",
&format!(
"Too few arguments to function {shown}(), {passed} passed in {file} \
on line {line} and {bound} {required} expected"
),
p.line,
)?;
Ok(false)
}
fn check_arg_types(
frame: &str,
params: &[Param],
args: Vec<Value>,
named: Vec<(String, Value)>,
) -> ArgCheck {
if params.iter().all(|p| p.ty.is_none()) {
return Ok(Some((args, named)));
}
let scope = TypeScope::of_frame(frame, None);
let called_with = args.clone();
let mut out = Vec::with_capacity(args.len());
for (i, a) in args.into_iter().enumerate() {
let p = params
.get(i)
.or_else(|| params.last().filter(|p| p.variadic));
match coerce_arg(p, a, &scope)? {
Ok(v) => out.push(v),
Err(given) => {
arg_type_error(frame, &called_with, p, i + 1, &given)?;
return Ok(None);
}
}
}
let mut nout = Vec::with_capacity(named.len());
for (n, v) in named {
let pos = params.iter().position(|p| !p.variadic && p.name == n);
let p = pos.map(|i| ¶ms[i]);
match coerce_arg(p, v, &scope)? {
Ok(v) => nout.push((n, v)),
Err(given) => {
arg_type_error(frame, &called_with, p, pos.map_or(0, |i| i + 1), &given)?;
return Ok(None);
}
}
}
Ok(Some((out, nout)))
}
#[allow(clippy::type_complexity)]
fn coerce_arg(
p: Option<&Param>,
v: Value,
scope: &TypeScope,
) -> Result<Result<Value, String>, String> {
let Some(p) = p else { return Ok(Ok(v)) };
let Some(ty) = &p.ty else { return Ok(Ok(v)) };
let ty = ty.clone();
if p.by_ref {
let line = p.line;
let (slot, cur) = with_host(|h| {
let slot = h.ref_slot_of_value(&v);
let cur = match slot {
Some(s) => h.ref_cell_value(s),
None => v.clone(),
};
(slot, cur)
});
let saved = warn_line();
set_warn_line(line);
let r = verify_type(cur, &ty, scope);
set_warn_line(saved);
return Ok(with_host(|h| {
r.map(|converted| match slot {
Some(s) => {
h.ref_cell_set(s, converted);
v
}
None => converted,
})
}));
}
let saved = warn_line();
set_warn_line(p.line);
let r = verify_type(v, &ty, scope);
set_warn_line(saved);
Ok(r)
}
fn throw_at_param(
frame: &str,
called_with: &[Value],
class: &str,
msg: &str,
decl_line: u32,
) -> Result<Value, String> {
let r = throw_from_callee(frame, called_with, class, msg);
if is_prelude_frame(frame) {
return r;
}
with_host(|h| {
if let Some(exc) = h.pending_throw.clone() {
h.prop_set(&exc, "line", Value::int(decl_line as i64));
}
});
r
}
fn is_prelude_frame(frame: &str) -> bool {
frame
.split_once("::")
.is_some_and(|(c, _)| crate::prelude_type(&c.to_ascii_lowercase()).is_some())
}
fn arg_type_error(
frame: &str,
called_with: &[Value],
p: Option<&Param>,
pos: usize,
given: &str,
) -> Result<Value, String> {
let (name, ty) = match p {
Some(p) if p.variadic => (String::new(), p.ty.clone()),
Some(p) => (format!(" (${})", p.name), p.ty.clone()),
None => (String::new(), None),
};
let rendered = ty
.map(|t| render_declared(&t, frame, None))
.unwrap_or_default();
let (file, line) = with_host(|h| (h.current_file().to_string(), h.cur_frame_line()));
let shown = callee_shown(frame);
let site = if is_prelude_frame(frame) {
String::new()
} else {
format!(", called in {file} on line {line}")
};
let msg = &format!(
"{shown}(): Argument #{pos}{name} must be of type {rendered}, {given} given{site}"
);
match p {
Some(p) => throw_at_param(frame, called_with, "TypeError", msg, p.line),
None => throw_from_callee(frame, called_with, "TypeError", msg),
}
}
fn check_ret_type(
frame: &str,
ret: Option<&TypeHint>,
called_with: &[Value],
v: Value,
static_class: Option<String>,
) -> Result<Value, String> {
let Some(ty) = ret else { return Ok(v) };
if ty
.parts
.iter()
.any(|p| p.eq_ignore_ascii_case("void") || p.eq_ignore_ascii_case("never"))
{
return Ok(v);
}
let ty = ty.clone();
let scope = TypeScope::of_frame(frame, static_class);
let scope_static = scope
.static_class
.clone()
.or_else(|| scope.self_class.clone());
match verify_type(v, &ty, &scope) {
Ok(nv) => Ok(nv),
Err(given) => throw_from_callee(
frame,
called_with,
"TypeError",
&format!(
"{}(): Return value must be of type {}, {given} returned",
callee_shown(frame),
render_declared(&ty, frame, scope_static.as_deref())
),
),
}
}
struct Signature<'a> {
params: &'a [Param],
ret: Option<&'a TypeHint>,
deprecated: Option<&'a crate::ast::Deprecation>,
}
fn invoke(
frame: &str,
sig: Signature<'_>,
body: Chunk,
pre: Vec<(String, Value)>,
args: Vec<Value>,
named: Vec<(String, Value)>,
is_generator: bool,
) -> Result<Value, String> {
invoke_with_locals(frame, sig, body, pre, args, named, is_generator, &[])
}
#[allow(clippy::too_many_arguments)]
fn invoke_with_locals(
frame: &str,
sig: Signature<'_>,
body: Chunk,
pre: Vec<(String, Value)>,
args: Vec<Value>,
named: Vec<(String, Value)>,
is_generator: bool,
locals: &[String],
) -> Result<Value, String> {
let Signature {
params,
ret,
deprecated,
} = sig;
if let Some(d) = deprecated {
raise_deprecated_call(frame, d);
drain_error_handlers();
if with_host(|h| h.pending_throw.is_some()) {
return Ok(Value::Undef);
}
}
let ctx = CalleeCtx {
this: pre
.iter()
.find(|(k, _)| k == "this")
.map(|(_, v)| v.clone()),
site: with_host(|h| h.pending_closure_site.clone()),
};
let checked = with_callee(&ctx, || check_call_shape(frame, params, &args, &named));
if !checked? {
return Ok(Value::Undef);
}
let typed = with_callee(&ctx, || check_arg_types(frame, params, args, named));
let Some((args, named)) = typed? else {
return Ok(Value::Undef);
};
let ret_args: Vec<Value> = match ret {
Some(_) => args.clone(),
None => Vec::new(),
};
let file = (!body.source.is_empty()).then(|| std::sync::Arc::from(body.source.as_str()));
let bound = with_host(|h| {
let scope = Scope {
name: Some(frame.to_string()),
static_class: h.lsb_take(),
closure_site: h.closure_site_take(),
transparent: std::mem::take(&mut h.pending_transparent)
|| params.first().is_some_and(|p| p.name == FCC_PARAM),
..Scope::default()
};
let scope = Scope { file, ..scope };
h.scopes.push(scope);
h.seed_slots(locals);
for (k, v) in pre {
match v {
Value::Obj(id) => match h.objs.get(id as usize) {
Some(PhpObj::Ref { slot }) => {
let slot = *slot;
h.bind_ref_slot(&k, slot);
}
_ => h.set_var(&k, v),
},
_ => h.set_var(&k, v),
}
}
let mut bound = vec![false; params.len()];
let mut ai = 0;
for (i, p) in params.iter().enumerate() {
if p.variadic {
let arr = h.new_array();
while ai < args.len() {
h.arr_push_auto(&arr, args[ai].clone());
ai += 1;
}
h.set_var(&p.name, arr);
bound[i] = true;
} else if ai < args.len() {
match (p.by_ref, &args[ai]) {
(true, Value::Obj(id))
if matches!(h.objs.get(*id as usize), Some(PhpObj::Ref { .. })) =>
{
let Some(PhpObj::Ref { slot }) = h.objs.get(*id as usize) else {
unreachable!("guarded by the match arm above")
};
let slot = *slot;
h.bind_ref_slot(&p.name, slot);
}
(true, a) => h.set_var(&p.name, a.clone()),
(false, a) => {
let a = match a {
Value::Obj(id) => match h.objs.get(*id as usize) {
Some(PhpObj::Ref { slot }) => {
let slot = *slot;
h.ref_cell_value(slot)
}
_ => a.clone(),
},
_ => a.clone(),
};
let copied = h.copy_on_assign(a);
h.set_var(&p.name, copied);
}
}
bound[i] = true;
ai += 1;
}
}
for (n, v) in &named {
if let Some(i) = params.iter().position(|p| !p.variadic && p.name == *n) {
let v = if params[i].by_ref {
v.clone()
} else {
h.copy_on_assign(v.clone())
};
h.set_var(¶ms[i].name, v);
bound[i] = true;
} else if let Some(vi) = params.iter().position(|p| p.variadic) {
let arr = h.get_var(¶ms[vi].name);
h.arr_set_key(&arr, &Value::str(n.clone()), v.clone());
}
}
for (i, p) in params.iter().enumerate() {
if !bound[i] && !p.variadic && p.default.is_none() {
h.set_var(&p.name, Value::Undef);
bound[i] = true;
}
}
let n_decl = params.iter().filter(|p| !p.variadic).count();
let mut argc = args.len();
for (n, _) in &named {
if let Some(i) = params.iter().position(|p| !p.variadic && p.name == *n) {
argc = argc.max(i + 1);
}
}
let argsarr = h.new_array();
let namesarr = h.new_array();
for i in 0..argc {
let declared = params.get(i).filter(|_| i < n_decl);
let (name, value) = match declared {
Some(p) => (Value::str(p.name.clone()), Value::Undef),
None => (Value::Undef, args.get(i).cloned().unwrap_or(Value::Undef)),
};
h.arr_push_auto(&namesarr, name);
h.arr_push_auto(&argsarr, value);
}
h.set_var("@args", argsarr);
h.set_var("@argnames", namesarr);
bound
});
for (i, p) in params.iter().enumerate() {
if p.variadic || bound[i] {
continue;
}
if let Some(chunk) = &p.default {
match run_chunk_on(chunk.clone()) {
Ok(v) => with_host(|h| h.set_var(&p.name, v)),
Err(e) => {
with_host(|h| {
h.scopes.pop();
});
return Err(e);
}
}
}
}
if is_generator {
let frame_scope = with_host(|h| h.scopes.pop().expect("generator call frame"));
return Ok(make_generator(body, frame_scope));
}
let r = run_chunk_on(body);
let sig = with_host(|h| {
let vals = params
.iter()
.map(|p| {
if p.by_ref {
h.get_var(&p.name)
} else {
Value::Undef
}
})
.collect();
h.byref_out_set(vals, params.iter().map(|p| p.by_ref).collect());
let static_class = h.scopes.pop().and_then(|s| s.static_class);
(h.signal.take(), static_class)
});
let (sig, static_class) = sig;
match sig {
Some(Signal::Return(v)) => with_callee(&ctx, || {
check_ret_type(frame, ret, &ret_args, v, static_class)
}),
Some(Signal::Break(_)) | Some(Signal::Continue(_)) | None => r.map(|_| Value::Undef),
}
}
fn invoke_closure(
cc: ClosureCall,
args: Vec<Value>,
named: Vec<(String, Value)>,
) -> Result<Value, String> {
let frame = match &cc.scope {
Some(s) => format!("{s}::{{closure}}"),
None => "{closure}".to_string(),
};
let mut pre = cc.captured;
if let Some(t) = cc.bound_this {
pre.retain(|(k, _)| k != "this");
pre.push(("this".to_string(), t));
}
with_host(|h| h.closure_site_for_next_call(cc.site));
with_host(|h| h.pending_lsb = cc.called_scope);
invoke(
&frame,
Signature {
params: &cc.params,
ret: cc.ret.as_ref(),
deprecated: None,
},
cc.chunk,
pre,
args,
named,
cc.is_generator,
)
}
fn not_callable(v: &Value) -> String {
let msg = with_host(|h| {
if h.is_array(v) {
"Array callback must have exactly two elements".to_string()
} else if h.is_object(v) {
let class = h.object_class(v).unwrap_or_else(|| "stdClass".to_string());
format!("Object of type {class} is not callable")
} else {
let t = match v {
Value::Bool(_) => "bool".to_string(),
other => h.type_name_for_error(other),
};
format!("Value of type {t} is not callable")
}
});
crate::builtins::throws_bare("Error", msg)
}
pub(crate) fn callable_method(callee: &Value) -> Option<(String, String, Option<Value>)> {
if with_host(|h| h.is_array(callee)) {
let pairs = with_host(|h| h.array_pairs(callee)).unwrap_or_default();
if pairs.len() != 2 {
return None;
}
let target = pairs[0].1.clone();
let method = with_host(|h| h.to_str(&pairs[1].1));
return match with_host(|h| h.object_class(&target)) {
Some(class) => Some((class, method, Some(target))),
None => Some((
anchored_class(&with_host(|h| h.to_str(&target))),
method,
None,
)),
};
}
if with_host(|h| h.is_object(callee)) {
let class = with_host(|h| h.object_class(callee))?;
if with_host(|h| h.class_has_method(&class, "__invoke")) {
return Some((class, "__invoke".to_string(), Some(callee.clone())));
}
return None;
}
if let Value::Str(s) = callee {
if let Some((class, method)) = s.as_str().split_once("::") {
return Some((anchored_class(class), method.to_string(), None));
}
}
None
}
pub(crate) fn callvalue_refusal(callee: &Value) -> Option<String> {
if with_host(|h| h.closure_of(callee)).is_some() {
return None;
}
if let Some((class, method, this)) = callable_method(callee) {
return callable_method_refusal(&class, &method, &this);
}
match callee {
Value::Str(s) => (!crate::stdlib::callable::function_resolves(s)).then(|| {
crate::builtins::throws_bare("Error", format!("Call to undefined function {s}()"))
}),
other => Some(not_callable(other)),
}
}
fn callable_method_refusal(class: &str, method: &str, this: &Option<Value>) -> Option<String> {
if class.eq_ignore_ascii_case("Closure") {
return None;
}
if !with_host(|h| h.class_exists(class)) {
if with_host(|h| h.class_has_method(class, method)) {
return None;
}
return Some(crate::builtins::throws_bare(
"Error",
format!("Class \"{}\" not found", display_class(class)),
));
}
if with_host(|h| h.is_enum_class(class))
&& matches!(
method.to_ascii_lowercase().as_str(),
"cases" | "from" | "tryfrom"
)
{
return None;
}
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)));
match with_host(|h| h.method_dispatch(class, method, has_this)) {
MethodDispatch::Direct | MethodDispatch::Magic => None,
MethodDispatch::Denied(msg) => Some(crate::builtins::throws_bare("Error", msg)),
MethodDispatch::Undefined => Some(crate::builtins::throws_bare(
"Error",
format!(
"Call to undefined method {}::{method}()",
display_class(class)
),
)),
}
}
pub fn fcc_refusal(callable: &Value, instance: bool) -> Option<String> {
if instance {
let pairs = with_host(|h| h.array_pairs(callable)).unwrap_or_default();
if let [(_, recv), (_, name)] = pairs.as_slice() {
if !with_host(|h| h.is_object_value(recv)) {
let method = with_host(|h| h.to_str(name));
let ty = with_host(|h| crate::builtins::receiver_type_name(h, recv));
return Some(crate::builtins::throws_bare(
"Error",
format!("Call to a member function {method}() on {ty}"),
));
}
}
}
callvalue_refusal(callable)
}
impl PhpHost {
fn same_callable(&self, a: &Value, b: &Value) -> bool {
match (a, b) {
(Value::Str(x), Value::Str(y)) => unanchored(x).eq_ignore_ascii_case(unanchored(y)),
(Value::Obj(x), Value::Obj(y)) if x == y => true,
_ if self.is_array(a) && self.is_array(b) => {
let (pa, pb) = (
self.array_pairs(a).unwrap_or_default(),
self.array_pairs(b).unwrap_or_default(),
);
pa.len() == 2
&& pb.len() == 2
&& self
.to_str(&pa[1].1)
.eq_ignore_ascii_case(&self.to_str(&pb[1].1))
&& match (&pa[0].1, &pb[0].1) {
(Value::Obj(x), Value::Obj(y)) if self.is_object(&pa[0].1) => x == y,
(x, y) => unanchored(&self.to_str(x))
.eq_ignore_ascii_case(unanchored(&self.to_str(y))),
}
}
_ => false,
}
}
pub fn autoload_register(&mut self, callback: Value, prepend: bool) {
if self
.autoloaders
.iter()
.any(|l| self.same_callable(l, &callback))
{
return;
}
if prepend {
self.autoloaders.insert(0, callback);
} else {
self.autoloaders.push(callback);
}
}
pub fn autoload_unregister(&mut self, callback: &Value) -> bool {
match self
.autoloaders
.iter()
.position(|l| self.same_callable(l, callback))
{
Some(i) => {
self.autoloaders.remove(i);
true
}
None => false,
}
}
pub fn autoload_functions(&self) -> Vec<Value> {
self.autoloaders.clone()
}
}
fn is_valid_class_name(name: &str) -> bool {
!name.is_empty()
&& name
.bytes()
.all(|c| c.is_ascii_alphanumeric() || c == b'_' || c == b'\\' || c >= 0x80)
}
pub fn autoload(class: &str) -> Result<bool, String> {
let name = unanchored(class);
let lname = name.to_ascii_lowercase();
let loaders = with_host(|h| {
if h.class_exists(name)
|| h.autoloaders.is_empty()
|| h.autoloading.contains(&lname)
|| !is_valid_class_name(name)
{
None
} else {
h.autoloading.insert(lname.clone());
Some(h.autoloaders.clone())
}
});
let Some(loaders) = loaders else {
return Ok(with_host(|h| h.class_exists(name)));
};
let mut out = Ok(());
for loader in loaders {
if let Err(e) = call_value(loader, vec![Value::str(name.to_string())]) {
out = Err(e);
break;
}
if unwinding() || with_host(|h| h.class_exists(name)) {
break;
}
}
with_host(|h| h.autoloading.remove(&lname));
out.map(|()| with_host(|h| h.class_exists(name)))
}
fn autoload_first(class: &str) -> Result<Option<Value>, String> {
if ["self", "parent", "static"]
.iter()
.any(|r| class.eq_ignore_ascii_case(r))
{
return Ok(None);
}
class_known(class)?;
Ok(unwinding().then_some(Value::Undef))
}
type DebugParam = (String, bool, bool, bool);
fn debug_param_rows(params: &[DebugParam]) -> Vec<(String, &'static str)> {
let required = params
.iter()
.rposition(|(_, _, has_default, variadic)| !has_default && !variadic)
.map_or(0, |i| i + 1);
params
.iter()
.enumerate()
.map(|(i, (name, by_ref, ..))| {
let amp = if *by_ref { "&" } else { "" };
let req = if i < required {
"<required>"
} else {
"<optional>"
};
(format!("{amp}${name}"), req)
})
.collect()
}
pub fn generator_debug_info(v: &Value) -> Option<Value> {
with_host(|h| {
let id = h.gen_id(v)?;
let function = Value::str(h.generators[id as usize].function.clone());
let out = h.new_array();
h.arr_set_key(&out, &Value::str("function"), function);
Some(out)
})
}
pub fn closure_debug_info(v: &Value) -> Option<Value> {
struct Real {
name: String,
file: String,
line: i64,
statics: Vec<(String, Value)>,
}
let (real, fake_callee, this, params) = with_host(|h| {
let Some(PhpObj::Closure {
params,
chunk,
captured,
bound_this,
site,
..
}) = h.as_array(v)
else {
return None;
};
let fake = params.first().is_some_and(|p| p.name == FCC_PARAM)
|| captured.iter().any(|(n, _)| n == "@fcc");
let callee = fake
.then(|| captured.iter().find(|(n, _)| n.starts_with("@fcc")))
.flatten()
.map(|(_, c)| h.deref(c.clone()));
let real = (!fake).then(|| Real {
name: site
.as_ref()
.map_or_else(|| "{closure}".to_string(), |s| s.render(&h.script_name)),
file: if chunk.source.is_empty() {
h.script_name.clone()
} else {
chunk.source.clone()
},
line: match site {
Some(DeclSite::Closure(_, line)) => i64::from(*line),
_ => 0,
},
statics: captured
.iter()
.filter_map(|(n, v)| match n.strip_prefix("@static#") {
Some(key) => {
let name = key.split_once(':').map_or(key, |(_, name)| name);
Some((name.to_string(), h.deref(v.clone())))
}
None if n.starts_with(['@', '$']) || n == "this" => None,
None => Some((n.clone(), v.clone())),
})
.collect(),
});
let params: Vec<DebugParam> = params
.iter()
.map(|p| (p.name.clone(), p.by_ref, p.default.is_some(), p.variadic))
.collect();
Some((real, callee, bound_this.clone(), params))
})?;
let (function, this, params, fn_statics) = match fake_callee {
Some(callee) => {
let (function, bound, params, statics) = fcc_target(&callee);
(Some(function), bound.or(this), params, statics)
}
None => (None, this, params, Vec::new()),
};
let rows = debug_param_rows(¶ms);
Some(with_host(|h| {
let out = h.new_array();
let set = |h: &mut PhpHost, k: &str, val: Value| h.arr_set_key(&out, &Value::str(k), val);
match (&real, function) {
(Some(r), _) => {
set(h, "name", Value::str(r.name.clone()));
set(h, "file", Value::str(r.file.clone()));
set(h, "line", Value::int(r.line));
if !r.statics.is_empty() {
let st = h.new_array();
for (n, val) in &r.statics {
h.arr_set_key(&st, &Value::str(n.clone()), val.clone());
}
set(h, "static", st);
}
}
(None, Some(f)) => {
set(h, "function", Value::str(f));
if !fn_statics.is_empty() {
let st = h.new_array();
for (n, val) in &fn_statics {
h.arr_set_key(&st, &Value::str(n.clone()), val.clone());
}
set(h, "static", st);
}
}
(None, None) => {}
}
if let Some(t) = this {
set(h, "this", t);
}
if !rows.is_empty() {
let ps = h.new_array();
for (k, req) in rows {
h.arr_set_key(&ps, &Value::str(k), Value::str(req.to_string()));
}
set(h, "parameter", ps);
}
out
}))
}
pub fn defined_statics(statics: &[(String, Option<Chunk>)]) -> Vec<(String, Value)> {
statics
.iter()
.map(|(key, init)| {
let name = key
.split_once(':')
.map_or(key.as_str(), |(_, n)| n)
.to_string();
let held = with_host(|h| h.static_slots.get(key).map(|&s| h.ref_cells[s].clone()));
let v = match (held, init) {
(Some(v), _) => v,
(None, Some(chunk)) => run_chunk_on(chunk.clone()).unwrap_or(Value::Undef),
(None, None) => Value::Undef,
};
(name, v)
})
.collect()
}
pub fn function_statics(name: &str) -> Vec<(String, Value)> {
let lower = unanchored(name).to_ascii_lowercase();
let defs = with_host(|h| h.functions.get(&lower).map(|d| d.statics.clone()));
defs.map(|d| defined_statics(&d)).unwrap_or_default()
}
pub fn doc_comment(kind: &str, target: &Value, name: &str) -> Option<String> {
with_host(|h| match kind {
"closure" => match h.as_array(target) {
Some(PhpObj::Closure { doc, .. }) => doc.clone(),
_ => None,
},
"function" => {
let lower = unanchored(&h.to_str(target)).to_ascii_lowercase();
h.functions.get(&lower).and_then(|d| d.doc.clone())
}
"method" => h
.resolve_method(&h.to_str(target), &name.to_ascii_lowercase())
.and_then(|(_, d)| d.doc),
_ => {
let key = if kind == "class" {
"class".to_string()
} else {
format!("{kind}:{name}")
};
let mut pending = vec![h.to_str(target).to_ascii_lowercase()];
let mut seen = Vec::new();
while let Some(c) = pending.pop() {
if seen.contains(&c) {
continue;
}
let Some(def) = h.classes.get(&c) else {
continue;
};
if let Some((_, d)) = def.docs.iter().find(|(k, _)| *k == key) {
return Some(d.clone());
}
if kind == "class" {
return None;
}
pending.extend(def.interfaces.iter().rev().map(|i| i.to_ascii_lowercase()));
pending.extend(def.uses.iter().rev().map(|t| t.to_ascii_lowercase()));
pending.extend(def.parent.iter().map(|p| p.to_ascii_lowercase()));
seen.push(c);
}
None
}
})
}
pub fn decl_span(kind: &str, target: &Value, name: &str) -> Option<DeclSpan> {
with_host(|h| match kind {
"closure" => match h.as_array(target) {
Some(PhpObj::Closure { span, .. }) => span.clone(),
_ => None,
},
"function" => {
let lower = unanchored(&h.to_str(target)).to_ascii_lowercase();
h.functions.get(&lower).and_then(|d| d.span.clone())
}
"method" => h
.resolve_method(&h.to_str(target), &name.to_ascii_lowercase())
.and_then(|(_, d)| d.span),
_ => h
.classes
.get(&unanchored(&h.to_str(target)).to_ascii_lowercase())
.and_then(|d| d.span.clone()),
})
}
pub fn refl_fn_flags(kind: &str, target: &Value, name: &str) -> (bool, bool, bool) {
with_host(|h| {
if let Some(PhpObj::Closure { is_static, .. }) = h.as_array(target) {
return (false, false, *is_static);
}
let def = match kind {
"function" => {
let lower = unanchored(&h.to_str(target)).to_ascii_lowercase();
h.functions.get(&lower).cloned()
}
"method" => h
.resolve_method(&h.to_str(target), &name.to_ascii_lowercase())
.map(|(_, d)| d),
_ => None,
};
def.map_or((false, false, false), |d| {
(d.deprecated.is_some(), d.returns_ref, false)
})
})
}
pub fn attr_defs(kind: &str, target: &Value, name: &str) -> Option<(String, Vec<AttrDef>)> {
with_host(|h| match kind {
"closure" => match h.as_array(target) {
Some(PhpObj::Closure { attrs, scope, .. }) => {
Some((scope.clone().unwrap_or_default(), attrs.clone()))
}
_ => None,
},
"function" => {
let lower = unanchored(&h.to_str(target)).to_ascii_lowercase();
h.functions
.get(&lower)
.map(|d| (String::new(), d.attrs.clone()))
}
"method" => h
.resolve_method(&h.to_str(target), &name.to_ascii_lowercase())
.map(|(c, d)| (c, d.attrs)),
_ => {
let key = if kind == "class" {
"class".to_string()
} else {
format!("{kind}:{name}")
};
let mut pending = vec![h.to_str(target).to_ascii_lowercase()];
let mut seen = Vec::new();
while let Some(c) = pending.pop() {
if seen.contains(&c) {
continue;
}
let Some(def) = h.classes.get(&c) else {
continue;
};
let alt = format!("case:{name}");
let found = def
.attrs
.iter()
.find(|(k, _)| *k == key || (kind == "const" && *k == alt));
if let Some((_, a)) = found {
return Some((def.name.clone(), a.clone()));
}
if kind == "class" {
return Some((def.name.clone(), Vec::new()));
}
pending.extend(def.interfaces.iter().rev().map(|i| i.to_ascii_lowercase()));
pending.extend(def.parent.iter().map(|p| p.to_ascii_lowercase()));
seen.push(c);
}
None
}
})
}
pub fn method_statics(class: &str, method: &str) -> Vec<(String, Value)> {
let defs = with_host(|h| {
h.resolve_method(class, &method.to_ascii_lowercase())
.map(|(_, d)| d.statics)
});
defs.map(|d| defined_statics(&d)).unwrap_or_default()
}
type FccTarget = (String, Option<Value>, Vec<DebugParam>, Vec<(String, Value)>);
fn fcc_target(callee: &Value) -> FccTarget {
let user_params = |def: &FuncDef| -> Vec<DebugParam> {
def.params
.iter()
.map(|p| (p.name.clone(), p.by_ref, p.default.is_some(), p.variadic))
.collect()
};
if let Some((class, method, this)) = callable_method(callee) {
let found = with_host(|h| {
let declared = h.class_display_name(&class.to_ascii_lowercase());
let def = h.resolve_method(&class, &method).map(|(_, d)| d);
(declared, def)
});
let (declared, def) = found;
let params = def.as_ref().map(user_params).unwrap_or_default();
let statics = def.map(|d| defined_statics(&d.statics)).unwrap_or_default();
return (format!("{declared}::{method}"), this, params, statics);
}
let name = with_host(|h| h.to_str(callee));
let name = unanchored(&name).to_string();
if let Some(def) = with_host(|h| h.functions.get(&name.to_ascii_lowercase()).cloned()) {
let params = user_params(&def);
let statics = defined_statics(&def.statics);
return (def.declared.clone().unwrap_or(name), None, params, statics);
}
let params = crate::argsig::library_params(&name)
.unwrap_or_default()
.into_iter()
.map(|p| (p.name, p.by_ref, p.def.is_some(), p.variadic))
.collect();
(name.to_ascii_lowercase(), None, params, Vec::new())
}
pub fn class_known(class: &str) -> Result<bool, String> {
if with_host(|h| h.class_exists(class)) {
return Ok(true);
}
autoload(class)
}
pub fn call_value(callee: Value, args: Vec<Value>) -> Result<Value, String> {
if let Some(cc) = with_host(|h| h.closure_of(&callee)) {
return invoke_closure(cc, args, Vec::new());
}
if let Some((class, method, this)) = callable_method(&callee) {
if let Some(e) = callable_method_refusal(&class, &method, &this) {
return Err(e);
}
return call_method(&class, &method, this, args);
}
match callee {
Value::Str(s) => call_function_dispatched(&s, args, Dispatch::Indirect),
other => Err(not_callable(&other)),
}
}
pub fn call_value_named(
callee: Value,
args: Vec<Value>,
named: Vec<(String, Value)>,
) -> Result<Value, String> {
if let Some(cc) = with_host(|h| h.closure_of(&callee)) {
return invoke_closure(cc, args, named);
}
if let Some((class, method, this)) = callable_method(&callee) {
if let Some(e) = callable_method_refusal(&class, &method, &this) {
return Err(e);
}
return call_method_named(&class, &method, this, args, named);
}
match callee {
Value::Str(s) => call_function_named(&s, args, named),
other => Err(not_callable(&other)),
}
}
pub fn closure_bind(closure: &Value, obj: Value, scope: Option<Value>) -> Result<Value, String> {
let this = matches!(obj, Value::Obj(_)).then_some(obj.clone());
let Some(mut scope_class) = with_host(|h| resolve_bind_scope(h, closure, scope)) else {
return Ok(Value::Undef);
};
let refusal = with_host(|h| {
if this.is_some() && h.closure_is_static(closure) {
return Some(
"Cannot bind an instance to a static closure, this will be an error in PHP 9"
.to_string(),
);
}
let current = h.closure_scope(closure).map(|s| s.to_ascii_lowercase());
let internal = scope_class.as_deref().filter(|s| {
let lower = s.to_ascii_lowercase();
Some(&lower) != current.as_ref() && h.is_internal_class(&lower)
});
internal.map(|s| {
format!(
"Cannot bind closure to scope of internal class {s}, this will be an error in PHP 9"
)
})
});
if let Some(msg) = refusal {
with_host(|h| h.warn(msg));
return Ok(Value::Undef);
}
if scope_class.is_none() && this.is_some() {
scope_class = Some("Closure".to_string());
}
match with_host(|h| h.rebind_closure(closure, this, scope_class)) {
Some(v) => Ok(v),
None => Err("Closure::bind expects a Closure".to_string()),
}
}
fn resolve_bind_scope(
h: &mut PhpHost,
closure: &Value,
scope: Option<Value>,
) -> Option<Option<String>> {
let s = match scope {
None => return Some(h.closure_scope(closure)),
Some(Value::Undef) => return Some(None),
Some(o @ Value::Obj(_)) if h.is_object(&o) => return Some(h.object_class(&o)),
Some(other) => h.to_str(&other),
};
if s == "static" {
return Some(h.closure_scope(closure));
}
if !h.class_exists(&s) {
h.warn(format!("Class \"{s}\" not found"));
return None;
}
let lower = s.to_ascii_lowercase();
Some(Some(match h.classes.get(&lower) {
Some(d) => d.name.clone(),
None => builtin_type(&lower).map_or(s, |(n, ..)| n.to_string()),
}))
}
pub fn closure_call(closure: &Value, obj: Value, args: Vec<Value>) -> Result<Value, String> {
let bound = closure_bind(closure, obj.clone(), Some(obj))?;
if matches!(bound, Value::Undef) {
return Ok(Value::Undef);
}
call_value(bound, args)
}
pub fn call_closure_method(
closure: &Value,
method: &str,
args: Vec<Value>,
) -> Result<Value, String> {
let mut args = args;
match method.to_ascii_lowercase().as_str() {
"bindto" => {
let obj = if args.is_empty() {
Value::Undef
} else {
args.remove(0)
};
let scope = if args.is_empty() {
None
} else {
Some(args.remove(0))
};
closure_bind(closure, obj, scope)
}
"call" => {
let obj = if args.is_empty() {
Value::Undef
} else {
args.remove(0)
};
closure_call(closure, obj, args)
}
"__invoke" => call_value(closure.clone(), args),
other => Err(crate::builtins::throws_bare(
"Error",
format!("Call to undefined method Closure::{other}()"),
)),
}
}
const CLOSURE_METHODS: &[&str] = &["bindto", "call", "__invoke"];
const GENERATOR_METHODS: &[&str] = &[
"current",
"key",
"next",
"valid",
"rewind",
"send",
"throw",
"getreturn",
];
pub fn engine_method_refusal(recv: &Value, method: &str) -> Option<String> {
let (class, methods) = if with_host(|h| h.is_closure(recv)) {
("Closure", CLOSURE_METHODS)
} else if with_host(|h| h.is_generator_val(recv)) {
("Generator", GENERATOR_METHODS)
} else {
return None;
};
let lname = method.to_ascii_lowercase();
if methods.contains(&lname.as_str()) {
return None;
}
Some(crate::builtins::throws_bare(
"Error",
format!("Call to undefined method {class}::{method}()"),
))
}
fn seed_throwable(class: &str, obj: &Value) {
with_host(|h| {
let cl = class.to_ascii_lowercase();
if !h.class_is_a(&cl, "exception") && !h.class_is_a(&cl, "error") {
return;
}
let top = h.scopes.len() - 1;
let mut i = top;
while i > 0 && h.scopes[i].name.as_deref().is_some_and(is_prelude_frame) {
i -= 1;
}
let (file, line) = if i == top {
(h.current_file().to_string(), h.cur_frame_line() as i64)
} else {
(h.scope_file(i).to_string(), h.scopes[i].line as i64)
};
let trace = h.trace_array(false, false, 0);
h.prop_set(obj, "file", Value::str(file));
h.prop_set(obj, "line", Value::int(line));
h.prop_set(obj, "trace", trace);
});
}
fn sensitive_params(func: &str) -> &'static [usize] {
match func.to_ascii_lowercase().as_str() {
"hash_hmac" | "hash_hmac_file" => &[2], "hash_pbkdf2" => &[1], _ => &[],
}
}
pub fn throw_from_internal(
func: &str,
args: &[Value],
class: &str,
message: &str,
) -> Result<Value, String> {
throw_from_internal_args(func, args, class, vec![Value::str(message.to_string())])
}
pub fn fatal_from_internal(func: &str, args: &[Value], message: &str) -> String {
let body = with_host(|h| {
let line = h.cur_frame_line();
h.scopes.push(Scope {
name: Some(func.to_string()),
line,
internal: true,
..Scope::default()
});
let argsarr = h.new_array();
for a in args {
h.arr_push_auto(&argsarr, a.clone());
}
h.set_var("@args", argsarr);
let trace = h.backtrace();
h.scopes.pop();
let body = format!(
"{message} in {} on line {line}\nStack trace:\n{trace}",
h.current_file()
);
h.fatal("Fatal error", &body);
body
});
format!("Fatal error: {body}")
}
pub fn throw_from_internal_args(
func: &str,
args: &[Value],
class: &str,
ctor_args: Vec<Value>,
) -> Result<Value, String> {
let sensitive = sensitive_params(func);
with_host(|h| {
let line = h.cur_frame_line();
h.scopes.push(Scope {
name: Some(func.to_string()),
line,
internal: true,
..Scope::default()
});
let argsarr = h.new_array();
for (i, a) in args.iter().enumerate() {
if sensitive.contains(&i) {
let obj = h.objs.len() as u32;
h.objs.push(PhpObj::Object {
class: "SensitiveParameterValue".to_string(),
props: IndexMap::new(),
});
h.arr_push_auto(&argsarr, Value::Obj(obj));
} else {
h.arr_push_auto(&argsarr, a.clone());
}
}
h.set_var("@args", argsarr);
});
let exc = new_object(class, ctor_args);
with_host(|h| {
h.scopes.pop();
});
set_pending_throw(exc?);
Ok(Value::Undef)
}
pub fn new_object(class: &str, args: Vec<Value>) -> Result<Value, String> {
let obj = alloc_object(class)?;
construct_object(&obj, class, args, Vec::new())?;
Ok(obj)
}
pub fn alloc_object(class: &str) -> Result<Value, String> {
if let Some(v) = autoload_first(class)? {
return Ok(v);
}
let cl = class.to_ascii_lowercase();
if let Some(e) = with_host(|h| h.class_instantiation_error(class)) {
return Err(crate::builtins::throws_bare("Error", e));
}
let Some(defaults) = with_host(|h| h.class_prop_default_chunks(&cl)) else {
return Err(crate::builtins::throws_bare(
"Error",
format!("Class \"{class}\" not found"),
));
};
let mut props: IndexMap<String, Value> = IndexMap::new();
for (name, (declaring, chunk, uninit)) in defaults {
if uninit {
continue;
}
let v = run_in_class_scope(&declaring, chunk)?;
props.insert(name, v);
}
let obj = with_host(|h| {
h.objs.push(PhpObj::Object {
class: class.to_string(),
props,
});
Value::Obj((h.objs.len() - 1) as u32)
});
seed_throwable(class, &obj);
Ok(obj)
}
pub fn new_alloc(class: &str) -> Result<Value, String> {
let refused = with_host(|h| {
h.class_instantiation_error(class)
.or_else(|| h.constructor_access_error(class))
});
if let Some(e) = refused {
return Err(crate::builtins::throws_bare("Error", e));
}
alloc_object(class)
}
pub fn construct_object(
obj: &Value,
class: &str,
args: Vec<Value>,
named: Vec<(String, Value)>,
) -> Result<(), String> {
let cl = class.to_ascii_lowercase();
if with_host(|h| h.method_declared(&cl, "__construct")) {
with_host(|h| h.lsb_set_for_next_call(class));
if named.is_empty() {
call_method(&cl, "__construct", Some(obj.clone()), args)?;
} else {
call_method_named(&cl, "__construct", Some(obj.clone()), args, named)?;
}
}
Ok(())
}
pub fn new_object_named(
class: &str,
args: Vec<Value>,
named: Vec<(String, Value)>,
) -> Result<Value, String> {
let obj = new_alloc(class)?;
construct_object(&obj, class, args, named)?;
Ok(obj)
}
pub fn call_method(
class: &str,
method: &str,
this: Option<Value>,
args: Vec<Value>,
) -> Result<Value, String> {
let method_l = method.to_ascii_lowercase();
if class.eq_ignore_ascii_case("Closure") {
return call_closure_static(&method_l, args);
}
if with_host(|h| h.is_enum_class(class)) {
match method_l.as_str() {
"cases" => return enum_cases_all(class),
"from" => {
return enum_from(
class,
args.into_iter().next().unwrap_or(Value::Undef),
false,
)
}
"tryfrom" => {
return enum_from(class, args.into_iter().next().unwrap_or(Value::Undef), true)
}
_ => {}
}
}
let Some((def_class, def)) = with_host(|h| h.resolve_method(class, &method_l)) else {
return call_magic_call(class, method, this, args);
};
let pre = match this {
Some(t) => vec![("this".to_string(), t)],
None => Vec::new(),
};
with_host(|h| h.lsb_set_for_next_call(class));
invoke_with_locals(
&format!("{def_class}::{method}"),
Signature {
params: &def.params,
ret: def.ret.as_ref(),
deprecated: def.deprecated.as_ref(),
},
def.chunk,
pre,
args,
Vec::new(),
def.is_generator,
&def.locals,
)
}
pub fn call_magic_call(
class: &str,
method: &str,
this: Option<Value>,
args: Vec<Value>,
) -> Result<Value, String> {
let packed = with_host(|h| {
let arr = h.new_array();
for a in &args {
let v = h.deref(a.clone());
let v = h.copy_on_assign(v);
h.arr_push_auto(&arr, v);
}
arr
});
call_magic_call_packed(class, method, this, packed)
}
pub fn call_magic_call_named(
class: &str,
method: &str,
this: Option<Value>,
args: Vec<Value>,
named: Vec<(String, Value)>,
) -> Result<Value, String> {
if named.is_empty() {
return call_magic_call(class, method, this, args);
}
let packed = with_host(|h| {
let arr = h.new_array();
for a in &args {
let v = h.deref(a.clone());
let v = h.copy_on_assign(v);
h.arr_push_auto(&arr, v);
}
for (k, v) in &named {
let v = h.deref(v.clone());
let v = h.copy_on_assign(v);
h.arr_set_key(&arr, &Value::str(k.clone()), v);
}
arr
});
call_magic_call_packed(class, method, this, packed)
}
fn call_magic_call_packed(
class: &str,
method: &str,
this: Option<Value>,
packed: Value,
) -> Result<Value, String> {
let has_this = this.is_some();
let Some(magic) = with_host(|h| h.magic_call_name(class, has_this)) else {
return Err(format!(
"Call to undefined method {}::{method}()",
display_class(class)
));
};
let magic_args = vec![Value::str(method.to_string()), packed];
let Some((def_class, def)) =
with_host(|h| h.resolve_method(class, &magic.to_ascii_lowercase()))
else {
return Err(format!(
"Call to undefined method {}::{method}()",
display_class(class)
));
};
let pre = match this {
Some(t) => vec![("this".to_string(), t)],
None => Vec::new(),
};
with_host(|h| h.lsb_set_for_next_call(class));
invoke(
&format!("{def_class}::{magic}"),
Signature {
params: &def.params,
ret: def.ret.as_ref(),
deprecated: def.deprecated.as_ref(),
},
def.chunk,
pre,
magic_args,
Vec::new(),
def.is_generator,
)
}
fn call_closure_static(method_l: &str, mut args: Vec<Value>) -> Result<Value, String> {
match method_l {
"bind" => {
let closure = if args.is_empty() {
Value::Undef
} else {
args.remove(0)
};
let obj = if args.is_empty() {
Value::Undef
} else {
args.remove(0)
};
let scope = if args.is_empty() {
None
} else {
Some(args.remove(0))
};
closure_bind(&closure, obj, scope)
}
"fromcallable" => {
const FRAME: &str = "Closure::fromCallable";
if args.len() != 1 {
let msg = format!(
"Closure::fromCallable() expects exactly 1 argument, {} given",
args.len()
);
return throw_from_internal(FRAME, &args, "ArgumentCountError", &msg);
}
let callable = args.into_iter().next().unwrap_or(Value::Undef);
if with_host(|h| h.is_closure(&callable)) {
return Ok(callable);
}
if let Some(why) = crate::stdlib::callable::callable_reason(&callable) {
let msg = format!("Failed to create closure from callable: {why}");
return throw_from_internal(
FRAME,
std::slice::from_ref(&callable),
"TypeError",
&msg,
);
}
Ok(with_host(|h| {
h.make_closure(
crate::FROM_CALLABLE_FORWARDER,
vec![
("c".to_string(), callable.clone()),
("@fcc".to_string(), callable),
],
)
}))
}
other => Err(format!("call to undefined method Closure::{other}()")),
}
}
pub fn call_method_named(
class: &str,
method: &str,
this: Option<Value>,
args: Vec<Value>,
named: Vec<(String, Value)>,
) -> Result<Value, String> {
let method_l = method.to_ascii_lowercase();
let Some((def_class, def)) = with_host(|h| h.resolve_method(class, &method_l)) else {
return call_magic_call_named(class, method, this, args, named);
};
let pre = match this {
Some(t) => vec![("this".to_string(), t)],
None => Vec::new(),
};
with_host(|h| h.lsb_set_for_next_call(class));
invoke_with_locals(
&format!("{def_class}::{method}"),
Signature {
params: &def.params,
ret: def.ret.as_ref(),
deprecated: def.deprecated.as_ref(),
},
def.chunk,
pre,
args,
named,
def.is_generator,
&def.locals,
)
}
fn in_clone_hook<T>(obj: &Value, body: impl FnOnce() -> Result<T, String>) -> Result<T, String> {
let Value::Obj(id) = obj else { return body() };
let prev = with_host(|h| h.cloning.replace(*id));
let r = body();
with_host(|h| h.cloning = prev);
r
}
pub fn in_clone_with<T>(copy: &Value, body: impl FnOnce() -> T) -> T {
let Value::Obj(id) = copy else { return body() };
let prev = with_host(|h| h.cloning_with.replace(*id));
let r = body();
with_host(|h| h.cloning_with = prev);
r
}
pub fn clone_object(v: Value) -> Result<Value, String> {
const UNCLONEABLE: [&str; 3] = [
"iteratoriterator",
"recursiveiteratoriterator",
"weakreference",
];
if with_host(|h| {
h.object_class(&v).is_some_and(|c| {
h.catch_matches(&c, "throwable") || UNCLONEABLE.iter().any(|u| h.class_is_a(&c, u))
})
}) {
let class = with_host(|h| h.object_class(&v)).unwrap_or_default();
return Err(crate::builtins::throws_bare(
"Error",
format!(
"Trying to clone an uncloneable object of class {}",
display_class(&class)
),
));
}
if let Some(class) = with_host(|h| h.object_class(&v).filter(|c| h.is_enum_class(c))) {
return Err(crate::builtins::throws_bare(
"Error",
format!(
"Trying to clone an uncloneable object of class {}",
display_class(&class)
),
));
}
let Some(copy) = with_host(|h| h.clone_obj(&v)) else {
if with_host(|h| h.gen_id(&v).is_some()) {
return Err(crate::builtins::throws_bare(
"Error",
"Trying to clone an uncloneable object of class Generator",
));
}
let t = with_host(|h| h.type_name_for_error(&v));
return Err(crate::builtins::throws_bare(
"TypeError",
format!("clone(): Argument #1 ($object) must be of type object, {t} given"),
));
};
if let Some(class) = with_host(|h| h.object_class(©)) {
if with_host(|h| h.method_declared(&class.to_ascii_lowercase(), "__phplang_clone")) {
call_method(
&class.to_ascii_lowercase(),
"__phplang_clone",
Some(copy.clone()),
vec![v.clone()],
)?;
}
if with_host(|h| h.method_declared(&class.to_ascii_lowercase(), "__clone")) {
in_clone_hook(©, || {
call_method(
&class.to_ascii_lowercase(),
"__clone",
Some(copy.clone()),
Vec::new(),
)
})?;
}
}
Ok(copy)
}
fn run_in_class_scope(declaring: &str, chunk: Chunk) -> Result<Value, String> {
with_host(|h| h.init_class_scope.push(declaring.to_string()));
let r = run_chunk_on(chunk);
with_host(|h| h.init_class_scope.pop());
r
}
pub fn class_const(class: &str, name: &str) -> Result<Value, String> {
class_const_with(class, name, ConstLookup::Use)
}
pub fn class_const_silent(class: &str, name: &str) -> Result<Value, String> {
class_const_with(class, name, ConstLookup::Silent)
}
pub fn class_const_reflect(class: &str, name: &str) -> Result<Value, String> {
class_const_with(class, name, ConstLookup::Reflect)
}
#[derive(PartialEq)]
enum ConstLookup {
Use,
Silent,
Reflect,
}
fn class_const_with(class: &str, name: &str, lookup: ConstLookup) -> Result<Value, String> {
let report = lookup == ConstLookup::Use;
if let Some(v) = autoload_first(class)? {
return Ok(v);
}
if let Some((declaring, chunk)) = with_host(|h| h.resolve_const_chunk(class, name)) {
if let Some(msg) = with_host(|h| h.const_access_denied(class, name))
.filter(|_| lookup != ConstLookup::Reflect)
{
return Err(crate::builtins::throws_bare("Error", msg));
}
if report && raise_deprecated_member(&declaring, &format!("const:{name}")) {
return Ok(Value::Undef);
}
return run_in_class_scope(&declaring, chunk);
}
let lower = class.to_ascii_lowercase();
if report
&& with_host(|h| h.is_enum_class(&lower) && h.enum_case_chunk(&lower, name).is_some())
&& raise_deprecated_member(&lower, &format!("case:{name}"))
{
return Ok(Value::Undef);
}
if let Some(r) = enum_case(class, name) {
return r;
}
let (declared, display) = with_host(|h| {
(
h.class_exists(class),
h.class_display_name(&class.to_ascii_lowercase()),
)
});
if !declared {
return Err(crate::builtins::throws_bare(
"Error",
format!("Class \"{}\" not found", display_class(class)),
));
}
Err(crate::builtins::throws_bare(
"Error",
format!("Undefined constant {display}::{name}"),
))
}
pub fn enum_case(class: &str, case: &str) -> Option<Result<Value, String>> {
let lower = class.to_ascii_lowercase();
if !with_host(|h| h.is_enum_class(&lower)) {
return None;
}
let chunk_opt = with_host(|h| h.enum_case_chunk(&lower, case))?;
let key = format!("{lower}::{case}");
if let Some(v) = with_host(|h| h.enum_case_cached(&key)) {
return Some(Ok(v));
}
let value = match chunk_opt {
Some(chunk) => match run_chunk_on(chunk) {
Ok(v) => Some(v),
Err(e) => return Some(Err(e)),
},
None => None,
};
let obj = with_host(|h| h.new_enum_object(class, case, value));
with_host(|h| h.enum_case_store(&key, obj.clone()));
Some(Ok(obj))
}
pub fn enum_cases_all(class: &str) -> Result<Value, String> {
let names = with_host(|h| h.enum_case_names(class));
let arr = with_host(|h| h.new_array());
for name in names {
match enum_case(class, &name) {
Some(Ok(v)) => with_host(|h| h.arr_push_auto(&arr, v)),
Some(Err(e)) => return Err(e),
None => {}
}
}
Ok(arr)
}
pub fn enum_from(class: &str, needle: Value, is_try: bool) -> Result<Value, String> {
let names = with_host(|h| h.enum_case_names(class));
let spelled = with_host(|h| h.declared_class_name(class));
let fname = if is_try { "tryFrom" } else { "from" };
let first = match names.first() {
Some(n) => match enum_case(class, n) {
Some(Ok(v)) => v,
Some(Err(e)) => return Err(e),
None => Value::Undef,
},
None => Value::Undef,
};
let want_int = match with_host(|h| h.prop_get(&first, "value")) {
Value::Int(_) => true,
Value::Str(_) => false,
_ => {
return Err(crate::builtins::throws_bare(
"Error",
format!("Call to undefined method {spelled}::{fname}()"),
))
}
};
let coerced = match enum_backing_coerce(&needle, want_int, &spelled, fname) {
Coerced::Value(v) => v,
Coerced::Refused(r) => return r,
};
let needle_s = with_host(|h| h.to_str(&coerced));
for name in names {
let case = match enum_case(class, &name) {
Some(Ok(v)) => v,
Some(Err(e)) => return Err(e),
None => continue,
};
let val = with_host(|h| h.prop_get(&case, "value"));
if with_host(|h| h.to_str(&val)) == needle_s {
return Ok(case);
}
}
if is_try {
return Ok(Value::Undef);
}
let shown = if want_int {
needle_s.clone()
} else {
format!("\"{needle_s}\"")
};
throw_from_internal(
&format!("{spelled}::from"),
&[needle],
"ValueError",
&format!("{shown} is not a valid backing value for enum {spelled}"),
)
}
fn enum_backing_coerce(v: &Value, want_int: bool, spelled: &str, fname: &str) -> Coerced {
let type_error = |v: &Value| -> Coerced {
let what = with_host(|h| h.type_name_for_error(v));
let want = if want_int { "int" } else { "string|int" };
let msg = format!(
"{spelled}::{fname}(): Argument #1 ($value) must be of type {want}, {what} given"
);
Coerced::Refused(throw_from_internal(
&format!("{spelled}::{fname}"),
std::slice::from_ref(v),
"TypeError",
&msg,
))
};
let as_int = |n: i64| -> Value {
if want_int {
Value::int(n)
} else {
Value::str(n.to_string())
}
};
match v {
Value::Obj(_) => type_error(v),
Value::Undef => {
with_host(|h| {
h.deprecated(format!(
"{spelled}::{fname}(): Passing null to parameter #1 ($value) of \
type string|int is deprecated"
))
});
Coerced::Value(as_int(0))
}
Value::Bool(b) => Coerced::Value(as_int(i64::from(*b))),
Value::Int(n) => Coerced::Value(as_int(*n)),
Value::Float(f) => {
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"
))
});
}
Coerced::Value(as_int(*f as i64))
}
Value::Str(s) => {
if !want_int {
return Coerced::Value(v.clone());
}
if !is_numeric_string(s) {
return type_error(v);
}
let f = with_host(|h| h.to_number(v)).to_float();
if f.fract() != 0.0 {
with_host(|h| {
h.deprecated(format!(
"Implicit conversion from float-string \"{s}\" to int loses precision"
))
});
}
Coerced::Value(Value::int(f as i64))
}
other => type_error(other),
}
}
enum Coerced {
Value(Value),
Refused(Result<Value, String>),
}
fn static_prop_denied(class: &str, name: &str) -> Option<String> {
with_host(|h| {
let (declaring, vis) = h.resolve_prop_vis(class, name)?;
if h.visibility_allows(vis, &declaring) {
return None;
}
let vname = match vis {
Visibility::Private => "private",
Visibility::Protected => "protected",
Visibility::Public => return None,
};
let shown = h.class_display_name(&class.to_ascii_lowercase());
Some(format!("Cannot access {vname} property {shown}::${name}"))
})
}
pub fn static_prop_ref_slot(class: &str, name: &str) -> Result<usize, String> {
static_prop_get(class, name)?;
let key = with_host(|h| h.resolve_static_key(class, name).map(|(k, _)| k))
.expect("resolved by the read above");
Ok(with_host(|h| h.static_ref_slot_ensure(&key)))
}
pub fn static_prop_bind(class: &str, name: &str, slot: usize) -> Result<Value, String> {
static_prop_get(class, name)?;
let key = with_host(|h| h.resolve_static_key(class, name).map(|(k, _)| k))
.expect("resolved by the read above");
Ok(with_host(|h| {
h.bind_static_to_slot(&key, slot);
h.ref_cell_value(slot)
}))
}
pub fn static_prop_get(class: &str, name: &str) -> Result<Value, String> {
if let Some(v) = autoload_first(class)? {
return Ok(v);
}
let Some((key, chunk)) = with_host(|h| h.resolve_static_key(class, name)) else {
return Err(crate::builtins::throws_bare(
"Error",
format!("Access to undeclared static property {class}::${name}"),
));
};
if let Some(msg) = static_prop_denied(class, name) {
return Err(crate::builtins::throws_bare("Error", msg));
}
if let Some(v) = with_host(|h| h.get_static_stored(&key)) {
return Ok(v);
}
let declaring = key
.split_once("::")
.map_or(key.as_str(), |(c, _)| c)
.to_string();
let v = run_in_class_scope(&declaring, chunk)?;
with_host(|h| h.set_static_stored(&key, v.clone()));
Ok(v)
}
pub fn static_prop_get_quiet(class: &str, name: &str) -> Result<Value, String> {
if let Some(v) = autoload_first(class)? {
return Ok(v);
}
let declared = with_host(|h| h.resolve_static_key(class, name).is_some());
if !declared {
if !with_host(|h| h.class_exists(class)) {
return Err(crate::builtins::throws_bare(
"Error",
format!("Class \"{}\" not found", display_class(class)),
));
}
return Ok(Value::Undef);
}
if static_prop_denied(class, name).is_some() {
return Ok(Value::Undef);
}
static_prop_get(class, name)
}
pub fn class_vars(class: &str) -> Result<Option<Value>, String> {
let cl = class.to_ascii_lowercase();
let Some(defaults) = with_host(|h| h.class_prop_default_chunks(&cl)) else {
return Ok(None);
};
let defaults: FxHashMap<String, _> = defaults.into_iter().collect();
let arr = with_host(|h| h.new_array());
if with_host(|h| h.is_enum_class(&cl)) {
let backed = with_host(|h| {
h.classes
.get(&cl)
.is_some_and(|d| d.enum_cases.iter().any(|(_, c)| c.is_some()))
});
with_host(|h| h.arr_set_key(&arr, &Value::str("name"), Value::Undef));
if backed {
with_host(|h| h.arr_set_key(&arr, &Value::str("value"), Value::Undef));
}
}
for name in with_host(|h| h.property_names_inheritance_order(&cl, false)) {
let visible = with_host(|h| {
h.resolve_prop_vis(&cl, &name)
.is_none_or(|(decl, vis)| h.visibility_allows(vis, &decl))
});
let Some((declaring, chunk, uninit)) = defaults.get(&name).cloned() else {
continue;
};
if !visible {
continue;
}
let v = if uninit {
Value::Undef
} else {
run_in_class_scope(&declaring, chunk)?
};
with_host(|h| h.arr_set_key(&arr, &Value::str(name), v));
}
for name in with_host(|h| h.property_names_inheritance_order(&cl, true)) {
if static_prop_denied(class, &name).is_some() {
continue;
}
let Some((key, chunk)) = with_host(|h| h.resolve_static_key(class, &name)) else {
continue;
};
let declaring = key
.split_once("::")
.map_or(key.as_str(), |(c, _)| c)
.to_string();
let v = run_in_class_scope(&declaring, chunk)?;
with_host(|h| h.arr_set_key(&arr, &Value::str(name), v));
}
Ok(Some(arr))
}
pub fn static_prop_set(class: &str, name: &str, val: Value) -> Result<Value, String> {
if let Some(v) = autoload_first(class)? {
return Ok(v);
}
let Some((key, _)) = with_host(|h| h.resolve_static_key(class, name)) else {
return Err(crate::builtins::throws_bare(
"Error",
format!("Access to undeclared static property {class}::${name}"),
));
};
if let Some(msg) = static_prop_denied(class, name) {
return Err(crate::builtins::throws_bare("Error", msg));
}
if let Some(msg) = with_host(|h| h.static_set_visibility_error(class, name)) {
return Err(crate::builtins::throws_bare("Error", msg));
}
with_host(|h| h.set_static_stored(&key, val.clone()));
Ok(val)
}
pub fn static_prop_ensure_array(class: &str, name: &str) -> Result<Value, String> {
let cur = static_prop_get(class, name)?;
if let Some(kept) = with_host(|h| h.dim_container_kept(&cur)) {
return Ok(kept);
}
let arr = with_host(|h| h.new_array());
static_prop_set(class, name, arr.clone())?;
Ok(arr)
}
pub fn is_unpackable(v: &Value) -> bool {
if with_host(|h| h.is_array(v) || h.is_generator_val(v)) {
return true;
}
let Some(class) = with_host(|h| h.object_class(v)) else {
return false;
};
with_host(|h| {
h.class_has_method(&class, "getIterator")
|| (h.class_has_method(&class, "valid") && h.class_has_method(&class, "current"))
})
}
pub fn is_lazy_iter(v: &Value) -> bool {
with_host(|h| {
h.is_generator_val(v)
|| h.object_class(v)
.is_some_and(|c| h.class_is_a_pub(&c, "Iterator"))
})
}
pub fn foreach_iter(v: Value) -> Result<Value, String> {
let mut v = v;
loop {
let Some(class) = with_host(|h| h.object_class(&v)) else {
return Ok(v);
};
if !with_host(|h| h.class_is_a_pub(&class, "IteratorAggregate")) {
return Ok(v);
}
let it = call_method(&class, "getIterator", Some(v.clone()), Vec::new())?;
if with_host(|h| h.pending_throw.is_some()) {
return Ok(Value::Undef);
}
let traversable = with_host(|h| {
h.is_generator_val(&it)
|| h.object_class(&it)
.is_some_and(|c| h.class_is_a_pub(&c, "Traversable"))
});
if !traversable {
let shown = with_host(|h| h.instance_class(&v)).unwrap_or(class);
let exc = new_object(
"Exception",
vec![Value::str(format!(
"Objects returned by {shown}::getIterator() must be traversable or implement interface Iterator"
))],
)?;
set_pending_throw(exc);
return Ok(Value::Undef);
}
v = it;
}
}
pub fn iter_call(v: &Value, method: &str) -> Result<Value, String> {
const NATIVE: &[&str] = &[
"arrayiterator",
"recursivearrayiterator",
"recursiveiteratoriterator",
"recursivetreeiterator",
"spldoublylinkedlist",
"splqueue",
"splstack",
"splheap",
"splminheap",
"splmaxheap",
"splpriorityqueue",
];
let class = with_host(|h| h.object_class(v)).ok_or("not an iterator")?;
let native = with_host(|h| {
["rewind", "valid", "current", "key", "next"]
.iter()
.all(|m| {
h.resolve_method(&class, m)
.is_some_and(|(owner, _)| NATIVE.contains(&owner.as_str()))
})
});
with_host(|h| h.pending_transparent = native);
let r = call_method(&class, method, Some(v.clone()), Vec::new());
with_host(|h| h.pending_transparent = false);
r
}
pub fn foreach_prep(v: Value) -> Result<Value, String> {
if with_host(|h| h.is_array(&v)) {
return Ok(v);
}
let arr = with_host(|h| h.new_array());
let set = |key: Value, cur: Value| {
with_host(|h| match key {
Value::Undef => h.arr_push_auto(&arr, cur),
k => h.arr_set_key(&arr, &k, cur),
})
};
if let Some(inner) = traverse(&v, &mut |k, c| set(k, c))? {
return foreach_prep(inner);
}
Ok(arr)
}
pub fn foreach_keys(subj: &Value, arr: &Value) -> Value {
with_host(|h| {
if !h.is_plain_foreach_object(subj) {
return h.array_keys(arr);
}
let keys = h.new_array();
for (k, _) in h.object_props_visible(subj) {
h.arr_push_auto(&keys, prop_key(&k));
}
keys
})
}
pub fn traversable_pairs(v: Value) -> Result<Vec<(Value, Value)>, String> {
if with_host(|h| h.is_array(&v)) {
return Ok(with_host(|h| h.array_pairs(&v).unwrap_or_default()));
}
let mut out = Vec::new();
if let Some(inner) = traverse(&v, &mut |k, c| out.push((k, c)))? {
return traversable_pairs(inner);
}
Ok(out)
}
fn traverse(v: &Value, sink: &mut dyn FnMut(Value, Value)) -> Result<Option<Value>, String> {
if with_host(|h| h.is_generator_val(v)) {
gen_foreach_rewind(v)?;
if with_host(|h| h.pending_throw.is_some()) {
return Ok(None);
}
while gen_valid(v)? {
let cur = gen_current(v)?;
let key = gen_key(v)?;
sink(key, cur);
gen_next(v)?;
}
return Ok(None);
}
let Some(class) = with_host(|h| h.object_class(v)) else {
return Ok(None);
};
if with_host(|h| h.class_has_method(&class, "getIterator")) {
return call_method(&class, "getIterator", Some(v.clone()), Vec::new()).map(Some);
}
if with_host(|h| h.class_has_method(&class, "valid") && h.class_has_method(&class, "current")) {
if with_host(|h| h.class_has_method(&class, "rewind")) {
iter_call(v, "rewind")?;
}
let has_key = with_host(|h| h.class_has_method(&class, "key"));
for _ in 0..100_000_000u64 {
let valid = iter_call(v, "valid")?;
if !with_host(|h| h.is_truthy(&valid)) {
break;
}
let cur = iter_call(v, "current")?;
let key = if has_key {
iter_call(v, "key")?
} else {
Value::Undef
};
sink(key, cur);
iter_call(v, "next")?;
}
return Ok(None);
}
for (k, val) in with_host(|h| h.object_props_visible(v)) {
sink(prop_key(&k), val);
}
Ok(None)
}
pub fn iterator_apply_walk(
v: Value,
step: &mut dyn FnMut() -> Result<bool, String>,
) -> Result<(), String> {
if with_host(|h| h.is_array(&v)) {
for _ in 0..with_host(|h| h.array_len(&v)) {
if !step()? {
break;
}
}
return Ok(());
}
if with_host(|h| h.is_generator_val(&v)) {
gen_foreach_rewind(&v)?;
while with_host(|h| h.pending_throw.is_none()) && gen_valid(&v)? {
if !step()? {
break;
}
gen_next(&v)?;
}
return Ok(());
}
let Some(class) = with_host(|h| h.object_class(&v)) else {
return Ok(());
};
if with_host(|h| h.class_has_method(&class, "getIterator")) {
let inner = call_method(&class, "getIterator", Some(v.clone()), Vec::new())?;
return iterator_apply_walk(inner, step);
}
if with_host(|h| h.class_has_method(&class, "rewind")) {
iter_call(&v, "rewind")?;
}
loop {
let valid = iter_call(&v, "valid")?;
if !with_host(|h| h.is_truthy(&valid)) || !step()? {
break;
}
iter_call(&v, "next")?;
}
Ok(())
}
pub fn fatal_reported() -> bool {
with_host(|h| h.fatal_reported())
}
pub fn set_return(v: Value) {
with_host(|h| h.signal = Some(Signal::Return(v)));
}
pub fn set_break(level: u32) {
with_host(|h| h.signal = Some(Signal::Break(level)));
}
pub fn set_continue(level: u32) {
with_host(|h| h.signal = Some(Signal::Continue(level)));
}
pub fn last_break_level() -> u32 {
with_host(|h| h.last_break_level)
}
pub fn set_pending_throw(v: Value) {
with_host(|h| h.pending_throw = Some(v));
}
pub fn set_pending_exit(status: i32) {
with_host(|h| h.pending_exit = Some(status));
}
pub fn pending_exit() -> Option<i32> {
with_host(|h| h.pending_exit)
}
pub fn unwinding() -> bool {
with_host(|h| h.pending_throw.is_some() || h.pending_exit.is_some())
}
enum TryStatus {
Normal,
Exit,
Return(Value),
Throw(Value),
Break,
Continue,
Fatal(String),
}
fn run_body(chunk: Chunk) -> TryStatus {
match run_chunk_on(chunk) {
Err(e) => TryStatus::Fatal(e),
Ok(_) => with_host(|h| {
if h.pending_exit.is_some() {
return TryStatus::Exit;
}
if let Some(exc) = h.pending_throw.take() {
return TryStatus::Throw(exc);
}
match h.signal.take() {
Some(Signal::Return(v)) => TryStatus::Return(v),
Some(Signal::Break(n)) => {
h.last_break_level = n;
TryStatus::Break
}
Some(Signal::Continue(n)) => {
h.last_break_level = n;
TryStatus::Continue
}
None => TryStatus::Normal,
}
}),
}
}
pub fn run_try_orchestrator(id: i64) -> Result<i64, String> {
let Some(def) = with_host(|h| h.try_defs.get(id as usize).cloned()) else {
return Err(format!("internal: no try-def #{id}"));
};
let suppress_depth = with_host(|h| h.suppress_depth());
let mut status = run_body(def.try_chunk);
with_host(|h| h.suppress_restore(suppress_depth));
if matches!(status, TryStatus::Exit) {
return Ok(2);
}
if let TryStatus::Throw(exc) = &status {
if let Some(class) = with_host(|h| h.object_class(exc)) {
let exc = exc.clone();
for c in &def.catches {
let matched = with_host(|h| c.classes.iter().any(|t| h.catch_matches(&class, t)));
if matched {
if let Some(var) = &c.var {
with_host(|h| h.set_var(var, exc.clone()));
}
status = run_body(c.chunk.clone());
break;
}
}
}
}
if let Some(fin) = def.finally_chunk {
match run_body(fin) {
TryStatus::Normal => {}
other => status = other,
}
}
Ok(match status {
TryStatus::Normal => 0,
TryStatus::Exit => 2,
TryStatus::Return(v) => {
with_host(|h| h.signal = Some(Signal::Return(v)));
1
}
TryStatus::Throw(v) => {
with_host(|h| h.pending_throw = Some(v));
2
}
TryStatus::Break => 3,
TryStatus::Continue => 4,
TryStatus::Fatal(e) => return Err(e),
})
}
fn float_to_php_string(f: f64) -> String {
if f.is_nan() {
return "NAN".into();
}
if f.is_infinite() {
return if f < 0.0 { "-INF" } else { "INF" }.into();
}
if f == 0.0 {
return if f.is_sign_negative() { "-0" } else { "0" }.into();
}
php_gcvt(f, 14)
}
pub fn php_gcvt(f: f64, precision: usize) -> String {
if f == 0.0 {
return if f.is_sign_negative() {
"-0".into()
} else {
"0".into()
};
}
let neg = f < 0.0;
let a = f.abs();
let exp = a.log10().floor() as i32;
let sci = exp < -4 || exp >= precision as i32;
let body = if sci {
let raw = format!("{:.*e}", precision.saturating_sub(1), a);
let (mant, ex) = raw.split_once('e').unwrap_or((raw.as_str(), "0"));
let mant = mant.trim_end_matches('0');
let mant = if let Some(stripped) = mant.strip_suffix('.') {
format!("{stripped}.0")
} else if mant.contains('.') {
mant.to_string()
} else {
format!("{mant}.0")
};
let exp_n: i32 = ex.parse().unwrap_or(0);
format!(
"{mant}E{}{}",
if exp_n < 0 { "-" } else { "+" },
exp_n.abs()
)
} else {
let decimals = (precision as i32 - 1 - exp).max(0) as usize;
let s = format!("{a:.decimals$}");
if s.contains('.') {
s.trim_end_matches('0').trim_end_matches('.').to_string()
} else {
s
}
};
if neg {
format!("-{body}")
} else {
body
}
}
const PHP_SPACE: &[char] = &[' ', '\t', '\n', '\r', '\x0b', '\x0c'];
fn scan_php_number(s: &str) -> Option<(Value, usize, bool)> {
let t = s.trim_start_matches(PHP_SPACE);
let b = &*crate::bytes::to_bytes(t);
let mut i = 0;
if i < b.len() && (b[i] == b'+' || b[i] == b'-') {
i += 1;
}
let digits_start = i;
while i < b.len() && b[i].is_ascii_digit() {
i += 1;
}
let mut end = if i > digits_start { i } else { 0 };
let mut is_float = false;
if i < b.len() && b[i] == b'.' {
let frac_start = i + 1;
let mut j = frac_start;
while j < b.len() && b[j].is_ascii_digit() {
j += 1;
}
if j > frac_start || end != 0 {
i = j;
end = j;
is_float = true;
}
}
if end == 0 {
return None;
}
if i < b.len() && (b[i] == b'e' || b[i] == b'E') {
let mut j = i + 1;
if j < b.len() && (b[j] == b'+' || b[j] == b'-') {
j += 1;
}
let exp_digits = j;
while j < b.len() && b[j].is_ascii_digit() {
j += 1;
}
if j > exp_digits {
end = j;
is_float = true;
}
}
let text = &t[..end];
let value = match (is_float, text.parse::<i64>()) {
(false, Ok(n)) => Value::int(n),
_ => Value::float(text.parse::<f64>().ok()?),
};
Some((value, end, is_float))
}
pub fn numeric_prefix_is_float(s: &str) -> bool {
scan_php_number(s).is_some_and(|(_, _, is_float)| is_float)
}
fn parse_php_number(s: &str) -> Value {
scan_php_number(s).map_or(Value::int(0), |(v, _, _)| v)
}
fn increment_alnum_string(s: &str) -> String {
let mut b = (*crate::bytes::to_bytes(s)).to_vec();
let mut i = b.len();
let mut carry = false;
while i > 0 {
i -= 1;
match b[i] {
b'z' => {
b[i] = b'a';
carry = true;
}
b'Z' => {
b[i] = b'A';
carry = true;
}
b'9' => {
b[i] = b'0';
carry = true;
}
c if c.is_ascii_alphanumeric() => {
b[i] = c + 1;
carry = false;
break;
}
_ => {
carry = false;
break;
}
}
if !carry {
break;
}
}
if carry {
let lead = match b.first() {
Some(b'0') => b'1',
Some(b'A') => b'A',
_ => b'a',
};
b.insert(0, lead);
}
crate::bytes::from_bytes(&b)
}
pub fn long_of(v: &Value) -> i64 {
match v {
Value::Str(s) => parse_php_number_full(s)
.unwrap_or_else(|| parse_php_number(s))
.to_int(),
other => other.to_int(),
}
}
pub fn is_numeric_string(s: &str) -> bool {
parse_php_number_full(s).is_some()
}
pub fn canonical_int_key(s: &str) -> Option<i64> {
let b = &*crate::bytes::to_bytes(s);
let digits = match b.first()? {
b'-' => &b[1..],
_ => b,
};
if digits.is_empty() || !digits.iter().all(u8::is_ascii_digit) {
return None;
}
if digits[0] == b'0' && (digits.len() > 1 || b[0] == b'-') {
return None;
}
s.parse::<i64>().ok()
}
pub enum StrOffset {
At(i64, bool),
Bad,
}
pub fn classify_string_offset(key: &Value) -> StrOffset {
match key {
Value::Int(n) => StrOffset::At(*n, false),
Value::Bool(b) => StrOffset::At(i64::from(*b), true),
Value::Undef => StrOffset::At(0, true),
Value::Float(f) => StrOffset::At(dval_to_lval(*f), true),
Value::Str(s) => {
let t = s.trim_matches(PHP_SPACE);
let digits = t.strip_prefix(['+', '-']).unwrap_or(t);
match (!digits.is_empty() && digits.bytes().all(|b| b.is_ascii_digit()))
.then(|| t.parse::<i64>().ok())
.flatten()
{
Some(n) => StrOffset::At(n, false),
None => StrOffset::Bad,
}
}
_ => StrOffset::Bad,
}
}
pub fn dval_to_lval(f: f64) -> i64 {
const TWO_63: f64 = 9223372036854775808.0; const TWO_64: f64 = 18446744073709551616.0; if !f.is_finite() {
return 0;
}
if (-TWO_63..TWO_63).contains(&f) {
return f as i64;
}
let wrapped = f.trunc().rem_euclid(TWO_64);
if wrapped >= TWO_63 {
(wrapped - TWO_64) as i64
} else {
wrapped as i64
}
}
pub fn parse_php_number_full(s: &str) -> Option<Value> {
let t = s.trim_matches(PHP_SPACE);
let (value, used, _) = scan_php_number(t)?;
(used == t.len()).then_some(value)
}
pub enum ArithOperand {
Numeric(Value),
Leading(Value),
Unsupported,
}
pub fn classify_arith(v: &Value) -> ArithOperand {
match v {
Value::Int(_) | Value::Float(_) => ArithOperand::Numeric(v.clone()),
Value::Bool(b) => ArithOperand::Numeric(Value::int(*b as i64)),
Value::Undef => ArithOperand::Numeric(Value::int(0)),
Value::Str(s) => match parse_php_number_full(s) {
Some(n) => ArithOperand::Numeric(n),
None => match scan_php_number(s) {
Some((n, _, _)) => ArithOperand::Leading(n),
None => ArithOperand::Unsupported,
},
},
_ => ArithOperand::Unsupported,
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TypeKind {
Class,
Interface,
Trait,
Enum,
}
type BuiltinType = (
&'static str,
TypeKind,
&'static [&'static str],
&'static [&'static str],
);
const BUILTIN_TYPES: &[BuiltinType] = &[
(
"Closure",
TypeKind::Class,
&[],
&["bind", "bindTo", "call", "fromCallable", "getCurrent"],
),
(
"Generator",
TypeKind::Class,
&["Iterator", "Traversable"],
&[
"rewind",
"valid",
"current",
"key",
"next",
"send",
"throw",
"getReturn",
"__debugInfo",
],
),
("Traversable", TypeKind::Interface, &[], &[]),
(
"Iterator",
TypeKind::Interface,
&["Traversable"],
&["current", "next", "key", "valid", "rewind"],
),
(
"IteratorAggregate",
TypeKind::Interface,
&["Traversable"],
&["getIterator"],
),
("Countable", TypeKind::Interface, &[], &["count"]),
(
"ArrayAccess",
TypeKind::Interface,
&[],
&["offsetExists", "offsetGet", "offsetSet", "offsetUnset"],
),
("Stringable", TypeKind::Interface, &[], &["__toString"]),
(
"JsonSerializable",
TypeKind::Interface,
&[],
&["jsonSerialize"],
),
(
"Throwable",
TypeKind::Interface,
&["Stringable"],
&[
"getMessage",
"getCode",
"getFile",
"getLine",
"getTrace",
"getPrevious",
"getTraceAsString",
"__toString",
],
),
("UnitEnum", TypeKind::Interface, &[], &["cases"]),
(
"BackedEnum",
TypeKind::Interface,
&["UnitEnum"],
&["from", "tryFrom", "cases"],
),
];
fn builtin_type(name: &str) -> Option<&'static BuiltinType> {
BUILTIN_TYPES
.iter()
.find(|(n, ..)| n.eq_ignore_ascii_case(name))
}
fn builtin_type_kind(name: &str) -> Option<TypeKind> {
builtin_type(name).map(|(_, k, ..)| *k)
}
fn builtin_type_parents(name: &str) -> &'static [&'static str] {
builtin_type(name).map_or(&[][..], |(_, _, p, _)| *p)
}
fn builtin_type_methods(name: &str) -> &'static [&'static str] {
builtin_type(name).map_or(&[][..], |(.., m)| *m)
}
pub fn const_key(name: &str) -> String {
match name.rsplit_once('\\') {
Some((ns, short)) => format!("{}\\{short}", ns.to_ascii_lowercase()),
None => name.to_string(),
}
}
pub fn unanchored(name: &str) -> &str {
name.strip_prefix('\\').unwrap_or(name)
}
pub fn anchored_class(name: &str) -> String {
let bare = unanchored(name);
if bare.len() != name.len() && with_host(|h| h.class_exists(bare)) {
bare.to_string()
} else {
name.to_string()
}
}
pub fn display_class(name: &str) -> &str {
match name.split_once('\0') {
Some((head, _)) => head,
None => name,
}
}
pub fn final_violation<'a>(
def: &ClassDef,
find: impl Fn(&str) -> Option<&'a ClassDef>,
) -> Option<(String, Option<u32>)> {
let mut chain: Vec<&ClassDef> = Vec::new();
let mut next = def.parent.as_deref();
while let Some(p) = next {
let Some(d) = find(p) else { break };
if chain.iter().any(|c| std::ptr::eq(*c, d)) {
break;
}
chain.push(d);
next = d.parent.as_deref();
}
if let Some(parent) = chain.first() {
if parent.is_final {
return Some((
format!(
"Class {} cannot extend final class {}",
display_class(&def.name),
parent.name
),
None,
));
}
}
let mut seen: FxHashSet<&str> = FxHashSet::default();
for anc in &chain {
let names = anc.prop_defaults.iter().chain(&anc.static_prop_defaults);
for (name, _) in names {
if seen.insert(name)
&& anc.final_props.contains(name)
&& def.prop_vis.contains_key(name)
{
return Some((
format!("Cannot override final property {}::${name}", anc.name),
None,
));
}
}
}
let rank = |v: Visibility| match v {
Visibility::Public => 0,
Visibility::Protected => 1,
Visibility::Private => 2,
};
let word = |v: Visibility| match v {
Visibility::Public => "public",
Visibility::Protected => "protected",
Visibility::Private => "private",
};
for (name, vis) in &def.prop_vis {
let Some(anc) = chain.iter().find(|a| a.prop_vis.contains_key(name)) else {
continue;
};
let own_set = def.prop_set_vis.get(name).copied();
match anc.prop_set_vis.get(name).copied() {
Some(p) if rank(own_set.unwrap_or(*vis)) > rank(p) => {
return Some((
format!(
"Set access level of {}::${name} must be {}(set) (as in class {}) or weaker",
display_class(&def.name),
word(p),
anc.name
),
None,
));
}
None if own_set.is_some_and(|s| rank(s) > 0) => {
return Some((
format!(
"Set access level of {}::${name} must be omitted (as in class {})",
display_class(&def.name),
anc.name
),
None,
));
}
_ => {}
}
}
let mut ifaces: Vec<&ClassDef> = Vec::new();
let mut pending: Vec<&str> = def
.interfaces
.iter()
.chain(chain.iter().flat_map(|c| &c.interfaces))
.map(String::as_str)
.collect();
let mut i = 0;
while i < pending.len() {
if let Some(d) = find(pending[i]) {
if !ifaces.iter().any(|x| std::ptr::eq(*x, d)) {
ifaces.push(d);
pending.extend(d.interfaces.iter().map(String::as_str));
}
}
i += 1;
}
seen.clear();
for anc in chain.iter().chain(&ifaces) {
for (name, _) in &anc.consts {
if seen.insert(name)
&& anc.final_consts.contains(name)
&& def.consts.iter().any(|(n, _)| n == name)
{
return Some((
format!(
"{}::{name} cannot override final constant {}::{name}",
display_class(&def.name),
anc.name
),
None,
));
}
}
}
let mut seen: FxHashSet<String> = FxHashSet::default();
for anc in &chain {
for (spelled, _) in &anc.method_sites {
let key = spelled.to_ascii_lowercase();
if !seen.insert(key.clone()) || !anc.final_methods.contains(&key) {
continue;
}
let own = def
.method_sites
.iter()
.find(|(n, _)| n.eq_ignore_ascii_case(spelled));
if let Some((own, line)) = own {
return Some((
format!("Cannot override final method {}::{own}()", anc.name),
Some(*line),
));
}
}
}
throwable_violation(def, &find, &chain).or_else(|| abstract_violation(def, &find, &chain))
}
fn throwable_violation<'a>(
def: &ClassDef,
find: &impl Fn(&str) -> Option<&'a ClassDef>,
chain: &[&ClassDef],
) -> Option<(String, Option<u32>)> {
if def.is_interface || def.is_trait {
return None;
}
let roots = std::iter::once(def).chain(chain.iter().copied());
if roots
.clone()
.any(|c| c.name.eq_ignore_ascii_case("exception") || c.name.eq_ignore_ascii_case("error"))
{
return None;
}
let mut pending: Vec<String> = roots
.flat_map(|c| c.interfaces.iter().map(|i| i.to_ascii_lowercase()))
.collect();
let mut seen: FxHashSet<String> = FxHashSet::default();
while let Some(iface) = pending.pop() {
if iface == "throwable" {
let name = display_class(&def.name);
return Some((
if def.is_enum {
format!("Enum {name} cannot implement interface Throwable")
} else {
format!(
"Class {name} cannot implement interface Throwable, extend Exception or Error instead"
)
},
None,
));
}
if seen.insert(iface.clone()) {
if let Some(d) = find(&iface) {
pending.extend(d.interfaces.iter().map(|i| i.to_ascii_lowercase()));
}
}
}
None
}
fn abstract_violation<'a>(
def: &ClassDef,
find: &impl Fn(&str) -> Option<&'a ClassDef>,
chain: &[&ClassDef],
) -> Option<(String, Option<u32>)> {
if def.is_abstract || def.is_interface || def.is_trait {
return None;
}
let mut decided: FxHashSet<String> = FxHashSet::default();
let mut missing: Vec<String> = Vec::new();
for anc in std::iter::once(def).chain(chain.iter().copied()) {
for (spelled, _) in &anc.method_sites {
let key = spelled.to_ascii_lowercase();
if decided.insert(key.clone()) && anc.abstract_methods.contains(&key) {
missing.push(format!("{}::{spelled}", display_class(&anc.name)));
}
}
}
let mut visited: Vec<String> = Vec::new();
let mut pending: Vec<String> = std::iter::once(def)
.chain(chain.iter().copied())
.flat_map(|c| c.interfaces.iter().map(|i| i.to_ascii_lowercase()))
.rev()
.collect();
while let Some(iface) = pending.pop() {
if visited.contains(&iface) {
continue;
}
visited.push(iface.clone());
if matches!(iface.as_str(), "stringable" | "unitenum" | "backedenum") {
continue;
}
if let Some(d) = find(&iface) {
for (spelled, _) in &d.method_sites {
if decided.insert(spelled.to_ascii_lowercase()) {
missing.push(format!("{}::{spelled}", display_class(&d.name)));
}
}
pending.extend(d.interfaces.iter().rev().map(|i| i.to_ascii_lowercase()));
} else if let Some((spelled, ..)) = builtin_type(&iface) {
for m in builtin_type_methods(&iface) {
if decided.insert(m.to_ascii_lowercase()) {
missing.push(format!("{spelled}::{m}"));
}
}
pending.extend(
builtin_type_parents(&iface)
.iter()
.rev()
.map(|p| p.to_ascii_lowercase()),
);
}
}
if missing.is_empty() {
return None;
}
let n = missing.len();
let plural = if n == 1 { "" } else { "s" };
let mut listed = missing
.iter()
.take(3)
.cloned()
.collect::<Vec<_>>()
.join(", ");
if n > 3 {
listed.push_str(", ...");
}
let name = display_class(&def.name);
let msg = if def.is_enum {
format!("Enum {name} must implement {n} abstract method{plural} ({listed})")
} else if def.name.contains('\0') {
format!("Class {name} must implement {n} abstract method{plural} ({listed})")
} else {
format!(
"Class {name} contains {n} abstract method{plural} and must therefore be declared \
abstract or implement the remaining method{plural} ({listed})"
)
};
Some((msg, None))
}
pub fn arith_type_name(h: &PhpHost, v: &Value) -> String {
match v {
Value::Undef => "null".into(),
Value::Bool(_) => "bool".into(),
Value::Int(_) => "int".into(),
Value::Float(_) => "float".into(),
Value::Str(_) => "string".into(),
Value::Obj(_) if h.is_array(v) => "array".into(),
Value::Obj(_) if h.is_stream(v) => "resource".into(),
Value::Obj(_) => h.instance_class(v).unwrap_or_else(|| "object".into()),
_ => "mixed".into(),
}
}
pub type ParamShape = (String, bool, bool);
pub const INCLUDE_PATH: &str = ".";
impl PhpHost {
pub fn user_function_params(&self) -> Vec<(String, Vec<ParamShape>)> {
self.functions
.iter()
.filter(|(_, def)| def.closure_site.is_none())
.map(|(name, def)| {
let params = def
.params
.iter()
.map(|p| (p.name.clone(), p.by_ref, p.variadic))
.collect();
(name.clone(), params)
})
.collect()
}
pub fn included_files(&self) -> &[String] {
&self.included_files
}
pub fn set_compile_counters(&mut self, c: crate::compiler::Counters) {
self.compile_counters = c;
}
pub fn append_try_defs(&mut self, defs: Vec<TryDef>) {
self.try_defs.extend(defs);
}
}
fn resolve_include(name: &str) -> std::path::PathBuf {
let p = std::path::Path::new(name);
if p.is_absolute() || name.starts_with("./") || name.starts_with("../") {
return p.to_path_buf();
}
for dir in INCLUDE_PATH.split(':') {
let candidate = std::path::Path::new(dir).join(name);
if candidate.is_file() {
return candidate;
}
}
let here = with_host(|h| h.current_file().to_string());
if let Some(dir) = std::path::Path::new(&here)
.parent()
.filter(|_| here.starts_with('/'))
{
let candidate = dir.join(name);
if candidate.is_file() {
return candidate;
}
}
p.to_path_buf()
}
pub fn spl_autoload(class: &str, extensions: Option<&str>) -> Result<(), String> {
let exts = match extensions {
Some(e) => e.to_string(),
None => with_host(|h| h.autoload_extensions.clone()),
};
let stem = unanchored(class).to_ascii_lowercase().replace('\\', "/");
for ext in exts.split(',') {
let file = format!("{stem}{ext}");
if resolve_include(&file).is_file() {
run_include(crate::ast::IncludeKind::IncludeOnce, &Value::str(file))?;
return Ok(());
}
}
Ok(())
}
pub fn run_include(kind: crate::ast::IncludeKind, path: &Value) -> Result<Value, String> {
let name = to_str_ext(path);
let construct = kind.name();
if name.is_empty() {
return Err(crate::builtins::throws_bare(
"ValueError",
"Path must not be empty",
));
}
let target = resolve_include(&name);
let read = if target.is_dir() {
Err(std::io::Error::from_raw_os_error(0))
} else {
std::fs::read(&target)
};
let src = match read {
Ok(bytes) => crate::bytes::from_bytes(&bytes),
Err(e) => {
let shown = if target.is_dir() {
std::fs::canonicalize(&target)
.map_or_else(|_| name.clone(), |p| p.display().to_string())
} else {
name.clone()
};
let reason = match e.raw_os_error() {
Some(0) => "Undefined error: 0".to_string(),
_ => {
let s = e.to_string();
s.find(" (os error")
.map_or(s.clone(), |i| s[..i].to_string())
}
};
with_host(|h| {
h.warn(format!(
"{construct}({shown}): Failed to open stream: {reason}"
))
});
if kind.required() {
return Err(crate::builtins::throws_bare(
"Error",
format!("Failed opening required '{name}' (include_path='{INCLUDE_PATH}')"),
));
}
with_host(|h| {
h.warn(format!(
"{construct}(): Failed opening '{name}' for inclusion \
(include_path='{INCLUDE_PATH}')"
))
});
return Ok(Value::bool(false));
}
};
let real = std::fs::canonicalize(&target).map_or_else(
|_| target.display().to_string(),
|p| p.display().to_string(),
);
let seen = with_host(|h| h.included_files.contains(&real));
if kind.once() && seen {
return Ok(Value::bool(true));
}
with_host(|h| {
h.consume_resource_id();
if !seen {
h.included_files.push(real.clone());
}
});
run_loaded(&src, real.clone(), construct, Some(real), false)
}
pub fn run_eval(code: &Value) -> Result<Value, String> {
let src = to_str_ext(code);
let file = with_host(|h| {
format!(
"{}({}) : eval()'d code",
h.current_file(),
h.cur_frame_line()
)
});
run_loaded(&format!("<?php {src}"), file, "eval", None, true)
}
fn run_loaded(
src: &str,
file: String,
construct: &'static str,
arg: Option<String>,
eval: bool,
) -> Result<Value, String> {
let saved = with_host(|h| std::mem::replace(&mut h.script_name, file.clone()));
let counters = with_host(|h| h.compile_counters);
let compiled = crate::parser::parse_meta(src)
.map_err(|e| (e.severity, e.message))
.and_then(|(stmts, _meta)| {
crate::compiler::compile_nested(&stmts, counters, &file).map_err(|m| {
let m = match m.strip_prefix(crate::compiler::COMPILE_FATAL) {
Some(body) => body.to_string(),
None => m,
};
("Fatal error", m)
})
});
with_host(|h| h.script_name = saved);
let prog = match compiled {
Ok(p) => p,
Err(("Parse error", msg)) => return throw_parse_error(&msg, &file),
Err((severity, msg)) => {
with_host(|h| h.fatal(severity, &msg));
return Err(format!("{severity}: {msg}"));
}
};
let crate::compiler::Program {
main,
functions,
classes,
try_defs,
diags,
counters,
fn_sites,
class_sites,
..
} = prog;
let arc: std::sync::Arc<str> = std::sync::Arc::from(file.as_str());
let call_line = with_host(|h| {
h.set_compile_counters(counters);
h.load_program(functions);
h.load_classes(classes);
h.append_try_defs(try_defs);
h.record_decl_sites(&file, fn_sites, class_sites);
let call_line = h.cur_frame_line();
h.includes.push(IncludeFrame {
depth: h.scopes.len() - 1,
file: arc,
construct,
arg,
call_line,
});
for d in &diags {
h.diagnose(d.severity, d.level, d.line, &d.msg);
}
call_line
});
let r = run_chunk_on(main);
with_host(|h| {
h.includes.pop();
if let Some(scope) = h.scopes.last_mut() {
scope.line = call_line;
}
});
r?;
Ok(with_host(|h| match h.signal.take() {
Some(Signal::Return(v)) => v,
other => {
h.signal = other;
if eval {
Value::Undef
} else {
Value::int(1)
}
}
}))
}
fn throw_parse_error(msg: &str, file: &str) -> Result<Value, String> {
let tail = format!(" in {file} on line ");
let (message, line) = match msg.rfind(&tail) {
Some(i) => (
msg[..i].to_string(),
msg[i + tail.len()..].trim().parse::<i64>().unwrap_or(0),
),
None => (msg.to_string(), 0),
};
let exc = new_object("ParseError", vec![Value::str(message)])?;
with_host(|h| {
h.prop_set(&exc, "file", Value::str(file.to_string()));
h.prop_set(&exc, "line", Value::int(line));
});
set_pending_throw(exc);
Ok(Value::Undef)
}
impl PhpHost {
pub fn trait_defs(&self) -> Vec<(String, ClassDef)> {
self.classes
.iter()
.filter(|(_, d)| d.is_trait)
.map(|(k, d)| (k.clone(), d.clone()))
.collect()
}
}
fn class_kind_word(def: &ClassDef) -> &'static str {
if def.is_trait {
"trait"
} else if def.is_interface {
"interface"
} else if def.is_enum {
"enum"
} else {
"class"
}
}
fn type_kind_word(kind: TypeKind) -> &'static str {
match kind {
TypeKind::Class => "class",
TypeKind::Interface => "interface",
TypeKind::Trait => "trait",
TypeKind::Enum => "enum",
}
}
impl PhpHost {
fn user_exception_handler(&self) -> Option<Value> {
if !self.exception_handler_enabled {
return None;
}
self.exception_handlers
.last()
.filter(|v| !matches!(v, Value::Undef))
.cloned()
}
pub fn set_exception_handler(&mut self, callback: Value) -> Value {
let prev = self
.exception_handlers
.last()
.cloned()
.unwrap_or(Value::Undef);
self.exception_handlers.push(callback);
prev
}
pub fn restore_exception_handler(&mut self) {
self.exception_handlers.pop();
}
pub fn disable_exception_handler(&mut self) {
self.exception_handler_enabled = false;
}
pub fn register_shutdown_fn(&mut self, callback: Value, args: Vec<Value>) {
self.shutdown_fns.push((callback, args));
}
pub fn disable_destructors(&mut self) {
self.destructors_off = true;
}
fn handle_refs(&self, handle: u32, freed: &FxHashSet<u32>) -> usize {
let is = |v: &Value| matches!(v, Value::Obj(o) if *o == handle);
let in_frame = |s: &Scope| {
s.vars
.slots
.iter()
.filter(|slot| matches!(slot, Slot::Val(v) if is(v)))
.count()
};
let mut n = self.scopes.iter().map(in_frame).sum::<usize>()
+ self
.generators
.iter()
.flat_map(|g| g.ctx.frames.iter())
.map(in_frame)
.sum::<usize>()
+ self.main_frame_slots.iter().filter(|v| is(v)).count()
+ self.ref_cells.iter().filter(|v| is(v)).count()
+ self.static_props.values().filter(|v| is(v)).count()
+ self.constants.values().filter(|v| is(v)).count();
for (i, o) in self.objs.iter().enumerate() {
if freed.contains(&(i as u32)) {
continue;
}
n += match o {
PhpObj::Array { entries, .. } => entries.values().filter(|v| is(v)).count(),
PhpObj::Object { props, .. } => props.values().filter(|v| is(v)).count(),
PhpObj::Closure {
captured,
bound_this,
..
} => {
captured.iter().filter(|(_, v)| is(v)).count()
+ usize::from(bound_this.as_ref().is_some_and(is))
}
_ => 0,
};
}
n
}
fn held_handles(&self, handle: u32) -> Vec<u32> {
let vals: Vec<&Value> = match self.objs.get(handle as usize) {
Some(PhpObj::Array { entries, .. }) => entries.values().collect(),
Some(PhpObj::Object { props, .. }) => props.values().collect(),
Some(PhpObj::Closure {
captured,
bound_this,
..
}) => captured
.iter()
.map(|(_, v)| v)
.chain(bound_this.iter())
.collect(),
_ => Vec::new(),
};
vals.into_iter()
.filter_map(|v| match v {
Value::Obj(o) => Some(*o),
_ => None,
})
.collect()
}
fn global_objects_newest_first(&self) -> Vec<(String, u32)> {
let Some(g) = self.scopes.first() else {
return Vec::new();
};
let mut order: Vec<&String> = self.main_order.iter().collect();
let mut rest: Vec<(u32, &String)> = g
.vars
.index
.iter()
.filter(|(k, _)| !self.main_order.contains(k))
.map(|(k, &i)| (i, k))
.collect();
rest.sort_unstable();
order.extend(rest.into_iter().map(|(_, k)| k));
order
.into_iter()
.rev()
.filter_map(|k| {
let v = match self.main_promoted.iter().position(|p| p == k) {
Some(i) => self.main_frame_slots.get(i)?,
None => match g.vars.get(k) {
Slot::Val(v) => v,
_ => return None,
},
};
match v {
Value::Obj(o) if self.is_object_value(v) => Some((k.clone(), *o)),
_ => None,
}
})
.collect()
}
fn drop_global(&mut self, name: &str) {
match self.main_promoted.iter().position(|p| p == name) {
Some(i) => {
if let Some(v) = self.main_frame_slots.get_mut(i) {
*v = Value::Undef;
}
}
None => {
if let Some(g) = self.scopes.first_mut() {
if let Some(i) = g.vars.slot_of(name) {
g.vars.put(i, Slot::Unset);
}
}
}
}
}
pub fn set_main_layout(&mut self, order: Vec<String>, promoted: Vec<String>) {
self.main_order = order;
self.main_promoted = promoted;
self.main_frame_slots.clear();
}
fn pending_destructor(&self, handle: u32) -> Option<String> {
if self.destructed.contains(&handle) {
return None;
}
match self.objs.get(handle as usize) {
Some(PhpObj::Object { class, .. }) if self.class_has_method(class, "__destruct") => {
Some(class.clone())
}
_ => None,
}
}
}
pub fn request_shutdown(run_ok_or_uncaught: bool) -> Result<(), String> {
let exit = with_host(|h| h.pending_exit.take());
with_host(|h| {
if let Some(g) = h.scopes.first_mut() {
g.internal = true;
}
});
let r = run_shutdown_fns().and_then(|()| {
if run_ok_or_uncaught && !with_host(|h| h.destructors_off) {
call_destructors()
} else {
Ok(())
}
});
with_host(|h| {
if h.pending_exit.is_none() {
h.pending_exit = exit;
}
});
r
}
fn shutdown_escape() -> Result<(), String> {
match with_host(|h| h.pending_throw.take()) {
Some(exc) => Err(report_uncaught(exc)),
None => Ok(()),
}
}
fn run_shutdown_fns() -> Result<(), String> {
let mut i = 0;
while let Some((callback, args)) = with_host(|h| h.shutdown_fns.get(i).cloned()) {
i += 1;
call_value(callback, args)?;
with_host(|h| h.signal.take());
shutdown_escape()?;
if with_host(|h| h.pending_exit.is_some()) {
break;
}
}
Ok(())
}
fn call_destructors() -> Result<(), String> {
let mut freed: FxHashSet<u32> = FxHashSet::default();
loop {
let mut any = false;
for (name, handle) in with_host(|h| h.global_objects_newest_first()) {
if freed.contains(&handle) || with_host(|h| h.handle_refs(handle, &freed)) != 1 {
continue;
}
with_host(|h| h.drop_global(&name));
free_object(handle, &mut freed)?;
any = true;
}
if !any {
break;
}
}
let count = with_host(|h| h.objs.len()) as u32;
for handle in 0..count {
if !freed.contains(&handle) {
destruct_one(handle)?;
}
}
Ok(())
}
fn free_object(handle: u32, freed: &mut FxHashSet<u32>) -> Result<(), String> {
if !freed.insert(handle) {
return Ok(());
}
destruct_one(handle)?;
for child in with_host(|h| h.held_handles(handle)) {
if !freed.contains(&child) && with_host(|h| h.handle_refs(child, freed)) == 0 {
free_object(child, freed)?;
}
}
Ok(())
}
fn destruct_one(handle: u32) -> Result<(), String> {
if let Some(id) = with_host(|h| match h.objs.get(handle as usize) {
Some(PhpObj::Generator { id }) => Some(*id),
_ => None,
}) {
gen_destroy(id)?;
return shutdown_escape();
}
let Some(class) = with_host(|h| {
let c = h.pending_destructor(handle);
if c.is_some() {
h.destructed.insert(handle);
}
c
}) else {
return Ok(());
};
call_method(&class, "__destruct", Some(Value::Obj(handle)), Vec::new())?;
with_host(|h| h.signal.take());
shutdown_escape()
}
thread_local! {
static ERRORS_QUEUED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
impl PhpHost {
pub fn set_error_handler(&mut self, callback: Value, levels: i64) -> Value {
let prev = self
.error_handlers
.last()
.map(|(c, _)| c.clone())
.unwrap_or(Value::Undef);
self.error_handlers.push((callback, levels));
prev
}
pub fn restore_error_handler(&mut self) {
self.error_handlers.pop();
}
pub fn error_reporting_visible(&self) -> i64 {
if self.suppress > 0 {
self.error_reporting & errlevel::SILENCED
} else {
self.error_reporting
}
}
}
pub fn drain_error_handlers() -> bool {
if !ERRORS_QUEUED.with(|q| q.get()) {
return false;
}
loop {
let next = with_host(|h| {
if h.queued_errors.is_empty() {
ERRORS_QUEUED.with(|q| q.set(false));
return None;
}
let item = h.queued_errors.remove(0);
let handler = h.error_handlers.last().map(|(c, _)| c.clone());
Some((item, handler))
});
let Some(((severity, level, msg, file, line), handler)) = next else {
return false;
};
let Some(handler) = handler.filter(|c| !matches!(c, Value::Undef)) else {
with_host(|h| h.diagnose_default(&severity, level, line, &msg));
continue;
};
let r = invoke_error_handler(handler, level, &msg, file, line);
if unwinding() {
with_host(|h| h.queued_errors.clear());
ERRORS_QUEUED.with(|q| q.set(false));
return true;
}
match r {
Ok(Value::Bool(false)) => {
with_host(|h| h.diagnose_default(&severity, level, line, &msg))
}
Ok(_) => {}
Err(e) => {
with_host(|h| {
h.queued_errors.clear();
h.set_error(e);
});
ERRORS_QUEUED.with(|q| q.set(false));
return true;
}
}
}
}
pub fn invoke_error_handler(
handler: Value,
level: i64,
msg: &str,
file: String,
line: u32,
) -> Result<Value, String> {
with_host(|h| {
h.in_error_handler = true;
if let Some(s) = h.scopes.last_mut() {
s.line = line;
}
});
let args = vec![
Value::int(level),
Value::str(msg.to_string()),
Value::str(file),
Value::int(i64::from(line)),
];
let r = call_value(handler, args);
with_host(|h| {
h.in_error_handler = false;
h.signal.take();
});
r
}
impl PhpHost {
pub fn error_handler_for(&self, level: i64) -> Option<Value> {
if self.in_error_handler {
return None;
}
self.error_handlers
.last()
.filter(|(c, mask)| !matches!(c, Value::Undef) && mask & level != 0)
.map(|(c, _)| c.clone())
}
}
pub fn collect_object_hooks(
roots: &[Value],
methods: &[&str],
answer: &dyn Fn(&Value, &str, &str, Value) -> Option<Value>,
) -> Option<FxHashMap<u32, Value>> {
fn walk(
v: &Value,
methods: &[&str],
answer: &dyn Fn(&Value, &str, &str, Value) -> Option<Value>,
map: &mut FxHashMap<u32, Value>,
seen: &mut FxHashSet<u32>,
) -> bool {
let Value::Obj(id) = v else { return true };
if !seen.insert(*id) {
return true;
}
let hook = with_host(|h| {
let class = h.object_class(v)?;
let method = methods.iter().find(|m| h.class_has_method(&class, m))?;
Some((class, *method))
});
let closure_info = if hook.is_none() && methods.contains(&"__debugInfo") {
closure_debug_info(v).or_else(|| generator_debug_info(v))
} else {
None
};
let target = match hook {
None if closure_info.is_some() => {
let arr = closure_info.unwrap_or(Value::Undef);
map.insert(*id, arr.clone());
arr
}
Some((class, method)) => {
let r = call_method(&class, method, Some(v.clone()), Vec::new());
if unwinding() {
return false;
}
let Some(arr) = answer(v, &class, method, r.unwrap_or(Value::Undef)) else {
return false;
};
map.insert(*id, arr.clone());
arr
}
None => v.clone(),
};
let children: Vec<Value> = with_host(|h| {
if h.is_object(&target) {
h.object_props(&target)
.into_iter()
.map(|(_, x)| x)
.collect()
} else {
h.array_pairs(&target)
.unwrap_or_default()
.into_iter()
.map(|(_, x)| x)
.collect()
}
});
children.iter().all(|c| walk(c, methods, answer, map, seen))
}
let mut map = FxHashMap::default();
let mut seen = FxHashSet::default();
roots
.iter()
.all(|r| walk(r, methods, answer, &mut map, &mut seen))
.then_some(map)
}
pub fn try_call(f: Value) -> Result<Value, String> {
let r = call_value(f, Vec::new());
let thrown = with_host(|h| h.pending_throw.take());
let pair = match thrown {
Some(exc) => vec![Value::bool(false), exc],
None => vec![Value::bool(true), r?],
};
Ok(with_host(|h| {
let arr = h.new_array();
for v in pair {
h.arr_push_auto(&arr, v);
}
arr
}))
}
fn prelude_call_site_line(h: &PhpHost) -> Option<u32> {
let top = h.scopes.len() - 1;
let mut i = top;
while i > 0 && h.scopes[i].name.as_deref().is_some_and(is_prelude_frame) {
i -= 1;
}
(i < top).then(|| h.scopes[i].line)
}
pub const INT_PROP_MARK: char = '\u{10FF00}';
pub fn int_prop_name(n: i64) -> String {
format!("{INT_PROP_MARK}{n}")
}
pub fn prop_key(name: &str) -> Value {
match name
.strip_prefix(INT_PROP_MARK)
.and_then(|n| n.parse().ok())
{
Some(n) => Value::int(n),
None => Value::str(name.to_string()),
}
}
pub fn obj_append(obj: &Value, val: Value) {
with_host(|h| {
let next = h
.object_props(obj)
.iter()
.filter_map(|(n, _)| match prop_key(n) {
Value::Int(i) => Some(i + 1),
_ => None,
})
.max()
.unwrap_or(0);
h.obj_put_prop(obj, &int_prop_name(next), val);
});
}
pub fn obj_replace_table(obj: &Value, table: &Value) {
with_host(|h| {
let pairs = h.array_pairs(table).unwrap_or_default();
let props: IndexMap<String, Value> = pairs
.into_iter()
.map(|(k, v)| {
let name = match k {
Value::Int(n) => int_prop_name(n),
k => {
let s = h.to_str(&k);
match s.strip_prefix('\0').and_then(|r| r.split_once('\0')) {
Some((_, name)) => name.to_string(),
None => s,
}
}
};
(name, v)
})
.collect();
if let Some(PhpObj::Object { props: p, .. }) = h.as_array_mut(obj) {
*p = props;
}
});
}
pub fn spl_offset(offset: &Value) -> Result<Value, String> {
let v = with_host(|h| h.deref(offset.clone()));
let n = match &v {
Value::Int(n) => Some(*n),
Value::Str(s) => canonical_int_key(s),
Value::Bool(b) => Some(*b as i64),
Value::Float(f) => {
let f = *f;
let saved = warn_line();
if let Some(line) = with_host(|h| prelude_call_site_line(h)) {
set_warn_line(line);
}
let l = with_host(|h| {
let l = h.to_int_cast(&v);
const TWO_63: f64 = 9223372036854775808.0;
let fits = !(f >= TWO_63 || f < -TWO_63);
if l as f64 != f && fits {
let shown = crate::stdlib::types::serialize_float(f);
h.deprecated(format!(
"Implicit conversion from float {shown} to int loses precision"
));
}
l
});
set_warn_line(saved);
Some(l)
}
_ => None,
};
match n {
Some(n) => Ok(Value::int(n)),
None => {
let ty = with_host(|h| crate::stdlib::types::debug_type(h, &v));
throw_as_internal_method(
"TypeError",
&format!("Cannot access offset of type {ty} on SplFixedArray"),
)
}
}
}
pub fn throw_as_internal_method(class: &str, message: &str) -> Result<Value, String> {
let exc = new_object(class, vec![Value::str(message.to_string())])?;
with_host(|h| {
let n = h.scopes.len();
if n >= 2 {
let line = h.scopes[n - 2].line;
let file = h.scope_file(n - 2).to_string();
h.prop_set(&exc, "line", Value::int(line as i64));
h.prop_set(&exc, "file", Value::str(file));
}
});
set_pending_throw(exc);
Ok(Value::Undef)
}
pub fn warn_from_prelude(message: &str) {
let saved = warn_line();
if let Some(line) = with_host(|h| prelude_call_site_line(h)) {
set_warn_line(line);
}
with_host(|h| h.warn(message));
set_warn_line(saved);
}
pub fn deprecated_from_prelude(message: &str) {
let saved = warn_line();
if let Some(line) = with_host(|h| prelude_call_site_line(h)) {
set_warn_line(line);
}
with_host(|h| h.deprecated(message));
set_warn_line(saved);
}
pub fn warn_as_internal_method(message: &str) {
let caller = with_host(|h| {
let n = h.scopes.len();
(n >= 2).then(|| h.scopes[n - 2].line)
});
let saved = warn_line();
if let Some(line) = caller {
set_warn_line(line);
}
with_host(|h| h.warn(message));
set_warn_line(saved);
}
#[derive(Debug, Clone, Default)]
pub struct TypeScope {
pub self_class: Option<String>,
pub parent: Option<String>,
pub static_class: Option<String>,
}
impl TypeScope {
pub fn of_frame(frame: &str, static_class: Option<String>) -> TypeScope {
let self_class = frame.split_once("::").map(|(c, _)| c.to_string());
let parent = self_class
.as_ref()
.and_then(|c| with_host(|h| h.class_parent(c)));
TypeScope {
self_class,
parent,
static_class,
}
}
}
fn type_part_accepts(v: &Value, part: &str, scope: &TypeScope) -> bool {
let lower = part.to_ascii_lowercase();
if lower == "mixed" {
return true;
}
let (is_array, obj_class, is_closure) = with_host(|h| {
let arr = h.is_array(v);
let cls = if arr { None } else { h.instance_class(v) };
(arr, cls, h.is_closure(v))
});
let instance_of = |class: &str, target: &str| {
with_host(|h| h.is_a_class(&class.to_ascii_lowercase(), &target.to_ascii_lowercase()))
};
match (v, lower.as_str()) {
(Value::Undef, "null") => true,
(Value::Bool(_), "bool") => true,
(Value::Bool(true), "true") | (Value::Bool(false), "false") => true,
(Value::Int(_), "int") | (Value::Float(_), "float") | (Value::Str(_), "string") => true,
(Value::Str(_), "callable") => crate::stdlib::callable::callable_reason(v).is_none(),
(Value::Obj(_), _) if is_array => match lower.as_str() {
"array" | "iterable" => true,
"callable" => crate::stdlib::callable::callable_reason(v).is_none(),
_ => false,
},
(Value::Obj(_), _) => {
let Some(class) = obj_class else { return false };
match lower.as_str() {
"object" => true,
"iterable" => instance_of(&class, "Traversable"),
"callable" => is_closure || crate::stdlib::callable::callable_reason(v).is_none(),
"self" => scope
.self_class
.as_deref()
.is_some_and(|s| instance_of(&class, s)),
"parent" => scope
.parent
.as_deref()
.is_some_and(|s| instance_of(&class, s)),
"static" => scope
.static_class
.as_deref()
.or(scope.self_class.as_deref())
.is_some_and(|s| instance_of(&class, s)),
"array" | "int" | "float" | "string" | "bool" | "null" | "false" | "true"
| "void" | "never" => false,
_ => part
.split('&')
.all(|t| instance_of(&class, t.trim_start_matches('\\'))),
}
}
_ => false,
}
}
fn weak_scalar(h: &mut PhpHost, v: &Value, has: &dyn Fn(&str) -> bool) -> Option<Value> {
fn fits(f: f64) -> bool {
f.is_finite() && (-9223372036854775808.0..9223372036854775808.0).contains(&f)
}
if has("int") {
if has("float") && matches!(v, Value::Str(_)) {
if let Some(n) = parse_php_number_full(&h.to_str(v)) {
return Some(n);
}
} else {
let long = match v {
Value::Float(f) if f.is_nan() || !fits(*f) => None,
Value::Float(f) => {
if f.fract() != 0.0 {
let shown = crate::stdlib::types::serialize_float(*f);
h.deprecated(format!(
"Implicit conversion from float {shown} to int loses precision"
));
}
Some(*f as i64)
}
Value::Str(s) => match parse_php_number_full(s) {
Some(Value::Int(i)) => Some(i),
Some(n) => {
let f = n.to_float();
if !fits(f) {
None
} else {
if f.fract() != 0.0 {
h.deprecated(format!(
"Implicit conversion from float-string \"{s}\" to int loses precision"
));
}
Some(f as i64)
}
}
None => None,
},
Value::Bool(b) => Some(i64::from(*b)),
_ => None,
};
if let Some(l) = long {
return Some(Value::Int(l));
}
}
}
if has("float") {
let d = match v {
Value::Int(i) => Some(*i as f64),
Value::Str(s) => parse_php_number_full(s).map(|n| n.to_float()),
Value::Bool(b) => Some(f64::from(u8::from(*b))),
_ => None,
};
if let Some(d) = d {
return Some(Value::Float(d));
}
}
if has("string") && matches!(v, Value::Int(_) | Value::Float(_) | Value::Bool(_)) {
return Some(Value::str(h.to_str_diag(v)));
}
if has("bool") && matches!(v, Value::Int(_) | Value::Float(_) | Value::Str(_)) {
if matches!(v, Value::Float(f) if f.is_nan()) {
h.warn("unexpected NAN value was coerced to bool");
}
return Some(Value::bool(h.is_truthy(v)));
}
None
}
pub fn verify_type(v: Value, ty: &TypeHint, scope: &TypeScope) -> Result<Value, String> {
if ty.parts.iter().any(|p| type_part_accepts(&v, p, scope)) {
return Ok(v);
}
let has = |want: &str| ty.parts.iter().any(|p| p.eq_ignore_ascii_case(want));
let strict = with_host(|h| h.strict_types);
if strict {
if let (Value::Int(i), true) = (&v, has("float")) {
return Ok(Value::Float(*i as f64));
}
return Err(with_host(|h| h.type_name_for_error(&v)));
}
if has("string") && with_host(|h| h.is_object(&v)) {
let stringable = with_host(|h| {
h.object_class(&v)
.is_some_and(|c| h.class_has_method(&c.to_ascii_lowercase(), "__tostring"))
});
if stringable {
return Ok(Value::str(to_str_ext(&v)));
}
}
with_host(|h| match weak_scalar(h, &v, &has) {
Some(converted) => Ok(converted),
None => Err(h.type_name_for_error(&v)),
})
}
fn render_declared(ty: &TypeHint, frame: &str, static_class: Option<&str>) -> String {
let (self_class, parent) = match frame.split_once("::") {
Some((c, _)) => with_host(|h| {
let shown = h.class_display_name(&c.to_ascii_lowercase());
let parent = h
.class_parent(c)
.map(|p| h.class_display_name(&p.to_ascii_lowercase()));
(shown, parent)
}),
None => ("self".to_string(), None),
};
let mut ty = ty.clone();
if let Some(s) = static_class {
let shown = with_host(|h| h.class_display_name(&s.to_ascii_lowercase()));
for p in &mut ty.parts {
if p.eq_ignore_ascii_case("static") {
*p = shown.clone();
}
}
}
ty.declared(&self_class, parent.as_deref())
}
#[derive(Clone)]
struct CalleeCtx {
this: Option<Value>,
site: Option<DeclSite>,
}
thread_local! {
static CALLEE: RefCell<Option<CalleeCtx>> = const { RefCell::new(None) };
}
fn with_callee<R>(ctx: &CalleeCtx, f: impl FnOnce() -> R) -> R {
let saved = CALLEE.with(|c| c.replace(Some(ctx.clone())));
let r = f();
CALLEE.with(|c| *c.borrow_mut() = saved);
r
}
fn callee_shown(frame: &str) -> String {
let site = CALLEE.with(|c| c.borrow().as_ref().and_then(|x| x.site.clone()));
let Some(DeclSite::Closure(inner, line)) = site else {
return display_frame(frame);
};
let script = with_host(|h| h.script_name().to_string());
let rendered = format!("{{closure:{}:{line}}}", inner.render(&script));
match frame.split_once("::") {
Some((class, _)) => {
let shown = with_host(|h| h.class_display_name(&class.to_ascii_lowercase()));
format!("{shown}::{rendered}")
}
None => rendered,
}
}
fn throw_from_callee(
func: &str,
args: &[Value],
class: &str,
message: &str,
) -> Result<Value, String> {
let ctx = CALLEE.with(|c| c.borrow().clone());
let Some(ctx) = ctx else {
return throw_from_internal(func, args, class, message);
};
with_host(|h| {
let line = h.cur_frame_line();
h.scopes.push(Scope {
name: Some(func.to_string()),
line,
internal: true,
closure_site: ctx.site.clone(),
..Scope::default()
});
let argsarr = h.new_array();
for a in args {
h.arr_push_auto(&argsarr, a.clone());
}
h.set_var("@args", argsarr);
if let Some(this) = &ctx.this {
h.set_var("this", this.clone());
}
});
let exc = new_object(class, vec![Value::str(message.to_string())]);
with_host(|h| {
h.scopes.pop();
});
set_pending_throw(exc?);
Ok(Value::Undef)
}
fn is_prelude_helper_name(frame: &str) -> bool {
const MAGIC: &[&str] = &[
"__construct",
"__destruct",
"__callstatic",
"__get",
"__set",
"__isset",
"__unset",
"__tostring",
"__invoke",
"__set_state",
"__clone",
"__debuginfo",
"__serialize",
"__unserialize",
"__sleep",
"__wakeup",
];
let Some((class, method)) = frame.split_once("::") else {
return false;
};
class.starts_with("__")
|| (method.starts_with("__") && !MAGIC.contains(&method.to_ascii_lowercase().as_str()))
}
fn deprecation_suffix(d: &crate::ast::Deprecation) -> String {
let mut suffix = String::new();
if let Some(since) = &d.since {
suffix.push_str(&format!(" since {since}"));
}
if let Some(message) = &d.message {
suffix.push_str(&format!(", {message}"));
}
suffix
}
fn raise_deprecated_member(declaring: &str, key: &str) -> bool {
let Some((class, d)) = with_host(|h| {
let def = h.classes.get(declaring)?;
let (_, d) = def.member_deprecated.iter().find(|(k, _)| k == key)?;
Some((h.class_display_name(declaring), d.clone()))
}) else {
return false;
};
let (kind, name) = match key.split_once(':') {
Some(("case", name)) => ("Enum case", name),
Some((_, name)) => ("Constant", name),
None => ("Constant", key),
};
let msg = format!(
"{kind} {class}::{name} is deprecated{}",
deprecation_suffix(&d)
);
let level = if crate::prelude_type(declaring).is_some() {
errlevel::E_DEPRECATED
} else {
errlevel::E_USER_DEPRECATED
};
with_host(|h| h.diagnose("Deprecated", level, warn_line(), msg));
drain_error_handlers();
with_host(|h| h.pending_throw.is_some())
}
fn raise_deprecated_call(frame: &str, d: &crate::ast::Deprecation) {
let kind = if frame.contains("::") {
"Method"
} else {
"Function"
};
let msg = format!(
"{kind} {}() is deprecated{}",
display_frame(frame),
deprecation_suffix(d)
);
let level = if is_prelude_frame(frame) {
errlevel::E_DEPRECATED
} else {
errlevel::E_USER_DEPRECATED
};
with_host(|h| h.diagnose("Deprecated", level, warn_line(), msg));
}
pub mod refl_flags {
pub const PUBLIC: i64 = 1;
pub const PROTECTED: i64 = 2;
pub const PRIVATE: i64 = 4;
pub const STATIC: i64 = 16;
pub const FINAL: i64 = 32;
pub const ABSTRACT: i64 = 64;
pub const READONLY: i64 = 128;
pub const PUBLIC_SET: i64 = 1024;
pub const PROTECTED_SET: i64 = 2048;
pub const PRIVATE_SET: i64 = 4096;
}
pub struct ReflClass {
pub name: String,
pub is_readonly: bool,
pub enum_backing: Option<String>,
pub parent: Option<String>,
pub interfaces: Vec<String>,
pub traits: Vec<String>,
pub is_interface: bool,
pub is_trait: bool,
pub is_enum: bool,
pub is_abstract: bool,
pub is_final: bool,
pub internal: bool,
pub anonymous: bool,
}
pub struct ReflMember {
pub name: String,
pub class: String,
pub modifiers: i64,
pub ty: Option<crate::ast::TypeHint>,
pub has_default: bool,
}
fn vis_bits(v: Option<&Visibility>) -> i64 {
match v {
Some(Visibility::Private) => refl_flags::PRIVATE,
Some(Visibility::Protected) => refl_flags::PROTECTED,
_ => refl_flags::PUBLIC,
}
}
impl PhpHost {
fn refl_chain(&self, class: &str) -> Vec<(String, &ClassDef)> {
let mut out = Vec::new();
let mut cur = Some(unanchored(class).to_ascii_lowercase());
while let Some(c) = cur {
let Some(def) = self.classes.get(&c) else {
break;
};
cur = def.parent.as_ref().map(|p| p.to_ascii_lowercase());
out.push((c, def));
}
out
}
pub fn refl_class(&self, name: &str) -> Option<ReflClass> {
let lname = unanchored(name).to_ascii_lowercase();
if let Some(def) = self.classes.get(&lname) {
return Some(ReflClass {
name: def.name.clone(),
is_readonly: def.is_readonly,
enum_backing: def.enum_backing.clone(),
parent: def
.parent
.as_ref()
.map(|p| self.class_display_name(&p.to_ascii_lowercase())),
interfaces: self.class_interface_names(&lname),
traits: def.uses.clone(),
is_interface: def.is_interface,
is_trait: def.is_trait,
is_enum: def.is_enum,
is_abstract: def.is_abstract || def.is_interface,
is_final: def.is_final || def.is_enum,
internal: crate::prelude_type(&lname).is_some(),
anonymous: def.name.contains("@anonymous"),
});
}
let (spelled, kind, parents, _) = builtin_type(&lname)?;
Some(ReflClass {
name: spelled.to_string(),
is_readonly: false,
enum_backing: None,
parent: None,
interfaces: parents.iter().map(|p| p.to_string()).collect(),
traits: Vec::new(),
is_interface: *kind == TypeKind::Interface,
is_trait: false,
is_enum: false,
is_abstract: *kind == TypeKind::Interface,
is_final: matches!(lname.as_str(), "closure" | "generator"),
internal: true,
anonymous: false,
})
}
fn refl_method_of(&self, c: &str, def: &ClassDef, lname: &str) -> Option<ReflMember> {
if def.is_enum && !def.methods.contains_key(lname) {
let backed = def
.interfaces
.iter()
.any(|i| i.eq_ignore_ascii_case("BackedEnum"));
let spelled = match lname {
"cases" => "cases",
"from" if backed => "from",
"tryfrom" if backed => "tryFrom",
_ => return None,
};
let ret = match spelled {
"cases" => vec!["array".to_string()],
"from" => vec!["static".to_string()],
_ => vec!["static".to_string(), "null".to_string()],
};
return Some(ReflMember {
name: spelled.to_string(),
class: self.declared_class_name(c),
modifiers: refl_flags::PUBLIC | refl_flags::STATIC,
ty: Some(crate::ast::TypeHint { parts: ret }),
has_default: false,
});
}
let f = def.methods.get(lname)?;
let spelled = def
.method_sites
.iter()
.find(|(n, _)| n.eq_ignore_ascii_case(lname))
.map_or_else(|| lname.to_string(), |(n, _)| n.clone());
let mut modifiers = vis_bits(def.method_vis.get(lname));
if def.static_methods.contains(lname) {
modifiers |= refl_flags::STATIC;
}
if def.final_methods.contains(lname) {
modifiers |= refl_flags::FINAL;
}
if def.abstract_methods.contains(lname) {
modifiers |= refl_flags::ABSTRACT;
}
Some(ReflMember {
name: spelled,
class: self.declared_class_name(c),
modifiers,
ty: f.ret.clone(),
has_default: false,
})
}
pub fn refl_methods(&self, class: &str) -> Vec<ReflMember> {
let mut seen: Vec<String> = Vec::new();
let mut out = Vec::new();
for (depth, (c, def)) in self.refl_method_chain(class).into_iter().enumerate() {
let mut names: Vec<String> = def.method_sites.iter().map(|(n, _)| n.clone()).collect();
if def.is_enum {
names.extend(["cases", "from", "tryFrom"].map(String::from));
}
for name in &names {
let lname = name.to_ascii_lowercase();
if seen.contains(&lname)
|| (crate::prelude_type(&c).is_some()
&& is_prelude_helper_name(&format!("{c}::{name}")))
{
continue;
}
let Some(m) = self.refl_method_of(&c, def, &lname) else {
continue;
};
if depth > 0 && m.modifiers & refl_flags::PRIVATE != 0 {
continue;
}
seen.push(lname);
out.push(m);
}
}
out
}
pub fn refl_method(&self, class: &str, name: &str) -> Option<ReflMember> {
let lname = name.to_ascii_lowercase();
self.refl_method_chain(class)
.into_iter()
.find_map(|(c, def)| self.refl_method_of(&c, def, &lname))
}
fn refl_method_chain(&self, class: &str) -> Vec<(String, &ClassDef)> {
let mut out = self.refl_chain(class);
for i in self.class_interface_names(&unanchored(class).to_ascii_lowercase()) {
let li = i.to_ascii_lowercase();
if let Some(def) = self.classes.get(&li) {
if !out.iter().any(|(c, _)| *c == li) {
out.push((li, def));
}
}
}
out
}
pub fn refl_method_params(&self, class: &str, name: &str) -> Option<(String, Vec<Param>)> {
let lname = name.to_ascii_lowercase();
self.refl_chain(class).into_iter().find_map(|(c, def)| {
def.methods
.get(&lname)
.map(|f| (self.class_display_name(&c), f.params.clone()))
.or_else(|| {
let synthetic =
def.is_enum && matches!(lname.as_str(), "cases" | "from" | "tryfrom");
synthetic.then(|| {
let params = if lname == "cases" {
Vec::new()
} else {
vec![Param {
name: "value".to_string(),
line: 0,
default: None,
default_text: None,
variadic: false,
by_ref: false,
ty: Some(crate::ast::TypeHint {
parts: vec!["string".to_string(), "int".to_string()],
}),
attrs: Vec::new(),
}]
};
(self.class_display_name(&c), params)
})
})
})
}
fn refl_prop_of(&self, c: &str, def: &ClassDef, name: &str) -> Option<ReflMember> {
let is_static = def.static_prop_defaults.iter().any(|(n, _)| n == name);
if !is_static && !def.prop_defaults.iter().any(|(n, _)| n == name) {
return None;
}
let read = vis_bits(def.prop_vis.get(name));
let mut modifiers = read;
if is_static {
modifiers |= refl_flags::STATIC;
}
let write = match def.prop_set_vis.get(name) {
Some(v) => vis_bits(Some(v)),
None if def.readonly_props.contains(name) && read == refl_flags::PUBLIC => {
refl_flags::PROTECTED
}
None => read,
};
if write != read {
modifiers |= match write {
refl_flags::PRIVATE => refl_flags::PRIVATE_SET,
refl_flags::PROTECTED => refl_flags::PROTECTED_SET,
_ => refl_flags::PUBLIC_SET,
};
}
if def.readonly_props.contains(name) {
modifiers |= refl_flags::READONLY;
}
if def.final_props.contains(name) {
modifiers |= refl_flags::FINAL;
}
let ty = def.prop_types.get(name).cloned();
let has_default = ty.is_none() || !def.uninit_props.contains_key(name);
Some(ReflMember {
name: name.to_string(),
class: self.declared_class_name(c),
modifiers,
ty,
has_default,
})
}
fn enum_props(&self, c: &str, def: &ClassDef) -> Vec<ReflMember> {
if !def.is_enum {
return Vec::new();
}
let member = |name: &str, ty: &str| ReflMember {
name: name.to_string(),
class: self.declared_class_name(c),
modifiers: refl_flags::PUBLIC | refl_flags::READONLY | refl_flags::PROTECTED_SET,
ty: Some(crate::ast::TypeHint {
parts: vec![ty.to_string()],
}),
has_default: false,
};
let mut out = vec![member("name", "string")];
if let Some(b) = &def.enum_backing {
out.push(member("value", &b.to_ascii_lowercase()));
}
out
}
pub fn refl_props(&self, class: &str) -> Vec<ReflMember> {
let mut seen: Vec<String> = Vec::new();
let mut out = Vec::new();
for (depth, (c, def)) in self.refl_chain(class).into_iter().enumerate() {
for name in &def.prop_order {
if seen.contains(name) {
continue;
}
let Some(p) = self.refl_prop_of(&c, def, name) else {
continue;
};
if depth > 0 && p.modifiers & refl_flags::PRIVATE != 0 {
continue;
}
seen.push(name.clone());
out.push(p);
}
if depth == 0 {
for p in self.enum_props(&c, def) {
if !seen.contains(&p.name) {
seen.push(p.name.clone());
out.push(p);
}
}
}
}
out
}
pub fn refl_prop(&self, class: &str, name: &str) -> Option<ReflMember> {
self.refl_chain(class)
.into_iter()
.enumerate()
.find_map(|(depth, (c, def))| {
self.refl_prop_of(&c, def, name)
.filter(|p| depth == 0 || p.modifiers & refl_flags::PRIVATE == 0)
.or_else(|| {
(depth == 0)
.then(|| {
self.enum_props(&c, def)
.into_iter()
.find(|p| p.name == name)
})
.flatten()
})
})
}
pub fn refl_prop_default(&self, class: &str, name: &str) -> Option<(String, Chunk)> {
self.refl_chain(class).into_iter().find_map(|(c, def)| {
def.prop_defaults
.iter()
.chain(def.static_prop_defaults.iter())
.find(|(n, _)| n == name)
.map(|(_, chunk)| (c.clone(), chunk.clone()))
})
}
pub fn refl_default_text(&self, class: &str, name: &str) -> Option<String> {
self.refl_chain(class)
.into_iter()
.find(|(_, def)| {
def.prop_defaults
.iter()
.chain(def.static_prop_defaults.iter())
.any(|(n, _)| n == name)
})
.and_then(|(_, def)| {
def.default_texts
.iter()
.find(|(n, _)| n == name)
.map(|(_, t)| t.clone())
})
}
pub fn refl_const_names(&self, class: &str) -> Vec<String> {
let mut out: Vec<String> = Vec::new();
let mut visit: Vec<String> = vec![unanchored(class).to_ascii_lowercase()];
let mut done: Vec<String> = Vec::new();
while let Some(c) = (!visit.is_empty()).then(|| visit.remove(0)) {
if done.contains(&c) {
continue;
}
let Some(def) = self.classes.get(&c) else {
continue;
};
done.push(c.clone());
let names = def
.enum_cases
.iter()
.map(|(n, _)| n)
.chain(def.consts.iter().map(|(n, _)| n));
for n in names {
if !out.contains(n) {
out.push(n.clone());
}
}
if let Some(p) = &def.parent {
visit.push(p.to_ascii_lowercase());
}
visit.extend(def.interfaces.iter().map(|i| i.to_ascii_lowercase()));
}
out
}
pub fn refl_const_info(&self, class: &str, name: &str) -> Option<(String, i64, bool, bool)> {
let mut visit: Vec<String> = vec![unanchored(class).to_ascii_lowercase()];
let mut done: Vec<String> = Vec::new();
while let Some(c) = (!visit.is_empty()).then(|| visit.remove(0)) {
if done.contains(&c) {
continue;
}
let Some(def) = self.classes.get(&c) else {
continue;
};
done.push(c.clone());
let case = def.enum_cases.iter().any(|(n, _)| n == name);
if case || def.consts.iter().any(|(n, _)| n == name) {
let vis = match def.const_vis.get(name) {
Some(Visibility::Private) => 4,
Some(Visibility::Protected) => 2,
_ => 1,
};
return Some((def.name.clone(), vis, def.final_consts.contains(name), case));
}
if let Some(p) = &def.parent {
visit.push(p.to_ascii_lowercase());
}
visit.extend(def.interfaces.iter().map(|i| i.to_ascii_lowercase()));
}
None
}
pub fn refl_user_function(
&self,
name: &str,
) -> Option<(String, Vec<Param>, Option<crate::ast::TypeHint>)> {
let def = self.functions.get(&unanchored(name).to_ascii_lowercase())?;
Some((
def.declared.clone().unwrap_or_else(|| name.to_string()),
def.params.clone(),
def.ret.clone(),
))
}
pub fn refl_closure(
&self,
v: &Value,
) -> Option<(String, Vec<Param>, Option<crate::ast::TypeHint>)> {
let Some(PhpObj::Closure { params, ret, .. }) = self.as_array(v) else {
return None;
};
let name = self
.closure_callable_name(v)
.unwrap_or_else(|| "{closure}".to_string());
Some((name, params.clone(), ret.clone()))
}
}
pub fn refl_eval_default(class: &str, chunk: Chunk) -> Result<Value, String> {
run_in_class_scope(class, chunk)
}