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 STATIC_CLOSURE_CAPTURE: &str = "@static-closure";
pub const AUTO_INDEX: Value = Value::Status(i32::MIN);
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 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 variadic: bool,
pub by_ref: bool,
pub ty: Option<TypeHint>,
}
#[derive(Debug, Clone)]
pub struct FuncDef {
pub params: Vec<Param>,
pub chunk: Chunk,
pub locals: Vec<String>,
pub is_generator: bool,
pub ret: Option<TypeHint>,
pub closure_site: Option<DeclSite>,
}
#[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 is_generator: bool,
pub ret: Option<TypeHint>,
pub site: Option<DeclSite>,
}
#[derive(Debug, Clone)]
pub struct ClassDef {
pub name: String,
pub parent: Option<String>,
pub interfaces: Vec<String>,
pub consts: Vec<(String, Chunk)>,
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 readonly_props: FxHashSet<String>,
pub method_vis: FxHashMap<String, Visibility>,
pub is_enum: bool,
pub is_abstract: bool,
pub is_interface: bool,
pub allow_dynamic_props: bool,
pub enum_cases: Vec<(String, Option<Chunk>)>,
}
#[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()),
}
}
}
#[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>,
is_generator: bool,
ret: Option<TypeHint>,
is_static: bool,
site: Option<DeclSite>,
},
Generator { id: u32 },
Object {
class: String,
props: IndexMap<String, Value>,
},
Ref { slot: usize },
Resource {
path: String,
buf: Vec<u8>,
pos: usize,
writable: bool,
dirty: bool,
closed: bool,
},
}
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,
}
pub struct PhpHost {
objs: Vec<PhpObj>,
scopes: Vec<Scope>,
functions: FxHashMap<String, FuncDef>,
classes: FxHashMap<String, ClassDef>,
capture: Option<String>,
ob_stack: Vec<String>,
error: Option<String>,
signal: Option<Signal>,
pending_throw: Option<Value>,
pending_exit: Option<i32>,
last_break_level: u32,
try_defs: Vec<TryDef>,
constants: FxHashMap<String, Value>,
ref_cells: Vec<Value>,
byref_out: Vec<Value>,
byref_live: Vec<bool>,
static_props: FxHashMap<String, Value>,
static_slots: FxHashMap<String, usize>,
enum_case_cache: FxHashMap<String, Value>,
script_name: String,
strict_types: bool,
suppress: usize,
pending_lsb: Option<String>,
pending_closure_site: Option<DeclSite>,
ret_ref_slot: Option<usize>,
generators: Vec<GenCell>,
fatal_reported: bool,
error_reporting: i64,
ini: FxHashMap<String, String>,
preg_error: i64,
strtok_state: Option<(String, usize)>,
cloning: Option<u32>,
readonly_init: FxHashMap<u32, FxHashSet<String>>,
magic_in_progress: Vec<(u32, String, &'static str)>,
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 {
const VK_ESCAPE: u8 = 0x1b;
let bytes = s.as_bytes();
let cut = bytes.len().min(15);
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() > 15 {
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(),
classes: FxHashMap::default(),
capture: None,
error: None,
signal: None,
pending_throw: None,
pending_exit: None,
last_break_level: 1,
try_defs: Vec::new(),
constants: predefined_constants(),
ob_stack: Vec::new(),
ref_cells: Vec::new(),
byref_out: Vec::new(),
byref_live: Vec::new(),
static_props: FxHashMap::default(),
static_slots: FxHashMap::default(),
enum_case_cache: FxHashMap::default(),
script_name: "Command line code".to_string(),
suppress: 0,
pending_lsb: None,
pending_closure_site: None,
ret_ref_slot: None,
generators: Vec::new(),
fatal_reported: false,
error_reporting: errlevel::E_ALL,
ini: default_ini(),
preg_error: 0,
strtok_state: None,
cloning: None,
readonly_init: FxHashMap::default(),
magic_in_progress: Vec::new(),
transient_objs: FxHashSet::default(),
strict_types: false,
};
h.init_superglobals();
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_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 all_class_names(&self) -> Vec<String> {
self.classes.keys().cloned().collect()
}
pub fn const_fetch(&self, name: &str) -> Option<Value> {
self.constants.get(name).cloned()
}
pub fn const_defined(&self, name: &str) -> bool {
self.constants.contains_key(name)
}
pub fn const_define(&mut self, name: &str, value: Value) -> bool {
if self.constants.contains_key(name) {
self.warn(format!(
"Constant {name} already defined, this will be an error in PHP 9"
));
return false;
}
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.classes.insert(name, def);
}
}
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());
}
}
}
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 write_out(&mut self, s: &str) {
if let Some(top) = self.ob_stack.last_mut() {
top.push_str(s);
} else 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(s.as_bytes());
}
}
pub fn ob_start(&mut self) {
self.ob_stack.push(String::new());
}
pub fn ob_level(&self) -> i64 {
self.ob_stack.len() as i64
}
pub fn ob_contents(&self) -> Option<String> {
self.ob_stack.last().cloned()
}
pub fn ob_get_clean(&mut self) -> Option<String> {
self.ob_stack.pop()
}
pub fn ob_end_clean(&mut self) -> bool {
self.ob_stack.pop().is_some()
}
pub fn ob_end_flush(&mut self) -> bool {
match self.ob_stack.pop() {
Some(s) => {
self.write_out(&s);
true
}
None => false,
}
}
pub fn ob_flush(&mut self) -> bool {
if self.ob_stack.is_empty() {
return false;
}
let s = std::mem::take(self.ob_stack.last_mut().unwrap());
let empty = self.ob_stack.pop().unwrap();
self.write_out(&s);
self.ob_stack.push(empty);
true
}
pub fn set_script_name(&mut self, name: impl Into<String>) {
self.script_name = name.into();
}
pub fn script_name(&self) -> &str {
&self.script_name
}
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(),
_ => self.object_class(v).unwrap_or_else(|| "object".to_string()),
},
_ => "mixed".to_string(),
}
}
fn apply_scalar_type(&mut self, v: Value, ty: &TypeHint) -> Result<Value, String> {
let Some(want) = ty.scalar() else {
return Ok(v);
};
if matches!(v, Value::Undef) {
return if ty.nullable() {
Ok(Value::Undef)
} else {
Err("null".to_string())
};
}
let strict = self.strict_types;
match (want, &v) {
("int", Value::Int(_))
| ("float", Value::Float(_))
| ("string", Value::Str(_))
| ("bool", Value::Bool(_)) => Ok(v),
("float", Value::Int(i)) => Ok(Value::Float(*i as f64)),
_ if strict => Err(self.type_name_for_error(&v)),
_ if !matches!(
v,
Value::Bool(_) | Value::Int(_) | Value::Float(_) | Value::Str(_)
) =>
{
Err(self.type_name_for_error(&v))
}
("bool", _) => Ok(Value::bool(self.is_truthy(&v))),
("string", _) => Ok(Value::str(self.to_str(&v))),
("int", Value::Str(_)) | ("float", Value::Str(_)) => {
let s = self.to_str(&v);
let Some(num) = parse_php_number_full(&s) else {
return Err("string".to_string());
};
match (want, &num) {
("float", n) => Ok(Value::Float(n.to_float())),
(_, Value::Int(i)) => Ok(Value::Int(*i)),
(_, n) => {
let f = n.to_float();
if f.fract() != 0.0 {
self.deprecated(format!(
"Implicit conversion from float-string \"{s}\" to int loses precision"
));
}
Ok(Value::Int(f as i64))
}
}
}
("int", Value::Float(f)) => {
let f = *f;
if f.fract() != 0.0 {
self.deprecated(format!(
"Implicit conversion from float {} to int loses precision",
self.to_str(&Value::Float(f))
));
}
Ok(Value::Int(f as i64))
}
("int", Value::Bool(b)) => Ok(Value::Int(i64::from(*b))),
("float", Value::Bool(b)) => Ok(Value::Float(f64::from(*b))),
_ => Err(self.type_name_for_error(&v)),
}
}
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 = self.to_str(&Value::Float(f));
self.warn(format!(
"The float {shown} is not representable as an int, cast occurred"
));
}
dval_to_lval(f)
}
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, self.to_str(key));
if !f.is_finite() || !(-TWO_63..TWO_63).contains(&f) {
self.warn(format!(
"The float {shown} is not representable as an int, cast occurred"
));
} else if f.fract() != 0.0 {
self.deprecated(format!(
"Implicit conversion from float {shown} to int loses precision"
));
}
}
_ => {}
}
}
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 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) {
if self.suppress > 0 || self.error_reporting & level == 0 {
return;
}
let body = format!("{msg} in {} on line {line}", self.script_name);
if self.ini_flag("display_errors") {
self.write_out(&format!("\n{severity}: {body}\n"));
}
if self.ini_flag("log_errors") {
eprintln!("PHP {severity}: {body}");
}
}
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 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_closure(v) => "Object(Closure)".to_string(),
Value::Obj(_) => match self.object_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),
}
}
fn trace_frame_name(&self, scope: &Scope) -> String {
let Some(name) = &scope.name else {
return String::new();
};
if let Some(site) = &scope.closure_site {
let rendered = match site {
DeclSite::Closure(inner, line) => {
format!("{{closure:{}:{line}}}", inner.render(&self.script_name))
}
other => other.render(&self.script_name),
};
return match name.split_once("::") {
Some((class, _)) => {
let class = self
.classes
.get(class)
.map(|d| d.name.as_str())
.unwrap_or(class);
let sep = if !matches!(scope.vars.get("this"), Slot::Unset) {
"->"
} else {
"::"
};
format!("{class}{sep}{rendered}")
}
None => rendered,
};
}
let Some((class, method)) = name.split_once("::") else {
return name.clone();
};
let class = self
.classes
.get(class)
.map(|d| d.name.as_str())
.unwrap_or(class);
let sep = if !matches!(scope.vars.get("this"), Slot::Unset) {
"->"
} else {
"::"
};
format!("{class}{sep}{method}")
}
pub fn backtrace(&self) -> String {
let mut out = String::new();
let mut n = 0;
for i in (1..self.scopes.len()).rev() {
let scope = &self.scopes[i];
let args = self
.array_pairs(&self.get_var_in(i, "@args"))
.unwrap_or_default()
.iter()
.map(|(_, v)| self.trace_arg(v))
.collect::<Vec<_>>()
.join(", ");
let site = if self.scopes[i - 1].internal {
"[internal function]".to_string()
} else {
format!("{}({})", self.script_name, self.scopes[i - 1].line)
};
out.push_str(&format!(
"#{n} {site}: {}({args})\n",
self.trace_frame_name(scope)
));
n += 1;
}
out.push_str(&format!("#{n} {{main}}"));
out
}
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();
}
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("display_errors") {
self.write_out(&format!("\n{severity}: {body}\n"));
}
if self.ini_flag("log_errors") {
eprintln!("PHP {severity}: {body}");
}
self.fatal_reported = true;
}
pub fn fatal_reported(&self) -> bool {
self.fatal_reported
}
pub fn ob_flush_all(&mut self) {
while !self.ob_stack.is_empty() {
self.ob_end_flush();
}
}
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 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);
}
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 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);
if let Some(PhpObj::Object { props, .. }) = self.as_array_mut(recv) {
props.insert(name.to_string(), 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(*next_index);
*next_index = next_index.saturating_add(1);
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);
if let Some(PhpObj::Object { props, .. }) = self.as_array_mut(recv) {
props.insert(name.to_string(), 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_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
}
}
}
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: 0,
});
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 dup = dup.clone();
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
};
let bound_this = match self.get_var("this") {
_ if is_static => None,
t @ Value::Obj(_) => Some(t),
_ => None,
};
let scope = self.current_class_ctx();
self.objs.push(PhpObj::Closure {
params: def.params,
chunk: Box::new(def.chunk),
captured,
bound_this,
scope,
is_generator: def.is_generator,
ret: def.ret,
is_static,
site: def.closure_site,
});
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,
is_generator,
ret,
site,
..
}) => Some(ClosureCall {
params: params.clone(),
chunk: (**chunk).clone(),
captured: captured.clone(),
bound_this: bound_this.clone(),
scope: 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 (params, chunk, captured, is_generator, ret, is_static, site) = match self.as_array(v) {
Some(PhpObj::Closure {
params,
chunk,
captured,
is_generator,
ret,
is_static,
site,
..
}) => (
params.clone(),
chunk.clone(),
captured.clone(),
*is_generator,
ret.clone(),
*is_static,
site.clone(),
),
_ => return None,
};
if is_static && this.is_some() {
self.warn(
"Cannot bind an instance to a static closure, this will be an error in PHP 9",
);
return Some(Value::Undef);
}
self.objs.push(PhpObj::Closure {
params,
chunk,
captured,
bound_this: this,
scope,
is_generator,
ret,
is_static,
site,
});
Some(Value::Obj((self.objs.len() - 1) as u32))
}
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 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(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 { .. }) && !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 class_exists(&self, name: &str) -> bool {
self.classes.contains_key(&name.to_ascii_lowercase())
}
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_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 {
self.functions.contains_key(&name.to_ascii_lowercase())
}
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, target)
}
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 {
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 {
self.resolve_method(class, &method.to_ascii_lowercase())
.is_some()
}
pub fn class_has_prop(&self, class: &str, name: &str) -> bool {
let mut cur = Some(class.to_ascii_lowercase());
while let Some(c) = cur {
let Some(def) = self.classes.get(&c) else {
break;
};
if def.prop_defaults.iter().any(|(n, _)| n == name) {
return true;
}
cur = def.parent.as_ref().map(|p| p.to_ascii_lowercase());
}
false
}
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_resource(&mut self, path: &str, buf: Vec<u8>, pos: usize, writable: bool) -> Value {
self.objs.push(PhpObj::Resource {
path: path.to_string(),
buf,
pos,
writable,
dirty: false,
closed: false,
});
Value::Obj((self.objs.len() - 1) as u32)
}
pub fn is_resource(&self, v: &Value) -> bool {
matches!(
self.as_array(v),
Some(PhpObj::Resource { closed: false, .. })
)
}
pub fn res_eof(&self, v: &Value) -> bool {
match self.as_array(v) {
Some(PhpObj::Resource { buf, pos, .. }) => *pos >= buf.len(),
_ => true,
}
}
pub fn res_tell(&self, v: &Value) -> Option<i64> {
match self.as_array(v) {
Some(PhpObj::Resource {
pos, closed: false, ..
}) => Some(*pos as i64),
_ => None,
}
}
pub fn res_read(&mut self, v: &Value, n: usize) -> Option<String> {
if let Some(PhpObj::Resource { buf, pos, .. }) = self.as_array_mut(v) {
let end = (*pos + n).min(buf.len());
let out = String::from_utf8_lossy(&buf[*pos..end]).into_owned();
*pos = end;
Some(out)
} else {
None
}
}
pub fn res_gets(&mut self, v: &Value, max: Option<usize>) -> Option<String> {
if let Some(PhpObj::Resource { buf, pos, .. }) = self.as_array_mut(v) {
if *pos >= buf.len() {
return None;
}
let cap = max.map(|m| (*pos + m).min(buf.len())).unwrap_or(buf.len());
let mut end = *pos;
while end < cap && buf[end] != b'\n' {
end += 1;
}
if end < cap && buf[end] == b'\n' {
end += 1; }
let out = String::from_utf8_lossy(&buf[*pos..end]).into_owned();
*pos = end;
Some(out)
} else {
None
}
}
pub fn res_write(&mut self, v: &Value, bytes: &[u8]) -> Option<usize> {
if let Some(PhpObj::Resource {
buf,
pos,
writable: true,
dirty,
closed: false,
..
}) = self.as_array_mut(v)
{
if *pos > buf.len() {
buf.resize(*pos, 0);
}
for (i, b) in bytes.iter().enumerate() {
if *pos + i < buf.len() {
buf[*pos + i] = *b;
} else {
buf.push(*b);
}
}
*pos += bytes.len();
*dirty = true;
Some(bytes.len())
} else {
None
}
}
pub fn res_seek(&mut self, v: &Value, offset: i64, whence: i64) -> bool {
if let Some(PhpObj::Resource { buf, pos, .. }) = self.as_array_mut(v) {
let base = match whence {
1 => *pos as i64,
2 => buf.len() as i64,
_ => 0,
};
*pos = (base + offset).clamp(0, buf.len() as i64) as usize;
true
} else {
false
}
}
pub fn res_flush_data(&mut self, v: &Value) -> Option<(String, Vec<u8>)> {
if let Some(PhpObj::Resource {
path, buf, dirty, ..
}) = self.as_array_mut(v)
{
if *dirty {
*dirty = false;
return Some((path.clone(), buf.clone()));
}
}
None
}
pub fn res_close(&mut self, v: &Value) -> bool {
if let Some(PhpObj::Resource { closed, .. }) = self.as_array_mut(v) {
if !*closed {
*closed = true;
return true;
}
}
false
}
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;
}
if let Some(PhpObj::Object { props, .. }) = self.as_array_mut(recv) {
props.insert(name.to_string(), val);
}
}
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"
));
}
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 prop_ensure_array(&mut self, recv: &Value, name: &str) -> Value {
let cur = self.prop_get(recv, name);
if self.is_array(&cur) {
return cur;
}
let arr = self.new_array();
self.prop_set(recv, name, arr.clone());
arr
}
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> {
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_dir(&self) -> String {
let name = self.script_name();
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);
if self.readonly_is_init(recv, name) {
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 readonly_unset_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)?;
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) {
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 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);
}
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) {
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 method_l = method.to_ascii_lowercase();
let mut cur = Some(class.to_ascii_lowercase());
let found = loop {
let Some(c) = cur else {
break None;
};
let Some(def) = self.classes.get(&c) else {
break None;
};
if let Some(v) = def.method_vis.get(&method_l) {
break Some((c, *v));
}
cur = def.parent.as_ref().map(|p| p.to_ascii_lowercase());
};
let Some((declaring, vis)) = found else {
return Ok(());
};
if self.visibility_allows(vis, &declaring) {
return Ok(());
}
let vname = match vis {
Visibility::Private => "private",
Visibility::Protected => "protected",
Visibility::Public => unreachable!(),
};
let scope = match self.current_class_ctx() {
Some(c) => format!("scope {c}"),
None => "global scope".to_string(),
};
Err(format!(
"Call to {vname} method {class}::{method}() from {scope}"
))
}
fn magic_call_name(&self, class: &str, has_this: bool) -> Option<&'static str> {
let magic = if has_this { "__call" } else { "__callstatic" };
self.resolve_method(class, magic)
.map(|_| 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.resolve_method(class, &method_l).is_none() {
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),
},
}
}
fn class_prop_default_chunks(&self, class: &str) -> Option<Vec<(String, Chunk)>> {
let cl = class.to_ascii_lowercase();
if !self.classes.contains_key(&cl) {
return None;
}
let mut chain: Vec<&ClassDef> = Vec::new();
let mut cur = Some(cl);
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 map: IndexMap<String, Chunk> = IndexMap::new();
for def in chain.into_iter().rev() {
for (name, chunk) in &def.prop_defaults {
map.insert(name.clone(), chunk.clone());
}
}
Some(map.into_iter().collect())
}
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 get_static_stored(&self, key: &str) -> Option<Value> {
self.static_props.get(key).cloned()
}
fn set_static_stored(&mut self, key: &str, val: Value) {
self.static_props.insert(key.to_string(), val);
}
pub fn bind_static_local(&mut self, name: &str, slot_key: &str, init: Value) {
let slot = 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));
}
}
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 resolve_const_chunk(&self, class: &str, name: &str) -> Option<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.consts.iter().find(|(n, _)| n == name) {
return Some(chunk.clone());
}
cur = def.parent.as_ref().map(|p| 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(s.to_string()),
},
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 = s.as_bytes();
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(String::from_utf8_lossy(&bytes[b..b + 1]).into_owned());
}
}
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 = replacement.as_bytes()[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 = cur.as_bytes().to_vec();
if idx >= bytes.len() {
bytes.resize(idx + 1, b' ');
}
bytes[idx] = byte;
Ok(Some(String::from_utf8_lossy(&bytes).into_owned()))
}
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(*next_index);
*next_index = next_index.saturating_add(1);
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) {
let Some((last, inter)) = keys.split_last() else {
return;
};
let arr = self.ensure_path_array(name, inter);
self.arr_set_key(&arr, last, val);
}
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 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_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(*next_index);
*next_index = next_index.saturating_add(1);
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 = 0;
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 *n == before - 1 {
*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) => s.to_string(),
Value::Obj(_) => "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(_) => 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 self.is_resource(v) {
"resource"
} else {
"object"
}
}
_ => "unknown type",
}
}
}
pub fn is_superglobal(name: &str) -> bool {
matches!(
name,
"_SERVER"
| "_GET"
| "_POST"
| "_REQUEST"
| "_COOKIE"
| "_FILES"
| "_ENV"
| "_SESSION"
| "GLOBALS"
| "argv"
| "argc"
)
}
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);
si("PHP_MAJOR_VERSION", 8);
si("PHP_MINOR_VERSION", 3);
si("PHP_RELEASE_VERSION", 0);
si("PHP_VERSION_ID", 80300);
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("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("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_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("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("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("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);
let mut ss = |k: &str, v: &str| {
m.insert(k.to_string(), Value::str(v.to_string()));
};
ss("PHP_EOL", "\n");
ss("PHP_VERSION", "8.3.0");
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("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);
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));
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),
}
#[derive(Default)]
struct GenContext {
frames: Vec<Scope>,
signal: Option<Signal>,
pending_throw: Option<Value>,
error: Option<String>,
}
struct GenCell {
coro: Option<GenCoro>,
yielder: *const GenYielder,
ctx: GenContext,
cur_key: Value,
cur_val: Value,
auto_key: i64,
ret: Value,
started: bool,
done: bool,
inject: Option<GenInject>,
}
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;
h.generators.push(GenCell {
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,
done: false,
inject: None,
});
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()),
};
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(());
if let Some(GenInject::Throw(e)) = with_host(|h| h.generators[id as usize].inject.take()) {
set_pending_throw(e);
return Err("__generator_throw__".to_string());
}
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_rewind(&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| h.generators[id as usize].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_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].started) {
gen_resume(id, Value::Undef)?;
}
Ok(())
}
pub fn gen_valid(gen: &Value) -> Result<bool, String> {
gen_rewind(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_rewind(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_rewind(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_rewind(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_rewind(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 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(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> {
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())),
};
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_on(chunk);
with_host(|h| h.signal.take());
if let Some(exc) = with_host(|h| h.pending_throw.take()) {
let body = with_host(|h| {
let class = h
.object_class(&exc)
.unwrap_or_else(|| "Exception".to_string());
let msg = h.to_str(&h.prop_get(&exc, "message"));
let file = h.to_str(&h.prop_get(&exc, "file"));
let line = h.prop_get(&exc, "line").to_int();
let trace = h.to_str(&h.prop_get(&exc, "trace"));
format!(
"Uncaught {class}: {msg} in {file}:{line}\nStack trace:\n{trace}\n \
thrown in {file} on line {line}"
)
});
with_host(|h| {
h.fatal("Fatal error", &body);
h.ob_flush_all();
});
return Err(format!("Fatal error: {body}"));
}
with_host(|h| h.ob_flush_all());
r
}
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 {
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,
}
fn call_function_dispatched(name: &str, args: Vec<Value>, how: Dispatch) -> Result<Value, String> {
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(
name,
Signature {
params: &def.params,
ret: def.ret.as_ref(),
},
def.chunk,
Vec::new(),
args,
Vec::new(),
def.is_generator,
&def.locals,
);
}
call_library_throwing(name, args, how)
}
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" => argc == 2,
_ => 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()),
}
}
fn calls_back(name: &str) -> bool {
matches!(
name,
"array_map"
| "array_filter"
| "array_reduce"
| "array_walk"
| "array_walk_recursive"
| "array_find"
| "array_find_key"
| "array_any"
| "array_all"
| "array_udiff"
| "array_uintersect"
| "usort"
| "uasort"
| "uksort"
| "preg_replace_callback"
| "iterator_apply"
)
}
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());
if let Err(e) = crate::argtypes::check_call(name, &args) {
return if opcode {
throw_frameless_typed(&e)
} else {
throw_from_internal_typed(name, &args, 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) => {
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, &args, message));
}
if let Some((class, code, message)) = crate::builtins::untag_throw_code(&e) {
return throw_from_internal_args(
name,
&args,
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, &args, 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 def = with_host(|h| h.functions.get(&name.to_ascii_lowercase()).cloned());
if let Some(def) = def {
return invoke_with_locals(
name,
Signature {
params: &def.params,
ret: def.ret.as_ref(),
},
def.chunk,
Vec::new(),
args,
named,
def.is_generator,
&def.locals,
);
}
let mut all = args;
all.extend(named.into_iter().map(|(_, v)| v));
call_function(name, all)
}
#[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_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 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)? {
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)? {
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) -> 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;
return Ok(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(),
};
let saved = warn_line();
set_warn_line(line);
let r = h.apply_scalar_type(cur, &ty);
set_warn_line(saved);
r.map(|converted| match slot {
Some(s) => {
h.ref_cell_set(s, converted);
v
}
None => converted,
})
}));
}
Ok(with_host(|h| {
let saved = warn_line();
set_warn_line(p.line);
let r = h.apply_scalar_type(v, &ty);
set_warn_line(saved);
r
}))
}
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| t.render()).unwrap_or_default();
let (file, line) = with_host(|h| (h.script_name().to_string(), h.cur_frame_line()));
let shown = display_frame(frame);
throw_from_internal(
frame,
called_with,
"TypeError",
&format!(
"{shown}(): Argument #{pos}{name} must be of type {rendered}, {given} given, \
called in {file} on line {line}"
),
)
}
fn check_ret_type(
frame: &str,
ret: Option<&TypeHint>,
called_with: &[Value],
v: Value,
) -> Result<Value, String> {
let Some(ty) = ret else { return Ok(v) };
if ty.scalar().is_none() {
return Ok(v);
}
let ty = ty.clone();
match with_host(|h| h.apply_scalar_type(v, &ty)) {
Ok(nv) => Ok(nv),
Err(given) => throw_from_internal(
frame,
called_with,
"TypeError",
&format!(
"{}(): Return value must be of type {}, {given} returned",
display_frame(frame),
ty.render()
),
),
}
}
struct Signature<'a> {
params: &'a [Param],
ret: Option<&'a TypeHint>,
}
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 } = sig;
let Some((args, named)) = check_arg_types(frame, params, args, named)? else {
return Ok(Value::Undef);
};
let ret_args: Vec<Value> = match ret.filter(|t| t.scalar().is_some()) {
Some(_) => args.clone(),
None => Vec::new(),
};
let bound = with_host(|h| {
let scope = Scope {
name: Some(frame.to_string()),
static_class: h.lsb_take(),
closure_site: h.closure_site_take(),
..Scope::default()
};
h.scopes.push(scope);
h.seed_slots(locals);
let argsarr = h.new_array();
for a in &args {
h.arr_push_auto(&argsarr, a.clone());
}
for (_, v) in &named {
h.arr_push_auto(&argsarr, v.clone());
}
h.set_var("@args", argsarr);
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;
}
}
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());
h.scopes.pop();
h.signal.take()
});
match sig {
Some(Signal::Return(v)) => check_ret_type(frame, ret, &ret_args, v),
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));
invoke(
&frame,
Signature {
params: &cc.params,
ret: cc.ret.as_ref(),
},
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((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((class.to_string(), method.to_string(), None));
}
}
None
}
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) {
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) {
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 scope_class = with_host(|h| resolve_bind_scope(h, closure, &obj, scope));
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,
_obj: &Value,
scope: Option<Value>,
) -> Option<String> {
match scope {
Some(Value::Obj(_)) => h.object_class(scope.as_ref().unwrap()),
Some(Value::Str(s)) if !s.eq_ignore_ascii_case("static") => Some(s.to_string()),
_ => h.closure_scope(closure),
}
}
pub fn closure_call(closure: &Value, obj: Value, args: Vec<Value>) -> Result<Value, String> {
let bound = closure_bind(closure, obj.clone(), Some(obj))?;
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(format!("call to undefined method Closure::{other}()")),
}
}
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 file = h.script_name().to_string();
let line = h.cur_frame_line() as i64;
let trace = h.backtrace();
h.prop_set(obj, "file", Value::str(file));
h.prop_set(obj, "line", Value::int(line));
h.prop_set(obj, "trace", Value::str(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 {
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.script_name()
);
h.fatal("Fatal error", &body);
h.ob_flush_all();
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 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, chunk) in defaults {
let v = run_chunk_on(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);
if with_host(|h| h.resolve_method(&cl, "__construct").is_some()) {
with_host(|h| h.lsb_set_for_next_call(class));
call_method(&cl, "__construct", Some(obj.clone()), args)?;
}
Ok(obj)
}
pub fn new_object_named(
class: &str,
args: Vec<Value>,
named: Vec<(String, Value)>,
) -> Result<Value, String> {
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, chunk) in defaults {
let v = run_chunk_on(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);
if with_host(|h| h.resolve_method(&cl, "__construct").is_some()) {
with_host(|h| h.lsb_set_for_next_call(class));
call_method_named(&cl, "__construct", Some(obj.clone()), 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(),
},
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(),
},
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" => {
Ok(args.into_iter().next().unwrap_or(Value::Undef))
}
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(),
},
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 clone_object(v: Value) -> Result<Value, String> {
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.resolve_method(&class.to_ascii_lowercase(), "__clone")
.is_some()
}) {
in_clone_hook(©, || {
call_method(
&class.to_ascii_lowercase(),
"__clone",
Some(copy.clone()),
Vec::new(),
)
})?;
}
}
Ok(copy)
}
pub fn class_const(class: &str, name: &str) -> Result<Value, String> {
if let Some(chunk) = with_host(|h| h.resolve_const_chunk(class, name)) {
return run_chunk_on(chunk);
}
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 needle_s = with_host(|h| h.to_str(&needle));
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 = match with_host(|h| h.to_number(&needle)) {
_ if matches!(needle, Value::Int(_)) => needle_s.clone(),
_ => format!("\"{needle_s}\""),
};
let spelled = with_host(|h| h.declared_class_name(class));
throw_from_internal(
&format!("{spelled}::from"),
&[needle],
"ValueError",
&format!("{shown} is not a valid backing value for enum {spelled}"),
)
}
pub fn static_prop_get(class: &str, name: &str) -> Result<Value, String> {
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(v) = with_host(|h| h.get_static_stored(&key)) {
return Ok(v);
}
let v = run_chunk_on(chunk)?;
with_host(|h| h.set_static_stored(&key, v.clone()));
Ok(v)
}
pub fn static_prop_set(class: &str, name: &str, val: Value) -> Result<Value, String> {
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}"),
));
};
with_host(|h| h.set_static_stored(&key, val.clone()));
Ok(val)
}
pub fn foreach_prep(v: Value) -> Result<Value, String> {
if with_host(|h| h.is_array(&v)) {
return Ok(v);
}
if with_host(|h| h.is_generator_val(&v)) {
let arr = with_host(|h| h.new_array());
while gen_valid(&v)? {
let cur = gen_current(&v)?;
let key = gen_key(&v)?;
with_host(|h| match key {
Value::Undef => h.arr_push_auto(&arr, cur),
k => h.arr_set_key(&arr, &k, cur),
});
gen_next(&v)?;
}
return Ok(arr);
}
let Some(class) = with_host(|h| h.object_class(&v)) else {
return Ok(with_host(|h| h.new_array()));
};
if with_host(|h| h.class_has_method(&class, "getIterator")) {
let it = call_method(&class, "getIterator", Some(v.clone()), Vec::new())?;
return foreach_prep(it);
}
if with_host(|h| h.class_has_method(&class, "valid") && h.class_has_method(&class, "current")) {
let arr = with_host(|h| h.new_array());
if with_host(|h| h.class_has_method(&class, "rewind")) {
call_method(&class, "rewind", Some(v.clone()), Vec::new())?;
}
let has_key = with_host(|h| h.class_has_method(&class, "key"));
for _ in 0..100_000_000u64 {
let valid = call_method(&class, "valid", Some(v.clone()), Vec::new())?;
if !with_host(|h| h.is_truthy(&valid)) {
break;
}
let cur = call_method(&class, "current", Some(v.clone()), Vec::new())?;
let key = if has_key {
call_method(&class, "key", Some(v.clone()), Vec::new())?
} else {
Value::Undef
};
with_host(|h| match key {
Value::Undef => h.arr_push_auto(&arr, cur),
k => h.arr_set_key(&arr, &k, cur),
});
call_method(&class, "next", Some(v.clone()), Vec::new())?;
}
return Ok(arr);
}
let props = with_host(|h| h.object_props(&v));
Ok(with_host(|h| {
let a = h.new_array();
for (k, val) in props {
h.arr_set_key(&a, &Value::str(k), val);
}
a
}))
}
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 = t.as_bytes();
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 = s.as_bytes().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);
}
String::from_utf8_lossy(&b).into_owned()
}
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 = s.as_bytes();
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,
}
}
pub fn display_class(name: &str) -> &str {
match name.split_once('\0') {
Some((head, _)) => head,
None => name,
}
}
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_closure(v) => "Closure".into(),
Value::Obj(_) => h.object_class(v).unwrap_or_else(|| "object".into()),
_ => "mixed".into(),
}
}