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
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
use php_ast::owned::{ExprKind, FunctionCallExpr};
use php_ast::Span;
use std::sync::Arc;
use mir_codebase::definitions::{Assertion, AssertionKind, DeclaredParam, TemplateParam};
use mir_issues::{IssueKind, Severity};
use mir_types::atomic::FnParam as TypeFnParam;
use mir_types::{Atomic, Name, Type};
use crate::expr::ExpressionAnalyzer;
use crate::flow_state::FlowState;
use crate::generic::{check_template_bounds_with_inheritance, infer_template_bindings};
use crate::symbol::ReferenceKind;
use crate::taint::{classify_sink, is_expr_tainted, taint_sink_issue, SinkKind};
use super::args::{
check_args, distinct_spans_for_expansion, expand_sole_spread_arg,
expr_can_be_passed_by_reference_owned, spread_element_type, CheckArgsParams,
};
use super::callable::extract_callable_params;
use super::CallAnalyzer;
struct ResolvedFn {
fqn: std::sync::Arc<str>,
deprecated: Option<std::sync::Arc<str>>,
params: Vec<DeclaredParam>,
template_params: Vec<TemplateParam>,
assertions: Vec<Assertion>,
return_ty_raw: Type,
throws: Arc<[Arc<str>]>,
no_named_arguments: bool,
is_pure: bool,
/// `@psalm-mutation-free`/`@psalm-external-mutation-free` on a free
/// function — both forbid mutating an argument (a free function has no
/// `$this`, so the two collapse to the same "don't touch parameters"
/// meaning; see `FunctionDef::is_mutation_free`'s own doc comment).
is_mutation_free: bool,
taint_sink_params: Vec<(Arc<str>, Arc<str>)>,
}
fn resolve_fn(ea: &ExpressionAnalyzer<'_>, fqn: &str) -> Option<ResolvedFn> {
let db = ea.db;
let inferred = crate::db::inferred_function_return_type_demand(db, fqn);
let here = crate::db::Fqcn::from_str(db, fqn);
if let Some(f) = crate::db::find_function(db, here) {
let return_ty_raw = f
.return_type
.clone()
.or(inferred)
.map(|t| (*t).clone())
.unwrap_or_else(Type::mixed);
return Some(ResolvedFn {
fqn: f.fqn.clone(),
deprecated: f.deprecated.clone(),
params: f.params.to_vec(),
template_params: f.template_params.clone(),
assertions: f.assertions.clone(),
return_ty_raw,
throws: Arc::<[Arc<str>]>::from(f.throws.as_slice()),
no_named_arguments: f.no_named_arguments,
is_pure: f.is_pure,
is_mutation_free: f.is_mutation_free || f.is_external_mutation_free,
taint_sink_params: f.taint_sink_params.clone(),
});
}
None
}
impl CallAnalyzer {
pub fn analyze_function_call<'a>(
ea: &mut ExpressionAnalyzer<'a>,
call: &FunctionCallExpr,
ctx: &mut FlowState,
span: Span,
) -> Type {
let fn_name = match &call.name.kind {
ExprKind::Identifier(name) => name.as_ref().to_string(),
_ => {
let callee_ty = ea.analyze(&call.name, ctx);
if callee_ty.is_mixed() {
ea.emit(IssueKind::MixedFunctionCall, Severity::Info, span);
}
// Extract typed params once — used for both pre-marking (before arg
// analysis) and output writeback (after the call).
let callee_params = typed_params_from_callee(&callee_ty, ea);
// `$obj(...)` invoking an object's __invoke() is a real reference to
// that method — record it, or find-references/go-to-definition on
// __invoke never sees call sites reached only this way (unlike every
// other call form, which always records the resolved method).
for atomic in &callee_ty.types {
if let Atomic::TNamedObject { fqcn, .. } = atomic {
if let Some((_, storage)) = crate::db::find_method_respecting_precedence(
ea.db,
crate::db::Fqcn::from_str(ea.db, fqcn.as_ref()),
"__invoke",
) {
ea.record_ref(
Arc::from(format!(
"meth:{}::{}",
fqcn,
crate::util::php_ident_lowercase(&storage.name)
)),
call.name.span,
);
ea.record_symbol(
call.name.span,
ReferenceKind::MethodCall {
class: Arc::from(fqcn.as_ref()),
method: Arc::from("__invoke"),
},
callee_ty.clone(),
);
}
}
}
// Pre-mark by-ref parameter variables as defined BEFORE evaluating
// args, so a previously-undefined variable passed to an out-param
// (e.g. `$fn($x, $out)` where $out is fresh) is not flagged as
// UndefinedVariable when the argument expression is analyzed.
if let Some((_, ref params)) = callee_params {
super::premark_byref_arg_vars(params, &call.args, ctx);
}
// Collect arg types, spans, names and byref flags for type checking.
let mut inner_arg_types: Vec<Type> = Vec::with_capacity(call.args.len());
let mut sole_spread_ty: Option<Type> = None;
for arg in call.args.iter() {
// `None` is a PHP 8.6 partial-application placeholder (`?`/`...`)
// — not yet modeled; keep positional slots aligned with `mixed`.
let Some(value) = &arg.value else {
inner_arg_types.push(Type::mixed());
continue;
};
let ty = ea.analyze(value, ctx);
super::consume_arg_assignment(value, ctx);
if arg.unpack {
if call.args.len() == 1 {
sole_spread_ty = Some(ty.clone());
}
inner_arg_types.push(spread_element_type(ea.db, &ty));
} else {
inner_arg_types.push(ty);
}
}
let mut inner_arg_spans: Vec<Span> = call.args.iter().map(|a| a.span).collect();
let mut inner_arg_names: Vec<Option<String>> = call
.args
.iter()
.map(|a| a.name.as_ref().map(crate::parser::name_to_string_owned))
.collect();
let mut inner_arg_byref: Vec<bool> = call
.args
.iter()
.map(|a| {
a.value
.as_ref()
.is_some_and(expr_can_be_passed_by_reference_owned)
})
.collect();
let mut has_spread = call.args.iter().any(|a| a.unpack);
let mut arity_unknown = has_spread;
// A sole spread arg over a literal, sequentially-keyed shape can be
// expanded into one binding per element so each parameter is checked
// individually instead of only the first (see expand_sole_spread_arg).
// `arity_unknown` stays true even after expansion — PHP allows
// extra/spread positional args, so a concretely-known count still
// shouldn't trigger TooFew/TooManyArguments.
if let Some(expanded) = sole_spread_ty.and_then(|t| expand_sole_spread_arg(&t)) {
inner_arg_spans =
distinct_spans_for_expansion(inner_arg_spans[0], expanded.len());
inner_arg_names = vec![None; expanded.len()];
inner_arg_byref = vec![false; expanded.len()];
inner_arg_types = expanded;
has_spread = false;
arity_unknown = true;
}
if let Some((ref callee_fn_name, ref params)) = callee_params {
// Full type + arity checking via check_args.
check_args(
ea,
CheckArgsParams {
fn_name: callee_fn_name,
params,
arg_types: &inner_arg_types,
arg_spans: &inner_arg_spans,
arg_names: &inner_arg_names,
arg_can_be_byref: &inner_arg_byref,
call_span: span,
has_spread,
arity_unknown,
too_many_arity_unknown: false,
template_params: &[],
no_named_arguments: false,
},
);
} else if let Some(params) = extract_callable_params(&callee_ty, ea) {
// Arity-only fallback when full param types are unavailable.
// A spread arg (`...$args`) makes the real argument count
// unknowable from `call.args.len()` alone — same
// `arity_unknown` signal `check_args` above uses to skip
// TooFew/TooManyArguments for the exact same reason.
let required_count = params
.iter()
.filter(|p| !p.is_optional && !p.is_variadic)
.count();
let has_variadic = params.iter().any(|p| p.is_variadic);
let max_params = params.len();
let actual_count = call.args.len();
if arity_unknown {
// Skip TooFew/TooManyArguments — can't be checked precisely.
} else if actual_count < required_count {
ea.emit(
IssueKind::TooFewArguments {
fn_name: "callable".to_string(),
expected: required_count,
actual: actual_count,
},
Severity::Error,
span,
);
} else if !has_variadic && actual_count > max_params {
ea.emit(
IssueKind::TooManyArguments {
fn_name: "callable".to_string(),
expected: max_params,
actual: actual_count,
},
Severity::Error,
span,
);
}
}
// Write back output types to by-ref argument variables.
if let Some((_, ref params)) = callee_params {
let any_arg_tainted = call.args.iter().any(|arg| {
arg.value
.as_ref()
.is_some_and(|v| is_expr_tainted(v, ctx, ea.db, &ea.file))
});
for (i, param) in params.iter().enumerate() {
if param.is_byref {
let output_ty = param
.out_ty
.as_ref()
.or(param.ty.as_ref())
.map(|t| (**t).clone())
.unwrap_or_else(Type::mixed);
if param.is_variadic {
for arg in call.args.iter().skip(i) {
let Some(value) = &arg.value else { continue };
if let ExprKind::Variable(name) = &value.kind {
let var_name = name.trim_start_matches('$');
ea.check_var_write_purity(var_name, ctx, value.span);
ctx.set_var(var_name, output_ty.clone());
if any_arg_tainted {
ctx.taint_var(var_name);
} else {
ctx.clear_var_taint(var_name);
}
} else {
ea.check_byref_arg_purity(value, ctx, value.span);
}
}
} else if let Some(value) =
crate::call::resolve_named_arg_type_index(params, &call.args, i)
.and_then(|idx| call.args.get(idx))
.and_then(|arg| arg.value.as_ref())
{
if let ExprKind::Variable(name) = &value.kind {
let var_name = name.trim_start_matches('$');
ea.check_var_write_purity(var_name, ctx, value.span);
ctx.set_var(var_name, output_ty);
if any_arg_tainted {
ctx.taint_var(var_name);
} else {
ctx.clear_var_taint(var_name);
}
} else {
ea.check_byref_arg_purity(value, ctx, value.span);
}
}
}
}
}
// Invoking a closure/callable value (`$fn(...)`, `$obj(...)`)
// carries no purity metadata to consult — the callee's body
// is opaque here, and a bound closure can freely mutate the
// `$this` it captured. Conservatively assume it may mutate
// `$this` and any object passed as an argument.
ctx.invalidate_prop_refined_receiver("this");
for arg in call.args.iter() {
if let Some(ExprKind::Variable(name)) = arg.value.as_ref().map(|v| &v.kind) {
ctx.invalidate_prop_refined_receiver(name);
}
}
for atomic in &callee_ty.types {
match atomic {
Atomic::TClosure { data } => return data.return_type.clone(),
Atomic::TCallable {
return_type: Some(rt),
..
} => return *rt.clone(),
_ => {}
}
}
return Type::mixed();
}
};
// Taint sink check (M19): before evaluating args so we can inspect raw exprs
if let Some(sink_kind) = classify_sink(&fn_name) {
let relevant = sink_kind.tainted_arg_indices();
// A path/payload sink (File/Unserialize) cares about one specific
// PARAMETER, not whichever argument happens to sit at its
// declared positional index — a PHP 8 named-argument call can
// reorder arguments (`file_put_contents(data: 'safe', filename:
// $_GET['path'])`) so the tainted value is no longer at that
// index. Resolve by parameter name first; fall back to the
// plain positional slot for an ordinary (non-named) call.
// Html/Sql/Shell (`relevant == None`) check every argument
// regardless of position, so reordering can't hide anything
// from them in the first place.
let target_args: Vec<&php_ast::owned::Arg> = match relevant {
None => call.args.iter().collect(),
Some(idxs) => {
let fn_name_lower = crate::util::php_ident_lowercase(&fn_name);
let param_name = crate::taint::sink_param_name(&fn_name_lower);
let named = param_name.and_then(|name| {
call.args.iter().find(|a| {
a.name
.as_ref()
.is_some_and(|n| crate::parser::name_to_string_owned(n) == name)
})
});
named
.or_else(|| {
let idx = crate::taint::sink_positional_index_override(&fn_name_lower)
.or_else(|| idxs.first().copied());
idx.and_then(|idx| call.args.get(idx))
.filter(|a| a.name.is_none())
})
.into_iter()
.collect()
}
};
for arg in target_args {
let Some(value) = &arg.value else { continue };
if is_expr_tainted(value, ctx, ea.db, &ea.file) {
let issue_kind = match sink_kind {
SinkKind::Html => IssueKind::TaintedHtml,
SinkKind::Sql => IssueKind::TaintedSql,
SinkKind::Shell => IssueKind::TaintedShell,
SinkKind::File => IssueKind::TaintedInput {
sink: "file".to_string(),
},
SinkKind::Unserialize => IssueKind::TaintedInput {
sink: "unserialize".to_string(),
},
};
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);
if matches!(
fn_name.to_ascii_lowercase().as_str(),
"var_dump" | "shell_exec"
) {
ea.emit(
IssueKind::ForbiddenCode {
message: format!("Use of {} is forbidden", fn_name),
},
Severity::Warning,
span,
);
}
let resolved_fn_name: String = {
let imports = ea.db.file_imports(&ea.file);
let qualified = if let Some(imported) = imports.get(&Name::new(fn_name.as_str())) {
imported.as_str().to_string()
} else if fn_name.contains('\\') {
crate::db::resolve_name(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;
let here = crate::db::Fqcn::from_str(db, name);
crate::db::find_function(db, here).is_some()
};
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 {
super::premark_byref_arg_vars(&resolved.params, &call.args, ctx);
}
let mut arg_types = super::ARG_TYPES_BUF
.with(|b| b.borrow_mut().take())
.unwrap_or_default();
arg_types.clear();
let mut sole_spread_ty: Option<Type> = None;
for arg in call.args.iter() {
let Some(value) = &arg.value else {
arg_types.push(Type::mixed());
continue;
};
let ty = ea.analyze(value, ctx);
super::consume_arg_assignment(value, ctx);
if arg.unpack {
if call.args.len() == 1 {
sole_spread_ty = Some(ty.clone());
}
arg_types.push(spread_element_type(ea.db, &ty));
} else {
arg_types.push(ty);
}
}
let mut arg_spans: Vec<Span> = call.args.iter().map(|a| a.span).collect();
let mut arg_names: Vec<Option<String>> = call
.args
.iter()
.map(|a| a.name.as_ref().map(crate::parser::name_to_string_owned))
.collect();
let mut arg_can_be_byref: Vec<bool> = call
.args
.iter()
.map(|a| {
a.value
.as_ref()
.is_some_and(expr_can_be_passed_by_reference_owned)
})
.collect();
// array_multisort accepts ANY expression for both the sort-key arrays
// and the trailing SORT_* order/flags scalars bound to its `&...$rest`
// stub slot — verified empirically against real PHP, no "Only
// variables should be passed by reference" notice either, unlike
// sort()/usort() and other by-ref array functions.
if fn_name.eq_ignore_ascii_case("array_multisort") {
arg_can_be_byref = vec![true; call.args.len()];
}
let mut has_spread = call.args.iter().any(|a| a.unpack);
let mut arity_unknown = has_spread;
// A sole spread arg over a literal, sequentially-keyed shape can be
// expanded into one binding per element so each parameter (and
// template-binding inference below) is checked individually instead
// of only the first (see expand_sole_spread_arg). `arity_unknown`
// stays true even after expansion — PHP allows extra/spread
// positional args, so a concretely-known count still shouldn't
// trigger TooFew/TooManyArguments.
if let Some(expanded) = sole_spread_ty.and_then(|t| expand_sole_spread_arg(&t)) {
arg_spans = distinct_spans_for_expansion(arg_spans[0], expanded.len());
arg_names = vec![None; expanded.len()];
arg_can_be_byref = vec![false; expanded.len()];
arg_types = expanded;
has_spread = false;
arity_unknown = true;
}
// 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.
let mut call_user_func_string_arg = false;
if matches!(
resolved_fn_name.as_str(),
"call_user_func" | "call_user_func_array"
) {
if let Some(value) = call.args.first().and_then(|a| a.value.as_ref()) {
if let ExprKind::String(name) = &value.kind {
call_user_func_string_arg = true;
if let Some((class_name, method_name)) = name.as_ref().split_once("::") {
// "Class::method" static-callable string — resolve
// and record both, or a static method reachable only
// this way is falsely flagged UnusedMethod (and its
// class UnusedClass).
let resolved_class = crate::db::resolve_name(ea.db, &ea.file, class_name);
let here = crate::db::Fqcn::from_str(ea.db, &resolved_class);
if let Some((owner_fqcn, method)) =
crate::db::find_method_in_chain(ea.db, here, method_name)
{
ea.record_ref(Arc::from(format!("cls:{resolved_class}")), value.span);
ea.record_ref(
Arc::from(format!(
"meth:{owner_fqcn}::{}",
crate::util::php_ident_lowercase(&method.name)
)),
value.span,
);
}
} else {
// Runtime callable strings always resolve in the global
// namespace — no current-namespace fallback applies, unlike a
// direct `helper()` call. The function index itself is never
// keyed with a leading backslash (see the identical
// `strip_prefix` above for `resolved_fn_name`), so a lookup
// must strip one here too, not add one — a prepended `\`
// makes every lookup key mismatch and silently fail.
let fqn = name.as_ref().trim_start_matches('\\');
let here = crate::db::Fqcn::from_str(ea.db, fqn);
let canonical_fqn: Option<Arc<str>> =
crate::db::find_function(ea.db, here).map(|f| f.fqn.clone());
if let Some(canonical_fqn) = canonical_fqn {
ea.record_ref(Arc::from(format!("fn:{canonical_fqn}")), value.span);
}
}
}
}
}
// A string-literal class name passed to one of these reflection-like
// builtins is a real (runtime) reference to that class — record it,
// or a class checked/reflected on only this way is falsely flagged
// UnusedClass. `is_a`/`is_subclass_of`/`method_exists` take the class
// name in a different argument position than `class_exists`'s family.
// `class_alias`'s original-class argument is a hard requirement (PHP
// fatals if it doesn't exist), unlike the `*_exists` guards, but it's
// still just existence + reference recording here — no diagnostic is
// raised either way, matching how the rest of this table treats a
// string that fails to resolve to a real class.
let class_name_arg_index: Option<usize> = match resolved_fn_name
.to_ascii_lowercase()
.as_str()
{
"class_exists" | "interface_exists" | "trait_exists" | "enum_exists" => Some(0),
"is_a" | "is_subclass_of" => Some(1),
"method_exists" => Some(0),
"class_alias" => Some(0),
"class_implements" | "class_parents" | "class_uses" | "get_class_methods" => Some(0),
_ => None,
};
if let Some(idx) = class_name_arg_index {
if let Some(arg) = call.args.get(idx) {
if let Some(ExprKind::String(name)) = arg.value.as_ref().map(|v| &v.kind) {
let resolved_class = crate::db::resolve_name(ea.db, &ea.file, name.as_ref());
if crate::db::class_exists(ea.db, &resolved_class) {
ea.record_ref(Arc::from(format!("cls:{resolved_class}")), arg.span);
}
}
}
}
// compact() reads variables by string name at runtime; mark each string-literal arg as read.
// A non-literal argument (`compact($names)`/`compact(...$names)`) reads an
// unknowable set of names — reuse the same blanket exemption extract() gets
// below rather than risk flagging a variable that's actually read this way.
if fn_name == "compact" {
for arg in call.args.iter() {
if let Some(ExprKind::String(name)) = arg.value.as_ref().map(|v| &v.kind) {
ctx.read_vars.insert(mir_types::Name::from(name.as_ref()));
ctx.mark_consumed(name.as_ref());
} else {
ctx.has_dynamic_var_read = true;
}
}
}
// extract() defines variables whose names are only known at runtime (the
// keys of the passed array). After such a call, reads of otherwise-unknown
// variables must not be reported as undefined — the same handling as
// variable-variables.
if fn_name.eq_ignore_ascii_case("extract") {
ctx.has_dynamic_var_def = true;
// A tainted source array (`extract($_GET)`) means the variables
// it defines may carry attacker-controlled data too — their
// names aren't known statically, so mark the WHOLE scope as
// possibly holding a tainted dynamically-defined variable rather
// than trying (and failing) to taint a specific name.
if let Some(value) = call.args.first().and_then(|a| a.value.as_ref()) {
if crate::taint::is_expr_tainted(value, ctx, ea.db, &ea.file) {
ctx.has_dynamic_tainted_var_def = true;
}
}
}
if let Some(resolved) = resolved {
ea.record_ref(Arc::from(format!("fn:{}", resolved.fqn)), call.name.span);
let deprecated = resolved.deprecated;
let params = resolved.params;
let template_params = resolved.template_params;
let return_ty_raw = resolved.return_ty_raw;
let no_named_arguments = resolved.no_named_arguments;
let is_pure = resolved.is_pure;
let is_mutation_free = resolved.is_mutation_free;
let taint_sink_params = resolved.taint_sink_params;
// Taint sink check: emit the matching Tainted* issue when a
// tainted value reaches a @taint-sink annotated parameter.
// Mirrors call/method.rs's identical check for method/
// static-method calls — a plain function previously had no
// equivalent at all, so `@taint-sink` on one was a silent no-op.
if !taint_sink_params.is_empty() {
for (param_name, sink_kind) in &taint_sink_params {
let param_idx = params
.iter()
.position(|p| p.name.as_ref() == param_name.as_ref());
// A variadic sink parameter (`...$args`) swallows every
// trailing positional argument from its index onward, not
// just the first — check them all, mirroring how
// narrowing/assertions.rs's variadic assertion handling
// does the same for `@psalm-assert-if-true`.
let is_variadic = param_idx
.and_then(|idx| params.get(idx))
.is_some_and(|p| p.is_variadic);
let args: Vec<&php_ast::owned::Arg> = if is_variadic {
let idx = param_idx.unwrap();
call.args
.iter()
.filter(|a| a.name.is_none())
.skip(idx)
.collect()
} else {
let positional = param_idx.and_then(|idx| call.args.get(idx));
let named = call.args.iter().find(|a| {
a.name
.as_ref()
.map(|n| {
crate::parser::name_to_string_owned(n) == param_name.as_ref()
})
.unwrap_or(false)
});
positional.or(named).into_iter().collect()
};
for arg in args {
let Some(value) = &arg.value else { continue };
if is_expr_tainted(value, ctx, ea.db, &ea.file) {
ea.emit(taint_sink_issue(sink_kind), Severity::Error, span);
}
}
}
}
if ctx.is_in_pure_fn && !is_pure {
ea.emit(
IssueKind::ImpureFunctionCall {
fn_name: fn_name.rsplit('\\').next().unwrap_or(&fn_name).to_string(),
},
Severity::Warning,
span,
);
}
// Same check for @psalm-immutable/@psalm-external-mutation-free,
// scoped exactly like `new X(...)`'s own identical check in
// `expr/objects.rs`: an argument reachable from `$this`/a
// parameter that resolves to an OBJECT atom (not just a plain
// value read off it) lets a not-provably-safe callee store/
// mutate that object just as much as calling an impure METHOD
// on it would.
if (ctx.is_in_immutable_method || ctx.is_in_external_mutation_free_method)
&& !is_pure
&& !is_mutation_free
{
for arg in call.args.iter() {
let Some(value) = &arg.value else { continue };
let Some(recv_name) = crate::expr::root_receiver_var(value) else {
continue;
};
let recv_stripped = recv_name.trim_start_matches('$');
let reachable = (ctx.is_in_immutable_method && recv_stripped == "this")
|| (ctx.is_in_external_mutation_free_method
&& recv_stripped != "this"
&& ctx.param_names.contains(&Name::from(recv_stripped)));
if !reachable {
continue;
}
let arg_is_object = crate::expr::assignment::resolve_chained_receiver_type(
value, ctx, ea.db, &ea.file,
)
.is_some_and(|ty| {
ty.types.iter().any(|a| {
matches!(
a,
Atomic::TNamedObject { .. }
| Atomic::TSelf { .. }
| Atomic::TStaticObject { .. }
| Atomic::TParent { .. }
)
})
});
if arg_is_object {
ea.emit(
IssueKind::ImpureFunctionCall {
fn_name: fn_name
.rsplit('\\')
.next()
.unwrap_or(&fn_name)
.to_string(),
},
Severity::Warning,
span,
);
break;
}
}
}
// A free function has no receiver, but an object passed as an
// argument may have its own properties reassigned inside a
// callee that isn't proven pure — e.g. `save($this)` mutating
// `$this`. Free functions carry no separate "doesn't mutate its
// arguments" signal (unlike methods' `@psalm-external-mutation-
// free`), so `is_pure` is the only safe "touches nothing" check.
if !is_pure {
for arg in call.args.iter() {
if let Some(ExprKind::Variable(name)) = arg.value.as_ref().map(|v| &v.kind) {
ctx.invalidate_prop_refined_receiver(name);
}
}
}
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,
);
}
if let Some((used, canonical_str)) =
crate::fqcn_case_mismatch(&resolved_fn_name, resolved.fqn.as_ref())
{
ea.emit(
IssueKind::WrongCaseFunction {
used,
canonical: canonical_str,
},
Severity::Info,
call.name.span,
);
}
check_args(
ea,
CheckArgsParams {
fn_name: &fn_name,
params: ¶ms,
arg_types: &arg_types,
arg_spans: &arg_spans,
arg_names: &arg_names,
arg_can_be_byref: &arg_can_be_byref,
call_span: span,
has_spread,
arity_unknown,
too_many_arity_unknown: false,
template_params: &template_params,
no_named_arguments,
},
);
// Validate callbacks for built-in PHP functions with special callback requirements.
// Functions with dynamic or mode-dependent arity use specialized handlers.
// Functions with a fixed minimum arity are declared in callback_min_arity_spec.
match resolved_fn_name.as_str() {
"array_map" => {
super::array_builtins::check_array_map_callback(ea, &arg_types, &arg_spans)
}
"array_filter" => {
super::array_builtins::check_array_filter_callback(ea, &arg_types, &arg_spans)
}
fn_name => {
if let Some((cb_idx, min_arity)) =
super::callable::callback_min_arity_spec(fn_name)
{
super::callable::check_min_arity_callback(
ea, fn_name, cb_idx, min_arity, &arg_types, &arg_spans,
);
}
}
}
let template_bindings = if !template_params.is_empty() {
let (bindings, unchecked) = infer_template_bindings(
ea.db,
&template_params,
¶ms,
&arg_types,
&arg_names,
);
for (name, inferred, bound) in check_template_bounds_with_inheritance(
ea.db,
&bindings,
&template_params,
&unchecked,
None,
) {
ea.emit(
IssueKind::InvalidTemplateParam {
name: name.to_string(),
expected_bound: format!("{bound}"),
actual: format!("{inferred}"),
},
Severity::Error,
span,
);
}
Some(bindings)
} else {
None
};
// A by-ref output parameter's written-back value derives from the
// call's own arguments (e.g. `preg_match`'s `$matches` derives
// from the tainted subject) — conservatively taint (or clear) it
// the same "sticky" way `.=`/`??=` already treat their own
// result, rather than leaving its taint bit untouched from
// whatever it happened to hold before the call.
let any_arg_tainted = call.args.iter().any(|arg| {
arg.value
.as_ref()
.is_some_and(|v| is_expr_tainted(v, ctx, ea.db, &ea.file))
});
for (i, param) in params.iter().enumerate() {
if param.is_byref {
// Prefer @param-out type if declared; fall back to declared in-type.
// Substitute the function's own inferred template bindings so a
// generic identity/setter-style helper reports the concrete
// argument type, not the raw template atom.
let output_ty = param
.out_ty
.as_ref()
.or(param.ty.as_ref())
.map(|t| (**t).clone())
.unwrap_or_else(Type::mixed);
let output_ty = match &template_bindings {
Some(bindings) => output_ty.substitute_templates(bindings),
None => output_ty,
};
if param.is_variadic {
for arg in call.args.iter().skip(i) {
let Some(value) = &arg.value else { continue };
if let ExprKind::Variable(name) = &value.kind {
let var_name = name.as_ref().trim_start_matches('$');
// A plain-variable by-ref argument (`sort($items)`)
// mutates it exactly as much as an explicit write
// would — this branch used to go straight to
// `ctx.set_var` without ever routing through the
// purity check the `else` (non-variable) branch
// below already gets.
ea.check_var_write_purity(var_name, ctx, value.span);
ctx.set_var(var_name, output_ty.clone());
if any_arg_tainted {
ctx.taint_var(var_name);
} else {
ctx.clear_var_taint(var_name);
}
} else {
ea.check_byref_arg_purity(value, ctx, value.span);
}
}
} else if let Some(value) =
crate::call::resolve_named_arg_type_index(¶ms, &call.args, i)
.and_then(|idx| call.args.get(idx))
.and_then(|arg| arg.value.as_ref())
{
if let ExprKind::Variable(name) = &value.kind {
let var_name = name.as_ref().trim_start_matches('$');
ea.check_var_write_purity(var_name, ctx, value.span);
ctx.set_var(var_name, output_ty);
if any_arg_tainted {
ctx.taint_var(var_name);
} else {
ctx.clear_var_taint(var_name);
}
} else {
ea.check_byref_arg_purity(value, ctx, value.span);
}
}
}
}
// A bare-statement (unconditional) `@psalm-assert` call —
// reuses the exact per-assertion body the conditional if-true/
// if-false dispatch uses (`apply_one_assertion`), which this
// hand-duplicated loop never did: it never read
// `assertion.param_key` (an array-key-targeted assertion
// silently no-oped), never handled a variadic param (only
// ever resolved a single positional arg via `call.args.get(index)`),
// and never resolved a named argument.
for assertion in resolved
.assertions
.iter()
.filter(|a| a.kind == AssertionKind::Assert)
{
crate::narrowing::apply_one_assertion(
assertion,
¶ms,
&call.args,
None,
ctx,
template_bindings.as_ref(),
ea.db,
&ea.file,
);
}
let return_ty = match &template_bindings {
Some(bindings) => return_ty_raw.substitute_templates(bindings),
None => return_ty_raw,
};
let return_ty =
crate::call::resolve_conditional_return(return_ty, ea.db, |param_name| {
params
.iter()
.position(|p| p.name.as_ref() == param_name)
.and_then(|idx| {
crate::call::resolve_named_arg_type_index(¶ms, &call.args, idx)
})
.and_then(|idx| arg_types.get(idx))
.cloned()
});
// Built-in array transformers whose stub return type is a generic
// `array`: refine the element type from the callback / source array
// so binding sites (e.g. `foreach` over the result) get a usable
// value type. Falls back to the stub return when inference is unsure.
let return_ty =
match resolved_fn_name.as_str() {
"array_map" => {
let callback_expr = call.args.first().and_then(|a| a.value.as_ref());
super::array_builtins::infer_array_map_return(
ea,
&arg_types,
ctx,
callback_expr,
)
.unwrap_or(return_ty)
}
"array_filter" => super::array_builtins::infer_array_filter_return(&arg_types)
.unwrap_or(return_ty),
"array_reduce" => {
let callback_expr = call.args.get(1).and_then(|a| a.value.as_ref());
super::array_builtins::infer_array_reduce_return(
ea,
&arg_types,
ctx,
callback_expr,
)
.unwrap_or(return_ty)
}
"array_values" => super::array_builtins::infer_array_values_return(&arg_types)
.unwrap_or(return_ty),
"array_merge" => super::array_builtins::infer_array_merge_return(&arg_types)
.unwrap_or(return_ty),
// array_fill with a positive count returns a non-empty list.
"array_fill" => super::array_builtins::array_fill_return_type(&arg_types)
.unwrap_or(return_ty),
// implode/join with a non-empty array of non-empty strings returns non-empty-string.
"implode" | "join" => {
super::callable::implode_return_type(&arg_types).unwrap_or(return_ty)
}
// str_split with a non-empty string returns a non-empty list<non-empty-string>.
"str_split" => {
super::callable::str_split_return_type(&arg_types).unwrap_or(return_ty)
}
// explode with a non-empty separator always returns non-empty-list<string>.
"explode" => super::callable::explode_return_type(&arg_types, &return_ty)
.unwrap_or(return_ty),
// array_slice preserves the element type (and list structure when not
// preserving keys).
"array_slice" => super::array_builtins::array_slice_return_type(&arg_types)
.unwrap_or(return_ty),
// array_keys of a non-empty array returns a non-empty list (preserving the
// stub's key type from template resolution).
"array_keys" => {
super::array_builtins::array_keys_return_type(&arg_types, &return_ty)
}
// array_reverse preserves the non-emptiness of the source array.
"array_reverse" => super::array_builtins::array_reverse_return_type(&arg_types)
.unwrap_or(return_ty),
// array_unique preserves key/value types and non-empty status.
"array_unique" => {
super::array_builtins::array_unique_return(&arg_types).unwrap_or(return_ty)
}
// array_diff/array_intersect (and their _key/_assoc/u*/uassoc variants)
// always return a subset of the first argument's own entries, so the
// result's key/value types are exactly the first argument's.
"array_diff"
| "array_diff_key"
| "array_diff_ukey"
| "array_udiff"
| "array_diff_assoc"
| "array_udiff_assoc"
| "array_diff_uassoc"
| "array_udiff_uassoc"
| "array_intersect"
| "array_intersect_key"
| "array_intersect_ukey"
| "array_uintersect"
| "array_intersect_assoc"
| "array_uintersect_assoc"
| "array_intersect_uassoc"
| "array_uintersect_uassoc" => {
super::array_builtins::array_diff_intersect_like_return_type(&arg_types)
.unwrap_or(return_ty)
}
// array_combine pairs $keys's values (as keys) with $values's values,
// positionally; non-empty $keys guarantees a non-empty result.
"array_combine" => super::array_builtins::array_combine_return_type(&arg_types)
.unwrap_or(return_ty),
// array_merge_recursive: for the all-lists case (no possible int-key
// collision) it's identical to array_merge; the general string-keyed
// collision-merging case isn't modeled.
"array_merge_recursive" => {
super::array_builtins::array_merge_recursive_return_type(&arg_types)
.unwrap_or(return_ty)
}
// array_count_values: keys are the source's distinct int|string values;
// values are always counts (int<1, max>).
"array_count_values" => {
super::array_builtins::array_count_values_return_type(&arg_types)
.unwrap_or(return_ty)
}
// array_change_key_case: string keys are case-folded (values untouched);
// a plain array<K,V>'s key TYPE doesn't change, only shape keys rewrite.
"array_change_key_case" => {
super::array_builtins::array_change_key_case_return_type(&arg_types)
.unwrap_or(return_ty)
}
// array_splice returns the removed elements; like array_slice's
// preserve_keys=false path, int keys are always renumbered from 0.
"array_splice" => super::array_builtins::array_splice_return_type(&arg_types)
.unwrap_or(return_ty),
// array_pad: a pure-list source always renumbers to a fresh list
// regardless of pad direction; string-keyed sources aren't modeled.
"array_pad" => super::array_builtins::array_pad_return_type(&arg_types)
.unwrap_or(return_ty),
// array_column: pulls one column out of each row of a single
// resolvable shape; the whole-rows ($column_key === null) form
// isn't modeled.
"array_column" => super::array_builtins::array_column_return_type(&arg_types)
.unwrap_or(return_ty),
// range($start, $end) with integer bounds returns non-empty-list<int<min,max>>.
"range" => super::callable::range_return_type(&arg_types).unwrap_or(return_ty),
// array_key_first/array_key_last: non-null for non-empty input; int for lists.
"array_key_first" | "array_key_last" => {
super::array_builtins::array_key_first_last_return(&arg_types)
.unwrap_or(return_ty)
}
// array_pop/array_shift: return value type (not mixed) when source is typed.
"array_pop" | "array_shift" => {
super::array_builtins::array_pop_shift_return(&arg_types)
.unwrap_or(return_ty)
}
// reset/end: return value type (plus false) when source is typed.
"reset" | "end" => super::array_builtins::array_reset_end_return(&arg_types)
.unwrap_or(return_ty),
// current/next/prev: always value|false — pointer position from
// prior calls isn't tracked, even for a provably non-empty source.
"current" | "next" | "prev" => {
super::array_builtins::array_current_next_prev_return(&arg_types)
.unwrap_or(return_ty)
}
// array_rand: narrow by a literal $num — key type alone (omitted/1),
// or non-empty-list<key_type> for a literal count > 1.
"array_rand" => super::array_builtins::array_rand_return_type(&arg_types)
.unwrap_or(return_ty),
// compact(): build a shape from each string-literal name's
// current variable type instead of a generic array.
"compact" => super::array_builtins::compact_return_type(ctx, &call.args)
.unwrap_or(return_ty),
// Faithful integer-range returns: counts and lengths are
// non-negative (and counts of non-empty collections are `>= 1`).
"count" | "sizeof" => {
super::callable::count_return_type(&arg_types).unwrap_or(return_ty)
}
"strlen" | "mb_strlen" => super::callable::strlen_return_type(&arg_types),
"abs" => super::callable::abs_return_type(&arg_types).unwrap_or(return_ty),
// floor() and ceil() always return a whole-valued float — represent as
// TIntegralFloat so passing the result to an int param doesn't emit a FP.
"floor" | "ceil" => Type::single(Atomic::TIntegralFloat),
// round() without a precision arg (or with precision=0) is also always integral.
"round" => {
let precision_is_integral = arg_types.get(1).is_none_or(|t| {
t.types.len() == 1 && t.types[0] == Atomic::TLiteralInt(0)
});
if precision_is_integral {
Type::single(Atomic::TIntegralFloat)
} else {
return_ty
}
}
"intdiv" => {
// intdiv() throws the exact same DivisionByZeroError as `$a / 0` for
// a literal-zero divisor — report it the same way BinaryOp::Div does,
// rather than only narrowing the return type.
if let Some(divisor_ty) = arg_types.get(1) {
if crate::expr::operand_is_definitely_zero(divisor_ty) {
ea.emit(
IssueKind::DivisionByZero {
op: "intdiv".to_string(),
},
Severity::Error,
arg_spans.get(1).copied().unwrap_or(span),
);
}
}
super::callable::intdiv_return_type(&arg_types).unwrap_or(return_ty)
}
"min" => super::callable::min_return_type(&arg_types).unwrap_or(return_ty),
"max" => super::callable::max_return_type(&arg_types).unwrap_or(return_ty),
"rand" | "mt_rand" | "random_int" => {
super::callable::rand_return_type(&arg_types).unwrap_or(return_ty)
}
// preg_match returns 1 on match, 0 on no-match, false on error.
"preg_match" => {
let mut ty = Type::single(Atomic::TIntRange {
min: Some(0),
max: Some(1),
});
ty.add_type(Atomic::TFalse);
ty
}
// preg_match_all returns the count of matches (>= 0) or false on error.
"preg_match_all" => {
let mut ty = Type::single(Atomic::TNonNegativeInt);
ty.add_type(Atomic::TFalse);
ty
}
// Case-folding, encoding, and similar string functions that preserve non-emptiness:
// a non-empty input always produces a non-empty output, and these functions
// always return string (not string|false).
"strtolower"
| "strtoupper"
| "mb_strtolower"
| "mb_strtoupper"
| "ucfirst"
| "lcfirst"
| "ucwords"
| "mb_convert_case"
| "mb_convert_kana"
| "htmlspecialchars"
| "htmlentities"
| "html_entity_decode"
| "htmlspecialchars_decode"
| "addslashes"
| "addcslashes"
| "nl2br"
| "urlencode"
| "urldecode"
| "rawurlencode"
| "rawurldecode"
| "base64_encode"
| "quoted_printable_encode"
| "quoted_printable_decode"
| "str_rot13"
| "str_pad"
| "chunk_split"
| "wordwrap" => {
super::callable::string_preserve_non_empty(&arg_types).unwrap_or(return_ty)
}
// sprintf/vsprintf: non-empty when the format string guarantees it.
// vsprintf's args are passed as a single array, but the return-type
// inference only ever looks at arg_types[0] (the format string), so
// the same helper applies unchanged.
"sprintf" | "vsprintf" => {
super::callable::sprintf_return_type(&arg_types).unwrap_or(return_ty)
}
// number_format() always returns a non-empty string.
"number_format" => super::callable::number_format_return_type(),
// str_repeat() with a non-empty string and positive count returns non-empty.
"str_repeat" => {
super::callable::str_repeat_return_type(&arg_types).unwrap_or(return_ty)
}
// array_chunk splits an array into sub-arrays; outer list is non-empty when
// source is non-empty; chunks are list<T> by default (preserve_keys=false).
"array_chunk" => super::array_builtins::array_chunk_return_type(&arg_types)
.unwrap_or(return_ty),
// array_fill_keys uses the values of $keys as result keys and $value as each result value.
"array_fill_keys" => {
super::array_builtins::array_fill_keys_return_type(&arg_types)
.unwrap_or(return_ty)
}
// preg_split with default flags always returns at least one part.
"preg_split" => {
super::callable::preg_split_return_type(&arg_types).unwrap_or(return_ty)
}
// array_search: narrow key type from haystack rather than returning string|int|false.
"array_search" => super::array_builtins::array_search_return_type(&arg_types)
.unwrap_or(return_ty),
// key(): narrow to the array's own key type (plus null) instead of
// the stub's unrefined int|string|null.
"key" => super::array_builtins::array_key_return_type(&arg_types)
.unwrap_or(return_ty),
// date/time formatting functions always return non-empty strings.
"date" | "gmdate" | "date_format" => Type::single(Atomic::TNonEmptyString),
// Encoding/conversion functions: strip |false from stubs — they only
// return false on bad input that PHP code never checks for in practice.
"mb_convert_encoding" => super::callable::string_preserve_non_empty(&arg_types)
.or_else(|| super::callable::string_if_string_arg(&arg_types, 0))
.unwrap_or(return_ty),
"iconv" => {
// iconv($from_encoding, $to_encoding, $str) — $str is arg 2
super::callable::string_if_string_arg(&arg_types, 2).unwrap_or(return_ty)
}
// preg_replace/preg_replace_callback: strip |null when subject is a string.
// The null case only fires on a regex error, which PHP code rarely handles.
"preg_replace" | "preg_replace_callback" => {
// subject is arg 2
super::callable::string_if_string_arg(&arg_types, 2).unwrap_or(return_ty)
}
// substr_replace: strip |array when $string is a scalar string.
"substr_replace" => {
super::callable::string_if_string_arg(&arg_types, 0).unwrap_or(return_ty)
}
// filter_var: map a literal FILTER_VALIDATE_* $filter argument to its
// real result type instead of the stub's blanket `mixed`.
"filter_var" => {
super::callable::filter_var_return_type(&arg_types).unwrap_or(return_ty)
}
_ => return_ty,
};
let mut return_ty = return_ty;
ea.apply_function_call_plugins(
resolved.fqn.as_ref(),
&call.args,
&arg_types,
span,
&mut return_ty,
);
// array_push/array_unshift: the by-ref loop above set $arr to the stub's
// generic `array` type — replace it with the precise post-push type derived
// from the original array type (arg_types[0]) and the pushed value types.
if matches!(resolved_fn_name.as_str(), "array_push" | "array_unshift") {
if let (Some(arr_arg), Some(original_arr)) = (call.args.first(), arg_types.first())
{
if let Some(ExprKind::Variable(name)) = arr_arg.value.as_ref().map(|v| &v.kind)
{
let var_name = name.as_ref().trim_start_matches('$');
let push_types: Vec<Type> = arg_types.iter().skip(1).cloned().collect();
let new_type = super::array_builtins::array_push_unshift_byref_type(
original_arr,
&push_types,
ctx.inside_loop,
);
ctx.set_var(var_name, new_type);
}
}
}
// Sort functions (and array_walk/array_walk_recursive, which mutate
// values in place without adding/removing/reordering keys — the same
// "restore the original type unchanged" shape as a key-preserving
// sort): the by-ref loop above set $arr to generic `array`; restore
// the original element type. Re-indexing sorts also convert to a list.
{
let reindex = matches!(
resolved_fn_name.as_str(),
"sort" | "rsort" | "usort" | "shuffle"
);
let preserve = matches!(
resolved_fn_name.as_str(),
"asort"
| "arsort"
| "ksort"
| "krsort"
| "uasort"
| "uksort"
| "natsort"
| "natcasesort"
| "array_walk"
| "array_walk_recursive"
);
if reindex || preserve {
if let (Some(arr_arg), Some(original_arr)) =
(call.args.first(), arg_types.first())
{
if let Some(ExprKind::Variable(name)) =
arr_arg.value.as_ref().map(|v| &v.kind)
{
let var_name = name.as_ref().trim_start_matches('$');
let new_type =
super::array_builtins::sort_byref_type(original_arr, reindex);
ctx.set_var(var_name, new_type);
}
}
}
}
// preg_match / preg_match_all: the by-ref loop above wrote the stub's
// generic `string[]` to `$matches`. Override with the flag-aware type:
// no PREG_OFFSET_CAPTURE → list<string>; with it → list<array{0:string,1:int}>.
// preg_match_all wraps one more list level.
if matches!(resolved_fn_name.as_str(), "preg_match" | "preg_match_all") {
if let Some(matches_arg) = call.args.get(2) {
if let Some(ExprKind::Variable(name)) =
matches_arg.value.as_ref().map(|v| &v.kind)
{
let var_name = name.as_ref().trim_start_matches('$');
let flags: i64 = arg_types
.get(3)
.and_then(|t| {
t.types.iter().find_map(|a| {
if let Atomic::TLiteralInt(v) = a {
Some(*v)
} else {
None
}
})
})
.unwrap_or(0);
let new_type = if resolved_fn_name.as_str() == "preg_match" {
super::callable::preg_match_matches_type(flags)
} else {
super::callable::preg_match_all_matches_type(flags)
};
ctx.set_var(var_name, new_type);
}
}
}
super::ARG_TYPES_BUF.with(|b| {
let mut g = b.borrow_mut();
if g.as_ref().map_or(0, |v| v.capacity()) < arg_types.capacity() {
*g = Some(arg_types);
}
});
// Check inter-procedural throws: if callee declares @throws, check if caller covers them.
// Unchecked exceptions (RuntimeException / LogicException descendants) are skipped by
// PHP convention — see [`is_unchecked_exception`].
for callee_throw in resolved.throws.iter() {
if crate::db::is_unchecked_exception(ea.db, callee_throw.as_ref()) {
continue;
}
if !ctx.fn_declared_throws.iter().any(|declared| {
declared.as_ref() == callee_throw.as_ref()
|| crate::db::extends_or_implements(
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,
ReferenceKind::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 Type::mixed();
}
} else {
// No docblock found; assume the function is available (conservative).
return Type::mixed();
}
}
}
// Don't emit UndefinedFunction if call_user_func/call_user_func_array with string arg
// - string args are runtime callable names that may not exist at compile time
// Also skip when guarded by `function_exists('fn')` (PHP function names
// are case-insensitive). The short name is matched too, since a bare
// call in a namespace falls back to the global function the guard names.
let short_fn = fn_name.rsplit('\\').next().unwrap_or(&fn_name);
let guarded = ctx
.function_exists_guards
.iter()
.any(|g| g.eq_ignore_ascii_case(&fn_name) || g.eq_ignore_ascii_case(short_fn));
if !call_user_func_string_arg && !guarded {
ea.emit(
IssueKind::UndefinedFunction { name: fn_name },
Severity::Error,
span,
);
}
Type::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 {}", crate::util::php_ident_lowercase(short_name));
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 {}", crate::util::php_ident_lowercase(short_name));
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
}
}
/// Convert `mir_types::atomic::FnParam` (from TClosure) to `mir_codebase::definitions::DeclaredParam`
/// so they can be passed to `check_args`.
fn type_param_to_storage_param(p: &TypeFnParam) -> DeclaredParam {
DeclaredParam {
name: p.name,
ty: p.ty.as_ref().map(|t| Arc::new(t.to_union())),
out_ty: p.out_ty.as_ref().map(|t| Arc::new(t.to_union())),
has_default: p.default.is_some(),
is_variadic: p.is_variadic,
is_byref: p.is_byref,
is_optional: p.is_optional,
}
}
/// Try to extract a callable name and full typed params from a callee type union.
/// Returns `Some((name, params))` for:
/// - `TClosure` — name is `"{closure}"`, params from the closure's param list
/// - `TNamedObject` with `__invoke` method — name is `"Fqcn::__invoke"`, params from DB
///
/// Returns `None` if the union contains a bare `TCallable { params: None }` (unknown arity),
/// same guard as `extract_callable_params`.
fn typed_params_from_callee(
union: &Type,
ea: &ExpressionAnalyzer<'_>,
) -> Option<(String, Vec<DeclaredParam>)> {
// Bare callable with unknown arity — we cannot determine params statically.
if union
.types
.iter()
.any(|a| matches!(a, Atomic::TCallable { params: None, .. }))
{
return None;
}
for atomic in &union.types {
match atomic {
Atomic::TClosure { data } => {
let storage_params = data
.params
.iter()
.map(type_param_to_storage_param)
.collect();
return Some(("{closure}".to_string(), storage_params));
}
Atomic::TCallable {
params: Some(params),
..
} => {
let storage_params = params.iter().map(type_param_to_storage_param).collect();
return Some(("callable".to_string(), storage_params));
}
Atomic::TNamedObject { fqcn, .. } => {
if let Some((_, storage)) = crate::db::find_method_respecting_precedence(
ea.db,
crate::db::Fqcn::from_str(ea.db, fqcn.as_ref()),
"__invoke",
) {
let fn_name = format!("{}::__invoke", fqcn);
return Some((fn_name, storage.params.to_vec()));
}
}
_ => {}
}
}
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
}