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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
use php_ast::ast::{ExprKind, FunctionCallExpr};
use php_ast::Span;
use std::sync::Arc;
use mir_codebase::storage::{Assertion, AssertionKind, FnParam, TemplateParam};
use mir_issues::{IssueKind, Severity};
use mir_types::{Atomic, Union};
use crate::context::Context;
use crate::expr::ExpressionAnalyzer;
use crate::generic::{check_template_bounds, infer_template_bindings};
use crate::symbol::SymbolKind;
use crate::taint::{classify_sink, is_expr_tainted, SinkKind};
use super::args::{
check_args, expr_can_be_passed_by_reference, spread_element_type, CheckArgsParams,
};
use super::CallAnalyzer;
struct ResolvedFn {
fqn: std::sync::Arc<str>,
deprecated: Option<std::sync::Arc<str>>,
params: Vec<FnParam>,
template_params: Vec<TemplateParam>,
assertions: Vec<Assertion>,
return_ty_raw: Union,
throws: Arc<[Arc<str>]>,
}
fn resolve_fn(ea: &ExpressionAnalyzer<'_>, fqn: &str) -> Option<ResolvedFn> {
let db = ea.db;
let node = db.lookup_function_node(fqn).filter(|n| n.active(db))?;
// `inferred_return_type` is the priming-sweep-derived type, published
// on `FunctionNode` via `MirDb::commit_inferred_return_types` after
// each priming sweep returns. Every entry path (batch `analyze`,
// `re_analyze_file`, lazy-load reanalysis sweep, `analyze_source`)
// runs a priming-sweep + commit before the issue-emitting pass.
let inferred = node.inferred_return_type(db);
let return_ty_raw = node
.return_type(db)
.or(inferred)
.map(|t| (*t).clone())
.unwrap_or_else(Union::mixed);
Some(ResolvedFn {
fqn: node.fqn(db),
deprecated: node.deprecated(db),
params: node.params(db).to_vec(),
template_params: node.template_params(db).to_vec(),
assertions: node.assertions(db).to_vec(),
return_ty_raw,
throws: node.throws(db),
})
}
impl CallAnalyzer {
pub fn analyze_function_call<'a, 'arena, 'src>(
ea: &mut ExpressionAnalyzer<'a>,
call: &FunctionCallExpr<'arena, 'src>,
ctx: &mut Context,
span: Span,
) -> Union {
let fn_name = match &call.name.kind {
ExprKind::Identifier(name) => (*name).to_string(),
_ => {
let callee_ty = ea.analyze(call.name, ctx);
for arg in call.args.iter() {
ea.analyze(&arg.value, ctx);
}
for atomic in &callee_ty.types {
match atomic {
Atomic::TClosure { return_type, .. } => return *return_type.clone(),
Atomic::TCallable {
return_type: Some(rt),
..
} => return *rt.clone(),
_ => {}
}
}
return Union::mixed();
}
};
// Taint sink check (M19): before evaluating args so we can inspect raw exprs
if let Some(sink_kind) = classify_sink(&fn_name) {
for arg in call.args.iter() {
if is_expr_tainted(&arg.value, ctx) {
let issue_kind = match sink_kind {
SinkKind::Html => IssueKind::TaintedHtml,
SinkKind::Sql => IssueKind::TaintedSql,
SinkKind::Shell => IssueKind::TaintedShell,
};
ea.emit(issue_kind, Severity::Error, span);
break;
}
}
}
// PHP resolves `foo()` as `\App\Ns\foo` first, then `\foo` if not found.
// A leading `\` means explicit global namespace.
let fn_name = fn_name
.strip_prefix('\\')
.map(|s: &str| s.to_string())
.unwrap_or(fn_name);
let resolved_fn_name: String = {
let imports = ea.db.file_imports(&ea.file);
let qualified = if let Some(imported) = imports.get(fn_name.as_str()) {
imported.clone()
} else if fn_name.contains('\\') {
crate::db::resolve_name_via_db(ea.db, &ea.file, &fn_name)
} else if let Some(ns) = ea.db.file_namespace(&ea.file) {
format!("{}\\{}", ns, fn_name)
} else {
fn_name.clone()
};
let fn_exists = |name: &str| -> bool {
let db = ea.db;
db.lookup_function_node(name).is_some_and(|n| n.active(db))
};
if fn_exists(qualified.as_str()) {
qualified
} else if fn_exists(fn_name.as_str()) {
fn_name.clone()
} else {
qualified
}
};
// Resolve once; reused below for by-ref pre-marking and full analysis.
let resolved = resolve_fn(ea, resolved_fn_name.as_str());
// Pre-mark by-reference parameter variables as defined BEFORE evaluating args
if let Some(ref resolved) = resolved {
for (i, param) in resolved.params.iter().enumerate() {
if param.is_byref {
if param.is_variadic {
for arg in call.args.iter().skip(i) {
if let ExprKind::Variable(name) = &arg.value.kind {
let var_name = name.as_str().trim_start_matches('$');
if !ctx.var_is_defined(var_name) {
ctx.set_var(var_name, Union::mixed());
}
}
}
} else if let Some(arg) = call.args.get(i) {
if let ExprKind::Variable(name) = &arg.value.kind {
let var_name = name.as_str().trim_start_matches('$');
if !ctx.var_is_defined(var_name) {
ctx.set_var(var_name, Union::mixed());
}
}
}
}
}
}
let arg_types: Vec<Union> = call
.args
.iter()
.map(|arg| {
let ty = ea.analyze(&arg.value, ctx);
if arg.unpack {
spread_element_type(&ty)
} else {
ty
}
})
.collect();
let arg_spans: Vec<Span> = call.args.iter().map(|a| a.span).collect();
// When call_user_func / call_user_func_array is called with a bare string
// literal as the callable argument, treat that string as a direct FQN
// reference so the named function is not flagged as dead code.
// Note: 'helper' always resolves to \helper (global) — no namespace
// fallback applies to runtime callable strings.
if matches!(
resolved_fn_name.as_str(),
"call_user_func" | "call_user_func_array"
) {
if let Some(arg) = call.args.first() {
if let ExprKind::String(name) = &arg.value.kind {
let fqn = name.strip_prefix('\\').unwrap_or(name);
if let Some(node) = ea.db.lookup_function_node(fqn).filter(|n| n.active(ea.db))
{
if !ea.inference_only {
let (line, col_start, col_end) = ea.span_to_ref_loc(arg.span);
ea.db.record_reference_location(crate::db::RefLoc {
symbol_key: Arc::from(node.fqn(ea.db).as_ref()),
file: ea.file.clone(),
line,
col_start,
col_end,
});
}
}
}
}
}
// compact() reads variables by string name at runtime; mark each string-literal arg as read
if fn_name == "compact" {
for arg in call.args.iter() {
if let ExprKind::String(name) = &arg.value.kind {
ctx.read_vars.insert((*name).to_string());
}
}
}
if let Some(resolved) = resolved {
if !ea.inference_only {
let (line, col_start, col_end) = ea.span_to_ref_loc(call.name.span);
ea.db.record_reference_location(crate::db::RefLoc {
symbol_key: resolved.fqn.clone(),
file: ea.file.clone(),
line,
col_start,
col_end,
});
}
let deprecated = resolved.deprecated;
let params = resolved.params;
let template_params = resolved.template_params;
let return_ty_raw = resolved.return_ty_raw;
if let Some(msg) = deprecated {
ea.emit(
IssueKind::DeprecatedCall {
name: resolved_fn_name.clone(),
message: Some(msg).filter(|m| !m.is_empty()),
},
Severity::Info,
span,
);
}
check_args(
ea,
CheckArgsParams {
fn_name: &fn_name,
params: ¶ms,
arg_types: &arg_types,
arg_spans: &arg_spans,
arg_names: &call
.args
.iter()
.map(|a| a.name.as_ref().map(|n| n.to_string_repr().into_owned()))
.collect::<Vec<_>>(),
arg_can_be_byref: &call
.args
.iter()
.map(|a| expr_can_be_passed_by_reference(&a.value))
.collect::<Vec<_>>(),
call_span: span,
has_spread: call.args.iter().any(|a| a.unpack),
},
);
match resolved_fn_name.as_str() {
"array_map" => {
super::callable::check_array_map_callback(ea, &arg_types, &arg_spans)
}
"array_filter" => {
super::callable::check_array_filter_callback(ea, &arg_types, &arg_spans)
}
"array_reduce" => {
super::callable::check_array_reduce_callback(ea, &arg_types, &arg_spans)
}
"usort" | "uasort" | "uksort" | "array_walk" | "array_walk_recursive" => {
super::callable::check_sort_callback(
ea,
&resolved_fn_name,
&arg_types,
&arg_spans,
)
}
_ => {}
}
for (i, param) in params.iter().enumerate() {
if param.is_byref {
if param.is_variadic {
for arg in call.args.iter().skip(i) {
if let ExprKind::Variable(name) = &arg.value.kind {
let var_name = name.as_str().trim_start_matches('$');
ctx.set_var(var_name, Union::mixed());
}
}
} else if let Some(arg) = call.args.get(i) {
if let ExprKind::Variable(name) = &arg.value.kind {
let var_name = name.as_str().trim_start_matches('$');
ctx.set_var(var_name, Union::mixed());
}
}
}
}
let template_bindings = if !template_params.is_empty() {
let bindings = infer_template_bindings(&template_params, ¶ms, &arg_types);
for (name, inferred, bound) in check_template_bounds(&bindings, &template_params) {
ea.emit(
IssueKind::InvalidTemplateParam {
name: name.to_string(),
expected_bound: format!("{bound}"),
actual: format!("{inferred}"),
},
Severity::Error,
span,
);
}
Some(bindings)
} else {
None
};
for assertion in resolved
.assertions
.iter()
.filter(|a| a.kind == AssertionKind::Assert)
{
if let Some(index) = params.iter().position(|p| p.name == assertion.param) {
if let Some(arg) = call.args.get(index) {
if let ExprKind::Variable(name) = &arg.value.kind {
let asserted_ty = match &template_bindings {
Some(b) => assertion.ty.substitute_templates(b),
None => assertion.ty.clone(),
};
ctx.set_var(name.as_str().trim_start_matches('$'), asserted_ty);
}
}
}
}
let return_ty = match &template_bindings {
Some(bindings) => return_ty_raw.substitute_templates(bindings),
None => return_ty_raw,
};
// Check inter-procedural throws: if callee declares @throws, check if caller covers them
for callee_throw in resolved.throws.iter() {
if !ctx.fn_declared_throws.iter().any(|declared| {
declared.as_ref() == callee_throw.as_ref()
|| crate::db::extends_or_implements_via_db(
ea.db,
callee_throw.as_ref(),
declared.as_ref(),
)
}) {
ea.emit(
IssueKind::MissingThrowsDocblock {
class: callee_throw.to_string(),
},
Severity::Info,
span,
);
}
}
ea.record_symbol(
call.name.span,
SymbolKind::FunctionCall(resolved.fqn.clone()),
return_ty.clone(),
);
return return_ty;
}
// Soft-fallback: if the build-time stub index recognises this name as
// a PHP built-in, the codebase miss is a stub-loading race rather
// than user error — the auto-discovery scanner missed it, the
// session is in essentials-only mode without auto-discovery, or the
// analyzer is mid-ingest. Suppressing the diagnostic avoids a class
// of false positives that would otherwise plague consumers running
// the lazy-stub setup. However, don't suppress if the function is
// version-filtered (e.g. @removed in the target version) — it should
// be reported as undefined.
if let Some(stub_path) = crate::stubs::stub_path_for_function(&fn_name) {
if let Some(stub_src) = crate::stubs::stub_content_for_path(stub_path) {
// Parse the stub to check if this function is version-compatible.
if let Some(docblock_text) = extract_function_docblock(stub_src, &fn_name) {
let doc = crate::parser::DocblockParser::parse(docblock_text);
// Check if the function is available in the current PHP version.
if ea
.php_version
.includes_symbol(doc.since.as_deref(), doc.removed.as_deref())
{
return Union::mixed();
}
} else {
// No docblock found; assume the function is available (conservative).
return Union::mixed();
}
}
}
ea.emit(
IssueKind::UndefinedFunction { name: fn_name },
Severity::Error,
span,
);
Union::mixed()
}
}
/// Extract the docblock for a function from PHP stub source code.
/// Returns the docblock text (without /** */ delimiters) if found.
fn extract_function_docblock<'a>(src: &'a str, fn_name: &str) -> Option<&'a str> {
// Simple extraction: find /** ... */ followed by function declaration.
let fn_pattern = format!("function {fn_name}");
extract_docblock_before(src, &fn_pattern)
}
/// Extract the docblock for a class from PHP stub source code.
/// Returns the docblock text (without /** */ delimiters) if found.
pub(crate) fn extract_class_docblock<'a>(src: &'a str, class_name: &str) -> Option<&'a str> {
// Handle both class and interface declarations.
// Extract the short name (after last backslash if present).
let short_name = class_name.split('\\').next_back().unwrap_or(class_name);
// Try case-insensitive matching for "class" declarations.
let class_pattern_lower = format!("class {}", short_name.to_lowercase());
if let Some(docblock) = extract_docblock_case_insensitive(src, &class_pattern_lower) {
return Some(docblock);
}
// Try case-insensitive matching for "interface" declarations.
let interface_pattern_lower = format!("interface {}", short_name.to_lowercase());
extract_docblock_case_insensitive(src, &interface_pattern_lower)
}
/// Generic docblock extraction: find /** ... */ before a pattern (case-sensitive).
fn extract_docblock_before<'a>(src: &'a str, pattern: &str) -> Option<&'a str> {
if let Some(pos) = src.find(pattern) {
extract_docblock_at_position(src, pos)
} else {
None
}
}
/// Case-insensitive docblock extraction: find /** ... */ before a pattern.
fn extract_docblock_case_insensitive<'a>(src: &'a str, pattern: &str) -> Option<&'a str> {
let src_lower = src.to_lowercase();
if let Some(pos) = src_lower.find(pattern) {
extract_docblock_at_position(src, pos)
} else {
None
}
}
/// Extract docblock before a given byte position in the source.
fn extract_docblock_at_position(src: &str, pos: usize) -> Option<&str> {
// Look back for /** from the position.
if let Some(doc_start_pos) = src[..pos].rfind("/**") {
if let Some(doc_end_pos) = src[doc_start_pos..].find("*/") {
let end_abs = doc_start_pos + doc_end_pos;
let docblock_raw = &src[doc_start_pos + 3..end_abs];
return Some(docblock_raw);
}
}
None
}