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
/// Statement analyzer — walks statement nodes threading context through
/// control flow (if/else, loops, try/catch, return).
mod control_flow;
mod declarations;
mod expressions;
mod flow;
mod loops;
mod return_type;
pub(crate) use return_type::erase_templates_to_bounds;
pub(crate) use flow::return_type_is_invalid;
pub(crate) use loops::infer_foreach_types;
pub(crate) use loops::resolve_iterator_item_types;
use loops::{vars_stabilized, widen_unstable};
pub(crate) use return_type::named_object_return_compatible;
pub(crate) use return_type::resolve_union_for_file;
pub(crate) use return_type::resolve_union_for_file_native;
pub(crate) use return_type::resolve_union_for_file_with_templates;
pub(crate) use return_type::return_arrays_compatible;
use std::sync::Arc;
use crate::parser::docblock::parse_type_string;
use crate::reference_key::ReferenceKeyCache;
use php_ast::owned::{Expr, ExprKind, StmtKind};
use mir_issues::{Issue, IssueBuffer, IssueKind, Location};
use mir_types::{Atomic, Type};
use crate::body_analysis::AnalysisMode;
use crate::db::MirDatabase;
use crate::expr::ExpressionAnalyzer;
use crate::flow_state::FlowState;
use crate::php_version::PhpVersion;
use crate::symbol::{NavigationFact, ResolvedNavigationFact, ResolvedSymbol};
// ---------------------------------------------------------------------------
// VarAnnotation
// ---------------------------------------------------------------------------
/// Parsed `@var` annotation from a docblock preceding a statement.
struct VarAnnotation {
/// `None` when no `$varname` was given — annotation applies to the statement's LHS.
name: Option<String>,
ty: mir_types::Type,
}
/// The `$name` (without `$`) of a simple `$x = expr;` statement LHS, if any.
fn simple_assignment_lhs(stmt: &php_ast::owned::Stmt) -> Option<&str> {
let php_ast::owned::StmtKind::Expression(e) = &stmt.kind else {
return None;
};
let php_ast::owned::ExprKind::Assign(a) = &e.kind else {
return None;
};
if !matches!(&a.op, php_ast::ast::AssignOp::Assign) {
return None;
}
let php_ast::owned::ExprKind::Variable(lhs_name) = &a.target.kind else {
return None;
};
Some(lhs_name.trim_start_matches('$'))
}
/// Calls `f` with the name of every plain-variable leaf of a (nested) destructuring target.
fn for_each_destructured_var(target: &php_ast::owned::Expr, f: &mut impl FnMut(&str)) {
let php_ast::owned::ExprKind::Array(elements) = &target.kind else {
return;
};
for elem in elements.iter() {
match &elem.value.kind {
php_ast::owned::ExprKind::Variable(name) => f(name.trim_start_matches('$')),
php_ast::owned::ExprKind::Array(_) => for_each_destructured_var(&elem.value, f),
_ => {}
}
}
}
/// Apply post-narrow: after `$x = expr()` or `static $x = expr;`, override the inferred type
/// with the annotated one. Named `@var Type $x` applies only when the target name matches. Bare
/// `@var Type` applies to a single simple LHS (it annotates the statement, not a specific
/// variable) — for a multi-var `static $a, $b;` declaration a bare annotation is ambiguous and
/// is skipped.
fn apply_post_narrow(stmt: &php_ast::owned::Stmt, annotation: &VarAnnotation, ctx: &mut FlowState) {
let apply = |name: &str, ctx: &mut FlowState| match &annotation.name {
Some(var_name) => {
if name == var_name.as_str() {
ctx.set_var(var_name.as_str(), annotation.ty.clone());
}
}
None => ctx.set_var(name, annotation.ty.clone()),
};
match &stmt.kind {
php_ast::owned::StmtKind::Expression(e) => {
let php_ast::owned::ExprKind::Assign(a) = &e.kind else {
return;
};
if !matches!(&a.op, php_ast::ast::AssignOp::Assign) {
return;
}
match &a.target.kind {
php_ast::owned::ExprKind::Variable(lhs_name) => {
apply(lhs_name.trim_start_matches('$'), ctx)
}
// Only a named annotation can pick its target out of a destructure.
php_ast::owned::ExprKind::Array(_) if annotation.name.is_some() => {
for_each_destructured_var(&a.target, &mut |n| apply(n, ctx));
}
_ => {}
}
}
php_ast::owned::StmtKind::StaticVar(vars) => {
if annotation.name.is_some() {
for sv in vars.iter() {
if let Some(name) = sv.name.as_deref() {
apply(name.trim_start_matches('$'), ctx);
}
}
} else if let [sv] = vars.as_ref() {
if let Some(name) = sv.name.as_deref() {
apply(name.trim_start_matches('$'), ctx);
}
}
}
_ => {}
}
}
/// Detects the "assign a closure literal, then immediately rebind it" idiom:
/// ```php
/// $copy = function (...) use (...) { ... };
/// return Closure::bind($copy, $newThis, Scope::class); // or `$x = ...`, or `$copy->bindTo($newThis, Scope::class)`
/// ```
/// (or `$copy->call($newThis)`) and classifies the rebind, so the closure body
/// (analyzed as part of `stmt`, the assignment) is checked against the rebound
/// scope/`$this` instead of its lexically enclosing class.
/// Deliberately narrow: only the statement immediately following the
/// assignment is considered, so nothing in between could have reassigned the
/// variable or invalidated the rebind.
fn closure_var_rebind(
db: &dyn MirDatabase,
file: &str,
stmt: &php_ast::owned::Stmt,
next: Option<&php_ast::owned::Stmt>,
) -> Option<crate::call::ClosureRebind> {
let StmtKind::Expression(e) = &stmt.kind else {
return None;
};
let ExprKind::Assign(assign) = &e.kind else {
return None;
};
if !matches!(&assign.op, php_ast::ast::AssignOp::Assign) {
return None;
}
let ExprKind::Variable(var_name) = &assign.target.kind else {
return None;
};
if !matches!(
&assign.value.kind,
ExprKind::Closure(_) | ExprKind::ArrowFunction(_)
) {
return None;
}
let next_expr: &Expr = match &next?.kind {
StmtKind::Expression(e) => e,
StmtKind::Return(Some(e)) => e,
_ => return None,
};
let call_expr = match &next_expr.kind {
ExprKind::Assign(a) => a.value.as_ref(),
_ => next_expr,
};
match &call_expr.kind {
ExprKind::StaticMethodCall(smc) => {
let ExprKind::Identifier(class_name) = &smc.class.kind else {
return None;
};
if !crate::db::resolve_name(db, file, class_name).eq_ignore_ascii_case("Closure") {
return None;
}
let ExprKind::Identifier(method_name) = &smc.method.kind else {
return None;
};
if !method_name.eq_ignore_ascii_case("bind") {
return None;
}
let first_arg = smc.args.first()?.value.as_ref()?;
if !matches!(&first_arg.kind, ExprKind::Variable(v) if v == var_name) {
return None;
}
let arg = |i: usize| smc.args.get(i).and_then(|a| a.value.as_ref());
crate::call::closure_rebind(db, file, arg(1), arg(2))
}
ExprKind::MethodCall(mc) => {
if !matches!(&mc.object.kind, ExprKind::Variable(v) if v == var_name) {
return None;
}
let ExprKind::Identifier(method_name) = &mc.method.kind else {
return None;
};
let arg = |i: usize| mc.args.get(i).and_then(|a| a.value.as_ref());
if method_name.eq_ignore_ascii_case("bindTo") {
crate::call::closure_rebind(db, file, arg(0), arg(1))
} else if method_name.eq_ignore_ascii_case("call") {
crate::call::closure_rebind(db, file, arg(0), None)
} else {
None
}
}
_ => None,
}
}
// ---------------------------------------------------------------------------
// StatementsAnalyzer
// ---------------------------------------------------------------------------
pub struct StatementsAnalyzer<'a> {
pub db: &'a dyn MirDatabase,
pub file: Arc<str>,
pub source: &'a str,
pub source_map: &'a php_rs_parser::source_map::SourceMap,
pub issues: &'a mut IssueBuffer,
pub symbols: Option<&'a mut Vec<ResolvedSymbol>>,
pub navigation_facts: &'a std::cell::RefCell<Vec<NavigationFact>>,
pub resolved_navigation_facts: &'a std::cell::RefCell<Vec<ResolvedNavigationFact>>,
pub php_version: PhpVersion,
pub mode: AnalysisMode,
/// When false, `ResolvedSymbol` recording is skipped entirely. Set by
/// pure inference walks whose caller discards the symbol buffer, so the
/// walk doesn't clone a Type per reference just to drop it.
pub collect_symbols: bool,
/// When false, recorded symbols keep only navigation shape and use
/// `Type::mixed()` instead of cloning the precise resolved type.
pub capture_symbol_types: bool,
/// When true, skip symbols that cannot map to a codebase-level
/// [`crate::Name`] (currently variables only on the stmt side).
pub codebase_symbols_only: bool,
/// When false, skip recording reference-location postings.
pub record_reference_locations: bool,
/// When true, collect compact codebase-name navigation facts.
pub collect_navigation_facts: bool,
/// When true, collect compact typed facts for codebase symbol resolution.
pub collect_resolved_navigation_facts: bool,
/// Accumulated inferred return types for the current function.
pub return_types: Vec<Type>,
/// `(key type, value type)` for every `yield`/`yield from` seen so far in
/// the current function body — see `ExpressionAnalyzer::yielded_types`.
pub yielded_types: Vec<(Type, Type)>,
/// Break-context stack: one entry per active loop/switch nesting level
/// (both count towards break/continue level targeting in PHP).
/// Each entry collects the context states at every `break`/switch-scoped
/// `continue` targeting that level.
break_ctx_stack: Vec<Vec<FlowState>>,
/// Parallel to `break_ctx_stack`, collecting real-loop `continue` states.
/// A continue may still reach the normal exit of a finite loop, but must
/// not make the code after an infinite loop reachable.
continue_ctx_stack: Vec<Vec<FlowState>>,
/// Parallel to `break_ctx_stack`: `true` if the corresponding level is a
/// real loop, `false` if it's a `switch`. `continue` behaves differently
/// depending on which kind its target level is — see `analyze_continue_stmt`.
loop_kind_stack: Vec<bool>,
/// Snapshot of the installed plugin registry — see
/// `ExpressionAnalyzer::plugins`.
plugins: Option<std::sync::Arc<mir_plugin::PluginRegistry>>,
/// Cache of the last `find_class_like` lookup done for `@var`-annotation
/// alias expansion (`extract_var_annotation_from`), keyed by FQCN. Many
/// consecutive `@var`-annotated statements within the same method/class
/// body share the same `self_fqcn`; without this, each one repeats an
/// `Arc<ClassDef>`-cloning workspace-index lookup that measurably added
/// up across a large corpus (see the alias-expansion commit's perf note).
class_like_cache: Option<(Arc<str>, Option<crate::db::ClassLike>)>,
/// Cache of the last `find_function` lookup done for `@var`-annotation
/// alias expansion in a free function's own body, mirroring
/// `class_like_cache`.
function_cache: Option<(
Arc<str>,
Option<Arc<mir_codebase::definitions::FunctionDef>>,
)>,
reference_key_cache: ReferenceKeyCache,
}
impl<'a> StatementsAnalyzer<'a> {
#[allow(clippy::too_many_arguments)]
pub fn new(
db: &'a dyn MirDatabase,
file: Arc<str>,
source: &'a str,
source_map: &'a php_rs_parser::source_map::SourceMap,
issues: &'a mut IssueBuffer,
symbols: Option<&'a mut Vec<ResolvedSymbol>>,
navigation_facts: &'a std::cell::RefCell<Vec<NavigationFact>>,
resolved_navigation_facts: &'a std::cell::RefCell<Vec<ResolvedNavigationFact>>,
php_version: PhpVersion,
mode: AnalysisMode,
) -> Self {
Self {
db,
file,
source,
source_map,
issues,
symbols,
navigation_facts,
resolved_navigation_facts,
php_version,
mode,
collect_symbols: true,
capture_symbol_types: true,
codebase_symbols_only: false,
record_reference_locations: true,
collect_navigation_facts: false,
collect_resolved_navigation_facts: false,
return_types: Vec::new(),
yielded_types: Vec::new(),
break_ctx_stack: Vec::new(),
continue_ctx_stack: Vec::new(),
loop_kind_stack: Vec::new(),
plugins: mir_plugin::snapshot(),
class_like_cache: None,
function_cache: None,
reference_key_cache: ReferenceKeyCache::default(),
}
}
/// `find_class_like(fqcn)`, memoized against the immediately preceding
/// call — cheap when consecutive calls share the same FQCN (the common
/// case: many `@var`-annotated statements in the same method body).
fn cached_class_like(&mut self, fqcn: &str) -> Option<&crate::db::ClassLike> {
let hit = self
.class_like_cache
.as_ref()
.is_some_and(|(cached_fqcn, _)| cached_fqcn.as_ref() == fqcn);
if !hit {
let resolved =
crate::db::find_class_like(self.db, crate::db::Fqcn::from_str(self.db, fqcn));
self.class_like_cache = Some((Arc::from(fqcn), resolved));
}
self.class_like_cache
.as_ref()
.and_then(|(_, cl)| cl.as_ref())
}
/// `find_function(fqn)`, memoized against the immediately preceding call —
/// mirrors `cached_class_like` for the free-function `@var` alias-expansion
/// fallback below.
fn cached_function(
&mut self,
fqn: &str,
) -> Option<Arc<mir_codebase::definitions::FunctionDef>> {
let hit = self
.function_cache
.as_ref()
.is_some_and(|(cached_fqn, _)| cached_fqn.as_ref() == fqn);
if !hit {
let resolved =
crate::db::find_function(self.db, crate::db::Fqcn::from_str(self.db, fqn));
self.function_cache = Some((Arc::from(fqn), resolved));
}
self.function_cache.as_ref().and_then(|(_, f)| f.clone())
}
pub fn analyze_stmts(&mut self, stmts: &[php_ast::owned::Stmt], ctx: &mut FlowState) {
for (i, stmt) in stmts.iter().enumerate() {
if ctx.diverges {
let (line, col_start) = self.offset_to_line_col(stmt.span.start);
let (line_end, col_end) = if stmt.span.start < stmt.span.end {
let (end_line, end_col) = self.offset_to_line_col(stmt.span.end);
(end_line, end_col)
} else {
(line, col_start + 1)
};
self.issues.add(
Issue::new(
IssueKind::UnreachableCode,
Location {
file: self.file.clone(),
line,
line_end,
col_start,
col_end: crate::diagnostics::clamp_col_end(
line, line_end, col_start, col_end,
),
},
)
.with_snippet(
crate::parser::span_text(self.source, stmt.span).unwrap_or_default(),
),
);
// Dead code is analyzed so symbol queries resolve, but it must
// not report issues or count as a usage of any member.
let mark = self.issues.issue_count();
let records_refs = std::mem::replace(&mut self.record_reference_locations, false);
let mut dead_ctx = ctx.clone();
dead_ctx.diverges = false;
self.analyze_stmts(&stmts[i..], &mut dead_ctx);
self.record_reference_locations = records_refs;
self.issues.truncate_to(mark);
break;
}
match closure_var_rebind(self.db, &self.file, stmt, stmts.get(i + 1)) {
Some(rebind) => {
let guard =
crate::flow_state::ScopeOverrideGuard::apply_rebind(ctx, self.db, &rebind);
self.analyze_stmt(stmt, ctx);
guard.restore(ctx);
}
None => self.analyze_stmt(stmt, ctx),
}
}
}
pub fn analyze_stmt(&mut self, stmt: &php_ast::owned::Stmt, ctx: &mut FlowState) {
crate::recursion::ensure_stack(|| self.analyze_stmt_inner(stmt, ctx));
}
fn analyze_stmt_inner(&mut self, stmt: &php_ast::owned::Stmt, ctx: &mut FlowState) {
let doc = crate::parser::find_preceding_docblock(self.source, stmt.span.start);
let suppressions = self.extract_suppressions_from(doc.as_deref());
let before = self.issues.issue_count();
let var_annotations = self.extract_var_annotations_from(
doc.as_deref(),
ctx.self_fqcn.as_deref(),
ctx.template_method().map(|m| &**m),
ctx.template_function().map(|f| &**f),
);
// Pre-narrow: `@var Type $varname` before any statement narrows that variable.
for ann in &var_annotations {
// UndefinedDocblockClass: `@var` names a class that doesn't exist;
// otherwise record it as a `cls:` reference so a class named only
// via a local `@var` assertion isn't falsely flagged UnusedClass.
for atomic in &ann.ty.types {
if let Atomic::TNamedObject { fqcn, type_params } = atomic {
if crate::diagnostics::is_docblock_keyword(fqcn.as_ref()) {
continue;
}
let (line, line_end, col_start, col_end) = self.span_to_location(stmt.span);
if !crate::db::class_exists(
self.db,
crate::diagnostics::docblock_class_part(fqcn.as_ref()),
) {
self.issues.add(Issue::new(
IssueKind::UndefinedDocblockClass {
name: fqcn.to_string(),
},
Location {
file: self.file.clone(),
line,
line_end,
col_start,
col_end: crate::diagnostics::clamp_col_end(
line, line_end, col_start, col_end,
),
},
));
} else {
if self.mode == AnalysisMode::Full && self.record_reference_locations {
self.db.record_reference_location(crate::db::RefLoc {
symbol_key: self.reference_key_cache.class(fqcn.as_ref()),
file: self.file.clone(),
line,
col_start,
col_end: crate::diagnostics::clamp_col_end(
line, line_end, col_start, col_end,
),
});
}
// Arity mismatch: `@var TypedMap<string>` against a
// class declaring 2 template params. A caller
// supplying NO type args at all (`@var TypedMap`) is
// the legitimate bare-generic-reference shorthand and
// deliberately not flagged here — only a supplied,
// wrong-length argument list is an error.
if !type_params.is_empty() {
let declared_count =
crate::db::class_template_params(self.db, fqcn.as_ref())
.map(|tps| tps.len())
.unwrap_or(0);
if declared_count != type_params.len() {
self.issues.add(Issue::new(
IssueKind::InvalidDocblock {
message: format!(
"{fqcn} expects {declared_count} template argument(s), got {}",
type_params.len()
),
},
Location {
file: self.file.clone(),
line,
line_end,
col_start,
col_end: crate::diagnostics::clamp_col_end(
line, line_end, col_start, col_end,
),
},
));
}
}
}
}
}
if let Some(ref name) = ann.name {
let current = ctx.get_var(name.as_str());
// `@var` is normally a legitimate widening/narrowing assertion
// (e.g. `Animal` -> `Dog`) that must stay silent — only flag it
// when the two types share NO possible overlap at all (e.g.
// `string` vs `int`), using coarse PHP type families so this
// never fires on object narrowing (both sides just map to the
// same OBJECT family bit) or on mixed/template/unknown types
// (family mask 0, treated as "nothing to compare").
let current_mask = crate::body_analysis::type_family_mask(¤t);
let ann_mask = crate::body_analysis::type_family_mask(&ann.ty);
if current_mask != 0 && ann_mask != 0 && current_mask & ann_mask == 0 {
let (line, line_end, col_start, col_end) = self.span_to_location(stmt.span);
self.issues.add(Issue::new(
IssueKind::DocblockTypeContradiction {
expr: format!("@var {} ${name}", ann.ty),
declared: current.to_string(),
},
Location {
file: self.file.clone(),
line,
line_end,
col_start,
col_end: crate::diagnostics::clamp_col_end(
line, line_end, col_start, col_end,
),
},
));
}
// `@var T $obj->prop` refines the property, not a variable.
match name.rsplit_once("->") {
Some((obj, prop)) => ctx.set_prop_refined(obj, prop, ann.ty.clone()),
None => {
// Not a write: a `@var` for a name never otherwise defined must not
// surface as UnusedVariable.
if !ctx.var_is_defined(name) {
ctx.read_vars.insert(mir_types::Name::from(name.as_str()));
}
ctx.set_var(name.as_str(), ann.ty.clone());
}
}
}
}
// Check `@mir-check` directives
let mir_checks = self.extract_mir_checks_from(doc.as_deref());
let (line, line_end, col_start, col_end) = self.span_to_location(stmt.span);
for (expr_text, expected_str) in mir_checks {
let expected_raw = parse_type_string(&expected_str);
// Resolve the expected type through the file's namespace/imports so that
// `\Foo\Bar` in a @mir-check directive matches the stored `Foo\Bar` (sans `\`).
let expected = resolve_union_for_file(expected_raw, self.db, &self.file);
let actual_raw = self.expr_analyzer(ctx).eval_check_expr(&expr_text, ctx);
if !mir_check_matches(&expected, &actual_raw) {
self.issues.add(Issue::new(
IssueKind::TypeCheckMismatch {
var: expr_text,
expected: expected.to_string(),
actual: widen_for_check(actual_raw).to_string(),
},
Location {
file: self.file.clone(),
line,
line_end,
col_start,
col_end: crate::diagnostics::clamp_col_end(
line, line_end, col_start, col_end,
),
},
));
}
}
// Emit `@trace $var` directives
if let Some(doc_str) = doc.as_deref() {
let trace_vars = crate::parser::DocblockParser::parse(doc_str).trace_vars;
for var_name in trace_vars {
let ty = ctx.get_var(&var_name);
self.issues.add(Issue::new(
IssueKind::Trace {
variable: var_name,
type_info: ty.to_string(),
},
Location {
file: self.file.clone(),
line,
line_end,
col_start,
col_end: crate::diagnostics::clamp_col_end(
line, line_end, col_start, col_end,
),
},
));
}
}
match &stmt.kind {
// ---- Expression statement ----------------------------------------
StmtKind::Expression(expr) => {
// @template on a closure or arrow function is not valid
if matches!(
expr.kind,
php_ast::owned::ExprKind::Closure(_)
| php_ast::owned::ExprKind::ArrowFunction(_)
) {
if let Some(raw_doc) = doc.as_deref() {
let parsed = crate::parser::DocblockParser::parse(raw_doc);
if let Some(&(tag_start, tag_end)) = parsed.template_spans.first() {
let doc_start = self.source[..stmt.span.start as usize]
.rfind(raw_doc)
.unwrap_or(0) as u32;
let (line, line_end, col_start, col_end) = self.span_to_location(
php_ast::Span::new(doc_start + tag_start, doc_start + tag_end),
);
self.issues.add(Issue::new(
IssueKind::InvalidDocblock {
message: "@template annotations are not supported on closures or arrow functions".to_string(),
},
Location {
file: self.file.clone(),
line,
line_end,
col_start,
col_end,
},
));
}
}
}
self.analyze_expression_stmt(expr, ctx);
}
// ---- Echo ---------------------------------------------------------
StmtKind::Echo(exprs) => {
self.analyze_echo_stmt(exprs, stmt.span, ctx);
}
// ---- Return -------------------------------------------------------
StmtKind::Return(opt_expr) => {
self.analyze_return_stmt(opt_expr, stmt, ctx);
}
// ---- Throw --------------------------------------------------------
StmtKind::Throw(expr) => {
self.analyze_throw_stmt(expr, stmt.span, ctx);
}
// ---- If -----------------------------------------------------------
StmtKind::If(if_stmt) => {
self.analyze_if_stmt(if_stmt, ctx);
}
// ---- While --------------------------------------------------------
StmtKind::While(w) => {
self.analyze_while_stmt(w, ctx);
}
// ---- Do-while -----------------------------------------------------
StmtKind::DoWhile(dw) => {
self.analyze_dowhile_stmt(dw, ctx);
}
// ---- For ----------------------------------------------------------
StmtKind::For(f) => {
self.analyze_for_stmt(f, ctx);
}
// ---- Foreach ------------------------------------------------------
StmtKind::Foreach(fe) => {
self.analyze_foreach_stmt(fe, stmt, ctx);
}
// ---- Switch -------------------------------------------------------
StmtKind::Switch(sw) => {
self.analyze_switch_stmt(sw, ctx);
}
// ---- Try/catch/finally -------------------------------------------
StmtKind::TryCatch(tc) => {
self.analyze_trycatch_stmt(tc, ctx);
}
// ---- Block --------------------------------------------------------
StmtKind::Block(block) => {
self.analyze_stmts(&block.stmts, ctx);
}
// ---- Break --------------------------------------------------------
StmtKind::Break(level) => {
self.analyze_break_stmt(ctx, break_continue_level(level));
}
// ---- Continue ----------------------------------------------------
StmtKind::Continue(level) => {
self.analyze_continue_stmt(ctx, break_continue_level(level));
}
// ---- Unset --------------------------------------------------------
StmtKind::Unset(vars) => {
self.analyze_unset_stmt(vars, ctx);
}
// ---- Static variable declaration ---------------------------------
StmtKind::StaticVar(vars) => {
self.analyze_static_var_stmt(vars, ctx);
}
// ---- Global declaration ------------------------------------------
StmtKind::Global(vars) => {
self.analyze_global_stmt(vars, ctx);
}
// ---- Declare -----------------------------------------------------
StmtKind::Declare(d) => {
self.analyze_declare_stmt(d, ctx);
}
// ---- Nested declarations (inside function bodies) ----------------
StmtKind::Function(decl) => {
self.analyze_function_decl_stmt(decl, ctx);
}
StmtKind::Class(decl) => {
self.analyze_class_decl_stmt(decl, ctx);
}
StmtKind::Interface(_) | StmtKind::Trait(_) | StmtKind::Enum(_) => {
// Interfaces/traits/enums are collected in definition collection — skip here
}
// ---- Namespace / use (at file level, already handled in definition
// collection; braced namespace bodies are walked by
// `BodyAnalyzer::analyze_global_exec` / `analyze_top_level_stmts`) --
StmtKind::Namespace(_) | StmtKind::Use(_) => {}
StmtKind::Const(items) => {
for item in items.iter() {
self.record_global_const_decl_name(item);
}
}
// ---- Inert --------------------------------------------------------
StmtKind::InlineHtml(_)
| StmtKind::Nop
| StmtKind::Goto(_)
| StmtKind::Label(_)
| StmtKind::HaltCompiler(_) => {}
StmtKind::Error => {}
}
// Post-narrow: after `$x = expr()`, override the inferred type if annotated.
for ann in &var_annotations {
// An annotation that exactly matches the inferred (widened) type
// of a simple assignment adds nothing — UnnecessaryVarAnnotation.
// Narrowing or widening annotations stay silent.
if self.mode == AnalysisMode::Full {
if let Some(lhs) = simple_assignment_lhs(stmt) {
let applies = ann.name.as_deref().is_none_or(|n| n == lhs);
if applies {
let ann_ty = crate::expr::helpers::resolve_named_objects_in_union(
ann.ty.clone(),
self.db,
self.file.as_ref(),
);
// Exact comparison, NO literal widening: `@var string`
// on `$s = 'hello'` deliberately widens the literal
// (it changes conditional-return resolution), so it is
// not unnecessary.
let inferred = ctx.get_var(lhs);
if !inferred.is_mixed() && inferred.to_string() == ann_ty.to_string() {
self.issues.add(Issue::new(
IssueKind::UnnecessaryVarAnnotation {
var: lhs.to_string(),
},
Location {
file: self.file.clone(),
line,
line_end,
col_start,
col_end: crate::diagnostics::clamp_col_end(
line, line_end, col_start, col_end,
),
},
));
}
}
}
}
// A non-mixed `@var` on `$x = expr` is the author's explicit type for `$x`.
if !ann.ty.is_mixed() {
if let (Some(lhs), php_ast::owned::StmtKind::Expression(e)) =
(simple_assignment_lhs(stmt), &stmt.kind)
{
if ann.name.as_deref().is_none_or(|n| n == lhs) {
let (line, _, col, _) = self.span_to_location(e.span);
self.issues.suppress_range_where(before, |i| {
matches!(&i.kind, IssueKind::MixedAssignment { var } if var == lhs)
&& i.location.line == line
&& i.location.col_start == col
});
}
}
}
apply_post_narrow(stmt, ann, ctx);
}
if let Some(plugins) = self.plugins.clone() {
if plugins.hooks().after_statement_analysis {
let file = self.file.clone();
let mut event = mir_plugin::AfterStatementAnalysisEvent {
stmt,
file: file.as_ref(),
issues: Vec::new(),
};
plugins.after_statement_analysis(&mut event);
let issues = event.issues;
self.emit_plugin_issues(issues, stmt.span);
}
}
// Runs after the plugin hook so statement-level `@mir-suppress` also
// covers plugin-raised issues.
if !suppressions.is_empty() {
self.issues.suppress_range(before, &suppressions);
}
}
/// Convert plugin-raised issues into diagnostics — statement-level twin
/// of `ExpressionAnalyzer::emit_plugin_issues`.
fn emit_plugin_issues(
&mut self,
issues: Vec<mir_plugin::PluginIssue>,
default_span: php_ast::Span,
) {
for pi in issues {
let span = pi.span.unwrap_or(default_span);
let (line, line_end, col_start, col_end) = self.span_to_location(span);
let mut issue = Issue::new(
IssueKind::PluginIssue {
name: pi.name,
message: pi.message,
},
Location {
file: self.file.clone(),
line,
line_end,
col_start,
col_end: crate::diagnostics::clamp_col_end(line, line_end, col_start, col_end),
},
);
issue.severity = pi.severity;
if let Some(text) = crate::parser::span_text(self.source, span) {
let trimmed = text.trim();
if !trimmed.is_empty() {
issue.snippet = Some(trimmed.to_string());
}
}
self.issues.add(issue);
}
}
// -----------------------------------------------------------------------
// Helper: create a short-lived ExpressionAnalyzer borrowing our fields
// -----------------------------------------------------------------------
pub(crate) fn expr_analyzer<'b>(&'b mut self, ctx: &FlowState) -> ExpressionAnalyzer<'b>
where
'a: 'b,
{
let mut ea = ExpressionAnalyzer::new(
self.db,
self.file.clone(),
self.source,
self.source_map,
self.issues,
self.symbols.as_deref_mut(),
self.navigation_facts,
self.resolved_navigation_facts,
self.php_version,
self.mode,
&mut self.yielded_types,
&mut self.reference_key_cache,
);
ea.strict_types = ctx.strict_types;
ea.collect_symbols = self.collect_symbols;
ea.capture_symbol_types = self.capture_symbol_types;
ea.codebase_symbols_only = self.codebase_symbols_only;
ea.record_reference_locations = self.record_reference_locations;
ea.collect_navigation_facts = self.collect_navigation_facts;
ea.collect_resolved_navigation_facts = self.collect_resolved_navigation_facts;
ea
}
fn record_symbol_for_var(&mut self, span: php_ast::Span, var_name: &str, ty: Type) {
use crate::symbol::ReferenceKind;
if self.collect_resolved_navigation_facts {
self.resolved_navigation_facts
.borrow_mut()
.push(ResolvedNavigationFact {
span,
expr_span: None,
kind: ReferenceKind::Variable(Arc::from(var_name)),
resolved_type: self.symbol_type(ty.clone()),
});
}
if !self.collect_symbols {
return;
}
if self.codebase_symbols_only {
return;
}
let resolved_type = self.symbol_type(ty);
if let Some(symbols) = self.symbols.as_deref_mut() {
symbols.push(ResolvedSymbol {
file: self.file.clone(),
span,
expr_span: None,
kind: ReferenceKind::Variable(Arc::from(var_name)),
resolved_type,
});
}
}
fn record_global_const_decl_name(&mut self, item: &php_ast::owned::ConstItem) {
let Some(name) = item.name.as_deref().filter(|n| !n.is_empty()) else {
return;
};
let span = crate::body_analysis::bare_name_span_in(self.source, &item.span, name);
let fqn: Arc<str> = match self.db.file_namespace(self.file.as_ref()) {
Some(ns) => format!("{ns}\\{name}").into(),
None => Arc::from(name),
};
self.record_symbol(
span,
crate::symbol::ReferenceKind::GlobalConstant(fqn),
Type::mixed(),
);
}
pub(crate) fn record_symbol(
&mut self,
span: php_ast::Span,
kind: crate::symbol::ReferenceKind,
ty: Type,
) {
let name = kind.to_name();
if self.codebase_symbols_only && name.is_none() {
return;
}
if self.collect_navigation_facts {
if let Some(name) = name.clone() {
self.navigation_facts.borrow_mut().push(NavigationFact {
span,
expr_span: None,
name,
});
}
}
if self.collect_resolved_navigation_facts {
self.resolved_navigation_facts
.borrow_mut()
.push(ResolvedNavigationFact {
span,
expr_span: None,
kind: kind.clone(),
resolved_type: self.symbol_type(ty.clone()),
});
}
if !self.collect_symbols {
return;
}
let resolved_type = self.symbol_type(ty);
if let Some(symbols) = self.symbols.as_deref_mut() {
symbols.push(ResolvedSymbol {
file: self.file.clone(),
span,
expr_span: None,
kind,
resolved_type,
});
}
}
fn symbol_type(&self, ty: Type) -> Type {
if self.capture_symbol_types {
ty
} else {
Type::mixed()
}
}
fn offset_to_line_col(&self, offset: u32) -> (u32, u16) {
crate::diagnostics::offset_to_line_col(self.source, offset, self.source_map)
}
/// Convert a span to Location (line, line_end, col_start, col_end).
fn span_to_location(&self, span: php_ast::Span) -> (u32, u32, u16, u16) {
let (line, col_start) = self.offset_to_line_col(span.start);
let (line_end, col_end) = if span.start < span.end {
self.offset_to_line_col(span.end)
} else {
(line, col_start)
};
(line, line_end, col_start, col_end)
}
/// Emit `UndefinedClass` for a `Name` AST node if the resolved class does not exist.
fn check_name_undefined_class(&mut self, name: &php_ast::owned::Name) {
let raw = crate::parser::name_to_string_owned(name);
let resolved = crate::db::resolve_name(self.db, &self.file, &raw);
if matches!(resolved.as_str(), "self" | "static" | "parent") {
return;
}
if crate::db::class_exists(self.db, &resolved) {
return;
}
let span = name.span;
let (line, col_start) = self.offset_to_line_col(span.start);
let (line_end, col_end) = self.offset_to_line_col(span.end);
self.issues.add(Issue::new(
IssueKind::UndefinedClass { name: resolved },
Location {
file: self.file.clone(),
line,
line_end,
col_start,
col_end: crate::diagnostics::clamp_col_end(line, line_end, col_start, col_end),
},
));
}
/// Record `resolved` as referenced, if it names a real class/interface/
/// trait/enum. Used for an anonymous class's `extends`/`implements`/
/// `use` targets, which — unlike a top-level class (checked via
/// `check_name_class`/`check_trait_constraints`, both of which record
/// refs) — are never collected into the codebase, so nothing else ever
/// marks these names as used. Without this, a class/trait reachable only
/// through an anonymous class's clause is falsely treated as unreferenced.
pub(crate) fn record_class_like_ref(&mut self, resolved: &str, span: php_ast::Span) {
if self.mode != AnalysisMode::Full
|| !self.record_reference_locations
|| !crate::db::class_exists(self.db, resolved)
{
return;
}
let (line, col_start) = self.offset_to_line_col(span.start);
let (line_end, col_end) = self.offset_to_line_col(span.end);
self.db.record_reference_location(crate::db::RefLoc {
symbol_key: self.reference_key_cache.class(resolved),
file: self.file.clone(),
line,
col_start,
col_end: crate::diagnostics::clamp_col_end(line, line_end, col_start, col_end),
});
}
/// Emit `UndefinedTrait` for a `use` clause's trait name if it does not
/// resolve to a real trait. Used by anonymous (and nested named) class
/// declarations, which — unlike a top-level class — are never collected
/// into the codebase, so `check_trait_constraints`'s definition-based
/// walk never sees them.
pub(crate) fn check_name_undefined_trait(&mut self, name: &php_ast::owned::Name) {
let raw = crate::parser::name_to_string_owned(name);
let resolved = crate::db::resolve_name(self.db, &self.file, &raw);
if crate::db::class_exists(self.db, &resolved) {
return;
}
let short = resolved
.rsplit('\\')
.next()
.unwrap_or(resolved.as_str())
.to_string();
let span = name.span;
let (line, col_start) = self.offset_to_line_col(span.start);
let (line_end, col_end) = self.offset_to_line_col(span.end);
self.issues.add(Issue::new(
IssueKind::UndefinedTrait { name: short },
Location {
file: self.file.clone(),
line,
line_end,
col_start,
col_end: crate::diagnostics::clamp_col_end(line, line_end, col_start, col_end),
},
));
}
// -----------------------------------------------------------------------
// @psalm-suppress / @suppress per-statement
// -----------------------------------------------------------------------
/// Extract suppression names from a parsed docblock string.
fn extract_suppressions_from(&self, doc: Option<&str>) -> Vec<String> {
let Some(doc) = doc else {
return vec![];
};
let mut suppressions = Vec::new();
for line in doc.lines() {
let line = line.trim().trim_start_matches('*').trim();
let rest = if let Some(r) = line.strip_prefix("@psalm-suppress ") {
r
} else if let Some(r) = line.strip_prefix("@suppress ") {
r
} else {
continue;
};
for name in rest.split_whitespace() {
suppressions.push(name.to_string());
}
}
suppressions
}
fn extract_mir_checks_from(&self, doc: Option<&str>) -> Vec<(String, String)> {
let Some(doc) = doc else {
return vec![];
};
crate::parser::DocblockParser::parse(doc).mir_checks
}
/// Extract a `@var` annotation from a parsed docblock string.
/// The type is resolved through the file's imports/namespace.
/// `self_fqcn` — the class/interface/trait/enum whose body is currently
/// being analysed (`FlowState::self_fqcn`), if any — supplies that
/// class-like's own `@psalm-type`/`@phpstan-type` aliases so a bare
/// `@var Result $x` expands exactly like a `@param`/`@return` reference
/// to the same alias already does (see `collector::build_method_storage`
/// / the "expand aliases first, then resolve" precedent). Expansion runs
/// before `resolve_union_for_file` so the `UndefinedDocblockClass`/
/// reference-recording checks in `analyze_stmt` see the real referenced
/// class(es), not the opaque alias name. When `self_fqcn` is `None` (a
/// free function's body, or a nested function decl that doesn't set
/// `current_function_fqn`), `current_function_fqn` supplies that
/// function's own `@psalm-type`/`@phpstan-type` aliases the same way.
fn extract_var_annotations_from(
&mut self,
doc: Option<&str>,
self_fqcn: Option<&str>,
current_method_name: Option<&str>,
current_function_fqn: Option<&str>,
) -> Vec<VarAnnotation> {
let Some(doc) = doc else {
return Vec::new();
};
let parsed = crate::parser::DocblockParser::parse(doc);
if parsed.var_tags.is_empty() {
return Vec::new();
}
// Template params visible at this point: the enclosing class's own
// (for a generic class referenced inside any of its methods) plus
// the current method's own (a per-method `@template`) — a bare name
// matching either must become a TTemplateParam, not get treated as
// an ordinary (and namespace-mis-qualified) class reference. E.g.
// `/** @var T */` inside a method of `class Box { @template T }`.
let mut template_names: rustc_hash::FxHashSet<String> = rustc_hash::FxHashSet::default();
let mut template_params: Vec<mir_codebase::definitions::TemplateParam> = Vec::new();
let defining_entity = self_fqcn.or(current_function_fqn).unwrap_or_default();
let mut tags = parsed.var_tags;
if let Some(fqcn) = self_fqcn {
if let Some(class_like) = self.cached_class_like(fqcn) {
let aliases = class_like.type_aliases();
if !aliases.is_empty() {
for (_, ty) in &mut tags {
*ty = crate::collector::expand_aliases_only(ty.clone(), aliases);
}
}
template_names.extend(
class_like
.template_params()
.iter()
.map(|tp| tp.name.to_string()),
);
template_params.extend(class_like.template_params().iter().cloned());
if let Some(method_name) = current_method_name {
let method_name = crate::util::php_ident_lowercase(method_name);
if let Some(method) = class_like.own_methods().get(method_name.as_str()) {
template_names
.extend(method.template_params.iter().map(|tp| tp.name.to_string()));
template_params.extend(method.template_params.iter().cloned());
}
}
}
} else if let Some(fqn) = current_function_fqn {
if let Some(function) = self.cached_function(fqn) {
if !function.type_aliases.is_empty() {
for (_, ty) in &mut tags {
*ty = crate::collector::expand_aliases_only(
ty.clone(),
&function.type_aliases,
);
}
}
template_names.extend(
function
.template_params
.iter()
.map(|tp| tp.name.to_string()),
);
template_params.extend(function.template_params.iter().cloned());
}
}
tags.into_iter()
.map(|(name, ty)| VarAnnotation {
name,
ty: return_type::resolve_union_for_file_with_templates(
ty,
self.db,
&self.file,
&template_names,
&template_params,
defining_entity,
),
})
.collect()
}
// -----------------------------------------------------------------------
// Fixed-point loop widening (M12)
// -----------------------------------------------------------------------
/// Analyse a loop body with a fixed-point widening algorithm (≤ 3 passes).
///
/// * `pre` — context *before* the loop (used as the merge base)
/// * `entry` — context on first iteration entry (may be narrowed / seeded)
/// * `body` — closure that analyses one loop iteration, receives `&mut Self`
/// and `&mut FlowState` for the current iteration context
/// * `loop_guaranteed` — whether the loop is guaranteed to execute at least once
/// * `is_infinite` — whether the loop condition is always-true (while(true)/for(;;)),
/// meaning normal loop exit is unreachable and only break paths matter
///
/// Returns the post-loop context that merges:
/// - the stable widened context after normal loop exit
/// - any contexts captured at `break` statements
fn analyze_loop_widened<F>(
&mut self,
pre: &FlowState,
entry: FlowState,
mut body: F,
loop_guaranteed: bool,
is_infinite: bool,
exit_condition: Option<&Expr>,
) -> FlowState
where
F: FnMut(&mut Self, &mut FlowState),
{
const MAX_ITERS: usize = 3;
// Push a fresh break-context bucket for this loop level
self.break_ctx_stack.push(Vec::new());
self.continue_ctx_stack.push(Vec::new());
self.loop_kind_stack.push(true);
let mut current = entry;
current.inside_loop = true;
let mut stabilized = false;
let mut back_edge_pass_done = false;
for iter_idx in 0..MAX_ITERS {
let prev_vars = current.vars.clone();
// `body` runs the real statement analyzer, which emits diagnostics
// directly into the shared issue buffer — not a scratch copy. Only
// the FINAL, stabilized pass reflects a realistic "any iteration"
// type state; earlier passes see overly-narrow entry
// approximations (e.g. a loop counter still at 0 or 1, a toggled
// bool still `true`) and can flag things that are only true on
// that unstabilized pass — an `if ($first)` toggle read as always
// true, or a comparison against a value the loop variable hasn't
// widened to yet read as always false. Mark the buffer here and
// roll back below if this pass turns out not to be the last one.
let issues_mark = self.issues.issue_count();
let mut iter = current.clone();
// `next` below is built from `pre.clone()` (merge_branches' else-path
// default), which resets `inside_loop` to whatever it was *before*
// this loop — so `current = next` loses it again after pass 1
// unless it's restored on every pass, not just the first.
iter.inside_loop = true;
body(self, &mut iter);
// A `continue` skips the rest of this iteration but it remains a
// valid entry to a later iteration. Include its state in the
// fixed-point input now, rather than only when constructing the
// post-loop result. Otherwise a later pass can retain only the
// false edge of `if ($condition) { continue; }` and incorrectly
// mark following body code unreachable.
let continue_ctxs = self.continue_ctx_stack.last().cloned().unwrap_or_default();
for continue_ctx in continue_ctxs {
iter = FlowState::merge_branches(¤t, iter, Some(continue_ctx));
iter.inside_loop = true;
}
// A guaranteed loop has no zero-iteration exit path. Merging its
// first body pass with `pre` would resurrect every pre-loop
// type/refinement and pending write: `do { $x = new X; }
// while (...)` would leave `$x` nullable, and a write consumed in
// the body would be reported unused after the loop. Start from the
// first completed iteration instead. Subsequent passes merge the
// already-valid post-body state with one more iteration, accounting
// for any number of executions without inventing a zeroth one.
let mut next = if loop_guaranteed {
if iter_idx == 0 {
iter.clone()
} else {
FlowState::merge_branches(¤t, iter.clone(), None)
}
} else {
FlowState::merge_branches(pre, iter.clone(), None)
};
// `merge_branches` above uses pre.clone() as the "loop never ran"
// path, which reintroduces pre-loop pending writes the body
// consumed. Drop exactly those; a pre-loop write the body only
// overwrote or never read stays pending. (`read_vars` is not
// usable here: it also holds reads from earlier outer iterations.)
for (name, pre_locs) in pre.last_write_locs.iter() {
if let Some(locs) = next.last_write_locs.get_mut(name) {
locs.retain(|l| {
!(pre_locs.contains(l) && iter.consumed_write_locs.contains(&(*name, *l)))
});
if locs.is_empty() {
next.last_write_locs.remove(name);
}
}
}
if vars_stabilized(&prev_vars, &next.vars) {
// A write left pending at the end of the body reaches the next
// iteration's reads, but only a pass entered with it pending
// can consume it. Types converge too early to provide one.
if !back_edge_pass_done && has_back_edge_read(&iter, ¤t) {
back_edge_pass_done = true;
if iter_idx + 1 < MAX_ITERS {
self.issues.truncate_to(issues_mark);
}
current = next;
continue;
}
current = next;
stabilized = true;
break;
}
// Not the fixed point yet, and (since the loop keeps going) not
// the last pass either — this pass's diagnostics were computed
// against a type state later passes will refine, so they're
// provisional. Roll them back; a real issue at the same
// condition will re-emit on a later pass if it's still real.
if iter_idx + 1 < MAX_ITERS {
self.issues.truncate_to(issues_mark);
}
current = next;
}
// Widen only if the bounded fixed-point search did not converge. Doing
// this after a converged guaranteed loop would merge stable body state
// back with `pre`, recreating the impossible zero-iteration path.
if !stabilized {
widen_unstable(
&pre.vars,
std::sync::Arc::make_mut(&mut current.vars),
loop_guaranteed,
);
}
// For infinite loops (while(true)/for(;;)) the normal-exit path is unreachable;
// only break statements can leave the loop. Marking current as diverging causes
// merge_branches below to use the break context directly, so variables assigned
// before every break are treated as definitely-assigned after the loop.
if is_infinite {
current.diverges = true;
} else if let Some(cond) = exit_condition {
// A non-break exit from a finite loop can only happen when the loop's
// own condition evaluates false — apply that negated narrowing to
// `current` (the "ran zero-or-more times, then condition failed" path)
// BEFORE merging in the break contexts below, since a `break` exits
// while the condition was still true (or mid-body) and must not be
// narrowed by it.
crate::narrowing::narrow_from_condition(cond, &mut current, false, self.db, &self.file);
}
// Pop break contexts and merge them into the post-loop result
let break_ctxs = self.break_ctx_stack.pop().unwrap_or_default();
let continue_ctxs = self.continue_ctx_stack.pop().unwrap_or_default();
self.loop_kind_stack.pop();
for bctx in break_ctxs {
current = FlowState::merge_branches(pre, current, Some(bctx));
}
// A real-loop `continue` returns to the next iteration and can reach
// the normal exit of a finite loop. It is not an exit from an infinite
// loop, whose post-loop state remains unreachable unless a `break`
// supplied one above.
if !is_infinite {
for cctx in continue_ctxs {
current = FlowState::merge_branches(pre, current, Some(cctx));
}
}
// Code after the loop is only "inside a loop" if an outer loop already
// put it there — restore `pre`'s value rather than leaving the `true`
// forced at loop entry.
current.inside_loop = pre.inside_loop;
current
}
}
/// Whether the body ends with a pending write to a variable it also reads and
/// that the loop entry did not already hold pending.
fn has_back_edge_read(end_of_body: &FlowState, entry: &FlowState) -> bool {
!end_of_body.diverges
&& end_of_body.last_write_locs.iter().any(|(name, locs)| {
end_of_body.read_vars.contains(name)
&& locs.iter().any(|loc| {
!end_of_body.consumed_write_locs.contains(&(*name, *loc))
&& !entry
.last_write_locs
.get(name)
.is_some_and(|entry_locs| entry_locs.contains(loc))
})
})
}
/// The loop-nesting level a `break`/`continue` statement targets. PHP only
/// accepts an integer-literal argument here (a non-literal is a compile
/// error), so any other shape (including `None`, i.e. bare `break;`) is
/// treated as the default level 1.
fn break_continue_level(level_expr: &Option<Box<Expr>>) -> usize {
match level_expr.as_deref().map(|e| &e.kind) {
Some(ExprKind::Int(n)) if *n >= 1 => *n as usize,
_ => 1,
}
}
/// Whether an `@mir-check $x is T` directive is satisfied by the inferred type.
///
/// The directive matches if the inferred type equals the expected type either
/// *exactly* or after [`widen_for_check`] widening. The exact arm lets fixtures
/// assert precise types the analyzer produces — integer ranges (`int<0, max>`),
/// literals — while the widened arm keeps the lenient default: writing
/// `@mir-check $x is int` still passes when `$x` infers to `int<0, max>` or a
/// literal. Widening is a one-directional relaxation, so this is strictly more
/// permissive than an exact-only check and never breaks an existing fixture.
pub(crate) fn mir_check_matches(expected: &Type, actual: &Type) -> bool {
let expected_str = expected.to_string();
expected_str == actual.to_string()
|| expected_str == widen_for_check(actual.clone()).to_string()
}
/// Widen literal types to their base scalar type. `TLiteralInt(42)` → `TInt`,
/// `TLiteralString("s")` → `TString`, etc. Used both for `@mir-check`
/// comparisons and to avoid carrying an over-narrow literal into a
/// substituted template binding.
pub(crate) fn widen_for_check(u: Type) -> Type {
let mut out = Type::empty();
for atomic in u.types {
let widened = match atomic {
Atomic::TLiteralInt(_) | Atomic::TIntRange { .. } => Atomic::TInt,
Atomic::TLiteralString(_) => Atomic::TString,
Atomic::TLiteralFloat(_, _) => Atomic::TFloat,
other => other,
};
out.add_type(widened);
}
out
}