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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
use std::sync::Arc;
use mir_codebase::definitions::{
wrap_return_type, wrap_template_bound, DeclaredParam, FunctionDef, TemplateParam,
};
use mir_types::Name;
use super::DefinitionCollector;
use crate::parser::type_from_hint_owned;
/// Returns `true` if `stmts` (does not recurse into nested function/closure
/// bodies) contain a call to `func_get_args()`, `func_get_arg()`, or
/// `func_num_args()`.
///
/// When a function uses these PHP intrinsics it can accept more positional
/// arguments than its declared parameter list suggests. We add a synthetic
/// trailing variadic parameter so the arity checker does not emit
/// `TooManyArguments` for such functions.
#[allow(clippy::redundant_closure)]
pub(crate) fn stmts_use_func_get_args(stmts: &[php_ast::owned::Stmt]) -> bool {
use php_ast::owned::{ExprKind, StmtKind};
fn check_expr(expr: &php_ast::owned::Expr) -> bool {
use ExprKind::*;
match &expr.kind {
FunctionCall(call) => {
if let Identifier(name) = &call.name.kind {
if matches!(
name.as_ref(),
"func_get_args" | "func_get_arg" | "func_num_args"
) {
return true;
}
}
call.args.iter().any(|a| check_expr(&a.value))
}
// Do NOT descend into new function/closure/arrow-fn bodies.
Closure(_) | ArrowFunction(_) | AnonymousClass(_) => false,
Assign(e) => check_expr(&e.target) || check_expr(&e.value),
Binary(e) => check_expr(&e.left) || check_expr(&e.right),
UnaryPrefix(e) => check_expr(&e.operand),
UnaryPostfix(e) => check_expr(&e.operand),
Cast(_, e) => check_expr(e),
Ternary(e) => {
check_expr(&e.condition)
|| e.then_expr.as_ref().is_some_and(|t| check_expr(t))
|| check_expr(&e.else_expr)
}
NullCoalesce(e) => check_expr(&e.left) || check_expr(&e.right),
MethodCall(e) | NullsafeMethodCall(e) => {
check_expr(&e.object) || e.args.iter().any(|a| check_expr(&a.value))
}
StaticMethodCall(e) => {
check_expr(&e.class) || e.args.iter().any(|a| check_expr(&a.value))
}
StaticDynMethodCall(e) => {
check_expr(&e.class)
|| check_expr(&e.method)
|| e.args.iter().any(|a| check_expr(&a.value))
}
New(e) => e.args.iter().any(|a| check_expr(&a.value)),
Array(elems) => elems
.iter()
.any(|el| el.key.as_ref().is_some_and(|k| check_expr(k)) || check_expr(&el.value)),
ArrayAccess(e) => {
check_expr(&e.array) || e.index.as_ref().is_some_and(|i| check_expr(i))
}
PropertyAccess(e) | NullsafePropertyAccess(e) => check_expr(&e.object),
Include(_, e) => check_expr(e),
ThrowExpr(e) | Print(e) | Clone(e) | Empty(e) | ErrorSuppress(e) | Parenthesized(e)
| Eval(e) | Exit(Some(e)) => check_expr(e),
Yield(e) => {
e.key.as_ref().is_some_and(|k| check_expr(k))
|| e.value.as_ref().is_some_and(|v| check_expr(v))
}
Match(e) => {
check_expr(&e.subject)
|| e.arms.iter().any(|arm| {
arm.conditions
.as_ref()
.is_some_and(|conds| conds.iter().any(|c| check_expr(c)))
|| check_expr(&arm.body)
})
}
Isset(exprs) => exprs.iter().any(|e| check_expr(e)),
_ => false,
}
}
fn check_stmt(stmt: &php_ast::owned::Stmt) -> bool {
use StmtKind::*;
match &stmt.kind {
// Do NOT recurse into nested function/class declarations.
Function(_) | Class(_) | Interface(_) | Trait(_) | Enum(_) => false,
Expression(e) => check_expr(e),
Return(Some(e)) => check_expr(e),
Throw(e) => check_expr(e),
Echo(exprs) => exprs.iter().any(|e| check_expr(e)),
If(s) => {
check_expr(&s.condition)
|| check_stmt(&s.then_branch)
|| s.elseif_branches
.iter()
.any(|b| check_expr(&b.condition) || check_stmt(&b.body))
|| s.else_branch.as_ref().is_some_and(|b| check_stmt(b))
}
While(s) => check_expr(&s.condition) || check_stmt(&s.body),
DoWhile(s) => check_stmt(&s.body) || check_expr(&s.condition),
For(s) => {
s.init.iter().any(|e| check_expr(e))
|| s.condition.iter().any(|e| check_expr(e))
|| s.update.iter().any(|e| check_expr(e))
|| check_stmt(&s.body)
}
Foreach(s) => {
check_expr(&s.expr)
|| s.key.as_ref().is_some_and(|k| check_expr(k))
|| check_expr(&s.value)
|| check_stmt(&s.body)
}
Switch(s) => {
check_expr(&s.expr)
|| s.body.cases.iter().any(|c| {
c.value.as_ref().is_some_and(|cond| check_expr(cond))
|| c.body.iter().any(|inner| check_stmt(inner))
})
}
TryCatch(t) => {
t.body.stmts.iter().any(|s| check_stmt(s))
|| t.catches
.iter()
.any(|c| c.body.stmts.iter().any(|s| check_stmt(s)))
|| t.finally
.as_ref()
.is_some_and(|f| f.stmts.iter().any(|s| check_stmt(s)))
}
Block(b) => b.stmts.iter().any(|s| check_stmt(s)),
_ => false,
}
}
stmts.iter().any(|s| check_stmt(s))
}
impl DefinitionCollector<'_> {
pub(super) fn collect_function(
&mut self,
decl: &php_ast::owned::FunctionDecl,
stmt_span: php_ast::Span,
) {
let short_name = decl.name.as_deref().unwrap_or_default().to_string();
let fqn = if let Some(ns) = &self.namespace {
format!("{ns}\\{short_name}")
} else {
short_name.clone()
};
let doc = self.parse_docblock_from_node(decl.doc_comment.as_ref());
let doc_span = decl
.doc_comment
.as_ref()
.map(|c| c.span.start)
.unwrap_or(stmt_span.start);
self.emit_docblock_issues(&doc, doc_span);
if !self.version_allows(&doc) || !self.version_attr_available(&decl.attributes) {
return;
}
let type_aliases = self.build_type_aliases(&doc);
// Build template names first so bound resolution below can recognise template-param
// names and avoid FQN-qualifying them (e.g. `@template T of K` where K is another param).
let template_names: rustc_hash::FxHashSet<String> = doc
.templates
.iter()
.map(|(n, _, _, _)| n.to_string())
.collect();
// Extract template parameters; resolve bounds with template-awareness so template
// names used as bounds are stored as TTemplateParam, not wrongly namespace-qualified.
let template_params = doc
.templates
.iter()
.map(|(name, bound, variance, default)| TemplateParam {
name: name.as_str().into(),
bound: wrap_template_bound(bound.clone().map(|b| {
Self::fill_self_static_parent(
self.resolve_union_doc_with_templates(
b,
&template_names,
fqn.as_str(),
&[],
),
fqn.as_str(),
)
})),
default: wrap_template_bound(default.clone().map(|d| {
Self::fill_self_static_parent(
self.resolve_union_doc_with_templates(
d,
&template_names,
fqn.as_str(),
&[],
),
fqn.as_str(),
)
})),
defining_entity: fqn.as_str().into(),
variance: *variance,
})
.collect::<Vec<_>>();
let mut params = Vec::new();
let mut local_scalar = 0usize;
let mut local_complex = 0usize;
let mut local_defaults = 0usize;
for p in decl.params.iter() {
// phpstorm-stubs `#[PhpStormStubsElementAvailable]`: a param that
// does not exist at the target version is omitted entirely (keeping
// it would corrupt arity checks).
if !self.version_attr_available(&p.attributes) {
continue;
}
let param_name = p.name.as_deref().unwrap_or_default();
let native_ty =
self.resolve_union_opt(p.type_hint.as_ref().map(|h| type_from_hint_owned(h, None)));
let ty = self
// phpstorm-stubs `#[LanguageLevelTypeAware]`: a version-specific
// type override wins over the (usually absent) hint/docblock type.
.version_attr_type_string(&p.attributes)
.map(|s| crate::parser::docblock::parse_type_string(&s))
.or_else(|| {
doc.get_param_type(param_name).cloned().map(|u| {
let expanded = self.expand_aliases_only(u, &type_aliases);
let doc_ty = self.resolve_union_doc_with_templates(
expanded,
&template_names,
&fqn,
&template_params,
);
// When the native hint is a concrete scalar and the docblock has only
// atoms from a different scalar family (e.g. `@param int` + `bool` hint),
// the PHP type hint is the runtime truth — prefer it over the docblock.
if native_ty.as_ref().is_some_and(|n| {
super::native_hint_wins_over_docblock_scalar(n, &doc_ty)
}) {
return native_ty.clone().unwrap();
}
// Partial conflict (e.g. `@param int|string` on a native `int`
// hint): strip the atoms foreign to the hint's family instead
// of storing the raw union, which would let body analysis
// believe $x could hold a value the native hint rules out.
let mut doc_ty = match native_ty.as_ref() {
Some(n) => super::resolve_docblock_scalar_conflict(n, doc_ty),
None => doc_ty,
};
// Mark the type as docblock-sourced so signature checks (e.g.
// param contravariance) can tell a `@param` refinement apart
// from a native type hint.
doc_ty.from_docblock = true;
doc_ty
})
})
.or(native_ty);
if let Some(ty_ref) = &ty {
if super::is_simple_scalar(ty_ref) {
local_scalar += 1;
} else {
local_complex += 1;
}
}
let has_default = p.default.is_some();
if has_default {
local_defaults += 1;
}
let out_ty = doc.get_out_param_type(param_name).cloned().map(|u| {
let expanded = self.expand_aliases_only(u, &type_aliases);
let mut doc_ty = self.resolve_union_doc_with_templates(
expanded,
&template_names,
&fqn,
&template_params,
);
doc_ty.from_docblock = true;
doc_ty
});
params.push(DeclaredParam {
name: Name::new(param_name),
ty: mir_codebase::wrap_param_type(ty),
out_ty: mir_codebase::wrap_param_type(out_ty),
has_default,
is_variadic: p.variadic,
is_byref: p.by_ref,
is_optional: has_default || p.variadic,
});
}
if local_scalar > 0 {
super::SCALAR_PARAM_COUNT.fetch_add(local_scalar, std::sync::atomic::Ordering::Relaxed);
}
if local_complex > 0 {
super::COMPLEX_PARAM_COUNT
.fetch_add(local_complex, std::sync::atomic::Ordering::Relaxed);
}
if local_defaults > 0 {
super::PARAM_WITH_DEFAULT
.fetch_add(local_defaults, std::sync::atomic::Ordering::Relaxed);
}
// If the function body calls func_get_args() / func_get_arg() /
// func_num_args(), it can accept more positional args than declared.
// Add a synthetic untyped variadic param so TooManyArguments is not
// emitted for such functions.
let last_is_variadic = params.last().is_some_and(|p| p.is_variadic);
if !last_is_variadic && stmts_use_func_get_args(&decl.body.stmts) {
params.push(DeclaredParam {
name: Name::new("..."),
ty: None,
out_ty: None,
has_default: false,
is_variadic: true,
is_byref: false,
is_optional: true,
});
}
// phpstorm-stubs `#[LanguageLevelTypeAware]` return type wins over the
// declared/docblock return type, routed through the same resolution.
let return_type = if let Some(s) = self.version_attr_type_string(&decl.attributes) {
let mut ty = crate::parser::docblock::parse_type_string(&s);
ty.from_docblock = true;
let expanded = self.expand_aliases_only(ty, &type_aliases);
Some(self.resolve_union_doc_with_templates(
expanded,
&template_names,
&fqn,
&template_params,
))
} else {
match (doc.return_type.clone(), decl.return_type.as_ref()) {
(Some(mut ty), _) => {
ty.from_docblock = true;
let expanded = self.expand_aliases_only(ty, &type_aliases);
Some(self.resolve_union_doc_with_templates(
expanded,
&template_names,
&fqn,
&template_params,
))
}
(None, Some(h)) => self.resolve_union_opt(Some(type_from_hint_owned(h, None))),
(None, None) => None,
}
};
let throws = doc
.throws
.iter()
.map(|t| {
Arc::from(
super::resolution::resolve_name(t, &self.namespace, &self.use_aliases).as_str(),
)
})
.collect();
let docstring = if doc.description.trim().is_empty() {
None
} else {
Some(Arc::from(doc.description.as_str()))
};
let storage = FunctionDef {
fqn: fqn.clone().into(),
short_name: short_name.into(),
params: Arc::from(params.into_boxed_slice()),
return_type: wrap_return_type(return_type),
inferred_return_type: None,
template_params,
assertions: self.build_assertions(&doc),
throws,
deprecated: doc.deprecated.as_deref().map(Arc::from).or_else(|| {
// Only detect #[Deprecated] without arguments (no-arg form used in
// user code). Stubs use #[Deprecated(since: '...', ...)] with args
// which would otherwise flood callers with spurious DeprecatedCall.
if decl.attributes.iter().any(|a| {
a.args.is_empty()
&& a.name
.parts
.last()
.map(|p| p.as_ref().eq_ignore_ascii_case("Deprecated"))
.unwrap_or(false)
}) {
Some(Arc::from(""))
} else {
None
}
}),
is_pure: doc.is_pure,
no_named_arguments: doc.no_named_arguments,
location: Some(self.location(stmt_span.start, stmt_span.end)),
docstring,
taint_sink_params: doc
.taint_sinks
.iter()
.map(|(param, kind)| (Arc::from(param.as_str()), Arc::from(kind.as_str())))
.collect(),
};
self.slice.functions.push(std::sync::Arc::new(storage));
// Scan the function body for `@var`-annotated global declarations.
self.scan_stmts_for_global_vars(&decl.body.stmts);
}
pub(super) fn collect_global_stmt(&mut self, stmt: &php_ast::owned::Stmt) {
// Top-level `global $x` — unusual in PHP but valid.
self.try_collect_global_var_annotation(stmt);
}
}