mir-analyzer 0.61.0

Analysis engine for the mir PHP static analyzer
Documentation
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
use std::sync::Arc;

use php_ast::owned::{
    DoWhileStmt, ExprKind, ForStmt, ForeachStmt, IfStmt, SwitchStmt, TryCatchStmt, WhileStmt,
};

use mir_issues::{Issue, IssueKind, Location};
use mir_types::{Atomic, Name, Type};

use crate::db;
use crate::expr::extract_simple_var;
use crate::flow_state::FlowState;
use crate::narrowing::narrow_from_condition;
use crate::parser;
use crate::symbol::ResolvedSymbol;

use super::loops::infer_foreach_types_with_db;
use super::StatementsAnalyzer;

impl<'a> StatementsAnalyzer<'a> {
    pub(super) fn analyze_if_stmt(&mut self, if_stmt: &IfStmt, ctx: &mut FlowState) {
        let pre_ctx = ctx.clone();

        let cond_type = self.expr_analyzer(ctx).analyze(&if_stmt.condition, ctx);
        self.check_docblock_contradiction(&if_stmt.condition, ctx);
        let pre_diverges = ctx.diverges;

        let mut then_ctx = ctx.branch();
        narrow_from_condition(&if_stmt.condition, &mut then_ctx, true, self.db, &self.file);
        let then_unreachable_from_narrowing = then_ctx.diverges;
        if !then_ctx.diverges {
            self.analyze_stmt(&if_stmt.then_branch, &mut then_ctx);
        }

        let mut elseif_ctxs: Vec<FlowState> = vec![];
        for elseif in if_stmt.elseif_branches.iter() {
            let mut pre_elseif = ctx.branch();
            narrow_from_condition(
                &if_stmt.condition,
                &mut pre_elseif,
                false,
                self.db,
                &self.file,
            );
            let pre_elseif_diverges = pre_elseif.diverges;

            let mut elseif_true_ctx = pre_elseif.clone();
            narrow_from_condition(
                &elseif.condition,
                &mut elseif_true_ctx,
                true,
                self.db,
                &self.file,
            );
            let mut elseif_false_ctx = pre_elseif.clone();
            narrow_from_condition(
                &elseif.condition,
                &mut elseif_false_ctx,
                false,
                self.db,
                &self.file,
            );
            if !pre_elseif_diverges && (elseif_true_ctx.diverges || elseif_false_ctx.diverges) {
                let (line, line_end, col_start, col_end) =
                    self.span_to_location(elseif.condition.span);
                let elseif_cond_type = self
                    .expr_analyzer(ctx)
                    .analyze(&elseif.condition, &mut ctx.branch());
                self.issues.add(
                    mir_issues::Issue::new(
                        IssueKind::RedundantCondition {
                            ty: format!("{elseif_cond_type}"),
                        },
                        mir_issues::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(
                        parser::span_text(self.source, elseif.condition.span).unwrap_or_default(),
                    ),
                );
            }

            let mut branch_ctx = elseif_true_ctx;
            self.expr_analyzer(&branch_ctx)
                .analyze(&elseif.condition, &mut branch_ctx);
            if !branch_ctx.diverges {
                self.analyze_stmt(&elseif.body, &mut branch_ctx);
            }
            elseif_ctxs.push(branch_ctx);
        }

        let mut else_ctx = ctx.branch();
        // For `if ($x = expr())`, in the false branch the assignment was evaluated
        // and found falsy — the write is consumed by the truthiness check. Remove
        // the pending-write entry so that using $x only in the true branch does not
        // trigger UnusedVariable.
        {
            let cond = match &if_stmt.condition.kind {
                ExprKind::Parenthesized(inner) => inner.as_ref(),
                _ => &if_stmt.condition,
            };
            if let ExprKind::Assign(a) = &cond.kind {
                if let Some(var_name) = extract_simple_var(&a.target) {
                    else_ctx
                        .last_write_locs
                        .remove(&Name::from(var_name.as_str()));
                }
            }
        }
        narrow_from_condition(
            &if_stmt.condition,
            &mut else_ctx,
            false,
            self.db,
            &self.file,
        );
        // Redundancy of the outer if condition depends only on its own narrowing, not elseifs.
        let else_unreachable_from_narrowing = else_ctx.diverges;
        // In the else branch all elseif conditions also failed — narrow them out for better
        // type accuracy in the else body (e.g. string|array|int becomes int after is_string
        // and is_array elseifs). Only applied when the else is itself reachable.
        if !else_ctx.diverges {
            for elseif in if_stmt.elseif_branches.iter() {
                if !else_ctx.diverges {
                    narrow_from_condition(
                        &elseif.condition,
                        &mut else_ctx,
                        false,
                        self.db,
                        &self.file,
                    );
                }
            }
        }
        if !else_ctx.diverges {
            if let Some(else_branch) = &if_stmt.else_branch {
                self.analyze_stmt(else_branch, &mut else_ctx);
            }
        }

        if !pre_diverges && (then_unreachable_from_narrowing || else_unreachable_from_narrowing) {
            let (line, line_end, col_start, col_end) =
                self.span_to_location(if_stmt.condition.span);
            self.issues.add(
                Issue::new(
                    IssueKind::RedundantCondition {
                        ty: format!("{cond_type}"),
                    },
                    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(
                    parser::span_text(self.source, if_stmt.condition.span).unwrap_or_default(),
                ),
            );
        }

        *ctx = FlowState::merge_branches(&pre_ctx, then_ctx, Some(else_ctx));
        for ec in elseif_ctxs {
            *ctx = FlowState::merge_branches(&pre_ctx, ec, Some(ctx.clone()));
        }
    }

    /// Emit `RedundantCondition` for a condition whose type-narrowing proves
    /// it can only ever resolve one way.
    fn emit_redundant_condition(&mut self, cond_ty: &Type, span: php_ast::Span) {
        let (line, line_end, col_start, col_end) = self.span_to_location(span);
        self.issues.add(
            Issue::new(
                IssueKind::RedundantCondition {
                    ty: format!("{cond_ty}"),
                },
                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(parser::span_text(self.source, span).unwrap_or_default()),
        );
    }

    pub(super) fn analyze_while_stmt(&mut self, w: &WhileStmt, ctx: &mut FlowState) {
        let cond_type = self.expr_analyzer(ctx).analyze(&w.condition, ctx);
        self.check_docblock_contradiction(&w.condition, ctx);
        let pre_diverges = ctx.diverges;
        let pre = ctx.clone();

        let mut entry = ctx.branch();
        narrow_from_condition(&w.condition, &mut entry, true, self.db, &self.file);
        // A condition narrowed to always-false makes the loop body dead code on
        // every entry — the same redundancy `if` reports when its then-branch
        // is unreachable. `while (true)` (the idiomatic infinite loop) is
        // exempted since it narrows the other way and is always intentional.
        if !pre_diverges && entry.diverges {
            self.emit_redundant_condition(&cond_type, w.condition.span);
        }

        // `while (1)` (and any other nonzero int literal) is just as much an
        // idiomatic infinite loop as `while (true)` — PHP truthiness treats
        // every nonzero int as true, only `0` is falsy.
        let is_infinite = matches!(w.condition.kind, ExprKind::Bool(true))
            || matches!(w.condition.kind, ExprKind::Int(n) if n != 0);
        let condition = w.condition.clone();
        let post = self.analyze_loop_widened(
            &pre,
            entry,
            |sa, iter| {
                // Re-apply condition narrowing at the start of each iteration so
                // variables introduced by assignments in the condition (e.g.
                // `while ($line = fgets($r))`) remain definitely-assigned in the body
                // even after loop-widening merges demote them to possibly-assigned.
                narrow_from_condition(&condition, iter, true, sa.db, &sa.file);
                sa.analyze_stmt(&w.body, iter);
                sa.expr_analyzer(iter).analyze(&w.condition, iter);
            },
            is_infinite,
            is_infinite,
            Some(&w.condition),
        );
        *ctx = post;
    }

    pub(super) fn analyze_dowhile_stmt(&mut self, dw: &DoWhileStmt, ctx: &mut FlowState) {
        let pre = ctx.clone();
        let entry = ctx.branch();
        // Do-while always executes at least once (body before condition check)
        let mut post = self.analyze_loop_widened(
            &pre,
            entry,
            |sa, iter| {
                sa.analyze_stmt(&dw.body, iter);
                sa.expr_analyzer(iter).analyze(&dw.condition, iter);
                sa.check_docblock_contradiction(&dw.condition, iter);
            },
            true,
            false,
            Some(&dw.condition),
        );
        // Since the body always executes at least once, variables introduced
        // inside the body are definitely defined after the loop. Strip any
        // possibly_undefined flag and promote possibly_assigned → assigned.
        {
            let new_names: Vec<mir_types::Name> = post
                .vars
                .keys()
                .filter(|n| !pre.vars.contains_key(*n))
                .copied()
                .collect();
            let post_vars = std::sync::Arc::make_mut(&mut post.vars);
            for name in &new_names {
                if let Some(ty) = post_vars.get_mut(name) {
                    if ty.possibly_undefined {
                        let mut stripped = (**ty).clone();
                        stripped.possibly_undefined = false;
                        *ty = mir_codebase::definitions::wrap_var_type(stripped);
                    }
                }
            }
            let assigned = std::sync::Arc::make_mut(&mut post.assigned_vars);
            let possibly = std::sync::Arc::make_mut(&mut post.possibly_assigned_vars);
            for name in &new_names {
                if possibly.contains(name) {
                    possibly.remove(name);
                    assigned.insert(*name);
                }
            }
        }
        *ctx = post;
    }

    pub(super) fn analyze_for_stmt(&mut self, f: &ForStmt, ctx: &mut FlowState) {
        for init in f.init.iter() {
            self.expr_analyzer(ctx).analyze(init, ctx);
        }
        let pre_diverges = ctx.diverges;
        let pre = ctx.clone();
        let mut entry = ctx.branch();
        let mut last_cond_type = None;
        for cond in f.condition.iter() {
            last_cond_type = Some(self.expr_analyzer(&entry).analyze(cond, &mut entry));
            self.check_docblock_contradiction(cond, &mut entry);
        }
        // Only the last comma-separated condition's truthiness controls the
        // loop (PHP evaluates the others and discards their value), so only
        // it is narrowed/checked for redundancy — same as `while`'s single
        // condition.
        if let Some(last_cond) = f.condition.last() {
            narrow_from_condition(last_cond, &mut entry, true, self.db, &self.file);
            if !pre_diverges && entry.diverges {
                if let Some(cond_type) = &last_cond_type {
                    self.emit_redundant_condition(cond_type, last_cond.span);
                }
            }
        }

        let is_infinite = f.condition.is_empty();
        let post = self.analyze_loop_widened(
            &pre,
            entry,
            |sa, iter| {
                sa.analyze_stmt(&f.body, iter);
                for update in f.update.iter() {
                    sa.expr_analyzer(iter).analyze(update, iter);
                }
                for cond in f.condition.iter() {
                    sa.expr_analyzer(iter).analyze(cond, iter);
                }
            },
            is_infinite,
            is_infinite,
            f.condition.last(),
        );
        *ctx = post;
    }

    pub(super) fn analyze_foreach_stmt(
        &mut self,
        fe: &ForeachStmt,
        stmt: &php_ast::owned::Stmt,
        ctx: &mut FlowState,
    ) {
        let arr_ty = self.expr_analyzer(ctx).analyze(&fe.expr, ctx);
        let (key_ty, mut value_ty) = infer_foreach_types_with_db(self.db, &arr_ty);

        if let Some(vname) = extract_simple_var(&fe.value) {
            let doc = crate::parser::find_preceding_docblock(self.source, stmt.span.start);
            if let Some(ann) = self.extract_var_annotation_from(
                doc.as_deref(),
                ctx.self_fqcn.as_deref(),
                ctx.current_function_fqn.as_deref(),
            ) {
                if ann.name.as_deref() == Some(vname.as_str()) {
                    value_ty = ann.ty;
                }
            }
        }

        let pre = ctx.clone();
        let mut entry = ctx.branch();

        if let Some(key_expr) = &fe.key {
            if let Some(var_name) = extract_simple_var(key_expr) {
                entry.set_var(&var_name, key_ty.clone());
                // Emit ResolvedSymbol for key variable at binding position
                self.record_symbol_for_var(key_expr.span, &var_name, key_ty.clone());
            }
        }
        let value_var = extract_simple_var(&fe.value);
        // The PHP parser silently discards the `&` in `foreach ($arr as &$val)`.
        // Detect it by checking whether the source character immediately preceding
        // the value span (skipping whitespace) is `&`. Reference iteration writes
        // back through the reference, so dead-write checks don't apply.
        let value_is_by_ref = value_var.is_some() && {
            let start = fe.value.span.start as usize;
            let pre = &self.source[..start.min(self.source.len())];
            pre.chars().rev().find(|c| !c.is_whitespace()) == Some('&')
        };
        if let Some(ref vname) = value_var {
            entry.set_var(vname.as_str(), value_ty.clone());
            if value_is_by_ref {
                // By-reference iteration: writes to this variable always mutate
                // the source array through the reference, so they are never dead.
                entry
                    .foreach_byref_var_names
                    .insert(Name::from(vname.as_str()));
            } else {
                entry
                    .foreach_value_var_names
                    .insert(Name::from(vname.as_str()));
            }
            // Record the header assignment so it appears in last_write_locs and
            // triggers UnusedForeachValue when the value is never read in the body.
            let (line, line_end, col_start, col_end) = self.span_to_location(fe.value.span);
            entry.record_write(vname.as_str(), line, col_start, line_end, col_end);
            // Emit ResolvedSymbol for value variable at binding position
            self.record_symbol_for_var(fe.value.span, vname, value_ty.clone());
            if value_ty.is_mixed_not_template() {
                self.issues.add(
                    Issue::new(
                        IssueKind::MixedAssignment { var: vname.clone() },
                        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(
                        parser::span_text(self.source, fe.value.span).unwrap_or_default(),
                    ),
                );
            }
        } else {
            self.expr_analyzer(&entry).assign_to_target(
                &fe.value,
                value_ty.clone(),
                &mut entry,
                fe.value.span,
            );
        }

        let loop_guaranteed = super::loops::loop_guaranteed_to_execute(&arr_ty);
        let post = self.analyze_loop_widened(
            &pre,
            entry,
            |sa, iter| {
                if let Some(key_expr) = &fe.key {
                    if let Some(var_name) = extract_simple_var(key_expr) {
                        iter.set_var(&var_name, key_ty.clone());
                    }
                }
                if let Some(ref vname) = value_var {
                    iter.set_var(vname.as_str(), value_ty.clone());
                } else {
                    sa.expr_analyzer(iter).assign_to_target(
                        &fe.value,
                        value_ty.clone(),
                        iter,
                        fe.value.span,
                    );
                }
                sa.analyze_stmt(&fe.body, iter);
            },
            loop_guaranteed,
            false,
            None,
        );
        *ctx = post;
    }

    /// Emit `ParadoxicalCondition` for `switch` cases whose literal value
    /// repeats an earlier case — the duplicate branch can never be reached
    /// because the first matching case wins. Only literal cases are compared,
    /// so dynamic `case $x:` arms are never flagged.
    fn check_duplicate_case_values(&mut self, sw: &SwitchStmt) {
        let values = sw.body.cases.iter().filter_map(|c| c.value.as_ref());
        for (span, value) in crate::expr::duplicate_literal_conditions(values) {
            let (line, line_end, col_start, col_end) = self.span_to_location(span);
            self.issues.add(
                Issue::new(
                    IssueKind::ParadoxicalCondition { value },
                    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(parser::span_text(self.source, span).unwrap_or_default()),
            );
        }
    }

    pub(super) fn analyze_switch_stmt(&mut self, sw: &SwitchStmt, ctx: &mut FlowState) {
        self.check_duplicate_case_values(sw);
        let subject_ty = self.expr_analyzer(ctx).analyze(&sw.expr, ctx);
        let subject_target =
            crate::narrowing::MatchSubject::extract(&sw.expr, ctx, self.db, &self.file);
        let switch_on_true = matches!(&sw.expr.kind, ExprKind::Bool(true));

        // `switch (gettype($x))`: a `case` whose string `gettype()` can never
        // return is dead code (e.g. `case "int"` — gettype returns "integer").
        if let Some(arg) = crate::contradiction::gettype_call_arg(&sw.expr) {
            let arg_ty = self.expr_analyzer(ctx).analyze(arg, ctx);
            let possible = crate::contradiction::gettype_possible_values(&arg_ty);
            for case in sw.body.cases.iter() {
                let Some(val) = &case.value else { continue };
                let ExprKind::String(s) = &val.kind else {
                    continue;
                };
                let s = s.as_ref();
                let reason = if !crate::contradiction::gettype_is_valid(s) {
                    let hint = crate::contradiction::gettype_suggestion(s)
                        .map(|h| format!(" (did you mean \"{h}\"?)"))
                        .unwrap_or_default();
                    Some(format!("gettype() never returns \"{s}\"{hint}"))
                } else if possible
                    .as_ref()
                    .is_some_and(|poss| poss.iter().all(|p| *p != s))
                {
                    Some(format!("gettype() of {arg_ty} never returns \"{s}\""))
                } else {
                    None
                };
                if let Some(reason) = reason {
                    let (line, line_end, col_start, col_end) = self.span_to_location(val.span);
                    self.issues.add(
                        Issue::new(
                            IssueKind::UnevaluatedCode { reason },
                            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(parser::span_text(self.source, val.span).unwrap_or_default()),
                    );
                }
            }
        }

        let pre_ctx = ctx.clone();
        self.break_ctx_stack.push(Vec::new());
        self.loop_kind_stack.push(false);

        let has_default = sw.body.cases.iter().any(|c| c.value.is_none());

        let mut case_results: Vec<FlowState> = Vec::new();
        // Case labels immediately preceding this one whose bodies were empty
        // — a `case` with a non-empty body executes whenever ANY of those
        // fell-through conditions matched too, OR semantics, not just this
        // case's own. Accumulated here and reset once a body actually runs.
        let mut pending_conditions: Vec<&php_ast::owned::Expr> = Vec::new();
        for case in sw.body.cases.iter() {
            let mut case_ctx = pre_ctx.branch();
            if let Some(val) = &case.value {
                pending_conditions.push(val);
                if switch_on_true {
                    narrow_from_condition(val, &mut case_ctx, true, self.db, &self.file);
                } else if let Some(target) = &subject_target {
                    let narrow_ty = match &val.kind {
                        ExprKind::Int(n) => Some(Type::single(Atomic::TLiteralInt(*n))),
                        ExprKind::String(s) => {
                            Some(Type::single(Atomic::TLiteralString(Arc::from(&**s))))
                        }
                        ExprKind::Bool(b) => Some(Type::single(if *b {
                            Atomic::TTrue
                        } else {
                            Atomic::TFalse
                        })),
                        ExprKind::Null => Some(Type::single(Atomic::TNull)),
                        _ => None,
                    };
                    if let Some(ref narrowed) = narrow_ty {
                        if !subject_ty.is_mixed() && narrowed.intersect_with(&subject_ty).is_never()
                        {
                            let (line, line_end, col_start, col_end) =
                                self.span_to_location(val.span);
                            self.issues.add(
                                Issue::new(
                                    IssueKind::TypeDoesNotContainType {
                                        left: format!("{subject_ty}"),
                                        right: format!("{narrowed}"),
                                    },
                                    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(
                                    parser::span_text(self.source, val.span).unwrap_or_default(),
                                ),
                            );
                        }
                        match target {
                            crate::narrowing::MatchSubject::Var(name) => {
                                case_ctx.set_var(name, narrowed.clone())
                            }
                            crate::narrowing::MatchSubject::Prop(obj, prop) => {
                                let current = crate::narrowing::resolve_prop_current_type(
                                    &case_ctx, obj, prop, self.db, &self.file,
                                );
                                crate::narrowing::apply_prop_narrowed(
                                    &mut case_ctx,
                                    obj,
                                    prop,
                                    current,
                                    narrowed.clone(),
                                    false,
                                );
                            }
                            crate::narrowing::MatchSubject::Static(fqcn, prop) => {
                                let current = crate::narrowing::resolve_static_prop_current_type(
                                    &case_ctx, fqcn, prop, self.db,
                                );
                                crate::narrowing::apply_prop_narrowed(
                                    &mut case_ctx,
                                    fqcn,
                                    prop,
                                    current,
                                    narrowed.clone(),
                                    false,
                                );
                            }
                        }
                    }
                }
                self.expr_analyzer(&case_ctx).analyze(val, &mut case_ctx);
            }

            let body_is_empty = case.body.is_empty();

            // A body reached via multiple fallen-through labels executes
            // under the UNION of their conditions, not just this case's own
            // — re-narrow from each condition's original (pre-case) type,
            // since `case_ctx` above was already narrowed by this case's
            // single condition alone.
            if !body_is_empty && pending_conditions.len() > 1 {
                if switch_on_true {
                    let mut union_ctx = pre_ctx.branch();
                    if let Some(vn) = crate::narrowing::narrow_instanceof_disjuncts(
                        &pending_conditions,
                        &mut union_ctx,
                        self.db,
                        &self.file,
                    ) {
                        case_ctx.set_var(&vn, union_ctx.get_var(&vn));
                    } else {
                        let mut union_ctx = pre_ctx.branch();
                        if let Some(vn) = crate::narrowing::narrow_type_fn_disjuncts(
                            &pending_conditions,
                            &mut union_ctx,
                            self.db,
                        ) {
                            case_ctx.set_var(&vn, union_ctx.get_var(&vn));
                        } else {
                            let mut union_ctx = pre_ctx.branch();
                            if let Some(vn) = crate::narrowing::narrow_mixed_disjuncts(
                                &pending_conditions,
                                &mut union_ctx,
                                self.db,
                                &self.file,
                            ) {
                                case_ctx.set_var(&vn, union_ctx.get_var(&vn));
                            } else {
                                let mut union_ctx = pre_ctx.branch();
                                let prop_result =
                                    crate::narrowing::narrow_prop_instanceof_disjuncts(
                                        &pending_conditions,
                                        &mut union_ctx,
                                        self.db,
                                        &self.file,
                                    )
                                    .or_else(|| {
                                        union_ctx = pre_ctx.branch();
                                        crate::narrowing::narrow_prop_type_fn_disjuncts(
                                            &pending_conditions,
                                            &mut union_ctx,
                                            self.db,
                                            &self.file,
                                        )
                                    })
                                    .or_else(|| {
                                        union_ctx = pre_ctx.branch();
                                        crate::narrowing::narrow_mixed_prop_disjuncts(
                                            &pending_conditions,
                                            &mut union_ctx,
                                            self.db,
                                            &self.file,
                                        )
                                    });
                                if let Some((obj, prop)) = prop_result {
                                    if let Some(refined) =
                                        union_ctx.get_prop_refined(&obj, &prop).cloned()
                                    {
                                        case_ctx.set_prop_refined(&obj, &prop, refined);
                                    }
                                    // The disjunct mergers also prove the receiver
                                    // non-null (see each merger's own doc comment for
                                    // the per-leaf-kind exclusions) — copy that fact
                                    // back too, not just the refined property, so it
                                    // survives into the fallthrough body.
                                    case_ctx.set_var(&obj, union_ctx.get_var(&obj));
                                } else {
                                    let mut union_ctx = pre_ctx.branch();
                                    let static_prop_result =
                                        crate::narrowing::narrow_static_prop_instanceof_disjuncts(
                                            &pending_conditions,
                                            &mut union_ctx,
                                            self.db,
                                            &self.file,
                                        )
                                        .or_else(|| {
                                            union_ctx = pre_ctx.branch();
                                            crate::narrowing::narrow_static_prop_type_fn_disjuncts(
                                                &pending_conditions,
                                                &mut union_ctx,
                                                self.db,
                                                &self.file,
                                            )
                                        })
                                        .or_else(|| {
                                            union_ctx = pre_ctx.branch();
                                            crate::narrowing::narrow_mixed_static_prop_disjuncts(
                                                &pending_conditions,
                                                &mut union_ctx,
                                                self.db,
                                                &self.file,
                                            )
                                        });
                                    // No receiver-var copy needed here: a static
                                    // property's "receiver" is the FQCN itself,
                                    // which is never null (unlike an instance
                                    // property's object receiver above).
                                    if let Some((fqcn, prop)) = static_prop_result {
                                        if let Some(refined) =
                                            union_ctx.get_prop_refined(&fqcn, &prop).cloned()
                                        {
                                            case_ctx.set_prop_refined(&fqcn, &prop, refined);
                                        }
                                    }
                                }
                            }
                        }
                    }
                } else if let Some(target) = &subject_target {
                    let mut union_ty = Type::empty();
                    let all_literal = pending_conditions.iter().all(|cond| {
                        let atom = match &cond.kind {
                            ExprKind::Int(n) => Some(Atomic::TLiteralInt(*n)),
                            ExprKind::String(s) => Some(Atomic::TLiteralString(Arc::from(&**s))),
                            ExprKind::Bool(b) => {
                                Some(if *b { Atomic::TTrue } else { Atomic::TFalse })
                            }
                            ExprKind::Null => Some(Atomic::TNull),
                            _ => None,
                        };
                        match atom {
                            Some(a) => {
                                union_ty.add_type(a);
                                true
                            }
                            None => false,
                        }
                    });
                    if all_literal && !union_ty.is_empty() {
                        match target {
                            crate::narrowing::MatchSubject::Var(name) => {
                                case_ctx.set_var(name, union_ty)
                            }
                            crate::narrowing::MatchSubject::Prop(obj, prop) => {
                                let current = crate::narrowing::resolve_prop_current_type(
                                    &case_ctx, obj, prop, self.db, &self.file,
                                );
                                crate::narrowing::apply_prop_narrowed(
                                    &mut case_ctx,
                                    obj,
                                    prop,
                                    current,
                                    union_ty,
                                    false,
                                );
                            }
                            crate::narrowing::MatchSubject::Static(fqcn, prop) => {
                                let current = crate::narrowing::resolve_static_prop_current_type(
                                    &case_ctx, fqcn, prop, self.db,
                                );
                                crate::narrowing::apply_prop_narrowed(
                                    &mut case_ctx,
                                    fqcn,
                                    prop,
                                    current,
                                    union_ty,
                                    false,
                                );
                            }
                        }
                    }
                }
            }

            self.analyze_stmts(&case.body, &mut case_ctx);
            case_results.push(case_ctx);
            if !body_is_empty {
                pending_conditions.clear();
            }
        }

        let n = case_results.len();
        let mut effective_diverges = vec![false; n];
        for i in (0..n).rev() {
            if case_results[i].diverges {
                effective_diverges[i] = true;
            } else if i + 1 < n {
                effective_diverges[i] = effective_diverges[i + 1];
            }
        }

        let mut fallthrough_ctxs: Vec<FlowState> = Vec::new();
        // Collect reads from diverging case bodies so pre-switch writes they
        // consume are not falsely reported as dead (e.g. `$description` passed
        // to `new InputArgument(...)` in an all-return switch(true)).
        let mut diverging_reads: rustc_hash::FxHashSet<mir_types::Name> =
            rustc_hash::FxHashSet::default();
        let mut diverging_consumed: rustc_hash::FxHashSet<(mir_types::Name, (u32, u16, u32, u16))> =
            rustc_hash::FxHashSet::default();
        for (i, case_ctx) in case_results.into_iter().enumerate() {
            if effective_diverges[i] {
                diverging_reads.extend(case_ctx.read_vars.iter().copied());
                diverging_consumed.extend(case_ctx.consumed_write_locs.iter().copied());
            } else {
                fallthrough_ctxs.push(case_ctx);
            }
        }

        let break_ctxs = self.break_ctx_stack.pop().unwrap_or_default();
        self.loop_kind_stack.pop();

        // With a default arm, some arm ALWAYS runs — the "fell past every case"
        // path doesn't exist, so don't seed the merge with pre_ctx (it would
        // keep pre-switch pending writes alive that every arm overwrote).
        let mut merged: Option<FlowState> = if has_default {
            None
        } else {
            Some(pre_ctx.clone())
        };

        for bctx in break_ctxs.into_iter().chain(fallthrough_ctxs) {
            merged = Some(match merged {
                Some(m) => FlowState::merge_branches(&pre_ctx, bctx, Some(m)),
                None => bctx,
            });
        }

        *ctx = merged.unwrap_or_else(|| {
            // has_default and every arm diverges: code after the switch is
            // unreachable.
            let mut m = pre_ctx.clone();
            m.diverges = true;
            m
        });
        // Apply reads gathered from diverging case arms.
        ctx.read_vars.extend(diverging_reads);
        ctx.consumed_write_locs
            .extend(diverging_consumed.iter().copied());
        {
            let consumed = &ctx.consumed_write_locs;
            ctx.last_write_locs.retain(|name, locs| {
                locs.retain(|loc| !consumed.contains(&(*name, *loc)));
                !locs.is_empty()
            });
        }
    }

    pub(super) fn analyze_trycatch_stmt(&mut self, tc: &TryCatchStmt, ctx: &mut FlowState) {
        let pre_ctx = ctx.clone();
        let mut try_ctx = ctx.branch();
        self.analyze_stmts(&tc.body.stmts, &mut try_ctx);

        let catch_base = FlowState::merge_branches(&pre_ctx, try_ctx.clone(), None);

        let mut non_diverging_catches: Vec<FlowState> = vec![];
        // Resolved types caught by any EARLIER catch clause on this try — used to
        // detect a later clause that can never run because an earlier one already
        // catches the same (or a broader) type. Accumulated after each clause
        // finishes, not during, so a union catch type (`catch (A|B $e)`) doesn't
        // shadow itself.
        let mut seen_catch_types: Vec<Arc<str>> = Vec::new();
        for catch in tc.catches.iter() {
            let mut catch_ctx = catch_base.clone();
            // For dead-write tracking, the catch block starts from the pre-try state:
            // an exception can be thrown at any point in the try body, so we don't know
            // which writes from the try body were committed before the throw.
            // Inheriting try-body last_write_locs would cause false "dead write" reports
            // when a catch block re-assigns variables also written in the try body.
            catch_ctx.last_write_locs = pre_ctx.last_write_locs.clone();
            let mut this_clause_types: Vec<Arc<str>> = Vec::new();
            for catch_ty in catch.types.iter() {
                self.check_name_undefined_class(catch_ty);
                if self.mode == crate::body_analysis::AnalysisMode::Full {
                    let raw = parser::name_to_string_owned(catch_ty);
                    let resolved = db::resolve_name(self.db, &self.file, &raw);
                    if !matches!(resolved.as_str(), "self" | "static" | "parent") {
                        let span = catch_ty.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.db.record_reference_location(crate::db::RefLoc {
                            symbol_key: Arc::from(format!("cls:{resolved}")),
                            file: self.file.clone(),
                            line,
                            col_start,
                            col_end: crate::diagnostics::clamp_col_end(
                                line, line_end, col_start, col_end,
                            ),
                        });
                        if self.collect_symbols {
                            let fqcn: Arc<str> = Arc::from(resolved.as_str());
                            self.symbols.push(ResolvedSymbol {
                                file: self.file.clone(),
                                span,
                                expr_span: None,
                                kind: crate::symbol::ReferenceKind::ClassReference(fqcn),
                                resolved_type: Type::single(Atomic::TClassString(None)),
                            });
                        }
                        // Check if the caught type extends Throwable
                        if crate::db::class_exists(self.db, &resolved) {
                            let here = crate::db::Fqcn::from_str(self.db, resolved.as_str());
                            if let Some(class) = crate::db::find_class_like(self.db, here) {
                                if let Some((used, canonical_str)) =
                                    crate::fqcn_case_mismatch(raw.as_str(), class.fqcn().as_ref())
                                {
                                    let (line_end, col_end2) = self.offset_to_line_col(span.end);
                                    self.issues.add(Issue::new(
                                        IssueKind::WrongCaseClass {
                                            used,
                                            canonical: canonical_str,
                                        },
                                        Location {
                                            file: self.file.clone(),
                                            line,
                                            line_end,
                                            col_start,
                                            col_end: crate::diagnostics::clamp_col_end(
                                                line, line_end, col_start, col_end2,
                                            ),
                                        },
                                    ));
                                }
                            }
                            let is_throwable = resolved == "Throwable"
                                || crate::db::extends_or_implements(
                                    self.db,
                                    &resolved,
                                    "Throwable",
                                );
                            if !is_throwable && !crate::db::has_unknown_ancestor(self.db, &resolved)
                            {
                                let (line_end, col_end2) = self.offset_to_line_col(span.end);
                                self.issues.add(Issue::new(
                                    IssueKind::InvalidCatch {
                                        ty: resolved.clone(),
                                    },
                                    Location {
                                        file: self.file.clone(),
                                        line,
                                        line_end,
                                        col_start,
                                        col_end: crate::diagnostics::clamp_col_end(
                                            line, line_end, col_start, col_end2,
                                        ),
                                    },
                                ));
                            }
                            // A type identical to (or a subtype of) one already
                            // caught by an earlier clause on this try can never
                            // reach this clause — the earlier one always wins.
                            if let Some(shadow) = seen_catch_types.iter().find(|prev| {
                                resolved.eq_ignore_ascii_case(prev)
                                    || crate::db::extends_or_implements(self.db, &resolved, prev)
                            }) {
                                let (line_end, col_end2) = self.offset_to_line_col(span.end);
                                self.issues.add(Issue::new(
                                    IssueKind::UnreachableCatch {
                                        ty: resolved.clone(),
                                        shadowed_by: shadow.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_end2,
                                        ),
                                    },
                                ));
                            }
                            this_clause_types.push(Arc::from(resolved.as_str()));
                        }
                    }
                }
            }
            seen_catch_types.extend(this_clause_types);
            if let Some(var) = &catch.var {
                let exc_ty = if catch.types.is_empty() {
                    Type::single(Atomic::TObject)
                } else {
                    let mut u = Type::empty();
                    for catch_ty in catch.types.iter() {
                        let raw = parser::name_to_string_owned(catch_ty);
                        let resolved = db::resolve_name(self.db, &self.file, &raw);
                        u.add_type(Atomic::TNamedObject {
                            fqcn: resolved.into(),
                            type_params: mir_types::union::empty_type_params(),
                        });
                    }
                    u
                };
                let var_name = var.trim_start_matches('$');
                catch_ctx.set_var(var_name, exc_ty);
                let (line, col_start) = self.offset_to_line_col(catch.span.start);
                let (line_end, col_end) = self.offset_to_line_col(catch.span.end);
                catch_ctx.record_var_location(var_name, line, col_start, line_end, col_end);
            }
            self.analyze_stmts(&catch.body.stmts, &mut catch_ctx);
            if !catch_ctx.diverges {
                non_diverging_catches.push(catch_ctx);
            }
        }

        let mut result = if non_diverging_catches.is_empty() {
            try_ctx
        } else {
            let mut r = try_ctx;
            for catch_ctx in non_diverging_catches {
                r = FlowState::merge_branches(&pre_ctx, r, Some(catch_ctx));
            }
            r
        };

        if let Some(finally_stmts) = &tc.finally {
            // `finally` runs no matter how control reaches it: the try body may
            // have completed successfully (`result`), or an exception may have
            // been thrown at ANY point in the try body and not yet reached a
            // catch (`catch_base`, the same conservative state catch blocks
            // themselves start from). Seed finally's view from the merge of
            // both, not just the optimistic success path, so a variable
            // reassigned only partway through the try body is correctly seen
            // as still possibly holding its earlier value inside finally.
            let finally_start =
                FlowState::merge_branches(&pre_ctx, result.clone(), Some(catch_base.clone()));
            let mut finally_ctx = finally_start;
            finally_ctx.inside_finally = true;
            // finally always executes regardless of whether try/catch diverged
            finally_ctx.diverges = false;
            self.analyze_stmts(&finally_stmts.stmts, &mut finally_ctx);
            if finally_ctx.diverges {
                result.diverges = true;
            }
            // finally executes last, so its own variable assignments are
            // authoritative for code after the try statement — propagate them
            // back onto `result`, which otherwise only reflects the pre-finally
            // state.
            result.vars = finally_ctx.vars.clone();
            result.assigned_vars = finally_ctx.assigned_vars.clone();
            result.possibly_assigned_vars = finally_ctx.possibly_assigned_vars.clone();
            result.var_locations = finally_ctx.var_locations.clone();
            result.has_dynamic_var_def =
                result.has_dynamic_var_def || finally_ctx.has_dynamic_var_def;
            result.has_dynamic_var_read =
                result.has_dynamic_var_read || finally_ctx.has_dynamic_var_read;
            // Variables read in the finally block count as used — propagate reads back
            // so that the save-restore pattern (assign before try, restore in finally)
            // is not falsely flagged as UnusedVariable.
            for name in finally_ctx.read_vars.iter() {
                result.read_vars.insert(*name);
                // If the try body overwrote this variable (making its pre-try write appear
                // dead), that pre-try write is NOT dead on the exception path (where the
                // overwrite never happened). Mark any pre-try writes as consumed so they
                // are not falsely reported.
                if let Some(locs) = pre_ctx.last_write_locs.get(name) {
                    for loc in locs {
                        result.consumed_write_locs.insert((*name, *loc));
                    }
                }
            }
            result
                .consumed_write_locs
                .extend(finally_ctx.consumed_write_locs.iter().copied());
            // Remove pending writes consumed in the finally block.
            {
                let consumed = result.consumed_write_locs.clone();
                result.last_write_locs.retain(|name, locs| {
                    locs.retain(|loc| !consumed.contains(&(*name, *loc)));
                    !locs.is_empty()
                });
            }
        }

        // Catch variables are bound by the clause, not explicitly assigned. Suppress
        // UnusedVariable for them by tracking their names in catch_var_names.
        for catch in tc.catches.iter() {
            if let Some(var) = &catch.var {
                let sym = mir_types::Name::from(var.trim_start_matches('$'));
                result.catch_var_names.insert(sym);
            }
        }

        *ctx = result;
    }
}