use crate::host::{with_host, TypeKind};
use fusevm::Value;
use super::common::{arg, str_arg, throws};
fn object_arg_type_error(func: &str, v: &Value) -> String {
let t = with_host(|h| h.type_name_for_error(v));
throws(
"TypeError",
format!("{func}(): Argument #1 ($object) must be of type object, {t} given"),
)
}
pub fn dispatch(name: &str, args: &[Value]) -> Option<Result<Value, String>> {
if let Some(class) = autoload_subject(name, args) {
if let Err(e) = crate::host::class_known(&class) {
return Some(Err(e));
}
}
let v = match name {
"__phplang_reflect" => return Some(reflect(args)),
"class_exists" | "interface_exists" | "trait_exists" | "enum_exists" => {
let n = str_arg(args, 0);
with_host(|h| {
let kind = h.type_kind(&n);
Value::bool(match name {
"class_exists" => matches!(kind, Some(TypeKind::Class | TypeKind::Enum)),
"interface_exists" => kind == Some(TypeKind::Interface),
"trait_exists" => kind == Some(TypeKind::Trait),
_ => kind == Some(TypeKind::Enum),
})
})
}
"method_exists" => {
let a = arg(args, 0);
if !matches!(a, Value::Str(_)) && !with_host(|h| h.is_object_value(&a)) {
let t = with_host(|h| h.type_name_for_error(&a));
return Some(Err(throws(
"TypeError",
format!(
"method_exists(): Argument #1 ($object_or_class) must be of type object|string, {t} given"
),
)));
}
let method = str_arg(args, 1);
with_host(|h| {
let class = h
.instance_class(&a)
.unwrap_or_else(|| crate::host::unanchored(&h.to_str(&a)).to_string());
let lname = method.to_ascii_lowercase();
Value::bool(
h.class_has_method(&class, &method) && !h.spl_array_forwarder(&class, &lname),
)
})
}
"property_exists" => {
let a = arg(args, 0);
let prop = str_arg(args, 1);
with_host(|h| Value::bool(h.property_exists(&a, &prop)))
}
"get_class" if args.is_empty() => {
let cls = with_host(|h| h.magic_class());
if cls.is_empty() {
return Some(Err(crate::builtins::throws_bare(
"Error",
"get_class() without arguments must be called from within a class",
)));
}
with_host(|h| h.deprecated("Calling get_class() without arguments is deprecated"));
Value::str(cls)
}
"get_called_class" => {
let cls = with_host(|h| h.lsb_class(&h.magic_class()));
if cls.is_empty() {
return Some(Err(crate::builtins::throws_bare(
"Error",
"get_called_class() must be called from within a class",
)));
}
Value::str(cls)
}
"get_class" => {
let a = arg(args, 0);
match with_host(|h| h.instance_class(&a)) {
Some(c) => Value::str(c),
None => return Some(Err(object_arg_type_error("get_class", &a))),
}
}
"get_parent_class" => {
let a = arg(args, 0);
with_host(|h| {
let class = if h.is_object(&a) {
h.object_class(&a)
} else if matches!(a, Value::Undef) {
None
} else {
Some(crate::host::unanchored(&h.to_str(&a)).to_string())
};
match class.and_then(|c| h.class_parent(&c)) {
Some(p) => Value::str(p),
None => Value::bool(false),
}
})
}
"get_object_vars" => {
let a = arg(args, 0);
if !with_host(|h| h.is_object_value(&a)) {
return Some(Err(object_arg_type_error("get_object_vars", &a)));
}
with_host(|h| {
let arr = h.new_array();
for (k, val) in h.object_props_visible(&a) {
h.arr_set_key(&arr, &crate::host::prop_key(&k), val);
}
arr
})
}
"get_class_methods" => {
let a = arg(args, 0);
let named = with_host(|h| match &a {
Value::Str(s) => h.class_exists(s),
_ => h.instance_class(&a).is_some(),
});
if !named {
let t = with_host(|h| h.type_name_for_error(&a));
return Some(Err(throws(
"TypeError",
format!("get_class_methods(): Argument #1 ($object_or_class) must be an object or a valid class name, {t} given"),
)));
}
with_host(|h| {
let class = h.instance_class(&a).unwrap_or_else(|| h.to_str(&a));
let arr = h.new_array();
for m in h.class_methods_visible(&class) {
h.arr_push_auto(&arr, Value::str(m));
}
arr
})
}
"is_a" => {
let a = arg(args, 0);
let target = str_arg(args, 1);
let allow_string = args.get(2).map(|v| with_host(|h| h.is_truthy(v)));
with_host(|h| match class_of(h, &a, allow_string.unwrap_or(false)) {
Some(class) => Value::bool(h.is_a_class(&class, &target)),
None => Value::bool(false),
})
}
"is_subclass_of" => {
let a = arg(args, 0);
let target = str_arg(args, 1);
let allow_string = args.get(2).map(|v| with_host(|h| h.is_truthy(v)));
with_host(|h| match class_of(h, &a, allow_string.unwrap_or(true)) {
Some(class) => Value::bool(
!class.eq_ignore_ascii_case(&target) && h.is_a_class(&class, &target),
),
None => Value::bool(false),
})
}
"class_parents" => {
let a = arg(args, 0);
with_host(|h| {
let Some(start) = resolve_named_class_warn(h, &a, "class_parents") else {
return Value::bool(false);
};
let arr = h.new_array();
let mut cur = h.class_parent(&start);
while let Some(p) = cur {
h.arr_set_key(&arr, &Value::str(p.clone()), Value::str(p.clone()));
cur = h.class_parent(&p);
}
arr
})
}
"class_implements" => {
let a = arg(args, 0);
with_host(
|h| match resolve_named_class_warn(h, &a, "class_implements") {
Some(c) => {
let arr = h.new_array();
for i in h.class_interface_names(&c) {
h.arr_set_key(&arr, &Value::str(i.clone()), Value::str(i));
}
arr
}
None => Value::bool(false),
},
)
}
"class_uses" => {
let a = arg(args, 0);
with_host(|h| match resolve_named_class_warn(h, &a, "class_uses") {
Some(c) => {
let arr = h.new_array();
for t in h.class_trait_names(&c) {
h.arr_set_key(&arr, &Value::str(t.clone()), Value::str(t));
}
arr
}
None => Value::bool(false),
})
}
"get_class_vars" => {
let name = str_arg(args, 0);
match crate::host::class_vars(&name) {
Ok(Some(arr)) => arr,
Ok(None) => {
return Some(Err(throws(
"TypeError",
format!("get_class_vars(): Argument #1 ($class) must be a valid class name, {name} given"),
)))
}
Err(e) => return Some(Err(e)),
}
}
"get_declared_classes" | "get_declared_interfaces" | "get_declared_traits" => {
with_host(|h| {
let kind = match name {
"get_declared_classes" => TypeKind::Class,
"get_declared_interfaces" => TypeKind::Interface,
_ => TypeKind::Trait,
};
let names: Vec<Value> =
h.declared_names(kind).into_iter().map(Value::str).collect();
let arr = h.new_array();
for n in names {
h.arr_push_auto(&arr, n);
}
arr
})
}
_ => return None,
};
Some(Ok(v))
}
fn autoload_subject(name: &str, args: &[Value]) -> Option<String> {
let Some(Value::Str(class)) = args.first() else {
return None;
};
let flag = |i: usize, default: bool| {
args.get(i)
.map_or(default, |v| with_host(|h| h.is_truthy(v)))
};
let looks_up = match name {
"method_exists" | "property_exists" | "get_parent_class" | "get_class_methods"
| "get_class_vars" => true,
"is_a" => flag(2, false),
"is_subclass_of" => flag(2, true),
"class_exists" | "interface_exists" | "trait_exists" | "enum_exists" | "class_parents"
| "class_implements" | "class_uses" => flag(1, true),
_ => false,
};
looks_up.then(|| class.to_string())
}
fn class_of(h: &crate::host::PhpHost, a: &Value, allow_string: bool) -> Option<String> {
if let Some(c) = h.instance_class(a) {
return Some(c);
}
match a {
Value::Str(_) if allow_string => {
let s = crate::host::unanchored(&h.to_str(a)).to_string();
h.class_exists(&s).then_some(s)
}
_ => None,
}
}
fn resolve_named_class(h: &crate::host::PhpHost, a: &Value) -> Option<String> {
if let Some(c) = h.instance_class(a) {
return Some(c);
}
match a {
Value::Str(_) => {
let s = crate::host::unanchored(&h.to_str(a)).to_string();
h.class_exists(&s).then_some(s)
}
_ => None,
}
}
fn resolve_named_class_warn(h: &mut crate::host::PhpHost, a: &Value, func: &str) -> Option<String> {
if let Some(c) = resolve_named_class(h, a) {
return Some(c);
}
let name = h.to_str(a);
h.warn(format!(
"{func}(): Class {name} does not exist and could not be loaded"
));
None
}
use super::common::{make_list, make_map};
fn key(s: &str) -> Value {
Value::str(s.to_string())
}
fn type_info(ty: Option<&crate::ast::TypeHint>, self_class: &str) -> Value {
let Some(ty) = ty else {
return Value::Undef;
};
let me = if self_class.is_empty() {
"self"
} else {
self_class
};
let name = ty.declared(me, Some("parent"));
let alts: Vec<&str> = name.trim_start_matches('?').split('|').collect();
let parts: Vec<Value> = if alts == ["null"] {
vec![key("null")]
} else {
alts.iter()
.filter(|p| **p != "null")
.map(|p| Value::str(p.to_string()))
.collect()
};
let null = ty.nullable() || name == "mixed" || name == "null";
make_map(vec![
(key("name"), Value::str(name.clone())),
(key("parts"), make_list(parts)),
(key("null"), Value::bool(null)),
])
}
fn member_info(m: crate::host::ReflMember) -> Value {
let ty = type_info(m.ty.as_ref(), &m.class);
make_map(vec![
(key("name"), Value::str(m.name)),
(key("class"), Value::str(m.class)),
(key("modifiers"), Value::Int(m.modifiers)),
(key("type"), ty),
(key("default"), Value::bool(m.has_default)),
])
}
fn param_rows(params: Vec<(String, bool, bool, bool, Value)>) -> Value {
let required = params
.iter()
.rposition(|(_, has_default, variadic, ..)| !has_default && !variadic)
.map_or(0, |i| i + 1);
make_list(
params
.into_iter()
.enumerate()
.map(|(i, (name, has_default, variadic, by_ref, ty))| {
make_map(vec![
(key("name"), Value::str(name)),
(key("optional"), Value::bool(i >= required)),
(key("variadic"), Value::bool(variadic)),
(key("byref"), Value::bool(by_ref)),
(key("type"), ty),
(key("default"), Value::bool(has_default)),
])
})
.collect(),
)
}
enum Callee {
User {
class: String,
params: Vec<crate::host::Param>,
},
Library(Vec<crate::argsig::LibParam>),
}
fn attr_defs_at(
kind: &str,
target: &Value,
name: &str,
param: i64,
) -> Option<(String, Vec<crate::host::AttrDef>)> {
if param < 0 {
return crate::host::attr_defs(kind, target, name);
}
match callee(kind, target, name)? {
Callee::User { class, params } => params
.into_iter()
.nth(param as usize)
.map(|p| (class, p.attrs)),
Callee::Library(_) => Some((String::new(), Vec::new())),
}
}
fn callee(kind: &str, target: &Value, name: &str) -> Option<Callee> {
match kind {
"method" => {
let class = with_host(|h| h.to_str(target));
let (class, params) = with_host(|h| h.refl_method_params(&class, name))?;
Some(Callee::User { class, params })
}
"closure" => {
let (_, params, _) = with_host(|h| h.refl_closure(target))?;
Some(Callee::User {
class: String::new(),
params,
})
}
_ => {
let fname = with_host(|h| h.to_str(target));
if let Some((_, params, _)) = with_host(|h| h.refl_user_function(&fname)) {
return Some(Callee::User {
class: String::new(),
params,
});
}
crate::argsig::library_params(&fname).map(Callee::Library)
}
}
}
fn format_default(v: &Value) -> String {
match v {
Value::Undef => "NULL".to_string(),
Value::Bool(b) => if *b { "true" } else { "false" }.to_string(),
Value::Int(n) => n.to_string(),
Value::Float(f) => {
let s = crate::host::php_gcvt(*f, 14);
if f.is_finite() && !s.contains('.') {
format!("{s}.0")
} else {
s
}
}
Value::Str(s) => format!("'{}'", crate::host::smart_str_escaped(s, usize::MAX)),
_ => {
if let Some((case, _)) = with_host(|h| h.enum_case_of(v)) {
let class = with_host(|h| h.object_class(v)).unwrap_or_default();
return format!("{class}::{case}");
}
if let Some(pairs) = with_host(|h| h.array_pairs(v)) {
let list = pairs
.iter()
.enumerate()
.all(|(i, (k, _))| matches!(k, Value::Int(n) if *n == i as i64));
let items: Vec<String> = pairs
.iter()
.map(|(k, x)| match (list, k) {
(true, _) => format_default(x),
(false, Value::Int(n)) => format!("{n} => {}", format_default(x)),
(false, k) => format!(
"'{}' => {}",
crate::host::smart_str_escaped(&with_host(|h| h.to_str(k)), usize::MAX),
format_default(x)
),
})
.collect();
return format!("[{}]", items.join(", "));
}
let class = with_host(|h| h.object_class(v)).unwrap_or_default();
format!("object({class})")
}
}
}
fn lib_default_text(d: crate::argsig::Def) -> String {
use crate::argsig::Def;
match d {
Def::Required | Def::Unknown => "<default>".to_string(),
Def::Null => "null".to_string(),
Def::Bool(b) => b.to_string(),
Def::Int(n) => n.to_string(),
Def::Float(f) => crate::host::php_gcvt(f, 17),
Def::Str(s) => format!("\"{s}\""),
Def::EmptyArray => "[]".to_string(),
}
}
fn lib_default(d: crate::argsig::Def) -> Option<Value> {
use crate::argsig::Def;
Some(match d {
Def::Required | Def::Unknown => return None,
Def::Null => Value::Undef,
Def::Bool(b) => Value::bool(b),
Def::Int(n) => Value::Int(n),
Def::Float(f) => Value::Float(f),
Def::Str(s) => Value::str(s.to_string()),
Def::EmptyArray => make_list(Vec::new()),
})
}
pub(crate) fn reflect(args: &[Value]) -> Result<Value, String> {
let op = str_arg(args, 0);
let a1 = arg(args, 1);
let s1 = str_arg(args, 1);
let s2 = str_arg(args, 2);
let s3 = str_arg(args, 3);
Ok(match op.as_str() {
"class" => {
let name = with_host(|h| h.instance_class(&a1)).unwrap_or(s1);
match with_host(|h| h.refl_class(&name)) {
None => Value::bool(false),
Some(c) => make_map(vec![
(key("name"), Value::str(c.name)),
(key("parent"), c.parent.map_or(Value::Undef, Value::str)),
(
key("interfaces"),
make_list(c.interfaces.into_iter().map(Value::str).collect()),
),
(
key("traits"),
make_list(c.traits.into_iter().map(Value::str).collect()),
),
(key("interface"), Value::bool(c.is_interface)),
(key("trait"), Value::bool(c.is_trait)),
(key("enum"), Value::bool(c.is_enum)),
(key("abstract"), Value::bool(c.is_abstract)),
(key("final"), Value::bool(c.is_final)),
(key("internal"), Value::bool(c.internal)),
(key("anonymous"), Value::bool(c.anonymous)),
(key("readonly"), Value::bool(c.is_readonly)),
(
key("backing"),
c.enum_backing.map_or(Value::Undef, Value::str),
),
]),
}
}
"methods" => make_list(
with_host(|h| h.refl_methods(&s1))
.into_iter()
.map(member_info)
.collect(),
),
"method" => with_host(|h| h.refl_method(&s1, &s2)).map_or(Value::Undef, member_info),
"props" => make_list(
with_host(|h| h.refl_props(&s1))
.into_iter()
.map(member_info)
.collect(),
),
"prop" => with_host(|h| h.refl_prop(&s1, &s2)).map_or(Value::Undef, member_info),
"const_info" => match with_host(|h| h.refl_const_info(&s1, &s2)) {
Some((class, vis, fin, case)) => make_list(vec![
Value::str(class),
Value::int(vis | if fin { 32 } else { 0 }),
Value::bool(case),
]),
None => Value::bool(false),
},
"double14" => Value::str(crate::host::php_gcvt(a1.to_float(), 14)),
"format_value" => Value::str(format_default(&a1)),
"fn_flags" => {
let (deprecated, by_ref, is_static) =
crate::host::refl_fn_flags(&s1, &arg(args, 2), &s3);
make_list(vec![
Value::bool(deprecated),
Value::bool(by_ref),
Value::bool(is_static),
])
}
"prop_default_text" => {
let kept = with_host(|h| h.refl_default_text(&s1, &s2));
match (kept, with_host(|h| h.refl_prop_default(&s1, &s2))) {
(Some(t), _) => Value::str(t),
(None, Some((class, chunk))) => {
let v = crate::host::refl_eval_default(&class, chunk)?;
Value::str(format_default(&v))
}
(None, None) => Value::Undef,
}
}
"prop_default" => match with_host(|h| h.refl_prop_default(&s1, &s2)) {
Some((class, chunk)) => crate::host::refl_eval_default(&class, chunk)?,
None => Value::Undef,
},
"const_value" => crate::host::class_const_reflect(&s1, &s2)?,
"consts" => {
let names = with_host(|h| h.refl_const_names(&s1));
let mut pairs = Vec::with_capacity(names.len());
for n in names {
let v = crate::host::class_const_reflect(&s1, &n)?;
pairs.push((Value::str(n), v));
}
make_map(pairs)
}
"attrs" => make_list(
attr_defs_at(&s1, &arg(args, 2), &s3, arg(args, 4).to_int())
.map(|(_, defs)| defs.into_iter().map(|d| Value::str(d.name)).collect())
.unwrap_or_default(),
),
"attr_args" => {
let found = attr_defs_at(&s1, &arg(args, 2), &s3, arg(args, 4).to_int());
let index = arg(args, 5).to_int() as usize;
match found.and_then(|(class, defs)| defs.into_iter().nth(index).map(|d| (class, d))) {
Some((class, def)) => crate::host::refl_eval_default(&class, def.args)?,
None => make_list(Vec::new()),
}
}
"doc" => {
crate::host::doc_comment(&s1, &arg(args, 2), &s3).map_or(Value::bool(false), Value::str)
}
"span" => match crate::host::decl_span(&s1, &arg(args, 2), &s3) {
Some(sp) => make_list(vec![
Value::str(sp.file),
Value::int(i64::from(sp.start)),
Value::int(i64::from(sp.end)),
]),
None => Value::bool(false),
},
"statics" if args.len() > 2 => {
let pairs = crate::host::method_statics(&s1, &s2);
make_map(pairs.into_iter().map(|(n, v)| (Value::str(n), v)).collect())
}
"statics" if !with_host(|h| h.is_closure(&a1)) => make_map(
crate::host::function_statics(&s1)
.into_iter()
.map(|(n, v)| (Value::str(n), v))
.collect(),
),
"statics" => {
let info = crate::host::closure_debug_info(&a1);
let st =
info.map(|i| with_host(|h| h.index_get(&i, &Value::str("static".to_string()))));
match st {
Some(v) if !matches!(v, Value::Undef) => v,
_ => make_map(Vec::new()),
}
}
"function" => {
let closure = with_host(|h| h.is_closure(&a1));
let found = if closure {
with_host(|h| h.refl_closure(&a1))
.map(|(n, _, ret)| (n, false, type_info(ret.as_ref(), "")))
} else if let Some((n, _, ret)) = with_host(|h| h.refl_user_function(&s1)) {
Some((n, false, type_info(ret.as_ref(), "")))
} else if crate::stdlib::callable::function_resolves(&s1) {
let ret = crate::argsig::return_type(&s1)
.map(|t| type_info(Some(&crate::ast::TypeHint { parts: t }), ""))
.unwrap_or(Value::Undef);
Some((crate::host::unanchored(&s1).to_ascii_lowercase(), true, ret))
} else {
None
};
match found {
None => Value::bool(false),
Some((name, internal, ret)) => make_map(vec![
(key("name"), Value::str(name)),
(key("internal"), Value::bool(internal)),
(key("closure"), Value::bool(closure)),
(key("return"), ret),
]),
}
}
"params" => match callee(&s1, &arg(args, 2), &s3) {
None => Value::bool(false),
Some(Callee::User { params, class }) => param_rows(
params
.into_iter()
.map(|p| {
let ty = type_info(p.ty.as_ref(), &class);
(p.name, p.default.is_some(), p.variadic, p.by_ref, ty)
})
.collect(),
),
Some(Callee::Library(params)) => param_rows(
params
.into_iter()
.map(|p| {
let ty = (!p.ty.is_empty()).then(|| crate::ast::TypeHint {
parts: p
.ty
.trim_start_matches('?')
.split('|')
.map(str::to_string)
.chain(p.ty.starts_with('?').then(|| "null".to_string()))
.collect(),
});
(
p.name,
p.def.is_some(),
p.variadic,
p.by_ref,
type_info(ty.as_ref(), ""),
)
})
.collect(),
),
},
"default_text" => {
let index = arg(args, 4).to_int() as usize;
match callee(&s1, &arg(args, 2), &s3) {
Some(Callee::User { class, params }) => match params.into_iter().nth(index) {
Some(crate::host::Param {
default_text: Some(t),
..
}) => Value::str(t),
Some(crate::host::Param {
default: Some(chunk),
..
}) => Value::str(format_default(&crate::host::refl_eval_default(
&class, chunk,
)?)),
_ => Value::Undef,
},
Some(Callee::Library(params)) => params.get(index).map_or(Value::Undef, |p| {
Value::str(
p.def
.map_or_else(|| "<default>".to_string(), lib_default_text),
)
}),
None => Value::Undef,
}
}
"default" => {
let index = arg(args, 4).to_int() as usize;
match callee(&s1, &arg(args, 2), &s3) {
Some(Callee::User { class, params }) => {
match params.into_iter().nth(index).and_then(|p| p.default) {
Some(chunk) => crate::host::refl_eval_default(&class, chunk)?,
None => Value::Undef,
}
}
Some(Callee::Library(params)) => params
.get(index)
.and_then(|p| p.def)
.and_then(lib_default)
.unwrap_or(Value::Undef),
None => Value::Undef,
}
}
"static_get" => crate::host::static_prop_get(&s1, &s2)?,
"static_set" => crate::host::static_prop_set(&s1, &s2, arg(args, 3))?,
"instantiate" => crate::host::alloc_object(&s1)?,
"deprecated" => {
with_host(|h| h.deprecated(s1));
Value::Undef
}
_ => Value::Undef,
})
}