1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
//! PHP `define`/`defined`/`constant`. Part of the `stdlib` chain; see
//! `src/stdlib/mod.rs`. Constants live in the host constant table (seeded with the
//! predefined constants), and a bare constant reference resolves through it.
use crate::host::with_host;
use fusevm::Value;
/// Dispatch the constant-management functions by lowercased name.
pub fn dispatch(name: &str, args: &[Value]) -> Option<Result<Value, String>> {
match name {
// define(name, value) — returns true, or false if already defined. The
// case-insensitive 3rd argument (removed in PHP 8) is accepted and ignored.
"define" => {
let cname = with_host(|h| h.to_str(args.first().unwrap_or(&Value::Undef)));
let value = args.get(1).cloned().unwrap_or(Value::Undef);
Some(Ok(Value::bool(with_host(|h| {
h.const_define(&cname, value)
}))))
}
// defined(name) — whether a constant of that name exists.
//
// A `Class::CONST` name is answered too, through the same lookup
// `Class::CONST` itself uses — inherited constants, interface constants
// and enum cases included. Without the `::` case both functions saw a
// class constant as a plain name that was never defined, so
// `defined("C::K")` was false and `constant("C::K")` an `Error` for
// every class in every program.
"defined" => {
let cname = with_host(|h| h.to_str(args.first().unwrap_or(&Value::Undef)));
if let Some((class, konst)) = cname.split_once("::") {
return Some(Ok(Value::bool(
crate::host::class_const_silent(class, konst).is_ok(),
)));
}
Some(Ok(Value::bool(with_host(|h| h.const_defined(&cname)))))
}
// constant(name) — the value of the named constant. Undefined is the same
// catchable `Error` a bare reference raises, with the same message.
"constant" => {
let cname = with_host(|h| h.to_str(args.first().unwrap_or(&Value::Undef)));
if let Some((class, konst)) = cname.split_once("::") {
// `class_const` raises the reference's own two messages here:
// `Undefined constant C::K` (unquoted, unlike the bare-name
// form) and `Class "Nope" not found`.
// `self`, `static` and `parent` name the calling scope's classes.
let resolved = with_host(|h| {
let scope = h.magic_class();
if scope.is_empty() {
None
} else if class.eq_ignore_ascii_case("self") {
Some(scope)
} else if class.eq_ignore_ascii_case("static") {
Some(h.lsb_class(&scope))
} else if class.eq_ignore_ascii_case("parent") {
h.class_parent(&scope)
} else {
None
}
});
return Some(crate::host::class_const(
resolved
.as_deref()
.unwrap_or(crate::host::unanchored(class)),
konst,
));
}
Some(match with_host(|h| h.const_use(&cname)) {
Some(v) => Ok(v),
None => Err(crate::builtins::throws(
"Error",
crate::builtins::undefined_constant(&cname),
)),
})
}
_ => None,
}
}