use crate::host::{call_value, call_value_named, with_host};
use crate::stdlib::common::*;
use fusevm::Value;
fn known_builtins() -> &'static std::collections::HashSet<&'static str> {
use std::sync::OnceLock;
static SET: OnceLock<std::collections::HashSet<&'static str>> = OnceLock::new();
SET.get_or_init(|| {
const NOT_FUNCTIONS: &[&str] = &[
"Predefined constant",
"Keyword",
"Operator",
"Prelude class",
"Language construct",
"Magic method",
"Cast",
"Built-in object methods",
];
let mut set: std::collections::HashSet<&'static str> = crate::corpus::CORPUS
.iter()
.filter(|(_, chapter, ..)| !NOT_FUNCTIONS.contains(chapter))
.map(|(name, ..)| *name)
.collect();
set.insert("exit");
set.insert("die");
set
})
}
fn invoke_callable(callee: Value, args: Vec<Value>) -> Result<Value, String> {
call_value(callee, args)
}
const NOT_IN_PHP: &[&str] = &["__cast_array", "__cast_object", "gmp_pow2"];
pub(crate) fn function_resolves(name: &str) -> bool {
let name = name.strip_prefix('\\').unwrap_or(name);
let lname = name.to_ascii_lowercase();
!NOT_IN_PHP.contains(&lname.as_str()) && dispatches(&lname)
}
pub(crate) fn is_library_function(name: &str) -> bool {
let lname = name.to_ascii_lowercase();
!NOT_IN_PHP.contains(&lname.as_str()) && known_builtins().contains(lname.as_str())
}
pub(crate) fn dispatches(name: &str) -> bool {
let name = name.strip_prefix('\\').unwrap_or(name);
with_host(|h| h.function_defined(name))
|| known_builtins().contains(name.to_ascii_lowercase().as_str())
|| fusevm::ffi::is_registered(name)
}
fn callable_resolves(v: &Value) -> bool {
callable_reason(v).is_none()
}
pub(crate) fn callable_reason(v: &Value) -> Option<String> {
const NOT_A_CALLABLE: &str = "no array or string given";
if with_host(|h| h.is_closure(v)) {
return None;
}
if with_host(|h| h.is_array(v)) {
let pairs = with_host(|h| h.array_pairs(v)).unwrap_or_default();
if pairs.len() != 2 {
return Some("array callback must have exactly two members".to_string());
}
if !matches!(pairs[0].0, Value::Int(0)) || !matches!(pairs[1].0, Value::Int(1)) {
return Some("array callback has to contain indices 0 and 1".to_string());
}
let target = pairs[0].1.clone();
let method = with_host(|h| h.to_str(&pairs[1].1));
if with_host(|h| h.is_object(&target)) {
let Some(class) = with_host(|h| h.object_class(&target)) else {
return Some(NOT_A_CALLABLE.to_string());
};
return method_reason(&class, &method, true);
}
if !matches!(target, Value::Str(_)) {
return Some("first array member is not a valid class name or object".to_string());
}
let class = crate::host::anchored_class(&with_host(|h| h.to_str(&target)));
return class_reason(&class).or_else(|| method_reason(&class, &method, false));
}
if with_host(|h| h.is_object(v)) {
let invokable = with_host(|h| {
h.object_class(v)
.is_some_and(|c| h.class_has_method(&c, "__invoke"))
});
return (!invokable).then(|| NOT_A_CALLABLE.to_string());
}
let Value::Str(s) = v else {
return Some(NOT_A_CALLABLE.to_string());
};
match s.as_str().split_once("::") {
Some((class, method)) => {
let class = crate::host::anchored_class(class);
class_reason(&class).or_else(|| method_reason(&class, method, false))
}
None => (!function_resolves(s.as_str()))
.then(|| format!("function \"{s}\" not found or invalid function name")),
}
}
fn class_reason(class: &str) -> Option<String> {
with_host(|h| (!h.class_exists(class)).then(|| format!("class \"{class}\" not found")))
}
fn method_reason(class: &str, method: &str, has_this: bool) -> Option<String> {
let shown = with_host(|h| h.class_display_name(&class.to_ascii_lowercase()));
match with_host(|h| h.method_dispatch(class, method, has_this)) {
crate::host::MethodDispatch::Magic => None,
crate::host::MethodDispatch::Direct => {
let statically = !has_this && !with_host(|h| h.method_is_static(class, method));
statically.then(|| {
format!("non-static method {shown}::{method}() cannot be called statically")
})
}
crate::host::MethodDispatch::Denied(_) => {
let vis = with_host(|h| h.method_visibility_name(class, method)).unwrap_or("private");
Some(format!("cannot access {vis} method {shown}::{method}()"))
}
crate::host::MethodDispatch::Undefined => {
Some(format!("class {shown} does not have a method \"{method}\""))
}
}
}
pub fn dispatch(name: &str, args: &[Value]) -> Option<Result<Value, String>> {
match name {
"call_user_func" => {
let callee = arg(args, 0);
let rest = args.get(1..).map(<[Value]>::to_vec).unwrap_or_default();
Some(invoke_callable(callee, rest))
}
"call_user_func_array" => {
let callee = arg(args, 0);
let arr = arg(args, 1);
let (mut pos, mut named) = (Vec::new(), Vec::new());
for (k, v) in with_host(|h| h.array_pairs(&arr)).unwrap_or_default() {
match k {
Value::Str(name) => named.push((name.to_string(), v)),
_ => pos.push(v),
}
}
Some(call_value_named(callee, pos, named))
}
"is_callable" => Some(Ok(Value::bool(callable_resolves(&arg(args, 0))))),
"function_exists" => Some(Ok(Value::bool(function_resolves(&str_arg(args, 0))))),
_ => None,
}
}