pub const NS_FALLBACK: char = '\u{1}';
pub fn ns_fallback(qualified: &str) -> String {
format!("{NS_FALLBACK}{qualified}")
}
pub fn split_ns_fallback(name: &str) -> Option<(&str, &str)> {
let qualified = name.strip_prefix(NS_FALLBACK)?;
let global = qualified.rsplit('\\').next().unwrap_or(qualified);
Some((qualified, global))
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BinOp {
Add,
Sub,
Mul,
Div,
Mod,
Pow,
Concat, LooseEq, LooseNe, StrictEq, StrictNe, Lt,
Gt,
Le,
Ge,
Spaceship, BitAnd, BitOr, BitXor, Shl, Shr, And, Or, }
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum UnOp {
Neg, Pos, Not, BitNot, }
#[derive(Debug, Clone, PartialEq)]
pub enum StrPart {
Lit(String),
Var(String),
Raw(String),
}
#[derive(Debug, Clone)]
pub enum InterpPart {
Lit(String),
Expr(Box<Expr>),
}
#[derive(Debug, Clone)]
pub enum ClassRef {
Name(String),
Expr(Box<Expr>),
}
impl ClassRef {
pub fn name(&self) -> Option<&str> {
match self {
ClassRef::Name(n) => Some(n),
ClassRef::Expr(_) => None,
}
}
pub fn operand(&self) -> Option<&Expr> {
match self {
ClassRef::Name(_) => None,
ClassRef::Expr(e) => Some(e),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ArraySyntax {
Short,
List,
Long,
}
#[derive(Debug, Clone)]
pub struct ArrayElem {
pub key: Option<Expr>,
pub value: Expr,
pub by_ref: bool,
}
impl ArrayElem {
pub fn new(key: Option<Expr>, value: Expr) -> Self {
Self {
key,
value,
by_ref: false,
}
}
}
#[derive(Debug, Clone)]
pub enum Member {
Name(String),
Dyn(Box<Expr>),
}
impl Member {
pub fn name(&self) -> Option<&str> {
match self {
Member::Name(n) => Some(n),
Member::Dyn(_) => None,
}
}
pub fn operand(&self) -> Option<&Expr> {
match self {
Member::Name(_) => None,
Member::Dyn(e) => Some(e),
}
}
}
#[derive(Debug, Clone)]
pub enum Expr {
Null,
Bool(bool),
Int(i64),
Float(f64),
Str(String),
Interp(Vec<InterpPart>),
Var(String),
VarVar(Box<Expr>),
Array(Vec<ArrayElem>, ArraySyntax),
Hole,
Index(Box<Expr>, Box<Expr>),
ListElem(Box<Expr>, Box<Expr>),
Append(Box<Expr>),
Unary(UnOp, Box<Expr>),
Binary(BinOp, Box<Expr>, Box<Expr>),
Assign(Box<Expr>, Option<BinOp>, Box<Expr>),
IncDec {
target: Box<Expr>,
inc: bool,
prefix: bool,
},
Call(String, Vec<Expr>),
Spread(Box<Expr>),
CallValue(Box<Expr>, Vec<Expr>),
Fcc {
callable: Box<Expr>,
instance: bool,
},
Closure {
params: Vec<Param>,
uses: Vec<Capture>,
body: Vec<Stmt>,
ret: Option<TypeHint>,
is_static: bool,
line: u32,
end_line: u32,
doc: Option<String>,
attrs: Vec<Attr>,
},
ArrowFn {
params: Vec<Param>,
body: Box<Expr>,
ret: Option<TypeHint>,
is_static: bool,
line: u32,
end_line: u32,
doc: Option<String>,
attrs: Vec<Attr>,
},
New(String, Vec<Expr>),
NewDyn(Box<Expr>, Vec<Expr>),
NewAnon {
decl: Box<ClassDecl>,
args: Vec<Expr>,
line: u32,
},
PropGet(Box<Expr>, Member),
MethodCall(Box<Expr>, Member, Vec<Expr>),
NullsafePropGet(Box<Expr>, Member),
NullsafeMethodCall(Box<Expr>, Member, Vec<Expr>),
NamedArg(String, Box<Expr>),
StaticGet(ClassRef, String),
StaticProp(ClassRef, Member),
StaticCall(ClassRef, String, Vec<Expr>),
Clone(Box<Expr>),
Ternary(Box<Expr>, Box<Expr>, Box<Expr>),
Elvis(Box<Expr>, Box<Expr>),
Coalesce(Box<Expr>, Box<Expr>),
Match {
subj: Box<Expr>,
arms: Vec<MatchArm>,
},
Throw(Box<Expr>),
ConstFetch(String),
Magic(MagicConst),
Unset(Vec<Expr>),
InstanceOf(Box<Expr>, String),
InstanceOfDyn(Box<Expr>, Box<Expr>),
RefAssign(Box<Expr>, Box<Expr>),
Quiet(Box<Expr>),
Suppress(Box<Expr>),
IssetOf(Box<Expr>),
EmptyOf(Box<Expr>),
Yield {
key: Option<Box<Expr>>,
value: Option<Box<Expr>>,
},
YieldFrom(Box<Expr>),
Print(Box<Expr>),
Include(IncludeKind, Box<Expr>),
Eval(Box<Expr>),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MagicConst {
File { prefix: String, suffix: String },
Class { prefix: String, suffix: String },
Dir,
}
impl MagicConst {
pub fn wrap(&self, before: &str, after: &str) -> MagicConst {
let wrapped = |prefix: &String, suffix: &String| {
(format!("{before}{prefix}"), format!("{suffix}{after}"))
};
match self {
MagicConst::File { prefix, suffix } => {
let (prefix, suffix) = wrapped(prefix, suffix);
MagicConst::File { prefix, suffix }
}
MagicConst::Class { prefix, suffix } => {
let (prefix, suffix) = wrapped(prefix, suffix);
MagicConst::Class { prefix, suffix }
}
MagicConst::Dir => MagicConst::Dir,
}
}
}
#[derive(Debug, Clone)]
pub struct MatchArm {
pub conds: Option<Vec<Expr>>,
pub body: Box<Expr>,
}
#[derive(Debug, Clone)]
pub struct Stmt {
pub line: u32,
pub kind: StmtKind,
}
#[derive(Debug, Clone)]
pub enum ForeachVal {
Var(String),
Pattern(Expr),
}
#[derive(Debug, Clone)]
pub enum StmtKind {
InlineHtml(String),
Echo(Vec<Expr>),
Expr(Expr),
If {
cond: Expr,
then: Vec<Stmt>,
elifs: Vec<(Expr, Vec<Stmt>)>,
els: Option<Vec<Stmt>>,
},
While {
cond: Expr,
body: Vec<Stmt>,
},
DoWhile {
cond: Expr,
body: Vec<Stmt>,
},
Switch {
subj: Expr,
cases: Vec<SwitchCase>,
},
For {
init: Vec<Expr>,
cond: Option<Expr>,
step: Vec<Expr>,
body: Vec<Stmt>,
},
Foreach {
arr: Expr,
key_var: Option<String>,
val: ForeachVal,
by_ref: bool,
body: Vec<Stmt>,
},
Function {
name: String,
params: Vec<Param>,
body: Vec<Stmt>,
ret: Option<TypeHint>,
by_ref_return: bool,
namespace: String,
deprecated: Option<Deprecation>,
doc: Option<String>,
lines: (u32, u32),
attrs: Vec<Attr>,
},
Class(ClassDecl),
Return(Option<Expr>),
Goto(String),
Label(String),
Break(u32),
Continue(u32),
Try {
body: Vec<Stmt>,
catches: Vec<CatchArm>,
finally: Option<Vec<Stmt>>,
},
Block(Vec<Stmt>),
StaticLocal(Vec<(String, Option<Expr>)>),
Global(Vec<String>),
ConstDecl(Vec<(String, Expr)>),
}
#[derive(Debug, Clone)]
pub struct CatchArm {
pub types: Vec<String>,
pub var: Option<String>,
pub body: Vec<Stmt>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TypeHint {
pub parts: Vec<String>,
}
impl TypeHint {
pub fn nullable(&self) -> bool {
self.parts.iter().any(|p| p.eq_ignore_ascii_case("null"))
}
pub fn declared(&self, self_class: &str, parent: Option<&str>) -> String {
const BUILTIN: [&str; 14] = [
"mixed", "static", "callable", "object", "array", "string", "int", "float", "bool",
"false", "true", "void", "never", "null",
];
let mut classes: Vec<String> = Vec::new();
let mut builtin = [false; BUILTIN.len()];
for p in &self.parts {
let lower = p.to_ascii_lowercase();
match lower.as_str() {
"self" => classes.push(self_class.to_string()),
"parent" => classes.push(parent.unwrap_or("parent").to_string()),
"iterable" => {
classes.push("Traversable".to_string());
builtin[4] = true;
}
b => match BUILTIN.iter().position(|n| *n == b) {
Some(i) => builtin[i] = true,
None => classes.push(p.clone()),
},
}
}
if builtin[0] {
return "mixed".to_string();
}
let nullable = builtin[13];
let mut out: Vec<String> = Vec::new();
let members = classes.len() + builtin[..13].iter().filter(|b| **b).count();
for c in classes {
if c.contains('&') && members + usize::from(nullable) > 1 {
out.push(format!("({c})"));
} else {
out.push(c);
}
}
for (i, name) in BUILTIN.iter().enumerate().take(13) {
if builtin[i] {
out.push((*name).to_string());
}
}
if nullable {
if out.len() == 1 && !out[0].contains('&') {
return format!("?{}", out[0]);
}
out.push("null".to_string());
}
out.join("|")
}
}
#[derive(Debug, Clone)]
pub struct Param {
pub name: String,
pub line: u32,
pub ty: Option<TypeHint>,
pub default: Option<Expr>,
pub variadic: bool,
pub promoted: bool,
pub promoted_vis: Visibility,
pub promoted_set_vis: Option<Visibility>,
pub readonly: bool,
pub by_ref: bool,
pub attrs: Vec<Attr>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Visibility {
Public,
Protected,
Private,
}
#[derive(Debug, Clone)]
pub struct PropDecl {
pub name: String,
pub default: Option<Expr>,
pub ty: Option<TypeHint>,
pub is_static: bool,
pub visibility: Visibility,
pub set_visibility: Option<Visibility>,
pub readonly: bool,
pub is_final: bool,
pub line: u32,
pub pos: usize,
}
#[derive(Debug, Clone)]
pub struct ClassDecl {
pub name: String,
pub lines: (u32, u32),
pub parent: Option<String>,
pub implements: Vec<String>,
pub uses: Vec<String>,
pub trait_insteadof: Vec<TraitInsteadof>,
pub trait_aliases: Vec<TraitAlias>,
pub is_interface: bool,
pub is_trait: bool,
pub is_readonly: bool,
pub is_abstract: bool,
pub is_final: bool,
pub is_enum: bool,
pub enum_backing: Option<String>,
pub cases: Vec<EnumCase>,
pub consts: Vec<(String, Expr)>,
pub const_lines: Vec<u32>,
pub const_pos: Vec<usize>,
pub const_vis: Vec<(String, Visibility)>,
pub final_consts: Vec<String>,
pub props: Vec<PropDecl>,
pub ctor_prop_slot: usize,
pub methods: Vec<Method>,
pub attributes: Vec<String>,
pub namespace: String,
pub docs: Vec<(String, String)>,
pub attrs: Vec<(String, Vec<Attr>)>,
}
#[derive(Debug, Clone)]
pub struct TraitInsteadof {
pub winner: String,
pub method: String,
pub losers: Vec<String>,
}
#[derive(Debug, Clone)]
pub struct TraitAlias {
pub from: Option<String>,
pub method: String,
pub alias: Option<String>,
pub visibility: Option<Visibility>,
}
#[derive(Debug, Clone)]
pub struct EnumCase {
pub name: String,
pub value: Option<Expr>,
pub line: u32,
}
#[derive(Debug, Clone)]
pub struct Attr {
pub name: String,
pub args: Vec<Expr>,
pub line: u32,
}
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Deprecation {
pub message: Option<String>,
pub since: Option<String>,
}
#[derive(Debug, Clone)]
pub struct Method {
pub name: String,
pub params: Vec<Param>,
pub body: Vec<Stmt>,
pub ret: Option<TypeHint>,
pub is_static: bool,
pub visibility: Visibility,
pub by_ref_return: bool,
pub is_abstract: bool,
pub is_final: bool,
pub has_body: bool,
pub line: u32,
pub end_line: u32,
pub deprecated: Option<Deprecation>,
}
#[derive(Debug, Clone)]
pub struct SwitchCase {
pub test: Option<Expr>,
pub body: Vec<Stmt>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Capture {
pub name: String,
pub by_ref: bool,
pub implicit: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IncludeKind {
Include,
IncludeOnce,
Require,
RequireOnce,
}
impl IncludeKind {
pub fn name(self) -> &'static str {
match self {
IncludeKind::Include => "include",
IncludeKind::IncludeOnce => "include_once",
IncludeKind::Require => "require",
IncludeKind::RequireOnce => "require_once",
}
}
pub fn code(self) -> i64 {
self as i64
}
pub fn from_code(n: i64) -> Self {
match n {
1 => IncludeKind::IncludeOnce,
2 => IncludeKind::Require,
3 => IncludeKind::RequireOnce,
_ => IncludeKind::Include,
}
}
pub fn once(self) -> bool {
matches!(self, IncludeKind::IncludeOnce | IncludeKind::RequireOnce)
}
pub fn required(self) -> bool {
matches!(self, IncludeKind::Require | IncludeKind::RequireOnce)
}
}