Skip to main content

mago_codex/ttype/
combiner.rs

1use std::collections::BTreeMap;
2use std::sync::Arc;
3use std::sync::LazyLock;
4
5use foldhash::HashSet;
6
7use mago_atom::Atom;
8use mago_atom::AtomSet;
9use mago_atom::atom;
10
11static ATOM_FALSE: LazyLock<Atom> = LazyLock::new(|| atom("false"));
12static ATOM_TRUE: LazyLock<Atom> = LazyLock::new(|| atom("true"));
13static ATOM_BOOL: LazyLock<Atom> = LazyLock::new(|| atom("bool"));
14static ATOM_VOID: LazyLock<Atom> = LazyLock::new(|| atom("void"));
15static ATOM_NULL: LazyLock<Atom> = LazyLock::new(|| atom("null"));
16static ATOM_STRING: LazyLock<Atom> = LazyLock::new(|| atom("string"));
17static ATOM_FLOAT: LazyLock<Atom> = LazyLock::new(|| atom("float"));
18static ATOM_INT: LazyLock<Atom> = LazyLock::new(|| atom("int"));
19static ATOM_MIXED: LazyLock<Atom> = LazyLock::new(|| atom("mixed"));
20static ATOM_SCALAR: LazyLock<Atom> = LazyLock::new(|| atom("scalar"));
21static ATOM_ARRAY_KEY: LazyLock<Atom> = LazyLock::new(|| atom("array-key"));
22static ATOM_NUMERIC: LazyLock<Atom> = LazyLock::new(|| atom("numeric"));
23static ATOM_NEVER: LazyLock<Atom> = LazyLock::new(|| atom("never"));
24
25use crate::metadata::CodebaseMetadata;
26use crate::symbol::SymbolKind;
27use crate::ttype::TType;
28use crate::ttype::atomic::TAtomic;
29use crate::ttype::atomic::array::TArray;
30use crate::ttype::atomic::array::key::ArrayKey;
31use crate::ttype::atomic::array::keyed::TKeyedArray;
32use crate::ttype::atomic::array::list::TList;
33use crate::ttype::atomic::mixed::TMixed;
34use crate::ttype::atomic::mixed::truthiness::TMixedTruthiness;
35use crate::ttype::atomic::object::TObject;
36use crate::ttype::atomic::object::named::TNamedObject;
37use crate::ttype::atomic::resource::TResource;
38use crate::ttype::atomic::scalar::TScalar;
39use crate::ttype::atomic::scalar::float::TFloat;
40use crate::ttype::atomic::scalar::int::TInteger;
41use crate::ttype::atomic::scalar::string::TString;
42use crate::ttype::atomic::scalar::string::TStringCasing;
43use crate::ttype::atomic::scalar::string::TStringLiteral;
44use crate::ttype::combination::CombinationFlags;
45use crate::ttype::combination::TypeCombination;
46use crate::ttype::combine_union_types;
47use crate::ttype::comparator::ComparisonResult;
48use crate::ttype::comparator::array_comparator::is_array_contained_by_array;
49use crate::ttype::comparator::object_comparator;
50use crate::ttype::comparator::union_comparator;
51use crate::ttype::template::variance::Variance;
52use crate::ttype::union::TUnion;
53use crate::utils::str_is_numeric;
54
55/// Default maximum number of sealed arrays to track before generalizing.
56///
57/// When combining array types, sealed arrays (arrays with known literal elements)
58/// are accumulated for later comparison. If the number of sealed arrays exceeds
59/// this threshold, they are immediately generalized to prevent O(n²) complexity
60/// in `finalize_sealed_arrays` and excessive memory usage.
61pub const DEFAULT_ARRAY_COMBINATION_THRESHOLD: u16 = 32;
62
63/// Default maximum number of literal strings to track before generalizing to string.
64///
65/// When combining types with many different literal string values, tracking each
66/// literal individually causes O(n) memory and O(n²) comparison time.
67/// Once the threshold is exceeded, we generalize to the base string type.
68pub const DEFAULT_STRING_COMBINATION_THRESHOLD: u16 = 128;
69
70/// Default maximum number of literal integers to track before generalizing to int.
71///
72/// When combining types with many different literal integer values, tracking each
73/// literal individually causes O(n) memory and O(n²) comparison time.
74/// Once the threshold is exceeded, we generalize to the base int type.
75pub const DEFAULT_INTEGER_COMBINATION_THRESHOLD: u16 = 128;
76
77/// Options for controlling type combination behavior.
78#[derive(Debug, Clone, Copy, PartialEq, Eq)]
79pub struct CombinerOptions {
80    /// When true, empty arrays are overwritten by non-empty arrays during combination.
81    pub overwrite_empty_array: bool,
82    /// Maximum number of sealed arrays to track before generalizing.
83    pub array_combination_threshold: u16,
84    /// Maximum number of literal strings to track before generalizing to string.
85    pub string_combination_threshold: u16,
86    /// Maximum number of literal integers to track before generalizing to int.
87    pub integer_combination_threshold: u16,
88}
89
90impl Default for CombinerOptions {
91    fn default() -> Self {
92        Self {
93            overwrite_empty_array: false,
94            array_combination_threshold: DEFAULT_ARRAY_COMBINATION_THRESHOLD,
95            string_combination_threshold: DEFAULT_STRING_COMBINATION_THRESHOLD,
96            integer_combination_threshold: DEFAULT_INTEGER_COMBINATION_THRESHOLD,
97        }
98    }
99}
100
101impl CombinerOptions {
102    /// Create options with overwrite_empty_array set to true.
103    #[inline]
104    #[must_use]
105    pub fn with_overwrite_empty_array(mut self) -> Self {
106        self.overwrite_empty_array = true;
107        self
108    }
109
110    /// Create options with a custom array combination threshold.
111    #[inline]
112    #[must_use]
113    pub fn with_array_combination_threshold(mut self, threshold: u16) -> Self {
114        self.array_combination_threshold = threshold;
115        self
116    }
117
118    /// Create options with a custom string combination threshold.
119    #[inline]
120    #[must_use]
121    pub fn with_string_combination_threshold(mut self, threshold: u16) -> Self {
122        self.string_combination_threshold = threshold;
123        self
124    }
125
126    /// Create options with a custom integer combination threshold.
127    #[inline]
128    #[must_use]
129    pub fn with_integer_combination_threshold(mut self, threshold: u16) -> Self {
130        self.integer_combination_threshold = threshold;
131        self
132    }
133}
134
135pub fn combine(types: Vec<TAtomic>, codebase: &CodebaseMetadata, options: CombinerOptions) -> Vec<TAtomic> {
136    if types.is_empty() {
137        debug_assert!(false, "combine() received an empty Vec; this is a caller bug");
138
139        return vec![TAtomic::Never];
140    }
141
142    if types.len() == 1 {
143        return types;
144    }
145
146    let mut combination = TypeCombination::new();
147
148    for atomic in types {
149        if let TAtomic::Derived(derived) = atomic {
150            combination.derived_types.insert(derived);
151            continue;
152        }
153
154        scrape_type_properties(atomic, &mut combination, codebase, options);
155    }
156
157    combination.integers.sort_unstable();
158    combination.integers.dedup();
159    combination.literal_floats.sort_unstable();
160    combination.literal_floats.dedup();
161
162    finalize_sealed_arrays(&mut combination.sealed_arrays, codebase);
163
164    let is_falsy_mixed = combination.flags.falsy_mixed().unwrap_or(false);
165    let is_truthy_mixed = combination.flags.truthy_mixed().unwrap_or(false);
166    let is_nonnull_mixed = combination.flags.nonnull_mixed().unwrap_or(false);
167
168    if is_falsy_mixed
169        || is_nonnull_mixed
170        || combination.flags.contains(CombinationFlags::GENERIC_MIXED)
171        || is_truthy_mixed
172    {
173        return vec![TAtomic::Mixed(TMixed::new().with_is_non_null(is_nonnull_mixed).with_truthiness(
174            if is_truthy_mixed && !is_falsy_mixed {
175                TMixedTruthiness::Truthy
176            } else if is_falsy_mixed && !is_truthy_mixed {
177                TMixedTruthiness::Falsy
178            } else {
179                TMixedTruthiness::Undetermined
180            },
181        ))];
182    } else if combination.flags.contains(CombinationFlags::HAS_MIXED) {
183        return vec![TAtomic::Mixed(TMixed::new())];
184    }
185
186    if combination.is_simple() {
187        if combination.value_types.contains_key(&*ATOM_FALSE) {
188            return vec![TAtomic::Scalar(TScalar::r#false())];
189        }
190
191        if combination.value_types.contains_key(&*ATOM_TRUE) {
192            return vec![TAtomic::Scalar(TScalar::r#true())];
193        }
194
195        return combination.value_types.into_values().collect();
196    }
197
198    if combination.value_types.remove(&*ATOM_VOID).is_some() && combination.value_types.contains_key(&*ATOM_NULL) {
199        combination.value_types.insert(*ATOM_NULL, TAtomic::Null);
200    }
201
202    if combination.value_types.contains_key(&*ATOM_FALSE) && combination.value_types.contains_key(&*ATOM_TRUE) {
203        combination.value_types.remove(&*ATOM_FALSE);
204        combination.value_types.remove(&*ATOM_TRUE);
205        combination.value_types.insert(*ATOM_BOOL, TAtomic::Scalar(TScalar::bool()));
206    }
207
208    let estimated_capacity = combination.derived_types.len()
209        + combination.integers.len().min(10)
210        + combination.literal_floats.len()
211        + combination.enum_names.len()
212        + combination.value_types.len()
213        + combination.sealed_arrays.len()
214        + 5;
215
216    let mut new_types = Vec::with_capacity(estimated_capacity);
217    for derived_type in combination.derived_types {
218        new_types.push(TAtomic::Derived(derived_type));
219    }
220
221    if combination.flags.contains(CombinationFlags::RESOURCE) {
222        new_types.push(TAtomic::Resource(TResource { closed: None }));
223    } else {
224        let open = combination.flags.contains(CombinationFlags::OPEN_RESOURCE);
225        let closed = combination.flags.contains(CombinationFlags::CLOSED_RESOURCE);
226        match (open, closed) {
227            (true, true) => {
228                new_types.push(TAtomic::Resource(TResource { closed: None }));
229            }
230            (true, false) => {
231                new_types.push(TAtomic::Resource(TResource { closed: Some(false) }));
232            }
233            (false, true) => {
234                new_types.push(TAtomic::Resource(TResource { closed: Some(true) }));
235            }
236            _ => {
237                // No resource type, do nothing
238            }
239        }
240    }
241
242    let mut arrays = vec![];
243
244    if combination.flags.contains(CombinationFlags::HAS_KEYED_ARRAY) {
245        arrays.push(TArray::Keyed(TKeyedArray {
246            known_items: if combination.keyed_array_entries.is_empty() {
247                None
248            } else {
249                Some(combination.keyed_array_entries)
250            },
251            parameters: if let Some((k, v)) = combination.keyed_array_parameters {
252                Some((Arc::new(k), Arc::new(v)))
253            } else {
254                None
255            },
256            non_empty: combination.flags.contains(CombinationFlags::KEYED_ARRAY_ALWAYS_FILLED),
257        }));
258    }
259
260    if let Some(list_parameter) = combination.list_array_parameter {
261        arrays.push(TArray::List(TList {
262            known_elements: if combination.list_array_entries.is_empty() {
263                None
264            } else {
265                Some(combination.list_array_entries)
266            },
267            element_type: Arc::new(list_parameter),
268            non_empty: combination.flags.contains(CombinationFlags::LIST_ARRAY_ALWAYS_FILLED),
269            known_count: None,
270        }));
271    }
272
273    for array in combination.sealed_arrays {
274        arrays.push(array);
275    }
276
277    if arrays.is_empty() && combination.flags.contains(CombinationFlags::HAS_EMPTY_ARRAY) {
278        arrays.push(TArray::Keyed(TKeyedArray { known_items: None, parameters: None, non_empty: false }));
279    }
280
281    new_types.extend(arrays.into_iter().map(TAtomic::Array));
282
283    for (_, (generic_type, generic_type_parameters)) in combination.object_type_params {
284        let generic_object = TAtomic::Object(TObject::Named(
285            TNamedObject::new(generic_type)
286                .with_is_static(*combination.object_static.get(&generic_type).unwrap_or(&false))
287                .with_type_parameters(Some(generic_type_parameters)),
288        ));
289
290        new_types.push(generic_object);
291    }
292
293    new_types.extend(combination.literal_strings.into_iter().map(|s| TAtomic::Scalar(TScalar::literal_string(s))));
294
295    if combination.value_types.contains_key(&*ATOM_STRING)
296        && combination.value_types.contains_key(&*ATOM_FLOAT)
297        && combination.value_types.contains_key(&*ATOM_BOOL)
298        && combination.integers.iter().any(super::atomic::scalar::int::TInteger::is_unspecified)
299    {
300        combination.integers.clear();
301        combination.value_types.remove(&*ATOM_STRING);
302        combination.value_types.remove(&*ATOM_FLOAT);
303        combination.value_types.remove(&*ATOM_BOOL);
304
305        new_types.push(TAtomic::Scalar(TScalar::Generic));
306    }
307
308    new_types.extend(TInteger::combine(combination.integers));
309    new_types.extend(combination.literal_floats.into_iter().map(|f| TAtomic::Scalar(TScalar::literal_float(f.into()))));
310
311    for (enum_name, enum_case) in combination.enum_names {
312        if combination.value_types.contains_key(&enum_name) {
313            continue;
314        }
315
316        let enum_object = match enum_case {
317            Some(case) => TAtomic::Object(TObject::new_enum_case(enum_name, case)),
318            None => TAtomic::Object(TObject::new_enum(enum_name)),
319        };
320
321        combination.value_types.insert(enum_object.get_id(), enum_object);
322    }
323
324    let mut has_never = combination.value_types.contains_key(&*ATOM_NEVER);
325
326    let combination_value_type_count = combination.value_types.len();
327    let mixed_from_loop_isset = combination.flags.mixed_from_loop_isset().unwrap_or(false);
328
329    for (_, atomic) in combination.value_types {
330        let tc = usize::from(has_never);
331        if atomic.is_mixed()
332            && mixed_from_loop_isset
333            && (combination_value_type_count > (tc + 1) || new_types.len() > tc)
334        {
335            continue;
336        }
337
338        if (atomic.is_never() || atomic.is_templated_as_never())
339            && (combination_value_type_count > 1 || !new_types.is_empty())
340        {
341            has_never = true;
342            continue;
343        }
344
345        new_types.push(atomic);
346    }
347
348    if new_types.is_empty() {
349        debug_assert!(has_never, "combine(): empty result without a `never` atomic in the combination");
350
351        return vec![TAtomic::Never];
352    }
353
354    new_types
355}
356
357fn finalize_sealed_arrays(arrays: &mut Vec<TArray>, codebase: &CodebaseMetadata) {
358    if arrays.len() <= 1 {
359        return;
360    }
361
362    arrays.sort_unstable_by_key(|a| match a {
363        TArray::List(list) => list.known_elements.as_ref().map_or(0, std::collections::BTreeMap::len),
364        TArray::Keyed(keyed) => keyed.known_items.as_ref().map_or(0, std::collections::BTreeMap::len),
365    });
366
367    let mut keep = vec![true; arrays.len()];
368
369    for i in 0..arrays.len() {
370        if !keep[i] {
371            continue;
372        }
373
374        for j in (i + 1)..arrays.len() {
375            if !keep[j] {
376                continue;
377            }
378
379            if is_array_contained_by_array(codebase, &arrays[i], &arrays[j], false, &mut ComparisonResult::new()) {
380                keep[i] = false;
381                break;
382            }
383
384            if is_array_contained_by_array(codebase, &arrays[j], &arrays[i], false, &mut ComparisonResult::new()) {
385                keep[j] = false;
386            }
387        }
388    }
389
390    let mut write = 0;
391    for (read, item) in keep.iter().enumerate().take(arrays.len()) {
392        if *item {
393            if write != read {
394                arrays.swap(write, read);
395            }
396
397            write += 1;
398        }
399    }
400
401    arrays.truncate(write);
402}
403
404fn scrape_type_properties(
405    atomic: TAtomic,
406    combination: &mut TypeCombination,
407    codebase: &CodebaseMetadata,
408    options: CombinerOptions,
409) {
410    if combination.flags.contains(CombinationFlags::GENERIC_MIXED) {
411        return;
412    }
413
414    if let TAtomic::Mixed(mixed) = atomic {
415        if mixed.is_isset_from_loop() {
416            if combination.flags.contains(CombinationFlags::GENERIC_MIXED) {
417                return; // Exit early, existing state is sufficient or broader
418            }
419
420            if combination.flags.mixed_from_loop_isset().is_none() {
421                combination.flags.set_mixed_from_loop_isset(Some(true));
422            }
423
424            combination.value_types.insert(*ATOM_MIXED, atomic);
425
426            return;
427        }
428
429        combination.flags.insert(CombinationFlags::HAS_MIXED);
430
431        if mixed.is_vanilla() {
432            combination.flags.set_falsy_mixed(Some(false));
433            combination.flags.set_truthy_mixed(Some(false));
434            combination.flags.set_mixed_from_loop_isset(Some(false));
435            combination.flags.insert(CombinationFlags::GENERIC_MIXED);
436
437            return;
438        }
439
440        if mixed.is_truthy() {
441            if combination.flags.contains(CombinationFlags::GENERIC_MIXED) {
442                return;
443            }
444
445            combination.flags.set_mixed_from_loop_isset(Some(false));
446
447            if combination.flags.falsy_mixed().unwrap_or(false) {
448                combination.flags.insert(CombinationFlags::GENERIC_MIXED);
449                combination.flags.set_falsy_mixed(Some(false));
450                return;
451            }
452
453            if combination.flags.truthy_mixed().is_some() {
454                return;
455            }
456
457            let has_non_truthy = combination.value_types.values().any(|v| !v.is_truthy())
458                || combination.literal_strings.iter().any(|s| s.is_empty() || s.as_str() == "0");
459
460            if has_non_truthy {
461                combination.flags.insert(CombinationFlags::GENERIC_MIXED);
462                return;
463            }
464
465            combination.flags.set_truthy_mixed(Some(true));
466        } else {
467            combination.flags.set_truthy_mixed(Some(false));
468        }
469
470        if mixed.is_falsy() {
471            if combination.flags.contains(CombinationFlags::GENERIC_MIXED) {
472                return;
473            }
474
475            combination.flags.set_mixed_from_loop_isset(Some(false));
476
477            if combination.flags.truthy_mixed().unwrap_or(false) {
478                combination.flags.insert(CombinationFlags::GENERIC_MIXED);
479                combination.flags.set_truthy_mixed(Some(false));
480                return;
481            }
482
483            if combination.flags.falsy_mixed().is_some() {
484                return;
485            }
486
487            let has_non_falsy = combination.value_types.values().any(|v| !v.is_falsy())
488                || combination.literal_strings.iter().any(|s| !s.is_empty() && s.as_str() != "0");
489
490            if has_non_falsy {
491                combination.flags.insert(CombinationFlags::GENERIC_MIXED);
492                return;
493            }
494
495            combination.flags.set_falsy_mixed(Some(true));
496        } else {
497            combination.flags.set_falsy_mixed(Some(false));
498        }
499
500        if mixed.is_non_null() {
501            if combination.flags.contains(CombinationFlags::GENERIC_MIXED) {
502                return;
503            }
504
505            combination.flags.set_mixed_from_loop_isset(Some(false));
506
507            if combination.value_types.contains_key(&*ATOM_NULL) {
508                combination.flags.insert(CombinationFlags::GENERIC_MIXED);
509                return;
510            }
511
512            if combination.flags.falsy_mixed().unwrap_or(false) {
513                combination.flags.set_falsy_mixed(Some(false));
514                combination.flags.insert(CombinationFlags::GENERIC_MIXED);
515                return;
516            }
517
518            if combination.flags.nonnull_mixed().is_some() {
519                return;
520            }
521
522            combination.flags.set_mixed_from_loop_isset(Some(false));
523            combination.flags.set_nonnull_mixed(Some(true));
524        } else {
525            combination.flags.set_nonnull_mixed(Some(false));
526        }
527
528        return;
529    }
530
531    if combination.flags.falsy_mixed().unwrap_or(false) {
532        if !atomic.is_falsy() {
533            combination.flags.set_falsy_mixed(Some(false));
534            combination.flags.insert(CombinationFlags::GENERIC_MIXED);
535        }
536
537        return;
538    }
539
540    if combination.flags.truthy_mixed().unwrap_or(false) {
541        if !atomic.is_truthy() {
542            combination.flags.set_truthy_mixed(Some(false));
543            combination.flags.insert(CombinationFlags::GENERIC_MIXED);
544        }
545
546        return;
547    }
548
549    if combination.flags.nonnull_mixed().unwrap_or(false) {
550        if let TAtomic::Null = atomic {
551            combination.flags.set_nonnull_mixed(Some(false));
552            combination.flags.insert(CombinationFlags::GENERIC_MIXED);
553        }
554
555        return;
556    }
557
558    if combination.flags.contains(CombinationFlags::HAS_MIXED) {
559        return;
560    }
561
562    if matches!(&atomic, TAtomic::Scalar(TScalar::Bool(bool)) if !bool.is_general())
563        && combination.value_types.contains_key(&*ATOM_BOOL)
564    {
565        return;
566    }
567
568    if let TAtomic::Resource(TResource { closed }) = atomic {
569        match closed {
570            Some(closed) => {
571                if closed {
572                    combination.flags.insert(CombinationFlags::CLOSED_RESOURCE);
573                } else {
574                    combination.flags.insert(CombinationFlags::OPEN_RESOURCE);
575                }
576            }
577            None => {
578                combination.flags.insert(CombinationFlags::RESOURCE);
579            }
580        }
581
582        return;
583    }
584
585    if matches!(&atomic, TAtomic::Scalar(TScalar::Bool(bool)) if bool.is_general()) {
586        combination.value_types.remove(&*ATOM_FALSE);
587        combination.value_types.remove(&*ATOM_TRUE);
588    }
589
590    if let TAtomic::Array(array) = atomic {
591        if options.overwrite_empty_array && array.is_empty() {
592            combination.flags.insert(CombinationFlags::HAS_EMPTY_ARRAY);
593
594            return;
595        }
596
597        // Accumulate sealed arrays for later comparison, but only up to a threshold.
598        // Once we exceed the threshold, we let the arrays fall through to be processed
599        // immediately, which generalizes them and prevents O(n²) complexity.
600        if !array.is_empty()
601            && array.is_sealed()
602            && combination.list_array_parameter.is_some()
603            && !combination.flags.contains(CombinationFlags::HAS_KEYED_ARRAY)
604            && combination.sealed_arrays.len() < options.array_combination_threshold as usize
605        {
606            combination.sealed_arrays.push(array);
607            return;
608        }
609
610        let mut sealed_arrays = vec![];
611        std::mem::swap(&mut sealed_arrays, &mut combination.sealed_arrays);
612        for array in std::iter::once(array).chain(sealed_arrays) {
613            match array {
614                TArray::List(TList { element_type, known_elements, non_empty, known_count }) => {
615                    if non_empty {
616                        if let Some(ref mut existing_counts) = combination.list_array_counts {
617                            if let Some(known_count) = known_count {
618                                existing_counts.insert(known_count);
619                            } else {
620                                combination.list_array_counts = None;
621                            }
622                        }
623
624                        combination.flags.insert(CombinationFlags::LIST_ARRAY_SOMETIMES_FILLED);
625                    } else {
626                        combination.flags.remove(CombinationFlags::LIST_ARRAY_ALWAYS_FILLED);
627                    }
628
629                    if let Some(known_elements) = known_elements {
630                        let mut has_defined_keys = false;
631
632                        for (candidate_element_index, (candidate_optional, candidate_element_type)) in known_elements {
633                            let existing_entry = combination.list_array_entries.get(&candidate_element_index);
634
635                            let new_entry = if let Some((existing_optional, existing_type)) = existing_entry {
636                                (
637                                    *existing_optional || candidate_optional,
638                                    combine_union_types(existing_type, &candidate_element_type, codebase, options),
639                                )
640                            } else {
641                                (
642                                    candidate_optional,
643                                    if let Some(ref mut existing_value_parameter) = combination.list_array_parameter {
644                                        if !existing_value_parameter.is_never() {
645                                            *existing_value_parameter = combine_union_types(
646                                                existing_value_parameter,
647                                                &candidate_element_type,
648                                                codebase,
649                                                options,
650                                            );
651
652                                            if !candidate_optional {
653                                                has_defined_keys = true;
654                                            }
655
656                                            continue;
657                                        }
658
659                                        candidate_element_type
660                                    } else {
661                                        candidate_element_type
662                                    },
663                                )
664                            };
665
666                            combination.list_array_entries.insert(candidate_element_index, new_entry);
667
668                            if !candidate_optional {
669                                has_defined_keys = true;
670                            }
671                        }
672
673                        if !has_defined_keys {
674                            combination.flags.remove(CombinationFlags::LIST_ARRAY_ALWAYS_FILLED);
675                        }
676                    } else if !options.overwrite_empty_array {
677                        if element_type.is_never() {
678                            for (pu, _) in combination.list_array_entries.values_mut() {
679                                *pu = true;
680                            }
681                        } else {
682                            for (_, entry_type) in combination.list_array_entries.values() {
683                                if let Some(ref mut existing_value_param) = combination.list_array_parameter {
684                                    *existing_value_param =
685                                        combine_union_types(existing_value_param, entry_type, codebase, options);
686                                }
687                            }
688
689                            combination.list_array_entries.clear();
690                        }
691                    }
692
693                    combination.list_array_parameter = if let Some(ref existing_type) = combination.list_array_parameter
694                    {
695                        Some(combine_union_types(existing_type, &element_type, codebase, options))
696                    } else {
697                        Some((*element_type).clone())
698                    };
699                }
700                TArray::Keyed(TKeyedArray { parameters, known_items, non_empty, .. }) => {
701                    let mut had_previous_keyed_array = combination.flags.contains(CombinationFlags::HAS_KEYED_ARRAY);
702                    let sealed_budget_available = !combination.sealed_keyed_budget_exhausted
703                        && combination.sealed_arrays.len() < options.array_combination_threshold as usize;
704
705                    if !sealed_budget_available
706                        && !combination.sealed_keyed_budget_exhausted
707                        && !combination.sealed_arrays.is_empty()
708                    {
709                        flush_sealed_keyed_arrays_into_combination(combination, codebase, options);
710                        combination.sealed_keyed_budget_exhausted = true;
711                        had_previous_keyed_array = combination.flags.contains(CombinationFlags::HAS_KEYED_ARRAY);
712                    }
713
714                    if had_previous_keyed_array && sealed_budget_available {
715                        let incoming_is_sealed = parameters.is_none();
716                        let existing_is_sealed = combination.keyed_array_parameters.is_none();
717
718                        if incoming_is_sealed && !existing_is_sealed && known_items.is_some() {
719                            let known_items = widen_known_items_with_params(
720                                known_items,
721                                &combination.keyed_array_parameters,
722                                &combination.keyed_array_entries,
723                                codebase,
724                                options,
725                            );
726
727                            combination.sealed_arrays.push(TArray::Keyed(TKeyedArray {
728                                known_items,
729                                parameters,
730                                non_empty,
731                            }));
732
733                            continue;
734                        }
735
736                        if !incoming_is_sealed && existing_is_sealed && !combination.keyed_array_entries.is_empty() {
737                            let mut frozen_entries = std::mem::take(&mut combination.keyed_array_entries);
738                            if let Some((ref key_param, ref value_param)) = parameters {
739                                for (key, (_, entry_type)) in frozen_entries.iter_mut() {
740                                    // If the incoming unsealed array also declares this key as a
741                                    // known item, the caller is saying this key is exactly the
742                                    // declared type - the generic value_param catch-all covers
743                                    // *other* keys only. Widening here would turn e.g.
744                                    // `array{count: int, id: int}` + `array{count: int, ...<string, mixed>}`
745                                    // into `array{count: mixed, id: mixed}`, which is a false loss.
746                                    if known_items.as_ref().is_some_and(|ki| ki.contains_key(key)) {
747                                        continue;
748                                    }
749
750                                    let key_type = TUnion::from_atomic(key.to_atomic());
751
752                                    if union_comparator::can_expression_types_be_identical(
753                                        codebase, &key_type, key_param, false, false,
754                                    ) {
755                                        *entry_type = combine_union_types(entry_type, value_param, codebase, options);
756                                    }
757                                }
758                            }
759
760                            let frozen = TArray::Keyed(TKeyedArray {
761                                known_items: Some(frozen_entries),
762                                parameters: None,
763                                non_empty: combination.flags.contains(CombinationFlags::KEYED_ARRAY_SOMETIMES_FILLED),
764                            });
765                            combination.sealed_arrays.push(frozen);
766                            combination.flags.remove(CombinationFlags::HAS_KEYED_ARRAY);
767                            combination.flags.remove(CombinationFlags::KEYED_ARRAY_SOMETIMES_FILLED);
768                            combination.flags.insert(CombinationFlags::KEYED_ARRAY_ALWAYS_FILLED);
769                            had_previous_keyed_array = false;
770                        }
771
772                        if incoming_is_sealed
773                            && existing_is_sealed
774                            && !combination.keyed_array_entries.is_empty()
775                            && let Some(known_items_inner) = known_items.as_ref()
776                            && !known_items_inner.keys().any(|k| combination.keyed_array_entries.contains_key(k))
777                            && combination.sealed_arrays.len() + 1 < options.array_combination_threshold as usize
778                        {
779                            let frozen = TArray::Keyed(TKeyedArray {
780                                known_items: Some(std::mem::take(&mut combination.keyed_array_entries)),
781                                parameters: None,
782                                non_empty: combination.flags.contains(CombinationFlags::KEYED_ARRAY_SOMETIMES_FILLED),
783                            });
784                            combination.sealed_arrays.push(frozen);
785                            combination.sealed_arrays.push(TArray::Keyed(TKeyedArray {
786                                known_items,
787                                parameters,
788                                non_empty,
789                            }));
790                            combination.flags.remove(CombinationFlags::HAS_KEYED_ARRAY);
791                            combination.flags.remove(CombinationFlags::KEYED_ARRAY_SOMETIMES_FILLED);
792                            combination.flags.insert(CombinationFlags::KEYED_ARRAY_ALWAYS_FILLED);
793
794                            continue;
795                        }
796                    }
797
798                    combination.flags.insert(CombinationFlags::HAS_KEYED_ARRAY);
799
800                    if non_empty {
801                        combination.flags.insert(CombinationFlags::KEYED_ARRAY_SOMETIMES_FILLED);
802                    } else {
803                        combination.flags.remove(CombinationFlags::KEYED_ARRAY_ALWAYS_FILLED);
804
805                        if parameters.is_none()
806                            && known_items.as_ref().is_none_or(|items| items.is_empty())
807                            && combination.list_array_parameter.is_some()
808                        {
809                            combination.flags.remove(CombinationFlags::LIST_ARRAY_ALWAYS_FILLED);
810                            had_previous_keyed_array = false;
811                            combination.flags.remove(CombinationFlags::HAS_KEYED_ARRAY);
812
813                            continue;
814                        }
815                    }
816
817                    if let Some(known_items) = known_items {
818                        let has_existing_entries =
819                            !combination.keyed_array_entries.is_empty() || had_previous_keyed_array;
820                        let mut possibly_undefined_entries =
821                            combination.keyed_array_entries.keys().copied().collect::<HashSet<_>>();
822
823                        let mut has_defined_keys = false;
824
825                        for (candidate_item_name, (cu, candidate_item_type)) in known_items {
826                            if let Some((eu, existing_type)) =
827                                combination.keyed_array_entries.get_mut(&candidate_item_name)
828                            {
829                                if cu {
830                                    *eu = true;
831                                }
832                                if &candidate_item_type != existing_type {
833                                    *existing_type =
834                                        combine_union_types(existing_type, &candidate_item_type, codebase, options);
835                                }
836                            } else {
837                                let new_item_value_type =
838                                    if let Some((ref mut existing_key_param, ref mut existing_value_param)) =
839                                        combination.keyed_array_parameters
840                                    {
841                                        adjust_keyed_array_parameters(
842                                            existing_value_param,
843                                            &candidate_item_type,
844                                            codebase,
845                                            options,
846                                            &candidate_item_name,
847                                            existing_key_param,
848                                        );
849
850                                        continue;
851                                    } else {
852                                        let new_type = candidate_item_type.clone();
853                                        (has_existing_entries || cu, new_type)
854                                    };
855
856                                combination.keyed_array_entries.insert(candidate_item_name, new_item_value_type);
857                            }
858
859                            possibly_undefined_entries.remove(&candidate_item_name);
860
861                            if !cu {
862                                has_defined_keys = true;
863                            }
864                        }
865
866                        if !has_defined_keys {
867                            combination.flags.remove(CombinationFlags::KEYED_ARRAY_ALWAYS_FILLED);
868                        }
869
870                        for possibly_undefined_type_key in possibly_undefined_entries {
871                            let possibly_undefined_type =
872                                combination.keyed_array_entries.get_mut(&possibly_undefined_type_key);
873                            if let Some((pu, _)) = possibly_undefined_type {
874                                *pu = true;
875                            }
876                        }
877                    } else if !options.overwrite_empty_array {
878                        if match &parameters {
879                            Some((_, value_param)) => value_param.is_never(),
880                            None => true,
881                        } {
882                            for (tu, _) in combination.keyed_array_entries.values_mut() {
883                                *tu = true;
884                            }
885                        } else {
886                            for (key, (_, entry_type)) in &combination.keyed_array_entries {
887                                if let Some((ref mut existing_key_param, ref mut existing_value_param)) =
888                                    combination.keyed_array_parameters
889                                {
890                                    adjust_keyed_array_parameters(
891                                        existing_value_param,
892                                        entry_type,
893                                        codebase,
894                                        options,
895                                        key,
896                                        existing_key_param,
897                                    );
898                                }
899                            }
900
901                            combination.keyed_array_entries.clear();
902                        }
903                    }
904
905                    combination.keyed_array_parameters = match (&combination.keyed_array_parameters, parameters) {
906                        (None, None) => None,
907                        (Some(existing_types), None) => Some(existing_types.clone()),
908                        (None, Some(params)) => Some(((*params.0).clone(), (*params.1).clone())),
909                        (Some(existing_types), Some(params)) => Some((
910                            combine_union_types(&existing_types.0, &params.0, codebase, options),
911                            combine_union_types(&existing_types.1, &params.1, codebase, options),
912                        )),
913                    };
914                }
915            }
916        }
917
918        return;
919    }
920
921    // this probably won't ever happen, but the object top type
922    // can eliminate variants
923    if let TAtomic::Object(TObject::Any) = atomic {
924        combination.flags.insert(CombinationFlags::HAS_OBJECT_TOP_TYPE);
925        combination.value_types.retain(|_, t| !matches!(t, TAtomic::Object(TObject::Named(_))));
926        combination.value_types.insert(atomic.get_id(), atomic);
927
928        return;
929    }
930
931    if let TAtomic::Object(TObject::Named(named_object)) = &atomic {
932        if let Some(object_static) = combination.object_static.get(&named_object.get_name()) {
933            if *object_static && !named_object.is_static {
934                combination.object_static.insert(named_object.get_name(), false);
935            }
936        } else {
937            combination.object_static.insert(named_object.get_name(), named_object.is_static);
938        }
939    }
940
941    if let TAtomic::Object(TObject::Named(named_object)) = &atomic {
942        let fq_class_name = named_object.get_name();
943        if let Some(type_parameters) = named_object.get_type_parameters() {
944            let object_type_key = get_combiner_key(fq_class_name, type_parameters, codebase);
945
946            if let Some((_, existing_type_params)) = combination.object_type_params.get(&object_type_key) {
947                let mut new_type_parameters = Vec::with_capacity(type_parameters.len());
948                for (i, type_param) in type_parameters.iter().enumerate() {
949                    if let Some(existing_type_param) = existing_type_params.get(i) {
950                        new_type_parameters.push(combine_union_types(
951                            existing_type_param,
952                            type_param,
953                            codebase,
954                            options,
955                        ));
956                    }
957                }
958
959                combination.object_type_params.insert(object_type_key, (fq_class_name, new_type_parameters));
960            } else {
961                combination.object_type_params.insert(object_type_key, (fq_class_name, type_parameters.to_vec()));
962            }
963
964            return;
965        }
966    }
967
968    if let TAtomic::Object(TObject::Enum(enum_object)) = atomic {
969        combination.enum_names.insert((enum_object.get_name(), enum_object.get_case()));
970
971        return;
972    }
973
974    if let TAtomic::Object(TObject::Named(named_object)) = &atomic {
975        let fq_class_name = named_object.get_name();
976        let intersection_types = named_object.get_intersection_types();
977
978        if combination.flags.contains(CombinationFlags::HAS_OBJECT_TOP_TYPE)
979            || combination.value_types.contains_key(&atomic.get_id())
980        {
981            return;
982        }
983
984        let Some(symbol_type) = codebase.symbols.get_kind(fq_class_name) else {
985            combination.value_types.insert(atomic.get_id(), atomic);
986            return;
987        };
988
989        if !matches!(symbol_type, SymbolKind::Class | SymbolKind::Enum | SymbolKind::Interface) {
990            combination.value_types.insert(atomic.get_id(), atomic);
991            return;
992        }
993
994        let is_class = matches!(symbol_type, SymbolKind::Class);
995        let is_interface = matches!(symbol_type, SymbolKind::Interface);
996
997        let mut types_to_remove: Vec<Atom> = Vec::new();
998
999        for (key, existing_type) in &combination.value_types {
1000            if let TAtomic::Object(TObject::Named(existing_object)) = &existing_type {
1001                let existing_name = existing_object.get_name();
1002
1003                if intersection_types.is_some() || existing_object.has_intersection_types() {
1004                    if object_comparator::is_shallowly_contained_by(
1005                        codebase,
1006                        existing_type,
1007                        &atomic,
1008                        false,
1009                        &mut ComparisonResult::new(),
1010                    ) {
1011                        types_to_remove.push(existing_name);
1012                        continue;
1013                    }
1014
1015                    if object_comparator::is_shallowly_contained_by(
1016                        codebase,
1017                        &atomic,
1018                        existing_type,
1019                        false,
1020                        &mut ComparisonResult::new(),
1021                    ) {
1022                        return;
1023                    }
1024
1025                    continue;
1026                }
1027
1028                let Some(existing_symbol_kind) = codebase.symbols.get_kind(existing_object.get_name()) else {
1029                    continue;
1030                };
1031
1032                if matches!(existing_symbol_kind, SymbolKind::Class) {
1033                    // remove subclasses
1034                    if codebase.is_instance_of(&existing_name, &fq_class_name) {
1035                        types_to_remove.push(*key);
1036                        continue;
1037                    }
1038
1039                    if is_class {
1040                        // if covered by a parent class
1041                        if codebase.class_extends(&fq_class_name, &existing_name) {
1042                            return;
1043                        }
1044                    } else if is_interface {
1045                        // if covered by a parent class
1046                        if codebase.class_implements(&fq_class_name, &existing_name) {
1047                            return;
1048                        }
1049                    }
1050                } else if matches!(existing_symbol_kind, SymbolKind::Interface) {
1051                    if codebase.class_implements(&existing_name, &fq_class_name) {
1052                        types_to_remove.push(existing_name);
1053                        continue;
1054                    }
1055
1056                    if (is_class || is_interface) && codebase.class_implements(&fq_class_name, &existing_name) {
1057                        return;
1058                    }
1059                }
1060            }
1061        }
1062
1063        combination.value_types.insert(atomic.get_id(), atomic);
1064
1065        for type_key in types_to_remove {
1066            combination.value_types.remove(&type_key);
1067        }
1068
1069        return;
1070    }
1071
1072    if let TAtomic::Scalar(TScalar::Generic) = atomic {
1073        combination.literal_strings.clear();
1074        combination.integers.clear();
1075        combination.literal_floats.clear();
1076        combination.value_types.retain(|k, _| {
1077            k != "string"
1078                && k != "bool"
1079                && k != "false"
1080                && k != "true"
1081                && k != "float"
1082                && k != "numeric"
1083                && k != "array-key"
1084        });
1085
1086        combination.value_types.insert(atomic.get_id(), atomic);
1087        return;
1088    }
1089
1090    if let TAtomic::Scalar(TScalar::ArrayKey) = atomic {
1091        if combination.value_types.contains_key(&*ATOM_SCALAR) {
1092            return;
1093        }
1094
1095        combination.literal_strings.clear();
1096        combination.integers.clear();
1097        combination.value_types.retain(|k, _| k != &*ATOM_STRING && k != &*ATOM_INT);
1098        combination.value_types.insert(atomic.get_id(), atomic);
1099
1100        return;
1101    }
1102
1103    if let TAtomic::Scalar(TScalar::String(_) | TScalar::Integer(_)) = atomic
1104        && (combination.value_types.contains_key(&*ATOM_SCALAR)
1105            || combination.value_types.contains_key(&*ATOM_ARRAY_KEY))
1106    {
1107        return;
1108    }
1109
1110    if let TAtomic::Scalar(TScalar::Float(_) | TScalar::Integer(_)) = atomic
1111        && (combination.value_types.contains_key(&*ATOM_NUMERIC) || combination.value_types.contains_key(&*ATOM_SCALAR))
1112    {
1113        return;
1114    }
1115
1116    if let TAtomic::Scalar(TScalar::String(mut string_scalar)) = atomic {
1117        if let Some(existing_string_type) = combination.value_types.get_mut(&*ATOM_STRING) {
1118            if let TAtomic::Scalar(TScalar::String(existing_string_type)) = existing_string_type {
1119                if let Some(lit_atom) = string_scalar.get_known_literal_atom() {
1120                    let lit_value = lit_atom.as_str();
1121                    let is_incompatible = (existing_string_type.is_numeric && !str_is_numeric(lit_value))
1122                        || (existing_string_type.is_truthy && (lit_value.is_empty() || lit_value == "0"))
1123                        || (existing_string_type.is_non_empty && lit_value.is_empty())
1124                        || (existing_string_type.is_lowercase() && lit_value.chars().any(char::is_uppercase))
1125                        || (existing_string_type.is_uppercase() && lit_value.chars().any(char::is_lowercase));
1126
1127                    if is_incompatible {
1128                        // Check threshold before adding literal string
1129                        if combination.literal_strings.len() >= options.string_combination_threshold as usize {
1130                            // Exceeded threshold - just merge into the base string type
1131                            *existing_string_type = combine_string_scalars(existing_string_type, string_scalar);
1132                        } else {
1133                            combination.literal_strings.insert(lit_atom);
1134                        }
1135                    } else {
1136                        *existing_string_type = combine_string_scalars(existing_string_type, string_scalar);
1137                    }
1138                } else {
1139                    *existing_string_type = combine_string_scalars(existing_string_type, string_scalar);
1140                }
1141            }
1142        } else if let Some(atom) = string_scalar.get_known_literal_atom() {
1143            // Check threshold before adding literal string
1144            if combination.literal_strings.len() >= options.string_combination_threshold as usize {
1145                // Exceeded threshold - generalize to base string type
1146                combination.literal_strings.clear();
1147                combination.value_types.insert(*ATOM_STRING, TAtomic::Scalar(TScalar::string()));
1148            } else {
1149                combination.literal_strings.insert(atom);
1150            }
1151        } else {
1152            let mut literals_to_keep = AtomSet::default();
1153            if !combination.literal_strings.is_empty() {
1154                string_scalar.is_callable = false;
1155            }
1156
1157            if string_scalar.is_truthy
1158                || string_scalar.is_non_empty
1159                || string_scalar.is_numeric
1160                || !string_scalar.casing.is_unspecified()
1161            {
1162                for value in &combination.literal_strings {
1163                    if value.is_empty() {
1164                        string_scalar.is_non_empty = false;
1165                        string_scalar.is_truthy = false;
1166                        string_scalar.is_numeric = false;
1167                        break;
1168                    } else if value == "0" {
1169                        string_scalar.is_truthy = false;
1170                    }
1171
1172                    if string_scalar.is_numeric && !str_is_numeric(value) {
1173                        literals_to_keep.insert(*value);
1174                    } else {
1175                        string_scalar.is_numeric = string_scalar.is_numeric && str_is_numeric(value);
1176                    }
1177
1178                    string_scalar.casing = match string_scalar.casing {
1179                        TStringCasing::Lowercase if value.chars().all(|c| c.is_lowercase()) => TStringCasing::Lowercase,
1180                        TStringCasing::Uppercase if value.chars().all(|c| c.is_uppercase()) => TStringCasing::Uppercase,
1181                        _ => TStringCasing::Unspecified,
1182                    };
1183                }
1184            }
1185
1186            combination.value_types.insert(*ATOM_STRING, TAtomic::Scalar(TScalar::String(string_scalar)));
1187
1188            std::mem::swap(&mut combination.literal_strings, &mut literals_to_keep);
1189        }
1190
1191        return;
1192    }
1193
1194    if let TAtomic::Scalar(TScalar::Integer(integer)) = &atomic {
1195        // If we already have the base int type, no need to track literals
1196        if combination.value_types.contains_key(&*ATOM_INT) {
1197            return;
1198        }
1199
1200        // Check if adding this integer would exceed the threshold
1201        if integer.is_literal() && combination.integers.len() >= options.integer_combination_threshold as usize {
1202            // Exceeded threshold - generalize to base int type
1203            combination.integers.clear();
1204            combination.value_types.insert(*ATOM_INT, TAtomic::Scalar(TScalar::int()));
1205            return;
1206        }
1207
1208        combination.integers.push(*integer);
1209
1210        return;
1211    }
1212
1213    if let TAtomic::Scalar(TScalar::Float(float_scalar)) = &atomic {
1214        if let Some(stored) = combination.value_types.get(&*ATOM_FLOAT) {
1215            if matches!(stored, TAtomic::Scalar(TScalar::Float(TFloat::Float))) {
1216                return;
1217            }
1218
1219            if matches!(float_scalar, TFloat::Float) {
1220                combination.literal_floats.clear();
1221                combination.value_types.insert(*ATOM_FLOAT, atomic);
1222            }
1223
1224            return;
1225        }
1226
1227        if let TFloat::Literal(literal_value) = float_scalar {
1228            if combination.literal_floats.len() >= options.string_combination_threshold as usize {
1229                combination.literal_floats.clear();
1230                combination.value_types.insert(*ATOM_FLOAT, TAtomic::Scalar(TScalar::float()));
1231                return;
1232            }
1233            combination.literal_floats.push(*literal_value);
1234        } else {
1235            combination.literal_floats.clear();
1236            combination.value_types.insert(*ATOM_FLOAT, atomic);
1237        }
1238
1239        return;
1240    }
1241
1242    combination.value_types.insert(atomic.get_id(), atomic);
1243}
1244
1245/// Widens known items in a sealed array with the generic value type from parameters.
1246/// This is needed when combining a sealed array with a parametric one, the parametric
1247/// array's generic string keys could overwrite any of the sealed array's known keys.
1248fn widen_known_items_with_params(
1249    known_items: Option<BTreeMap<ArrayKey, (bool, TUnion)>>,
1250    params: &Option<(TUnion, TUnion)>,
1251    other_known_items: &BTreeMap<ArrayKey, (bool, TUnion)>,
1252    codebase: &CodebaseMetadata,
1253    options: CombinerOptions,
1254) -> Option<BTreeMap<ArrayKey, (bool, TUnion)>> {
1255    let mut items = known_items?;
1256
1257    if let Some((key_param, value_param)) = params {
1258        let key_param_accepts_int;
1259        let key_param_accepts_string;
1260        if key_param.has_mixed() || key_param.has_mixed_template() {
1261            key_param_accepts_int = true;
1262            key_param_accepts_string = true;
1263        } else {
1264            let mut accepts_int = false;
1265            let mut accepts_string = false;
1266            for part in key_param.types.as_ref() {
1267                if accepts_int && accepts_string {
1268                    break;
1269                }
1270
1271                match part {
1272                    TAtomic::Scalar(TScalar::ArrayKey) => {
1273                        accepts_int = true;
1274                        accepts_string = true;
1275                    }
1276                    TAtomic::Scalar(TScalar::Integer(_)) => accepts_int = true,
1277                    TAtomic::Scalar(TScalar::String(_)) => accepts_string = true,
1278                    _ => {
1279                        accepts_int = true;
1280                        accepts_string = true;
1281                    }
1282                }
1283            }
1284
1285            key_param_accepts_int = accepts_int;
1286            key_param_accepts_string = accepts_string;
1287        }
1288
1289        if !key_param_accepts_int && !key_param_accepts_string {
1290            return Some(items);
1291        }
1292
1293        for (key, (_, entry_type)) in items.iter_mut() {
1294            if entry_type == value_param {
1295                continue;
1296            }
1297
1298            if other_known_items.contains_key(key) {
1299                continue;
1300            }
1301
1302            let key_compatible = match key {
1303                ArrayKey::Integer(_) => key_param_accepts_int,
1304                ArrayKey::String(_) => key_param_accepts_string,
1305                ArrayKey::ClassLikeConstant { .. } => key_param_accepts_int || key_param_accepts_string,
1306            };
1307
1308            if !key_compatible {
1309                continue;
1310            }
1311
1312            *entry_type = combine_union_types(entry_type, value_param, codebase, options);
1313        }
1314    }
1315
1316    Some(items)
1317}
1318
1319fn adjust_keyed_array_parameters(
1320    existing_value_param: &mut TUnion,
1321    entry_type: &TUnion,
1322    codebase: &CodebaseMetadata,
1323    options: CombinerOptions,
1324    key: &ArrayKey,
1325    existing_key_param: &mut TUnion,
1326) {
1327    *existing_value_param = combine_union_types(existing_value_param, entry_type, codebase, options);
1328    let new_key_type = key.to_union();
1329    *existing_key_param = combine_union_types(existing_key_param, &new_key_type, codebase, options);
1330}
1331
1332fn flush_sealed_keyed_arrays_into_combination(
1333    combination: &mut TypeCombination,
1334    codebase: &CodebaseMetadata,
1335    options: CombinerOptions,
1336) {
1337    let sealed = std::mem::take(&mut combination.sealed_arrays);
1338    let mut any_keyed = false;
1339    let mut put_back = Vec::new();
1340
1341    for array in sealed {
1342        let TArray::Keyed(keyed) = array else {
1343            put_back.push(array);
1344            continue;
1345        };
1346
1347        any_keyed = true;
1348        let TKeyedArray { known_items, parameters, non_empty } = keyed;
1349
1350        if non_empty {
1351            combination.flags.insert(CombinationFlags::KEYED_ARRAY_SOMETIMES_FILLED);
1352        } else {
1353            combination.flags.remove(CombinationFlags::KEYED_ARRAY_ALWAYS_FILLED);
1354        }
1355
1356        if let Some(known_items) = known_items {
1357            for (candidate_item_name, (candidate_optional, candidate_item_type)) in known_items {
1358                if let Some((existing_optional, existing_type)) =
1359                    combination.keyed_array_entries.get_mut(&candidate_item_name)
1360                {
1361                    if candidate_optional {
1362                        *existing_optional = true;
1363                    }
1364                    if &candidate_item_type != existing_type {
1365                        *existing_type = combine_union_types(existing_type, &candidate_item_type, codebase, options);
1366                    }
1367                } else {
1368                    let inserted = if let Some((ref mut existing_key_param, ref mut existing_value_param)) =
1369                        combination.keyed_array_parameters
1370                    {
1371                        adjust_keyed_array_parameters(
1372                            existing_value_param,
1373                            &candidate_item_type,
1374                            codebase,
1375                            options,
1376                            &candidate_item_name,
1377                            existing_key_param,
1378                        );
1379                        None
1380                    } else {
1381                        Some((true, candidate_item_type.clone()))
1382                    };
1383
1384                    if let Some(entry) = inserted {
1385                        combination.keyed_array_entries.insert(candidate_item_name, entry);
1386                    }
1387                }
1388            }
1389        }
1390
1391        combination.keyed_array_parameters = match (combination.keyed_array_parameters.take(), parameters) {
1392            (None, None) => None,
1393            (Some(existing_types), None) => Some(existing_types),
1394            (None, Some(params)) => Some(((*params.0).clone(), (*params.1).clone())),
1395            (Some(existing_types), Some(params)) => Some((
1396                combine_union_types(&existing_types.0, &params.0, codebase, options),
1397                combine_union_types(&existing_types.1, &params.1, codebase, options),
1398            )),
1399        };
1400    }
1401
1402    if any_keyed {
1403        combination.flags.insert(CombinationFlags::HAS_KEYED_ARRAY);
1404    }
1405
1406    combination.sealed_arrays = put_back;
1407}
1408
1409const COMBINER_KEY_STACK_BUF: usize = 256;
1410
1411fn get_combiner_key(name: Atom, type_params: &[TUnion], codebase: &CodebaseMetadata) -> Atom {
1412    let covariants = if let Some(class_like_metadata) = codebase.get_class_like(&name) {
1413        &class_like_metadata.template_variance
1414    } else {
1415        return name;
1416    };
1417
1418    let name_str = name.as_str();
1419    let mut estimated_len = name_str.len() + 2; // name + "<" + ">"
1420    for (i, tunion) in type_params.iter().enumerate() {
1421        if i > 0 {
1422            estimated_len += 2; // ", "
1423        }
1424
1425        if covariants.get(i) == Some(&Variance::Covariant) {
1426            estimated_len += 1; // "*"
1427        } else {
1428            estimated_len += tunion.get_id().len();
1429        }
1430    }
1431
1432    if estimated_len <= COMBINER_KEY_STACK_BUF {
1433        let mut buffer = [0u8; COMBINER_KEY_STACK_BUF];
1434        let mut pos = 0;
1435
1436        buffer[pos..pos + name_str.len()].copy_from_slice(name_str.as_bytes());
1437        pos += name_str.len();
1438
1439        buffer[pos] = b'<';
1440        pos += 1;
1441
1442        for (i, tunion) in type_params.iter().enumerate() {
1443            if i > 0 {
1444                buffer[pos..pos + 2].copy_from_slice(b", ");
1445                pos += 2;
1446            }
1447            let param_str =
1448                if covariants.get(i) == Some(&Variance::Covariant) { "*" } else { tunion.get_id().as_str() };
1449            buffer[pos..pos + param_str.len()].copy_from_slice(param_str.as_bytes());
1450            pos += param_str.len();
1451        }
1452
1453        buffer[pos] = b'>';
1454        pos += 1;
1455
1456        // SAFETY: We only write valid UTF-8 (ASCII characters and valid UTF-8 from Atom strings)
1457        return atom(unsafe { std::str::from_utf8_unchecked(&buffer[..pos]) });
1458    }
1459
1460    let mut result = String::with_capacity(estimated_len);
1461    result.push_str(name_str);
1462    result.push('<');
1463    for (i, tunion) in type_params.iter().enumerate() {
1464        if i > 0 {
1465            result.push_str(", ");
1466        }
1467        if covariants.get(i) == Some(&Variance::Covariant) {
1468            result.push('*');
1469        } else {
1470            result.push_str(tunion.get_id().as_str());
1471        }
1472    }
1473    result.push('>');
1474    atom(&result)
1475}
1476
1477fn combine_string_scalars(s1: &TString, s2: TString) -> TString {
1478    TString {
1479        literal: match (&s1.literal, s2.literal) {
1480            (Some(TStringLiteral::Value(v1)), Some(TStringLiteral::Value(v2))) => {
1481                if v1 == &v2 {
1482                    Some(TStringLiteral::Value(v2))
1483                } else {
1484                    Some(TStringLiteral::Unspecified)
1485                }
1486            }
1487            (Some(TStringLiteral::Unspecified), Some(_)) | (Some(_), Some(TStringLiteral::Unspecified)) => {
1488                Some(TStringLiteral::Unspecified)
1489            }
1490            _ => None,
1491        },
1492        is_numeric: s1.is_numeric && s2.is_numeric,
1493        is_truthy: s1.is_truthy && s2.is_truthy,
1494        is_non_empty: s1.is_non_empty && s2.is_non_empty,
1495        is_callable: s1.is_callable && s2.is_callable,
1496        casing: match (s1.casing, s2.casing) {
1497            (TStringCasing::Lowercase, TStringCasing::Lowercase) => TStringCasing::Lowercase,
1498            (TStringCasing::Uppercase, TStringCasing::Uppercase) => TStringCasing::Uppercase,
1499            _ => TStringCasing::Unspecified,
1500        },
1501    }
1502}
1503
1504#[cfg(test)]
1505mod tests {
1506    use std::collections::BTreeMap;
1507
1508    use super::*;
1509
1510    use crate::ttype::atomic::TAtomic;
1511    use crate::ttype::atomic::array::list::TList;
1512    use crate::ttype::atomic::scalar::TScalar;
1513
1514    #[test]
1515    fn test_combine_scalars() {
1516        let types = vec![
1517            TAtomic::Scalar(TScalar::string()),
1518            TAtomic::Scalar(TScalar::int()),
1519            TAtomic::Scalar(TScalar::float()),
1520            TAtomic::Scalar(TScalar::bool()),
1521        ];
1522
1523        let combined =
1524            combine(types, &CodebaseMetadata::default(), CombinerOptions::default().with_overwrite_empty_array());
1525
1526        assert_eq!(combined.len(), 1);
1527        assert!(matches!(combined[0], TAtomic::Scalar(TScalar::Generic)));
1528    }
1529
1530    #[test]
1531    fn test_combine_boolean_lists() {
1532        let types = vec![
1533            TAtomic::Array(TArray::List(TList::from_known_elements(BTreeMap::from_iter([
1534                (0, (false, TUnion::from_atomic(TAtomic::Scalar(TScalar::r#false())))),
1535                (1, (false, TUnion::from_atomic(TAtomic::Scalar(TScalar::r#true())))),
1536            ])))),
1537            TAtomic::Array(TArray::List(TList::from_known_elements(BTreeMap::from_iter([
1538                (0, (false, TUnion::from_atomic(TAtomic::Scalar(TScalar::r#true())))),
1539                (1, (false, TUnion::from_atomic(TAtomic::Scalar(TScalar::r#false())))),
1540            ])))),
1541        ];
1542
1543        let combined =
1544            combine(types, &CodebaseMetadata::default(), CombinerOptions::default().with_overwrite_empty_array());
1545
1546        assert_eq!(combined.len(), 2);
1547        assert!(matches!(combined[0], TAtomic::Array(TArray::List(_))));
1548        assert!(matches!(combined[1], TAtomic::Array(TArray::List(_))));
1549    }
1550
1551    #[test]
1552    fn test_combine_integer_lists() {
1553        let types = vec![
1554            TAtomic::Array(TArray::List(TList::from_known_elements(BTreeMap::from_iter([
1555                (0, (false, TUnion::from_atomic(TAtomic::Scalar(TScalar::Integer(TInteger::literal(1)))))),
1556                (1, (false, TUnion::from_atomic(TAtomic::Scalar(TScalar::Integer(TInteger::literal(2)))))),
1557            ])))),
1558            TAtomic::Array(TArray::List(TList::from_known_elements(BTreeMap::from_iter([
1559                (0, (false, TUnion::from_atomic(TAtomic::Scalar(TScalar::Integer(TInteger::literal(2)))))),
1560                (1, (false, TUnion::from_atomic(TAtomic::Scalar(TScalar::Integer(TInteger::literal(1)))))),
1561            ])))),
1562        ];
1563
1564        let combined =
1565            combine(types, &CodebaseMetadata::default(), CombinerOptions::default().with_overwrite_empty_array());
1566
1567        assert_eq!(combined.len(), 2);
1568        assert!(matches!(combined[0], TAtomic::Array(TArray::List(_))));
1569        assert!(matches!(combined[1], TAtomic::Array(TArray::List(_))));
1570    }
1571
1572    #[test]
1573    fn test_combine_string_lists() {
1574        let types = vec![
1575            TAtomic::Array(TArray::List(TList::from_known_elements(BTreeMap::from_iter([
1576                (0, (false, TUnion::from_atomic(TAtomic::Scalar(TScalar::String(TString::known_literal("a".into())))))),
1577                (1, (false, TUnion::from_atomic(TAtomic::Scalar(TScalar::String(TString::known_literal("b".into())))))),
1578            ])))),
1579            TAtomic::Array(TArray::List(TList::from_known_elements(BTreeMap::from_iter([
1580                (0, (false, TUnion::from_atomic(TAtomic::Scalar(TScalar::String(TString::known_literal("b".into())))))),
1581                (1, (false, TUnion::from_atomic(TAtomic::Scalar(TScalar::String(TString::known_literal("a".into())))))),
1582            ])))),
1583        ];
1584
1585        let combined =
1586            combine(types, &CodebaseMetadata::default(), CombinerOptions::default().with_overwrite_empty_array());
1587
1588        assert_eq!(combined.len(), 2);
1589        assert!(matches!(combined[0], TAtomic::Array(TArray::List(_))));
1590        assert!(matches!(combined[1], TAtomic::Array(TArray::List(_))));
1591    }
1592
1593    #[test]
1594    fn test_combine_mixed_literal_lists() {
1595        let types = vec![
1596            TAtomic::Array(TArray::List(TList::from_known_elements(BTreeMap::from_iter([
1597                (0, (false, TUnion::from_atomic(TAtomic::Scalar(TScalar::Integer(TInteger::literal(1)))))),
1598                (1, (false, TUnion::from_atomic(TAtomic::Scalar(TScalar::String(TString::known_literal("a".into())))))),
1599            ])))),
1600            TAtomic::Array(TArray::List(TList::from_known_elements(BTreeMap::from_iter([
1601                (0, (false, TUnion::from_atomic(TAtomic::Scalar(TScalar::String(TString::known_literal("b".into())))))),
1602                (1, (false, TUnion::from_atomic(TAtomic::Scalar(TScalar::Integer(TInteger::literal(2)))))),
1603            ])))),
1604        ];
1605
1606        let combined =
1607            combine(types, &CodebaseMetadata::default(), CombinerOptions::default().with_overwrite_empty_array());
1608
1609        assert_eq!(combined.len(), 2);
1610        assert!(matches!(combined[0], TAtomic::Array(TArray::List(_))));
1611        assert!(matches!(combined[1], TAtomic::Array(TArray::List(_))));
1612    }
1613
1614    #[test]
1615    fn test_combine_list_with_generic_list() {
1616        let types = vec![
1617            TAtomic::Array(TArray::List(TList::from_known_elements(BTreeMap::from_iter([
1618                (0, (false, TUnion::from_atomic(TAtomic::Scalar(TScalar::Integer(TInteger::literal(1)))))),
1619                (1, (false, TUnion::from_atomic(TAtomic::Scalar(TScalar::Integer(TInteger::literal(2)))))),
1620            ])))),
1621            TAtomic::Array(TArray::List(TList::new(Arc::new(TUnion::from_atomic(TAtomic::Scalar(TScalar::int())))))), // list<int>
1622        ];
1623
1624        let combined =
1625            combine(types, &CodebaseMetadata::default(), CombinerOptions::default().with_overwrite_empty_array());
1626
1627        // Expecting list{1,2} and list<int> = list<int>
1628        assert_eq!(combined.len(), 1);
1629
1630        let TAtomic::Array(TArray::List(list_type)) = &combined[0] else {
1631            panic!("Expected a list type");
1632        };
1633
1634        let Some(known_elements) = &list_type.known_elements else {
1635            panic!("Expected known elements");
1636        };
1637
1638        assert!(!list_type.is_non_empty());
1639        assert!(list_type.known_count.is_none());
1640        assert!(list_type.element_type.is_int());
1641
1642        assert_eq!(known_elements.len(), 2);
1643        assert!(known_elements.contains_key(&0));
1644        assert!(known_elements.contains_key(&1));
1645
1646        let Some(first_element) = known_elements.get(&0) else {
1647            panic!("Expected first element");
1648        };
1649
1650        let Some(second_element) = known_elements.get(&1) else {
1651            panic!("Expected second element");
1652        };
1653
1654        assert!(first_element.1.is_int());
1655        assert!(second_element.1.is_int());
1656    }
1657}