mago-codex 1.15.2

PHP type system representation, comparison logic, and codebase metadata for static analysis.
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
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
use std::borrow::Cow;
use std::hash::Hash;
use std::hash::Hasher;
use std::sync::Arc;

use serde::Deserialize;
use serde::Serialize;

use mago_atom::Atom;
use mago_atom::atom;
use mago_atom::concat_atom;
use mago_atom::empty_atom;

use crate::metadata::CodebaseMetadata;
use crate::reference::ReferenceSource;
use crate::reference::SymbolReferences;
use crate::symbol::Symbols;
use crate::ttype::TType;
use crate::ttype::TypeRef;
use crate::ttype::atomic::TAtomic;
use crate::ttype::atomic::array::TArray;
use crate::ttype::atomic::array::key::ArrayKey;
use crate::ttype::atomic::generic::TGenericParameter;
use crate::ttype::atomic::mixed::truthiness::TMixedTruthiness;
use crate::ttype::atomic::object::TObject;
use crate::ttype::atomic::object::named::TNamedObject;
use crate::ttype::atomic::object::with_properties::TObjectWithProperties;
use crate::ttype::atomic::populate_atomic_type;
use crate::ttype::atomic::scalar::TScalar;
use crate::ttype::atomic::scalar::bool::TBool;
use crate::ttype::atomic::scalar::class_like_string::TClassLikeString;
use crate::ttype::atomic::scalar::int::TInteger;
use crate::ttype::atomic::scalar::string::TString;
use crate::ttype::atomic::scalar::string::TStringLiteral;
use crate::ttype::flags::UnionFlags;
use crate::ttype::get_arraykey;
use crate::ttype::get_int;
use crate::ttype::get_mixed;

#[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialOrd, Ord)]
pub struct TUnion {
    pub types: Cow<'static, [TAtomic]>,
    pub flags: UnionFlags,
}

impl Hash for TUnion {
    fn hash<H: Hasher>(&self, state: &mut H) {
        for t in self.types.as_ref() {
            t.hash(state);
        }
    }
}

impl TUnion {
    /// The primary constructor for creating a `TUnion` from a Cow.
    ///
    /// This is the most basic way to create a `TUnion` and is used by both the
    /// zero-allocation static helpers and the `from_vec` constructor.
    #[must_use]
    pub fn new(types: Cow<'static, [TAtomic]>) -> TUnion {
        TUnion { types, flags: UnionFlags::empty() }
    }

    /// Creates a `TUnion` from an owned Vec, performing necessary cleanup.
    ///
    /// This preserves the original logic for cleaning up dynamically created unions,
    /// such as removing redundant `never` types.
    ///
    /// # Panics
    ///
    /// In debug builds, panics if:
    /// - The input Vec is empty (unions must contain at least one type)
    /// - The input contains a mix of `never` types with other types (invalid union construction)
    #[must_use]
    pub fn from_vec(mut types: Vec<TAtomic>) -> TUnion {
        if cfg!(debug_assertions) {
            assert!(
                !types.is_empty(),
                "TUnion::from_vec() received an empty Vec. This indicates a logic error \
                 in type construction - unions must contain at least one type. \
                 Consider using TAtomic::Never for empty/impossible types."
            );
        }

        // If we have more than one type, 'never' is redundant and can be removed,
        // as the union `A|never` is simply `A`.
        if types.len() > 1 {
            types.retain(|atomic| {
                !atomic.is_never() && !atomic.map_generic_parameter_constraint(TUnion::is_never).unwrap_or(false)
            });
        }

        // If the vector was originally empty, or contained only 'never' types
        // which were removed, ensure the final union is `never`.
        if types.is_empty() {
            types.push(TAtomic::Never);
        }

        Self::new(Cow::Owned(types))
    }

    /// Creates a `TUnion` from a single atomic type, which can be either
    /// borrowed from a static source or owned.
    ///
    /// This function is a key optimization point. When passed a `Cow::Borrowed`,
    /// it creates the `TUnion` without any heap allocation.
    #[must_use]
    pub fn from_single(atomic: Cow<'static, TAtomic>) -> TUnion {
        let types_cow = match atomic {
            Cow::Borrowed(borrowed_atomic) => Cow::Borrowed(std::slice::from_ref(borrowed_atomic)),
            Cow::Owned(owned_atomic) => Cow::Owned(vec![owned_atomic]),
        };

        TUnion::new(types_cow)
    }

    /// Creates a `TUnion` from a single owned atomic type.
    #[must_use]
    pub fn from_atomic(atomic: TAtomic) -> TUnion {
        TUnion::new(Cow::Owned(vec![atomic]))
    }

    #[inline]
    pub fn set_possibly_undefined(&mut self, possibly_undefined: bool, from_try: Option<bool>) {
        let from_try = from_try.unwrap_or(self.flags.contains(UnionFlags::POSSIBLY_UNDEFINED_FROM_TRY));

        self.flags.set(UnionFlags::POSSIBLY_UNDEFINED, possibly_undefined);
        self.flags.set(UnionFlags::POSSIBLY_UNDEFINED_FROM_TRY, from_try);
    }

    #[inline]
    #[must_use]
    pub const fn had_template(&self) -> bool {
        self.flags.contains(UnionFlags::HAD_TEMPLATE)
    }

    #[inline]
    #[must_use]
    pub const fn by_reference(&self) -> bool {
        self.flags.contains(UnionFlags::BY_REFERENCE)
    }

    #[inline]
    #[must_use]
    pub const fn reference_free(&self) -> bool {
        self.flags.contains(UnionFlags::REFERENCE_FREE)
    }

    #[inline]
    #[must_use]
    pub const fn possibly_undefined_from_try(&self) -> bool {
        self.flags.contains(UnionFlags::POSSIBLY_UNDEFINED_FROM_TRY)
    }

    #[inline]
    #[must_use]
    pub const fn possibly_undefined(&self) -> bool {
        self.flags.contains(UnionFlags::POSSIBLY_UNDEFINED)
    }

    #[inline]
    #[must_use]
    pub const fn ignore_nullable_issues(&self) -> bool {
        self.flags.contains(UnionFlags::IGNORE_NULLABLE_ISSUES)
    }

    #[inline]
    #[must_use]
    pub const fn ignore_falsable_issues(&self) -> bool {
        self.flags.contains(UnionFlags::IGNORE_FALSABLE_ISSUES)
    }

    #[inline]
    #[must_use]
    pub const fn from_template_default(&self) -> bool {
        self.flags.contains(UnionFlags::FROM_TEMPLATE_DEFAULT)
    }

    #[inline]
    #[must_use]
    pub const fn populated(&self) -> bool {
        self.flags.contains(UnionFlags::POPULATED)
    }

    #[inline]
    #[must_use]
    pub const fn has_nullsafe_null(&self) -> bool {
        self.flags.contains(UnionFlags::NULLSAFE_NULL)
    }

    #[inline]
    pub fn set_had_template(&mut self, value: bool) {
        self.flags.set(UnionFlags::HAD_TEMPLATE, value);
    }

    #[inline]
    pub fn set_by_reference(&mut self, value: bool) {
        self.flags.set(UnionFlags::BY_REFERENCE, value);
    }

    #[inline]
    pub fn set_reference_free(&mut self, value: bool) {
        self.flags.set(UnionFlags::REFERENCE_FREE, value);
    }

    #[inline]
    pub fn set_possibly_undefined_from_try(&mut self, value: bool) {
        self.flags.set(UnionFlags::POSSIBLY_UNDEFINED_FROM_TRY, value);
    }

    #[inline]
    pub fn set_ignore_nullable_issues(&mut self, value: bool) {
        self.flags.set(UnionFlags::IGNORE_NULLABLE_ISSUES, value);
    }

    #[inline]
    pub fn set_ignore_falsable_issues(&mut self, value: bool) {
        self.flags.set(UnionFlags::IGNORE_FALSABLE_ISSUES, value);
    }

    #[inline]
    pub fn set_from_template_default(&mut self, value: bool) {
        self.flags.set(UnionFlags::FROM_TEMPLATE_DEFAULT, value);
    }

    #[inline]
    pub fn set_populated(&mut self, value: bool) {
        self.flags.set(UnionFlags::POPULATED, value);
    }

    #[inline]
    pub fn set_nullsafe_null(&mut self, value: bool) {
        self.flags.set(UnionFlags::NULLSAFE_NULL, value);
    }

    /// Creates a new `TUnion` with the same properties as the original, but with a new set of types.
    #[must_use]
    pub fn clone_with_types(&self, types: Vec<TAtomic>) -> TUnion {
        TUnion { types: Cow::Owned(types), flags: self.flags }
    }

    #[must_use]
    pub fn to_non_nullable(&self) -> TUnion {
        TUnion { types: Cow::Owned(self.get_non_nullable_types()), flags: self.flags & !UnionFlags::NULLSAFE_NULL }
    }

    #[must_use]
    pub fn to_truthy(&self) -> TUnion {
        TUnion { types: Cow::Owned(self.get_truthy_types()), flags: self.flags }
    }

    #[must_use]
    pub fn get_non_nullable_types(&self) -> Vec<TAtomic> {
        self.types
            .iter()
            .filter_map(|t| match t {
                TAtomic::Null | TAtomic::Void => None,
                TAtomic::GenericParameter(parameter) => Some(TAtomic::GenericParameter(TGenericParameter {
                    parameter_name: parameter.parameter_name,
                    defining_entity: parameter.defining_entity,
                    intersection_types: parameter.intersection_types.clone(),
                    constraint: Arc::new(parameter.constraint.to_non_nullable()),
                })),
                TAtomic::Mixed(mixed) => Some(TAtomic::Mixed(mixed.with_is_non_null(true))),
                atomic => Some(atomic.clone()),
            })
            .collect()
    }

    #[must_use]
    pub fn get_truthy_types(&self) -> Vec<TAtomic> {
        self.types
            .iter()
            .filter_map(|t| match t {
                TAtomic::GenericParameter(parameter) => Some(TAtomic::GenericParameter(TGenericParameter {
                    parameter_name: parameter.parameter_name,
                    defining_entity: parameter.defining_entity,
                    intersection_types: parameter.intersection_types.clone(),
                    constraint: Arc::new(parameter.constraint.to_truthy()),
                })),
                TAtomic::Mixed(mixed) => Some(TAtomic::Mixed(mixed.with_truthiness(TMixedTruthiness::Truthy))),
                atomic => {
                    if atomic.is_falsy() {
                        None
                    } else {
                        Some(atomic.clone())
                    }
                }
            })
            .collect()
    }

    /// Adds `null` to the union type, making it nullable.
    #[must_use]
    pub fn as_nullable(mut self) -> TUnion {
        let types = self.types.to_mut();

        for atomic in types.iter_mut() {
            if let TAtomic::Mixed(mixed) = atomic {
                *mixed = mixed.with_is_non_null(false);
            }
        }

        if !types.iter().any(|atomic| atomic.is_null() || atomic.is_mixed()) {
            types.push(TAtomic::Null);
        }

        self
    }

    /// Removes a specific atomic type from the union.
    pub fn remove_type(&mut self, bad_type: &TAtomic) {
        self.types.to_mut().retain(|t| t != bad_type);
    }

    /// Replaces a specific atomic type in the union with a new type.
    pub fn replace_type(&mut self, remove_type: &TAtomic, add_type: TAtomic) {
        let types = self.types.to_mut();

        if let Some(index) = types.iter().position(|t| t == remove_type) {
            types[index] = add_type;
        } else {
            types.push(add_type);
        }
    }

    #[must_use]
    pub fn is_int(&self) -> bool {
        for atomic in self.types.as_ref() {
            if !atomic.is_int() {
                return false;
            }
        }

        true
    }

    #[must_use]
    pub fn has_int_or_float(&self) -> bool {
        for atomic in self.types.as_ref() {
            if atomic.is_int_or_float() {
                return true;
            }
        }

        false
    }

    #[must_use]
    pub fn has_int_and_float(&self) -> bool {
        let mut has_int = false;
        let mut has_float = false;

        for atomic in self.types.as_ref() {
            if atomic.is_int() {
                has_int = true;
            } else if atomic.is_float() {
                has_float = true;
            } else if atomic.is_int_or_float() {
                has_int = true;
                has_float = true;
            }

            if has_int && has_float {
                return true;
            }
        }

        false
    }

    #[must_use]
    pub fn has_int_and_string(&self) -> bool {
        let mut has_int = false;
        let mut has_string = false;

        for atomic in self.types.as_ref() {
            if atomic.is_int() {
                has_int = true;
            } else if atomic.is_string() {
                has_string = true;
            } else if atomic.is_array_key() {
                has_int = true;
                has_string = true;
            }

            if has_int && has_string {
                return true;
            }
        }

        false
    }

    #[must_use]
    pub fn has_int(&self) -> bool {
        for atomic in self.types.as_ref() {
            if atomic.is_int() || atomic.is_array_key() || atomic.is_numeric() {
                return true;
            }
        }

        false
    }

    #[must_use]
    pub fn has_float(&self) -> bool {
        for atomic in self.types.as_ref() {
            if atomic.is_float() {
                return true;
            }
        }

        false
    }

    #[must_use]
    pub fn is_array_key(&self) -> bool {
        for atomic in self.types.as_ref() {
            if atomic.is_array_key() {
                continue;
            }

            return false;
        }

        true
    }

    #[must_use]
    pub fn is_any_string(&self) -> bool {
        for atomic in self.types.as_ref() {
            if !atomic.is_any_string() {
                return false;
            }
        }

        true
    }

    pub fn is_string(&self) -> bool {
        self.types.iter().all(TAtomic::is_string) && !self.types.is_empty()
    }

    #[must_use]
    pub fn is_always_array_key(&self, ignore_never: bool) -> bool {
        self.types.iter().all(|atomic| match atomic {
            TAtomic::Never => ignore_never,
            TAtomic::Scalar(scalar) => matches!(
                scalar,
                TScalar::ArrayKey | TScalar::Integer(_) | TScalar::String(_) | TScalar::ClassLikeString(_)
            ),
            TAtomic::GenericParameter(generic_parameter) => {
                generic_parameter.constraint.is_always_array_key(ignore_never)
            }
            _ => false,
        })
    }

    pub fn is_non_empty_string(&self) -> bool {
        self.types.iter().all(TAtomic::is_non_empty_string) && !self.types.is_empty()
    }

    pub fn is_empty_array(&self) -> bool {
        self.types.iter().all(TAtomic::is_empty_array) && !self.types.is_empty()
    }

    pub fn has_string(&self) -> bool {
        self.types.iter().any(TAtomic::is_string) && !self.types.is_empty()
    }

    pub fn is_float(&self) -> bool {
        self.types.iter().all(TAtomic::is_float) && !self.types.is_empty()
    }

    pub fn is_bool(&self) -> bool {
        self.types.iter().all(TAtomic::is_bool) && !self.types.is_empty()
    }

    pub fn is_never(&self) -> bool {
        self.types.iter().all(TAtomic::is_never) || self.types.is_empty()
    }

    pub fn is_never_template(&self) -> bool {
        self.types.iter().all(TAtomic::is_templated_as_never) && !self.types.is_empty()
    }

    #[must_use]
    pub fn is_placeholder(&self) -> bool {
        self.types.iter().all(|t| matches!(t, TAtomic::Placeholder)) && !self.types.is_empty()
    }

    /// Returns true if this union or any type parameter within it contains a Placeholder.
    #[must_use]
    pub fn contains_placeholder(&self) -> bool {
        self.types.iter().any(|t| t.contains_placeholder())
    }

    pub fn is_true(&self) -> bool {
        self.types.iter().all(TAtomic::is_true) && !self.types.is_empty()
    }

    pub fn is_false(&self) -> bool {
        self.types.iter().all(TAtomic::is_false) && !self.types.is_empty()
    }

    #[must_use]
    pub fn is_nonnull(&self) -> bool {
        self.types.len() == 1 && matches!(self.types[0], TAtomic::Mixed(mixed) if mixed.is_non_null())
    }

    pub fn is_numeric(&self) -> bool {
        self.types.iter().all(TAtomic::is_numeric) && !self.types.is_empty()
    }

    pub fn is_int_or_float(&self) -> bool {
        self.types.iter().all(TAtomic::is_int_or_float) && !self.types.is_empty()
    }

    /// Returns `Some(true)` if all types are effectively int, `Some(false)` if all are effectively float,
    /// or `None` if mixed or neither. Handles unions like `1|2` (all int) or `3.4|4.5` (all float).
    #[must_use]
    pub fn effective_int_or_float(&self) -> Option<bool> {
        let mut result: Option<bool> = None;
        for atomic in self.types.as_ref() {
            match atomic.effective_int_or_float() {
                Some(is_int) => {
                    if let Some(prev) = result {
                        if prev != is_int {
                            return None;
                        }
                    } else {
                        result = Some(is_int);
                    }
                }
                None => return None,
            }
        }

        result
    }

    #[must_use]
    pub fn is_mixed(&self) -> bool {
        self.types.iter().all(|t| matches!(t, TAtomic::Mixed(_))) && !self.types.is_empty()
    }

    pub fn is_mixed_template(&self) -> bool {
        self.types.iter().all(TAtomic::is_templated_as_mixed) && !self.types.is_empty()
    }

    #[must_use]
    pub fn has_mixed(&self) -> bool {
        self.types.iter().any(|t| matches!(t, TAtomic::Mixed(_))) && !self.types.is_empty()
    }

    pub fn has_mixed_template(&self) -> bool {
        self.types.iter().any(TAtomic::is_templated_as_mixed) && !self.types.is_empty()
    }

    #[must_use]
    pub fn has_nullable_mixed(&self) -> bool {
        self.types.iter().any(|t| matches!(t, TAtomic::Mixed(mixed) if !mixed.is_non_null())) && !self.types.is_empty()
    }

    #[must_use]
    pub fn has_void(&self) -> bool {
        self.types.iter().any(|t| matches!(t, TAtomic::Void)) && !self.types.is_empty()
    }

    #[must_use]
    pub fn has_null(&self) -> bool {
        self.types.iter().any(|t| matches!(t, TAtomic::Null)) && !self.types.is_empty()
    }

    #[must_use]
    pub fn has_nullish(&self) -> bool {
        self.types.iter().any(|t| match t {
            TAtomic::Null | TAtomic::Void => true,
            TAtomic::Mixed(mixed) => !mixed.is_non_null(),
            TAtomic::GenericParameter(parameter) => parameter.constraint.has_nullish(),
            _ => false,
        }) && !self.types.is_empty()
    }

    #[must_use]
    pub fn is_nullable_mixed(&self) -> bool {
        if self.types.len() != 1 {
            return false;
        }

        match &self.types[0] {
            TAtomic::Mixed(mixed) => !mixed.is_non_null(),
            _ => false,
        }
    }

    #[must_use]
    pub fn is_falsy_mixed(&self) -> bool {
        if self.types.len() != 1 {
            return false;
        }

        matches!(&self.types[0], &TAtomic::Mixed(mixed) if mixed.is_falsy())
    }

    #[must_use]
    pub fn is_vanilla_mixed(&self) -> bool {
        if self.types.len() != 1 {
            return false;
        }

        self.types[0].is_vanilla_mixed()
    }

    #[must_use]
    pub fn is_templated_as_vanilla_mixed(&self) -> bool {
        if self.types.len() != 1 {
            return false;
        }

        self.types[0].is_templated_as_vanilla_mixed()
    }

    #[must_use]
    pub fn has_template_or_static(&self) -> bool {
        for atomic in self.types.as_ref() {
            if let TAtomic::GenericParameter(_) = atomic {
                return true;
            }

            if let TAtomic::Object(TObject::Named(named_object)) = atomic {
                if named_object.is_static {
                    return true;
                }

                if let Some(intersections) = named_object.get_intersection_types() {
                    for intersection in intersections {
                        if let TAtomic::GenericParameter(_) = intersection {
                            return true;
                        }
                    }
                }
            }
        }

        false
    }

    #[must_use]
    pub fn has_template(&self) -> bool {
        for atomic in self.types.as_ref() {
            if let TAtomic::GenericParameter(_) = atomic {
                return true;
            }

            if let Some(intersections) = atomic.get_intersection_types() {
                for intersection in intersections {
                    if let TAtomic::GenericParameter(_) = intersection {
                        return true;
                    }
                }
            }
        }

        false
    }

    #[must_use]
    pub fn has_template_types(&self) -> bool {
        let all_child_nodes = self.get_all_child_nodes();

        for child_node in all_child_nodes {
            if let TypeRef::Atomic(
                TAtomic::GenericParameter(_)
                | TAtomic::Scalar(TScalar::ClassLikeString(TClassLikeString::Generic { .. })),
            ) = child_node
            {
                return true;
            }
        }

        false
    }

    #[must_use]
    pub fn get_template_types(&self) -> Vec<&TAtomic> {
        let all_child_nodes = self.get_all_child_nodes();

        let mut template_types = Vec::new();

        for child_node in all_child_nodes {
            if let TypeRef::Atomic(inner) = child_node {
                match inner {
                    TAtomic::GenericParameter(_) => {
                        template_types.push(inner);
                    }
                    TAtomic::Scalar(TScalar::ClassLikeString(TClassLikeString::Generic { .. })) => {
                        template_types.push(inner);
                    }
                    _ => {}
                }
            }
        }

        template_types
    }

    pub fn is_objecty(&self) -> bool {
        for atomic in self.types.as_ref() {
            if let &TAtomic::Object(_) = atomic {
                continue;
            }

            if let TAtomic::Callable(callable) = atomic
                && callable.get_signature().is_none_or(super::atomic::callable::TCallableSignature::is_closure)
            {
                continue;
            }

            return false;
        }

        true
    }

    #[must_use]
    pub fn is_generator(&self) -> bool {
        for atomic in self.types.as_ref() {
            if atomic.is_generator() {
                continue;
            }

            return false;
        }

        true
    }

    #[must_use]
    pub fn extends_or_implements(&self, codebase: &CodebaseMetadata, interface: &str) -> bool {
        for atomic in self.types.as_ref() {
            if !atomic.extends_or_implements(codebase, interface) {
                return false;
            }
        }

        true
    }

    #[must_use]
    pub fn is_generic_parameter(&self) -> bool {
        self.types.len() == 1 && matches!(self.types[0], TAtomic::GenericParameter(_))
    }

    #[must_use]
    pub fn get_generic_parameter_constraint(&self) -> Option<&TUnion> {
        if self.is_generic_parameter()
            && let TAtomic::GenericParameter(parameter) = &self.types[0]
        {
            return Some(&parameter.constraint);
        }

        None
    }

    #[must_use]
    pub fn is_null(&self) -> bool {
        self.types.iter().all(|t| matches!(t, TAtomic::Null)) && !self.types.is_empty()
    }

    #[must_use]
    pub fn is_nullable(&self) -> bool {
        self.types.iter().any(|t| match t {
            TAtomic::Null => self.types.len() >= 2,
            TAtomic::GenericParameter(param) => param.constraint.is_nullable(),
            _ => false,
        })
    }

    #[must_use]
    pub fn can_be_null(&self) -> bool {
        self.types.iter().any(|t| match t {
            TAtomic::Null => true,
            TAtomic::Void => true,
            TAtomic::Mixed(mixed) if !mixed.is_non_null() => true,
            TAtomic::GenericParameter(param) => param.constraint.can_be_null(),
            _ => false,
        })
    }

    #[must_use]
    pub fn is_void(&self) -> bool {
        self.types.iter().all(|t| matches!(t, TAtomic::Void)) && !self.types.is_empty()
    }

    #[must_use]
    pub fn is_voidable(&self) -> bool {
        self.types.iter().any(|t| matches!(t, TAtomic::Void)) && !self.types.is_empty()
    }

    pub fn has_resource(&self) -> bool {
        self.types.iter().any(TAtomic::is_resource)
    }

    pub fn is_resource(&self) -> bool {
        self.types.iter().all(TAtomic::is_resource) && !self.types.is_empty()
    }

    pub fn is_array(&self) -> bool {
        self.types.iter().all(TAtomic::is_array) && !self.types.is_empty()
    }

    pub fn is_list(&self) -> bool {
        self.types.iter().all(TAtomic::is_list) && !self.types.is_empty()
    }

    pub fn is_vanilla_array(&self) -> bool {
        self.types.iter().all(TAtomic::is_vanilla_array) && !self.types.is_empty()
    }

    pub fn is_keyed_array(&self) -> bool {
        self.types.iter().all(TAtomic::is_keyed_array) && !self.types.is_empty()
    }

    pub fn is_falsable(&self) -> bool {
        self.types.len() >= 2 && self.types.iter().any(TAtomic::is_false)
    }

    #[must_use]
    pub fn has_bool(&self) -> bool {
        self.types.iter().any(|t| t.is_bool() || t.is_generic_scalar()) && !self.types.is_empty()
    }

    /// Checks if the union explicitly contains the generic `scalar` type.
    ///
    /// This is a specific check for the `scalar` type itself, not for a
    /// combination of types that would form a scalar (e.g., `int|string|bool|float`).
    /// For that, see `has_scalar_combination`.
    pub fn has_scalar(&self) -> bool {
        self.types.iter().any(TAtomic::is_generic_scalar)
    }

    /// Checks if the union contains a combination of types that is equivalent
    /// to the generic `scalar` type (i.e., contains `int`, `float`, `bool`, and `string`).
    #[must_use]
    pub fn has_scalar_combination(&self) -> bool {
        const HAS_INT: u8 = 1 << 0;
        const HAS_FLOAT: u8 = 1 << 1;
        const HAS_BOOL: u8 = 1 << 2;
        const HAS_STRING: u8 = 1 << 3;
        const ALL_SCALARS: u8 = HAS_INT | HAS_FLOAT | HAS_BOOL | HAS_STRING;

        let mut flags = 0u8;

        for atomic in self.types.as_ref() {
            if atomic.is_int() {
                flags |= HAS_INT;
            } else if atomic.is_float() {
                flags |= HAS_FLOAT;
            } else if atomic.is_bool() {
                flags |= HAS_BOOL;
            } else if atomic.is_string() {
                flags |= HAS_STRING;
            } else if atomic.is_array_key() {
                flags |= HAS_INT | HAS_STRING;
            } else if atomic.is_numeric() {
                // We don't add `string` as `numeric-string` does not contain `string` type
                flags |= HAS_INT | HAS_FLOAT;
            } else if atomic.is_generic_scalar() {
                return true;
            }

            // Early exit if we've already found all scalar types
            if flags == ALL_SCALARS {
                return true;
            }
        }

        flags == ALL_SCALARS
    }
    pub fn has_array_key(&self) -> bool {
        self.types.iter().any(TAtomic::is_array_key)
    }

    pub fn has_iterable(&self) -> bool {
        self.types.iter().any(TAtomic::is_iterable) && !self.types.is_empty()
    }

    pub fn has_array(&self) -> bool {
        self.types.iter().any(TAtomic::is_array) && !self.types.is_empty()
    }

    #[must_use]
    pub fn has_traversable(&self, codebase: &CodebaseMetadata) -> bool {
        self.types.iter().any(|atomic| atomic.is_traversable(codebase)) && !self.types.is_empty()
    }

    #[must_use]
    pub fn has_array_key_like(&self) -> bool {
        self.types.iter().any(|atomic| atomic.is_array_key() || atomic.is_int() || atomic.is_string())
    }

    pub fn has_numeric(&self) -> bool {
        self.types.iter().any(TAtomic::is_numeric) && !self.types.is_empty()
    }

    pub fn is_always_truthy(&self) -> bool {
        self.types.iter().all(TAtomic::is_truthy) && !self.types.is_empty()
    }

    pub fn is_always_falsy(&self) -> bool {
        self.types.iter().all(TAtomic::is_falsy) && !self.types.is_empty()
    }

    #[must_use]
    pub fn is_literal_of(&self, other: &TUnion) -> bool {
        let Some(other_atomic_type) = other.types.first() else {
            return false;
        };

        match other_atomic_type {
            TAtomic::Scalar(TScalar::String(_)) => {
                for self_atomic_type in self.types.as_ref() {
                    if self_atomic_type.is_string_of_literal_origin() {
                        continue;
                    }

                    return false;
                }

                true
            }
            TAtomic::Scalar(TScalar::Integer(_)) => {
                for self_atomic_type in self.types.as_ref() {
                    if self_atomic_type.is_literal_int() {
                        continue;
                    }

                    return false;
                }

                true
            }
            TAtomic::Scalar(TScalar::Float(_)) => {
                for self_atomic_type in self.types.as_ref() {
                    if self_atomic_type.is_literal_float() {
                        continue;
                    }

                    return false;
                }

                true
            }
            _ => false,
        }
    }

    #[must_use]
    pub fn all_literals(&self) -> bool {
        self.types
            .iter()
            .all(|atomic| atomic.is_string_of_literal_origin() || atomic.is_literal_int() || atomic.is_literal_float())
    }

    #[must_use]
    pub fn has_static_object(&self) -> bool {
        self.types
            .iter()
            .any(|atomic| matches!(atomic, TAtomic::Object(TObject::Named(named_object)) if named_object.is_static))
    }

    #[must_use]
    pub fn is_static_object(&self) -> bool {
        self.types
            .iter()
            .all(|atomic| matches!(atomic, TAtomic::Object(TObject::Named(named_object)) if named_object.is_static))
    }

    #[inline]
    #[must_use]
    pub fn is_single(&self) -> bool {
        self.types.len() == 1
    }

    #[inline]
    #[must_use]
    pub fn get_single_string(&self) -> Option<&TString> {
        if self.is_single()
            && let TAtomic::Scalar(TScalar::String(string)) = &self.types[0]
        {
            Some(string)
        } else {
            None
        }
    }

    #[inline]
    #[must_use]
    pub fn get_single_array(&self) -> Option<&TArray> {
        if self.is_single()
            && let TAtomic::Array(array) = &self.types[0]
        {
            Some(array)
        } else {
            None
        }
    }

    #[inline]
    #[must_use]
    pub fn get_single_bool(&self) -> Option<&TBool> {
        if self.is_single()
            && let TAtomic::Scalar(TScalar::Bool(bool)) = &self.types[0]
        {
            Some(bool)
        } else {
            None
        }
    }

    #[inline]
    #[must_use]
    pub fn get_single_named_object(&self) -> Option<&TNamedObject> {
        if self.is_single()
            && let TAtomic::Object(TObject::Named(named_object)) = &self.types[0]
        {
            Some(named_object)
        } else {
            None
        }
    }

    #[inline]
    #[must_use]
    pub fn get_single_shaped_object(&self) -> Option<&TObjectWithProperties> {
        if self.is_single()
            && let TAtomic::Object(TObject::WithProperties(shaped_object)) = &self.types[0]
        {
            Some(shaped_object)
        } else {
            None
        }
    }

    #[inline]
    #[must_use]
    pub fn get_single(&self) -> &TAtomic {
        &self.types[0]
    }

    #[inline]
    #[must_use]
    pub fn get_single_owned(self) -> TAtomic {
        self.types[0].clone()
    }

    #[inline]
    #[must_use]
    pub fn is_named_object(&self) -> bool {
        self.types.iter().all(|t| matches!(t, TAtomic::Object(TObject::Named(_))))
    }

    #[must_use]
    pub fn is_enum(&self) -> bool {
        self.types.iter().all(|t| matches!(t, TAtomic::Object(TObject::Enum(_))))
    }

    #[must_use]
    pub fn is_enum_case(&self) -> bool {
        self.types.iter().all(|t| matches!(t, TAtomic::Object(TObject::Enum(r#enum)) if r#enum.case.is_some()))
    }

    #[must_use]
    pub fn is_single_enum_case(&self) -> bool {
        self.is_single()
            && self.types.iter().all(|t| matches!(t, TAtomic::Object(TObject::Enum(r#enum)) if r#enum.case.is_some()))
    }

    #[inline]
    #[must_use]
    pub fn has_named_object(&self) -> bool {
        self.types.iter().any(|t| matches!(t, TAtomic::Object(TObject::Named(_))))
    }

    #[inline]
    #[must_use]
    pub fn has_object(&self) -> bool {
        self.types.iter().any(|t| matches!(t, TAtomic::Object(TObject::Any | TObject::WithProperties(_))))
    }

    #[inline]
    #[must_use]
    pub fn has_callable(&self) -> bool {
        self.types.iter().any(|t| matches!(t, TAtomic::Callable(_)))
    }

    #[inline]
    #[must_use]
    pub fn is_callable(&self) -> bool {
        self.types.iter().all(|t| matches!(t, TAtomic::Callable(_)))
    }

    #[inline]
    #[must_use]
    pub fn has_object_type(&self) -> bool {
        self.types.iter().any(|t| matches!(t, TAtomic::Object(_)))
    }

    /// Return a vector of pairs containing the enum name, and their case name
    /// if specified.
    #[must_use]
    pub fn get_enum_cases(&self) -> Vec<(Atom, Option<Atom>)> {
        self.types
            .iter()
            .filter_map(|t| match t {
                TAtomic::Object(TObject::Enum(enum_object)) => Some((enum_object.name, enum_object.case)),
                _ => None,
            })
            .collect()
    }

    #[must_use]
    pub fn get_single_int(&self) -> Option<TInteger> {
        if self.is_single() { self.get_single().get_integer() } else { None }
    }

    #[must_use]
    pub fn get_single_literal_int_value(&self) -> Option<i64> {
        if self.is_single() { self.get_single().get_literal_int_value() } else { None }
    }

    #[must_use]
    pub fn get_single_maximum_int_value(&self) -> Option<i64> {
        if self.is_single() { self.get_single().get_maximum_int_value() } else { None }
    }

    #[must_use]
    pub fn get_single_minimum_int_value(&self) -> Option<i64> {
        if self.is_single() { self.get_single().get_minimum_int_value() } else { None }
    }

    #[must_use]
    pub fn get_single_literal_float_value(&self) -> Option<f64> {
        if self.is_single() { self.get_single().get_literal_float_value() } else { None }
    }

    #[must_use]
    pub fn get_single_literal_string_value(&self) -> Option<&str> {
        if self.is_single() { self.get_single().get_literal_string_value() } else { None }
    }

    #[must_use]
    pub fn get_single_class_string_value(&self) -> Option<Atom> {
        if self.is_single() { self.get_single().get_class_string_value() } else { None }
    }

    #[must_use]
    pub fn get_single_array_key(&self) -> Option<ArrayKey> {
        if self.is_single() { self.get_single().to_array_key() } else { None }
    }

    #[must_use]
    pub fn get_single_key_of_array_like(&self) -> Option<TUnion> {
        if !self.is_single() {
            return None;
        }

        match self.get_single() {
            TAtomic::Array(array) => match array {
                TArray::List(_) => Some(get_int()),
                TArray::Keyed(keyed_array) => match &keyed_array.parameters {
                    Some((k, _)) => Some((**k).clone()),
                    None => Some(get_arraykey()),
                },
            },
            _ => None,
        }
    }

    #[must_use]
    pub fn get_single_value_of_array_like(&self) -> Option<Cow<'_, TUnion>> {
        if !self.is_single() {
            return None;
        }

        match self.get_single() {
            TAtomic::Array(array) => match array {
                TArray::List(list) => Some(Cow::Borrowed(&list.element_type)),
                TArray::Keyed(keyed_array) => match &keyed_array.parameters {
                    Some((_, v)) => Some(Cow::Borrowed(v)),
                    None => Some(Cow::Owned(get_mixed())),
                },
            },
            _ => None,
        }
    }

    #[must_use]
    pub fn get_literal_ints(&self) -> Vec<&TAtomic> {
        self.types.iter().filter(|a| a.is_literal_int()).collect()
    }

    #[must_use]
    pub fn get_literal_strings(&self) -> Vec<&TAtomic> {
        self.types.iter().filter(|a| a.is_known_literal_string()).collect()
    }

    #[must_use]
    pub fn get_literal_string_values(&self) -> Vec<Option<Atom>> {
        self.get_literal_strings()
            .into_iter()
            .map(|atom| match atom {
                TAtomic::Scalar(TScalar::String(TString { literal: Some(TStringLiteral::Value(value)), .. })) => {
                    Some(*value)
                }
                _ => None,
            })
            .collect()
    }

    #[must_use]
    pub fn has_literal_float(&self) -> bool {
        self.types.iter().any(|atomic| match atomic {
            TAtomic::Scalar(scalar) => scalar.is_literal_float(),
            _ => false,
        })
    }

    #[must_use]
    pub fn has_literal_int(&self) -> bool {
        self.types.iter().any(|atomic| match atomic {
            TAtomic::Scalar(scalar) => scalar.is_literal_int(),
            _ => false,
        })
    }

    #[must_use]
    pub fn has_literal_string(&self) -> bool {
        self.types.iter().any(|atomic| match atomic {
            TAtomic::Scalar(scalar) => scalar.is_known_literal_string(),
            _ => false,
        })
    }

    #[must_use]
    pub fn has_literal_value(&self) -> bool {
        self.types.iter().any(|atomic| match atomic {
            TAtomic::Scalar(scalar) => scalar.is_literal_value(),
            _ => false,
        })
    }

    #[must_use]
    pub fn accepts_false(&self) -> bool {
        self.types.iter().any(|t| match t {
            TAtomic::GenericParameter(parameter) => parameter.constraint.accepts_false(),
            TAtomic::Mixed(mixed) if !mixed.is_truthy() => true,
            TAtomic::Scalar(TScalar::Generic | TScalar::Bool(TBool { value: None | Some(false) })) => true,
            _ => false,
        })
    }

    #[must_use]
    pub fn accepts_null(&self) -> bool {
        self.types.iter().any(|t| match t {
            TAtomic::GenericParameter(generic_parameter) => generic_parameter.constraint.accepts_null(),
            TAtomic::Mixed(mixed) if !mixed.is_non_null() => true,
            TAtomic::Null | TAtomic::Placeholder => true,
            _ => false,
        })
    }
}

impl TType for TUnion {
    fn get_child_nodes(&self) -> Vec<TypeRef<'_>> {
        self.types.iter().map(TypeRef::Atomic).collect()
    }

    fn needs_population(&self) -> bool {
        !self.flags.contains(UnionFlags::POPULATED) && self.types.iter().any(super::TType::needs_population)
    }

    fn is_expandable(&self) -> bool {
        if self.types.is_empty() {
            return true;
        }

        self.types.iter().any(super::TType::is_expandable)
    }

    fn is_complex(&self) -> bool {
        self.types.len() > 3 || self.types.iter().any(super::TType::is_complex)
    }

    fn get_id(&self) -> Atom {
        let len = self.types.len();

        let mut atomic_ids: Vec<Atom> = self
            .types
            .as_ref()
            .iter()
            .map(|atomic| {
                let id = atomic.get_id();
                if atomic.is_generic_parameter() || atomic.has_intersection_types() && len > 1 {
                    concat_atom!("(", id.as_str(), ")")
                } else {
                    id
                }
            })
            .collect();

        if len <= 1 {
            return atomic_ids.pop().unwrap_or_else(empty_atom);
        }

        atomic_ids.sort_unstable();
        let mut result = atomic_ids[0];
        for id in &atomic_ids[1..] {
            result = concat_atom!(result.as_str(), "|", id.as_str());
        }

        result
    }

    fn get_pretty_id_with_indent(&self, indent: usize) -> Atom {
        let len = self.types.len();

        if len <= 1 {
            return self.types.first().map_or_else(empty_atom, |atomic| atomic.get_pretty_id_with_indent(indent));
        }

        // Use multiline format for unions with more than 3 types
        if len > 3 {
            let mut atomic_ids: Vec<Atom> = self
                .types
                .as_ref()
                .iter()
                .map(|atomic| {
                    let id = atomic.get_pretty_id_with_indent(indent + 2);
                    if atomic.has_intersection_types() { concat_atom!("(", id.as_str(), ")") } else { id }
                })
                .collect();

            atomic_ids.sort_unstable();

            let mut result = String::new();
            result += &atomic_ids[0];
            for id in &atomic_ids[1..] {
                result += "\n";
                result += &" ".repeat(indent);
                result += "| ";
                result += id.as_str();
            }

            atom(&result)
        } else {
            // Use inline format for smaller unions
            let mut atomic_ids: Vec<Atom> = self
                .types
                .as_ref()
                .iter()
                .map(|atomic| {
                    let id = atomic.get_pretty_id_with_indent(indent);
                    if atomic.has_intersection_types() && len > 1 { concat_atom!("(", id.as_str(), ")") } else { id }
                })
                .collect();

            atomic_ids.sort_unstable();
            let mut result = atomic_ids[0];
            for id in &atomic_ids[1..] {
                result = concat_atom!(result.as_str(), " | ", id.as_str());
            }

            result
        }
    }
}

impl PartialEq for TUnion {
    fn eq(&self, other: &TUnion) -> bool {
        if std::ptr::eq(self, other) {
            return true;
        }

        const SEMANTIC_FLAGS: UnionFlags = UnionFlags::HAD_TEMPLATE
            .union(UnionFlags::BY_REFERENCE)
            .union(UnionFlags::REFERENCE_FREE)
            .union(UnionFlags::POSSIBLY_UNDEFINED_FROM_TRY)
            .union(UnionFlags::POSSIBLY_UNDEFINED)
            .union(UnionFlags::IGNORE_NULLABLE_ISSUES)
            .union(UnionFlags::IGNORE_FALSABLE_ISSUES)
            .union(UnionFlags::FROM_TEMPLATE_DEFAULT);

        if self.flags.intersection(SEMANTIC_FLAGS) != other.flags.intersection(SEMANTIC_FLAGS) {
            return false;
        }

        let len = self.types.len();
        if len != other.types.len() {
            return false;
        }

        // Fast path: unions are commonly constructed in stable type order.
        // When order already matches, this keeps comparison linear.
        if self.types == other.types {
            return true;
        }

        // Check self ⊆ other
        for i in 0..len {
            let mut has_match = false;
            for j in 0..len {
                if self.types[i] == other.types[j] {
                    has_match = true;
                    break;
                }
            }

            if !has_match {
                return false;
            }
        }

        // Check other ⊆ self (needed when duplicates exist in either side)
        for i in 0..len {
            let mut has_match = false;
            for j in 0..len {
                if other.types[i] == self.types[j] {
                    has_match = true;
                    break;
                }
            }

            if !has_match {
                return false;
            }
        }

        true
    }
}

pub fn populate_union_type(
    unpopulated_union: &mut TUnion,
    codebase_symbols: &Symbols,
    reference_source: Option<&ReferenceSource>,
    symbol_references: &mut SymbolReferences,
    force: bool,
) {
    if unpopulated_union.flags.contains(UnionFlags::POPULATED) && !force {
        return;
    }

    if !unpopulated_union.needs_population() {
        return;
    }

    unpopulated_union.flags.insert(UnionFlags::POPULATED);
    let unpopulated_atomics = unpopulated_union.types.to_mut();
    for unpopulated_atomic in unpopulated_atomics {
        match unpopulated_atomic {
            TAtomic::Scalar(TScalar::ClassLikeString(
                TClassLikeString::Generic { constraint, .. } | TClassLikeString::OfType { constraint, .. },
            )) => {
                populate_atomic_type(
                    Arc::make_mut(constraint),
                    codebase_symbols,
                    reference_source,
                    symbol_references,
                    force,
                );
            }
            _ => {
                populate_atomic_type(unpopulated_atomic, codebase_symbols, reference_source, symbol_references, force);
            }
        }
    }
}