use fusevm::{Chunk, VMResult, Value, VM};
use indexmap::IndexMap;
use rustc_hash::FxHashMap;
use std::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; }
#[derive(Debug, Clone)]
pub struct FuncDef {
pub params: Vec<String>,
pub chunk: 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,
},
}
enum Signal {
Return(Value),
}
#[derive(Default)]
struct Scope {
vars: FxHashMap<String, Value>,
}
pub struct PhpHost {
objs: Vec<PhpObj>,
scopes: Vec<Scope>,
functions: FxHashMap<String, FuncDef>,
capture: Option<String>,
error: Option<String>,
signal: Option<Signal>,
}
impl Default for PhpHost {
fn default() -> Self {
Self::new()
}
}
impl PhpHost {
pub fn new() -> Self {
PhpHost {
objs: Vec::new(),
scopes: vec![Scope::default()],
functions: FxHashMap::default(),
capture: None,
error: None,
signal: None,
}
}
pub fn load_program(&mut self, functions: Vec<(String, FuncDef)>) {
for (name, def) in functions {
self.functions.insert(name, def);
}
}
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) {
match &mut self.capture {
Some(buf) => buf.push_str(s),
None => {
use std::io::Write;
let mut out = std::io::stdout();
let _ = out.write_all(s.as_bytes());
}
}
}
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()
}
pub fn get_var(&self, name: &str) -> Value {
self.scopes
.last()
.and_then(|s| s.vars.get(name).cloned())
.unwrap_or(Value::Undef)
}
pub fn set_var(&mut self, name: &str, val: Value) {
if let Some(scope) = self.scopes.last_mut() {
scope.vars.insert(name.to_string(), val);
}
}
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)
}
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(*f as i64),
Value::Undef => ArrayKey::Str(String::new()),
Value::Str(s) => {
if let Ok(n) = s.parse::<i64>() {
if n.to_string() == **s {
return ArrayKey::Int(n);
}
}
ArrayKey::Str(s.to_string())
}
Value::Obj(_) => ArrayKey::Str("Array".into()),
_ => ArrayKey::Str(self.to_str(key)),
}
}
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);
return entries.get(&k).cloned().unwrap_or(Value::Undef);
}
if let Value::Str(s) = recv {
let i = key.to_int();
if i >= 0 {
if let Some(ch) = s.chars().nth(i as usize) {
return Value::str(ch.to_string());
}
}
}
Value::Undef
}
pub fn index_set_var(&mut self, name: &str, key: &Value, val: Value) {
let arr = self.ensure_array_var(name);
let k = self.norm_key(key);
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 + 1;
}
}
entries.insert(k, val);
}
}
pub fn append_var(&mut self, name: &str, val: Value) {
let arr = self.ensure_array_var(name);
if let Some(PhpObj::Array {
entries,
next_index,
}) = self.as_array_mut(&arr)
{
let k = ArrayKey::Int(*next_index);
*next_index += 1;
entries.insert(k, val);
}
}
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
}
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 += 1;
entries.insert(k, v);
}
}
pub fn arr_set_key(&mut self, arr: &Value, key: &Value, v: Value) {
let k = self.norm_key(key);
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 + 1;
}
}
entries.insert(k, v);
}
}
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 += 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 + 1;
}
}
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, .. }) = self.as_array_mut(&arr) {
return entries.pop().map(|(_, v)| v).unwrap_or(Value::Undef);
}
Value::Undef
}
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, .. }) => Some(
entries
.iter()
.map(|(k, v)| (k.to_value(), v.clone()))
.collect(),
),
_ => None,
}
}
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.array_len(v) != 0,
_ => true,
}
}
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(),
}
}
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.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(_) => "array",
_ => "unknown type",
}
}
}
thread_local! {
static HOST: RefCell<PhpHost> = RefCell::new(PhpHost::new());
}
pub fn with_host<R>(f: impl FnOnce(&mut PhpHost) -> R) -> R {
HOST.with(|h| f(&mut h.borrow_mut()))
}
pub fn reset_host() {
HOST.with(|h| *h.borrow_mut() = PhpHost::new());
}
fn run_chunk_on(chunk: Chunk) -> Result<Value, String> {
let mut vm = VM::new(chunk);
crate::builtins::install(&mut vm);
vm.set_numeric_hook(std::sync::Arc::new(|op, a, b| {
crate::builtins::numeric_hook(op, a, b)
}));
vm.enable_tracing_jit();
let outcome = vm.run();
if let Some(e) = with_host(|h| h.take_error()) {
return Err(e);
}
match outcome {
VMResult::Ok(v) => Ok(v),
VMResult::Halted => Ok(vm.stack.last().cloned().unwrap_or(Value::Undef)),
VMResult::Error(e) => Err(e),
}
}
pub fn run_main(chunk: Chunk) -> Result<Value, String> {
let r = run_chunk_on(chunk);
with_host(|h| h.signal.take());
r
}
pub fn call_function(name: &str, args: Vec<Value>) -> Result<Value, String> {
let def = with_host(|h| h.functions.get(&name.to_ascii_lowercase()).cloned());
if let Some(def) = def {
with_host(|h| {
let mut scope = Scope::default();
for (i, p) in def.params.iter().enumerate() {
scope
.vars
.insert(p.clone(), args.get(i).cloned().unwrap_or(Value::Undef));
}
h.scopes.push(scope);
});
let r = run_chunk_on(def.chunk.clone());
let sig = with_host(|h| {
h.scopes.pop();
h.signal.take()
});
return match sig {
Some(Signal::Return(v)) => Ok(v),
None => r.map(|_| Value::Undef),
};
}
crate::builtins::call_library(name, args)
}
pub fn set_return(v: Value) {
with_host(|h| h.signal = Some(Signal::Return(v)));
}
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
}
}
fn parse_php_number(s: &str) -> Value {
let t = s.trim_start();
let bytes = t.as_bytes();
let mut i = 0;
let mut seen_dot = false;
let mut seen_exp = false;
if i < bytes.len() && (bytes[i] == b'+' || bytes[i] == b'-') {
i += 1;
}
while i < bytes.len() {
match bytes[i] {
b'0'..=b'9' => i += 1,
b'.' if !seen_dot && !seen_exp => {
seen_dot = true;
i += 1;
}
b'e' | b'E' if !seen_exp && i > 0 => {
seen_exp = true;
i += 1;
if i < bytes.len() && (bytes[i] == b'+' || bytes[i] == b'-') {
i += 1;
}
}
_ => break,
}
}
let prefix = &t[..i];
if prefix.is_empty() || prefix == "+" || prefix == "-" {
return Value::int(0);
}
if seen_dot || seen_exp {
Value::float(prefix.parse().unwrap_or(0.0))
} else {
match prefix.parse::<i64>() {
Ok(n) => Value::int(n),
Err(_) => Value::float(prefix.parse().unwrap_or(0.0)),
}
}
}
pub fn is_numeric_string(s: &str) -> bool {
let t = s.trim();
if t.is_empty() {
return false;
}
parse_php_number_full(t).is_some()
}
pub fn parse_php_number_full(s: &str) -> Option<Value> {
let t = s.trim();
if let Ok(n) = t.parse::<i64>() {
return Some(Value::int(n));
}
if let Ok(f) = t.parse::<f64>() {
if f.is_finite() {
return Some(Value::float(f));
}
}
None
}