mago-analyzer 1.47.1

A PHP static analyzer that can detect type errors in PHP code, and provide suggestions for fixing them.
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
use mago_allocator::Arena;
use std::cell::RefCell;
use std::rc::Rc;

use foldhash::HashSet;

use mago_algebra::assertion_set::AssertionSet;
use mago_algebra::clause::Clause;
use mago_codex::assertion::Assertion;
use mago_codex::context::ScopeContext;
use mago_codex::ttype::TType;
use mago_codex::ttype::add_optional_union_type;
use mago_codex::ttype::comparator::ComparisonResult;
use mago_codex::ttype::comparator::union_comparator;
use mago_codex::ttype::get_mixed;
use mago_codex::ttype::get_never;
use mago_codex::ttype::union::TUnion;
use mago_span::Span;
use mago_word::Word;
use mago_word::WordMap;
use mago_word::WordSet;
use mago_word::word;

use crate::common::global::get_super_globals;
use crate::context::Context;
use crate::context::block_flags::BlockContextFlags;
use crate::context::scope::control_action::ControlActionSet;
use crate::context::scope::finally_scope::FinallyScope;
use crate::context::scope::var_has_root;
use crate::reconciler::assertion_reconciler;
use crate::reconciler::negated_assertion_reconciler;
use mago_bytes::BytesDisplay;

#[derive(Clone, PartialEq, Eq, Debug)]
pub enum BreakContext {
    Switch,
    Loop,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ReferenceConstraintSource {
    Global,
    Static,
    Parameter,
    Argument,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ReferenceConstraint {
    pub constraint_span: Span,
    pub source: ReferenceConstraintSource,
    pub constraint_type: Option<Rc<TUnion>>,
}

#[derive(Clone, Debug)]
pub struct BlockContext<'ctx> {
    pub scope: ScopeContext<'ctx>,
    pub locals: WordMap<Rc<TUnion>>,
    pub static_locals: WordSet,
    pub variables_possibly_in_scope: WordSet,
    pub conditionally_referenced_variable_ids: WordSet,
    pub assigned_variable_ids: WordMap<u32>,
    pub possibly_assigned_variable_ids: WordSet,

    /// Maps variable names to the number of times they have been referenced in the current scope.
    ///
    /// This might not contain all variables in `locals`, as it is only updated when a variable is referenced.
    pub referenced_counts: WordMap<u32>,

    /// Maps variable names to the local variable that they reference.
    ///
    /// All keys and values in this map are guaranteed to be set in `locals`.
    pub references_in_scope: WordMap<Word>,

    /// Set of references to variables in another scope. These references will be marked as used if they are assigned to.
    pub references_to_external_scope: WordSet,

    /// A set of references that might still be in scope from a scope likely to cause confusion. This applies
    /// to references set inside a loop or if statement, since it's easy to forget about PHP's weird scope
    /// rules, and assigning to a reference will change the referenced variable rather than shadowing it.
    pub references_possibly_from_confusing_scope: WordSet,

    /// A map of variable names to their reference constraints,
    /// where the key is the variable name and the value is the reference constraint.
    pub by_reference_constraints: WordMap<ReferenceConstraint>,

    /// Bitflags for various context states (inside_conditional, inside_isset, etc.)
    pub flags: BlockContextFlags,

    pub clauses: Vec<Rc<Clause>>,
    pub reconciled_expression_clauses: Vec<Rc<Clause>>,
    pub known_functions: WordSet,
    pub known_constants: WordSet,
    pub break_types: Vec<BreakContext>,
    pub finally_scope: Option<Rc<RefCell<FinallyScope>>>,
    pub parent_conflicting_clause_variables: WordSet,
    pub loop_bounds: (u32, u32),
    pub if_body_context: Option<Rc<RefCell<Self>>>,
    pub control_actions: ControlActionSet,
    pub possibly_thrown_exceptions: WordMap<HashSet<Span>>,

    /// Properties that are DEFINITELY initialized in ALL code paths.
    /// Uses intersection semantics - a property must be initialized in ALL branches.
    pub definitely_initialized_properties: WordSet,

    /// Properties that are POSSIBLY initialized (in at least one path).
    /// Uses union semantics - a property initialized in ANY branch is included.
    pub possibly_initialized_properties: WordSet,

    /// Property expression IDs proven uninitialized by the active control-flow path.
    ///
    /// This is populated by negated `isset()` assertions and consumed by readonly
    /// initialization checks. The declared property type is still consulted so that
    /// nullable properties are not treated as definitely uninitialized.
    pub definitely_uninitialized_property_ids: WordSet,

    /// Methods called on $this that are DEFINITELY called in ALL code paths.
    /// Uses intersection semantics for tracking transitive initialization.
    pub definitely_called_methods: HashSet<Word>,

    /// Methods called on $this in at least one path.
    /// Uses union semantics.
    pub called_methods: HashSet<Word>,

    /// If this method calls `parent::`<method>() where <method> is a class initializer,
    /// this holds the initializer method name.
    pub calls_parent_initializer: Option<Word>,

    /// Active method call assertions from guard methods.
    /// When inside a conditional like `if ($obj->isValid())`, this tracks assertions
    /// about method return types that should be applied.
    ///
    /// Key: method call expression id (e.g., "$statements->first()")
    /// Value: assertion set to apply to the method's return type
    pub active_method_call_assertions: WordMap<AssertionSet>,

    /// Assertions inferred for repeated zero-argument method calls in the active branch.
    pub stable_method_call_assertions: WordMap<AssertionSet>,

    /// Zero-argument method calls known to be stable since the last potentially
    /// mutating invocation.
    pub stable_method_calls: WordSet,
}

impl BreakContext {
    #[inline]
    pub const fn is_switch(&self) -> bool {
        matches!(self, BreakContext::Switch)
    }
}

impl ReferenceConstraint {
    pub fn new(constraint_span: Span, source: ReferenceConstraintSource, constraint_type: Option<Rc<TUnion>>) -> Self {
        let constraint_type = constraint_type.map(|mut constraint_type| {
            Rc::make_mut(&mut constraint_type).widen_literals();

            constraint_type
        });

        Self { constraint_span, source, constraint_type }
    }
}

/// Locate the first accessor separator (`->` or `[`) in `var_name`. Returns
/// the byte offset of the separator, or `None` if the name is a plain `$ident`.
///
/// A single linear scan with very favorable branch prediction.
#[inline]
fn find_accessor_separator(bytes: &[u8]) -> Option<usize> {
    let mut i = 0;
    let len = bytes.len();
    while i < len {
        let b = bytes[i];
        if b == b'[' {
            return Some(i);
        }

        if b == b'-' && i + 1 < len && bytes[i + 1] == b'>' {
            return Some(i);
        }

        i += 1;
    }

    None
}

impl<'ctx> BlockContext<'ctx> {
    pub fn new(scope: ScopeContext<'ctx>, register_super_globals: bool) -> Self {
        let mut block_context = Self {
            scope,
            locals: WordMap::default(),
            static_locals: WordSet::default(),
            variables_possibly_in_scope: WordSet::default(),
            conditionally_referenced_variable_ids: WordSet::default(),
            assigned_variable_ids: WordMap::default(),
            possibly_assigned_variable_ids: WordSet::default(),
            referenced_counts: WordMap::default(),
            references_in_scope: WordMap::default(),
            references_to_external_scope: WordSet::default(),
            references_possibly_from_confusing_scope: WordSet::default(),
            by_reference_constraints: WordMap::default(),
            flags: BlockContextFlags::new(),
            clauses: Vec::new(),
            reconciled_expression_clauses: Vec::new(),
            known_functions: WordSet::default(),
            known_constants: WordSet::default(),
            break_types: Vec::new(),
            finally_scope: None,
            parent_conflicting_clause_variables: WordSet::default(),
            loop_bounds: (0, 0),
            if_body_context: None,
            control_actions: ControlActionSet::new(),
            possibly_thrown_exceptions: WordMap::default(),
            definitely_initialized_properties: WordSet::default(),
            possibly_initialized_properties: WordSet::default(),
            definitely_uninitialized_property_ids: WordSet::default(),
            definitely_called_methods: HashSet::default(),
            called_methods: HashSet::default(),
            calls_parent_initializer: None,
            active_method_call_assertions: WordMap::default(),
            stable_method_call_assertions: WordMap::default(),
            stable_method_calls: WordSet::default(),
        };

        if register_super_globals {
            for (var_name, var_type) in get_super_globals() {
                block_context.locals.insert(word(var_name), var_type);
            }
        }

        block_context
    }

    pub fn is_global_scope(&self) -> bool {
        self.scope.is_global()
    }

    pub fn update_references_possibly_from_confusing_scope(&mut self, confusing_scope_context: &BlockContext<'ctx>) {
        let references = confusing_scope_context
            .references_in_scope
            .keys()
            .chain(confusing_scope_context.references_to_external_scope.iter());

        for reference_id in references {
            if !self.references_in_scope.contains_key(reference_id)
                && !self.references_to_external_scope.contains(reference_id)
            {
                self.references_possibly_from_confusing_scope.insert(*reference_id);
            }
        }

        self.references_possibly_from_confusing_scope
            .extend(confusing_scope_context.references_possibly_from_confusing_scope.iter().copied());
    }

    pub fn get_redefined_locals(
        &self,
        new_locals: &WordMap<Rc<TUnion>>,
        include_new_vars: bool,
        removed_vars: &mut WordSet,
    ) -> WordMap<Rc<TUnion>> {
        let mut redefined_vars = WordMap::default();

        for (var_id, this_type) in &self.locals {
            if let Some(new_type) = new_locals.get(var_id) {
                if new_type != this_type {
                    redefined_vars.insert(*var_id, Rc::clone(this_type));
                }
            } else if include_new_vars {
                redefined_vars.insert(*var_id, Rc::clone(this_type));
            }
        }

        for var_id in new_locals.keys() {
            if !self.locals.contains_key(var_id) {
                removed_vars.insert(*var_id);
            }
        }

        redefined_vars
    }

    pub fn get_new_or_updated_locals(original_context: &Self, new_context: &Self) -> WordSet {
        let mut redefined_var_ids = WordSet::default();

        for (var_id, new_type) in &new_context.locals {
            if let Some(original_type) = original_context.locals.get(var_id) {
                if original_context.assigned_variable_ids.get(var_id).unwrap_or(&0)
                    != new_context.assigned_variable_ids.get(var_id).unwrap_or(&0)
                    || original_type != new_type
                {
                    redefined_var_ids.insert(*var_id);
                }
            } else {
                redefined_var_ids.insert(*var_id);
            }
        }

        redefined_var_ids
    }

    pub fn remove_reconciled_clause_refs(
        clauses: &Vec<Rc<Clause>>,
        changed_var_ids: &WordSet,
    ) -> (Vec<Rc<Clause>>, Vec<Rc<Clause>>) {
        let mut included_clauses = Vec::new();
        let mut rejected_clauses = Vec::new();

        'outer: for c in clauses {
            if c.wedge {
                included_clauses.push(Rc::clone(c));
                continue;
            }

            for (key, assertions) in &c.possibilities {
                for changed_var_id in changed_var_ids {
                    if changed_var_id == key
                        || var_has_root(*key, *changed_var_id)
                        || assertions.values().any(|assertion| {
                            assertion
                                .referenced_variable()
                                .is_some_and(|variable| var_has_root(variable, *changed_var_id))
                        })
                    {
                        rejected_clauses.push(Rc::clone(c));
                        continue 'outer;
                    }
                }
            }

            included_clauses.push(Rc::clone(c));
        }

        (included_clauses, rejected_clauses)
    }

    pub fn remove_reconciled_clauses(clauses: &Vec<Clause>, changed_var_ids: &WordSet) -> (Vec<Clause>, Vec<Clause>) {
        let mut included_clauses = Vec::new();
        let mut rejected_clauses = Vec::new();

        'outer: for c in clauses {
            if c.wedge {
                included_clauses.push(c.clone());
                continue;
            }

            for (key, assertions) in &c.possibilities {
                if changed_var_ids.contains(key)
                    || assertions.values().any(|assertion| {
                        assertion.referenced_variable().is_some_and(|variable| changed_var_ids.contains(&variable))
                    })
                {
                    rejected_clauses.push(c.clone());
                    continue 'outer;
                }
            }

            included_clauses.push(c.clone());
        }

        (included_clauses, rejected_clauses)
    }

    pub(crate) fn filter_clauses<'arena, A>(
        context: &mut Context<'ctx, 'arena, A>,
        remove_var_id: Word,
        clauses: Vec<Rc<Clause>>,
        new_type: Option<&TUnion>,
    ) -> Vec<Rc<Clause>>
    where
        A: Arena,
    {
        let mut clauses_to_keep = Vec::new();
        let mut other_clauses = Vec::new();

        'outer: for clause in clauses {
            for (var_id, assertions) in &clause.possibilities {
                if var_has_root(*var_id, remove_var_id)
                    || assertions.values().any(|assertion| {
                        assertion.referenced_variable().is_some_and(|variable| var_has_root(variable, remove_var_id))
                    })
                {
                    continue 'outer;
                }
            }

            let keep_clause = should_keep_clause(&clause, remove_var_id, new_type);

            if keep_clause {
                clauses_to_keep.push(Rc::clone(&clause));
            } else {
                other_clauses.push(clause);
            }
        }

        if let Some(new_type) = new_type
            && !new_type.is_mixed()
        {
            for clause in other_clauses {
                let mut type_changed = false;
                let Some(possibilities) = clause.possibilities.get(&remove_var_id) else {
                    clauses_to_keep.push(Rc::clone(&clause));

                    continue;
                };

                for (_, assertion) in possibilities {
                    if assertion.is_negation() {
                        type_changed = true;
                        break;
                    }

                    let result_type = assertion_reconciler::reconcile(
                        context,
                        assertion,
                        Some(&new_type.clone()),
                        None,
                        false,
                        None,
                        false,
                        false,
                    );

                    if result_type != *new_type {
                        type_changed = true;
                        break;
                    }
                }

                if !type_changed {
                    clauses_to_keep.push(Rc::clone(&clause));
                }
            }
        }

        clauses_to_keep
    }

    pub(crate) fn remove_variable_from_conflicting_clauses<'arena, A>(
        &mut self,
        context: &mut Context<'ctx, 'arena, A>,
        remove_var_id: Word,
        new_type: Option<&TUnion>,
    ) where
        A: Arena,
    {
        self.clauses = BlockContext::filter_clauses(context, remove_var_id, self.clauses.clone(), new_type);

        self.parent_conflicting_clause_variables.insert(remove_var_id);
    }

    pub(crate) fn remove_descendants<'arena, A>(
        &mut self,
        context: &mut Context<'ctx, 'arena, A>,
        remove_var_id: Word,
        existing_type: &TUnion,
        new_type: Option<&TUnion>,
    ) where
        A: Arena,
    {
        self.remove_variable_from_conflicting_clauses(
            context,
            remove_var_id,
            if existing_type.is_mixed() {
                None
            } else if let Some(new_type) = new_type {
                Some(new_type)
            } else {
                None
            },
        );

        let keys = self.locals.keys().copied().collect::<Vec<_>>();

        for var_id in keys {
            if var_has_root(var_id, remove_var_id) {
                self.locals.remove(&var_id);
            }
        }
    }

    /// Registers a variable that is referenced conditionally, like in a property
    /// or array access (`$foo->bar`, `$foo[0]`).
    pub fn add_conditionally_referenced_variable(&mut self, var_name: &[u8]) {
        match find_accessor_separator(var_name) {
            None if var_name == b"$this" => {
                // Nothing
            }
            _ => {
                self.conditionally_referenced_variable_ids.insert(word(var_name));
            }
        }
    }

    /// Checks if a variable exists in the local scope, while also registering it
    /// as a conditionally referenced variable if it's part of an access chain.
    #[must_use]
    pub fn has_variable(&mut self, var_name: &[u8]) -> bool {
        self.add_conditionally_referenced_variable(var_name);
        self.locals.contains_key(&word(var_name))
    }

    /// Variant of [`add_conditionally_referenced_variable`] that accepts an
    /// already-interned [`Word`] together with the original string. Saves one
    /// `word()` lookup on the hot path that already has the atom available.
    pub fn add_conditionally_referenced_variable_atom(&mut self, var_name: &[u8], var_atom: Word) {
        match find_accessor_separator(var_name) {
            None if var_name == b"$this" => {
                // Nothing
            }
            _ => {
                self.conditionally_referenced_variable_ids.insert(var_atom);
            }
        }
    }

    pub(crate) fn remove_variable<'arena, A>(
        &mut self,
        var_name: &[u8],
        remove_descendants: bool,
        context: &mut Context<'ctx, 'arena, A>,
    ) where
        A: Arena,
    {
        let var_atom = word(var_name);
        if let Some(existing_type) = self.locals.remove(&var_atom)
            && remove_descendants
        {
            self.remove_descendants(context, var_atom, &existing_type, None);
        }

        self.assigned_variable_ids.remove(&var_atom);
        self.possibly_assigned_variable_ids.remove(&var_atom);
        self.conditionally_referenced_variable_ids.remove(&var_atom);
    }

    pub fn remove_possible_reference(&mut self, remove_var_id: &[u8]) {
        let remove_var_atom = word(remove_var_id);
        if let Some(reference_count) = self.referenced_counts.get(&remove_var_atom)
            && *reference_count > 0
        {
            // If a referenced variable goes out of scope, we need to update the references.
            // All of the references to this variable are still references to the same value,
            // so we pick one as the new root and point the rest at it. The candidates are
            // sorted so the choice is deterministic regardless of map iteration order.
            let mut references = vec![];
            for (reference, referenced) in &self.references_in_scope {
                if *referenced == remove_var_atom {
                    references.push(*reference);
                }
            }

            references.sort_unstable();
            for reference in &references {
                self.references_in_scope.remove(reference);
            }

            debug_assert!(
                !references.is_empty(),
                "No references found for variable {}, even though it has a reference count of {reference_count}",
                BytesDisplay(remove_var_id)
            );

            if !references.is_empty() {
                self.referenced_counts.remove(&remove_var_atom);

                let first_reference = references.remove(0);
                if !references.is_empty() {
                    let reassigned_references = references.len() as u32;
                    if let Some(existing_count) = self.referenced_counts.get_mut(&first_reference) {
                        *existing_count += reassigned_references;
                    } else {
                        self.referenced_counts.insert(first_reference, reassigned_references);
                    }

                    for reference in references {
                        self.references_in_scope.insert(reference, first_reference);
                    }
                }
            }
        }

        if self.references_in_scope.contains_key(&remove_var_atom) {
            self.decrement_reference_count(remove_var_id);
        }

        self.locals.remove(&remove_var_atom);
        self.variables_possibly_in_scope.remove(&remove_var_atom);
        self.assigned_variable_ids.remove(&remove_var_atom);
        self.possibly_assigned_variable_ids.remove(&remove_var_atom);
        self.conditionally_referenced_variable_ids.remove(&remove_var_atom);
    }

    pub fn update<A>(
        &mut self,
        context: &mut Context<'ctx, '_, A>,
        start_block_context: &Self,
        end_block_context: &mut Self,
        has_leaving_statements: bool,
        vars_to_update: &WordSet,
        updated_vars: &mut WordSet,
    ) where
        A: Arena,
    {
        if vars_to_update.is_empty() {
            return;
        }

        for (variable_id, old_type) in &start_block_context.locals {
            if !vars_to_update.contains(variable_id) {
                continue;
            }

            let new_type = if !has_leaving_statements && end_block_context.has_variable(variable_id.as_bytes()) {
                end_block_context.locals.get(variable_id).cloned()
            } else {
                None
            };

            let Some(existing_type) = self.locals.get(variable_id).map(std::convert::AsRef::as_ref).cloned() else {
                if let Some(new_type) = new_type {
                    self.locals.insert(*variable_id, new_type);
                    updated_vars.insert(*variable_id);
                }

                continue;
            };

            let old_type = old_type.as_ref().clone();

            let should_substitute = match &new_type {
                Some(new_type) => !old_type.eq(new_type),
                None => existing_type.types.len() > 1,
            };

            let resulting_type = if should_substitute {
                updated_vars.insert(*variable_id);

                substitute_types(context, existing_type, old_type, new_type.as_deref())
            } else {
                existing_type
            };

            self.locals.insert(*variable_id, Rc::new(resulting_type));
        }
    }

    /// Decrement the reference count of the variable that $`ref_id` is referring to. This needs to
    /// be done before $`ref_id` is changed to no longer reference its currently referenced variable,
    /// for example by unsetting, reassigning to another reference, or being shadowed by a global.
    pub fn decrement_reference_count(&mut self, ref_id: &[u8]) -> bool {
        let ref_atom = word(ref_id);
        let Some(ref_target) = self.references_in_scope.get(&ref_atom) else {
            return false;
        };

        let Some(reference_count) = self.referenced_counts.get_mut(ref_target) else {
            return false;
        };

        if *reference_count < 1 {
            return false;
        }

        *reference_count -= 1;

        true
    }
}

impl std::fmt::Display for ReferenceConstraintSource {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ReferenceConstraintSource::Global => write!(f, "global"),
            ReferenceConstraintSource::Static => write!(f, "static"),
            ReferenceConstraintSource::Parameter => write!(f, "parameter"),
            ReferenceConstraintSource::Argument => write!(f, "argument"),
        }
    }
}

fn substitute_types<A>(
    context: &mut Context<'_, '_, A>,
    existing_type: TUnion,
    old_type: TUnion,
    new_type: Option<&TUnion>,
) -> TUnion
where
    A: Arena,
{
    if existing_type.is_mixed() || existing_type.is_never() {
        return existing_type;
    }

    if existing_type.eq(&old_type) {
        let Some(new_type) = new_type else {
            return existing_type;
        };

        return add_optional_union_type(get_mixed(), Some(new_type), context.codebase);
    }

    let updated_type = subtract_union_types(context, existing_type, old_type);

    add_optional_union_type(updated_type, new_type, context.codebase)
}

/// Subtracts the types in `type_to_remove` from `existing_type`.
///
/// This function iterates through each atomic type in `existing_type`. For each of these,
/// it iteratively applies the logic of "is not `atomic_from_remove_set`" for every
/// atomic type in `type_to_remove`. This effectively refines each part of `existing_type`
/// to exclude any possibilities covered by `type_to_remove`.
///
/// This is primarily useful for determining remaining possible types for a match subject
/// after some conditional arms have been considered.
///
/// # Arguments
///
/// * `context` - The reconciliation context, and providing access to codebase.
/// * `existing_type` - The initial `TUnion` type (the minuend).
/// * `type_to_remove` - The `TUnion` type whose components should be subtracted from `existing_type`.
///
/// # Returns
///
/// A new `TUnion` representing `existing_type - type_to_remove`.
pub fn subtract_union_types<A>(
    context: &mut Context<'_, '_, A>,
    existing_type: TUnion,
    type_to_remove: TUnion,
) -> TUnion
where
    A: Arena,
{
    if existing_type == type_to_remove {
        return get_never();
    }

    if !(existing_type.has_literal_value() && type_to_remove.has_literal_value())
        && union_comparator::is_contained_by(
            context.codebase,
            &existing_type,
            &type_to_remove,
            false,
            false,
            true,
            &mut ComparisonResult::new(),
        )
    {
        return existing_type;
    }

    let mut result = existing_type;
    for atomic in type_to_remove.types.into_owned() {
        let assertion = Assertion::IsNotType(atomic);
        let key = result.get_id();

        result = negated_assertion_reconciler::reconcile(context, &assertion, &result, None, key, None, true);
        if result.is_never() {
            break;
        }
    }

    result
}

fn should_keep_clause(clause: &Rc<Clause>, remove_var_id: Word, new_type: Option<&TUnion>) -> bool {
    if let Some(possibilities) = clause.possibilities.get(&remove_var_id) {
        if possibilities.len() == 1
            && let Some((_, Assertion::IsType(assertion_type))) = possibilities.first()
            && let Some(new_type) = new_type
            && new_type.is_single()
        {
            return new_type.get_single() == assertion_type;
        }

        false
    } else {
        true
    }
}

#[cfg(test)]
mod tests {
    use std::rc::Rc;

    use mago_codex::context::ScopeContext;
    use mago_codex::reference::ReferenceOrigin;
    use mago_codex::ttype::get_mixed;
    use mago_word::word;

    use super::BlockContext;

    fn block_context_with_locals(vars: &[&str]) -> BlockContext<'static> {
        let mut block_context = BlockContext::new(ScopeContext::new(ReferenceOrigin::File(word("test.php"))), false);
        for variable in vars {
            let variable_atom = word(variable);
            block_context.locals.insert(variable_atom, Rc::new(get_mixed()));
            block_context.variables_possibly_in_scope.insert(variable_atom);
        }

        block_context
    }

    #[test]
    fn remove_possible_reference_preserves_promoted_reference_counts() {
        let mut block_context = block_context_with_locals(&["$a", "$b", "$c"]);

        // Model: $b =& $a; $c =& $b.
        block_context.references_in_scope.insert(word("$b"), word("$a"));
        block_context.references_in_scope.insert(word("$c"), word("$b"));
        block_context.referenced_counts.insert(word("$a"), 1);
        block_context.referenced_counts.insert(word("$b"), 1);

        block_context.remove_possible_reference(b"$a");

        // $b is promoted to root, but still has $c pointing to it.
        assert_eq!(block_context.references_in_scope.get(&word("$c")).copied(), Some(word("$b")));
        assert_eq!(block_context.referenced_counts.get(&word("$b")).copied(), Some(1));

        // Removing $b should re-root $c and clear dangling reference links.
        block_context.remove_possible_reference(b"$b");
        assert!(!block_context.references_in_scope.contains_key(&word("$c")));
    }

    #[test]
    fn remove_possible_reference_adds_to_existing_promoted_count() {
        let mut block_context = block_context_with_locals(&["$a", "$b", "$c", "$d"]);

        // Model before removal:
        // $b =& $a, $c =& $a, and $d =& $b.
        block_context.references_in_scope.insert(word("$b"), word("$a"));
        block_context.references_in_scope.insert(word("$c"), word("$a"));
        block_context.references_in_scope.insert(word("$d"), word("$b"));
        block_context.referenced_counts.insert(word("$a"), 2);
        block_context.referenced_counts.insert(word("$b"), 1);

        block_context.remove_possible_reference(b"$a");

        // $b is promoted and keeps its prior 1, plus 1 reassigned reference from $c.
        assert_eq!(block_context.referenced_counts.get(&word("$b")).copied(), Some(2));
        assert_eq!(block_context.references_in_scope.get(&word("$c")).copied(), Some(word("$b")));
        assert_eq!(block_context.references_in_scope.get(&word("$d")).copied(), Some(word("$b")));
    }

    #[test]
    fn remove_possible_reference_sets_promoted_count_when_missing() {
        let mut block_context = block_context_with_locals(&["$a", "$b", "$c"]);

        // Model before removal:
        // $b =& $a, $c =& $a with no prior count entry for $b.
        block_context.references_in_scope.insert(word("$b"), word("$a"));
        block_context.references_in_scope.insert(word("$c"), word("$a"));
        block_context.referenced_counts.insert(word("$a"), 2);

        block_context.remove_possible_reference(b"$a");

        // $b becomes primary and should have count 1 (the reassigned $c).
        assert_eq!(block_context.referenced_counts.get(&word("$b")).copied(), Some(1));
        assert_eq!(block_context.references_in_scope.get(&word("$c")).copied(), Some(word("$b")));
    }

    #[test]
    #[cfg(debug_assertions)]
    #[should_panic(expected = "No references found for variable")]
    fn remove_possible_reference_panics_on_stale_counts_in_debug() {
        let mut block_context = block_context_with_locals(&["$stale"]);
        block_context.referenced_counts.insert(word("$stale"), 1);

        // No references_in_scope entry for $stale -> intentional debug panic.
        block_context.remove_possible_reference(b"$stale");
    }
}