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                                codebase,
723                                options,
724                            );
725
726                            combination.sealed_arrays.push(TArray::Keyed(TKeyedArray {
727                                known_items,
728                                parameters,
729                                non_empty,
730                            }));
731
732                            continue;
733                        }
734
735                        if !incoming_is_sealed && existing_is_sealed && !combination.keyed_array_entries.is_empty() {
736                            let mut frozen_entries = std::mem::take(&mut combination.keyed_array_entries);
737                            if let Some((ref key_param, ref value_param)) = parameters {
738                                for (key, (_, entry_type)) in frozen_entries.iter_mut() {
739                                    let key_type = TUnion::from_atomic(key.to_atomic());
740
741                                    if union_comparator::can_expression_types_be_identical(
742                                        codebase, &key_type, key_param, false, false,
743                                    ) {
744                                        *entry_type = combine_union_types(entry_type, value_param, codebase, options);
745                                    }
746                                }
747                            }
748
749                            let frozen = TArray::Keyed(TKeyedArray {
750                                known_items: Some(frozen_entries),
751                                parameters: None,
752                                non_empty: combination.flags.contains(CombinationFlags::KEYED_ARRAY_SOMETIMES_FILLED),
753                            });
754                            combination.sealed_arrays.push(frozen);
755                            combination.flags.remove(CombinationFlags::HAS_KEYED_ARRAY);
756                            combination.flags.remove(CombinationFlags::KEYED_ARRAY_SOMETIMES_FILLED);
757                            combination.flags.insert(CombinationFlags::KEYED_ARRAY_ALWAYS_FILLED);
758                            had_previous_keyed_array = false;
759                        }
760
761                        if incoming_is_sealed
762                            && existing_is_sealed
763                            && !combination.keyed_array_entries.is_empty()
764                            && let Some(known_items_inner) = known_items.as_ref()
765                            && !known_items_inner.keys().any(|k| combination.keyed_array_entries.contains_key(k))
766                            && combination.sealed_arrays.len() + 1 < options.array_combination_threshold as usize
767                        {
768                            let frozen = TArray::Keyed(TKeyedArray {
769                                known_items: Some(std::mem::take(&mut combination.keyed_array_entries)),
770                                parameters: None,
771                                non_empty: combination.flags.contains(CombinationFlags::KEYED_ARRAY_SOMETIMES_FILLED),
772                            });
773                            combination.sealed_arrays.push(frozen);
774                            combination.sealed_arrays.push(TArray::Keyed(TKeyedArray {
775                                known_items,
776                                parameters,
777                                non_empty,
778                            }));
779                            combination.flags.remove(CombinationFlags::HAS_KEYED_ARRAY);
780                            combination.flags.remove(CombinationFlags::KEYED_ARRAY_SOMETIMES_FILLED);
781                            combination.flags.insert(CombinationFlags::KEYED_ARRAY_ALWAYS_FILLED);
782
783                            continue;
784                        }
785                    }
786
787                    combination.flags.insert(CombinationFlags::HAS_KEYED_ARRAY);
788
789                    if non_empty {
790                        combination.flags.insert(CombinationFlags::KEYED_ARRAY_SOMETIMES_FILLED);
791                    } else {
792                        combination.flags.remove(CombinationFlags::KEYED_ARRAY_ALWAYS_FILLED);
793
794                        if parameters.is_none()
795                            && known_items.as_ref().is_none_or(|items| items.is_empty())
796                            && combination.list_array_parameter.is_some()
797                        {
798                            combination.flags.remove(CombinationFlags::LIST_ARRAY_ALWAYS_FILLED);
799                            had_previous_keyed_array = false;
800                            combination.flags.remove(CombinationFlags::HAS_KEYED_ARRAY);
801
802                            continue;
803                        }
804                    }
805
806                    if let Some(known_items) = known_items {
807                        let has_existing_entries =
808                            !combination.keyed_array_entries.is_empty() || had_previous_keyed_array;
809                        let mut possibly_undefined_entries =
810                            combination.keyed_array_entries.keys().copied().collect::<HashSet<_>>();
811
812                        let mut has_defined_keys = false;
813
814                        for (candidate_item_name, (cu, candidate_item_type)) in known_items {
815                            if let Some((eu, existing_type)) =
816                                combination.keyed_array_entries.get_mut(&candidate_item_name)
817                            {
818                                if cu {
819                                    *eu = true;
820                                }
821                                if &candidate_item_type != existing_type {
822                                    *existing_type =
823                                        combine_union_types(existing_type, &candidate_item_type, codebase, options);
824                                }
825                            } else {
826                                let new_item_value_type =
827                                    if let Some((ref mut existing_key_param, ref mut existing_value_param)) =
828                                        combination.keyed_array_parameters
829                                    {
830                                        adjust_keyed_array_parameters(
831                                            existing_value_param,
832                                            &candidate_item_type,
833                                            codebase,
834                                            options,
835                                            &candidate_item_name,
836                                            existing_key_param,
837                                        );
838
839                                        continue;
840                                    } else {
841                                        let new_type = candidate_item_type.clone();
842                                        (has_existing_entries || cu, new_type)
843                                    };
844
845                                combination.keyed_array_entries.insert(candidate_item_name, new_item_value_type);
846                            }
847
848                            possibly_undefined_entries.remove(&candidate_item_name);
849
850                            if !cu {
851                                has_defined_keys = true;
852                            }
853                        }
854
855                        if !has_defined_keys {
856                            combination.flags.remove(CombinationFlags::KEYED_ARRAY_ALWAYS_FILLED);
857                        }
858
859                        for possibly_undefined_type_key in possibly_undefined_entries {
860                            let possibly_undefined_type =
861                                combination.keyed_array_entries.get_mut(&possibly_undefined_type_key);
862                            if let Some((pu, _)) = possibly_undefined_type {
863                                *pu = true;
864                            }
865                        }
866                    } else if !options.overwrite_empty_array {
867                        if match &parameters {
868                            Some((_, value_param)) => value_param.is_never(),
869                            None => true,
870                        } {
871                            for (tu, _) in combination.keyed_array_entries.values_mut() {
872                                *tu = true;
873                            }
874                        } else {
875                            for (key, (_, entry_type)) in &combination.keyed_array_entries {
876                                if let Some((ref mut existing_key_param, ref mut existing_value_param)) =
877                                    combination.keyed_array_parameters
878                                {
879                                    adjust_keyed_array_parameters(
880                                        existing_value_param,
881                                        entry_type,
882                                        codebase,
883                                        options,
884                                        key,
885                                        existing_key_param,
886                                    );
887                                }
888                            }
889
890                            combination.keyed_array_entries.clear();
891                        }
892                    }
893
894                    combination.keyed_array_parameters = match (&combination.keyed_array_parameters, parameters) {
895                        (None, None) => None,
896                        (Some(existing_types), None) => Some(existing_types.clone()),
897                        (None, Some(params)) => Some(((*params.0).clone(), (*params.1).clone())),
898                        (Some(existing_types), Some(params)) => Some((
899                            combine_union_types(&existing_types.0, &params.0, codebase, options),
900                            combine_union_types(&existing_types.1, &params.1, codebase, options),
901                        )),
902                    };
903                }
904            }
905        }
906
907        return;
908    }
909
910    // this probably won't ever happen, but the object top type
911    // can eliminate variants
912    if let TAtomic::Object(TObject::Any) = atomic {
913        combination.flags.insert(CombinationFlags::HAS_OBJECT_TOP_TYPE);
914        combination.value_types.retain(|_, t| !matches!(t, TAtomic::Object(TObject::Named(_))));
915        combination.value_types.insert(atomic.get_id(), atomic);
916
917        return;
918    }
919
920    if let TAtomic::Object(TObject::Named(named_object)) = &atomic {
921        if let Some(object_static) = combination.object_static.get(&named_object.get_name()) {
922            if *object_static && !named_object.is_static {
923                combination.object_static.insert(named_object.get_name(), false);
924            }
925        } else {
926            combination.object_static.insert(named_object.get_name(), named_object.is_static);
927        }
928    }
929
930    if let TAtomic::Object(TObject::Named(named_object)) = &atomic {
931        let fq_class_name = named_object.get_name();
932        if let Some(type_parameters) = named_object.get_type_parameters() {
933            let object_type_key = get_combiner_key(fq_class_name, type_parameters, codebase);
934
935            if let Some((_, existing_type_params)) = combination.object_type_params.get(&object_type_key) {
936                let mut new_type_parameters = Vec::with_capacity(type_parameters.len());
937                for (i, type_param) in type_parameters.iter().enumerate() {
938                    if let Some(existing_type_param) = existing_type_params.get(i) {
939                        new_type_parameters.push(combine_union_types(
940                            existing_type_param,
941                            type_param,
942                            codebase,
943                            options,
944                        ));
945                    }
946                }
947
948                combination.object_type_params.insert(object_type_key, (fq_class_name, new_type_parameters));
949            } else {
950                combination.object_type_params.insert(object_type_key, (fq_class_name, type_parameters.to_vec()));
951            }
952
953            return;
954        }
955    }
956
957    if let TAtomic::Object(TObject::Enum(enum_object)) = atomic {
958        combination.enum_names.insert((enum_object.get_name(), enum_object.get_case()));
959
960        return;
961    }
962
963    if let TAtomic::Object(TObject::Named(named_object)) = &atomic {
964        let fq_class_name = named_object.get_name();
965        let intersection_types = named_object.get_intersection_types();
966
967        if combination.flags.contains(CombinationFlags::HAS_OBJECT_TOP_TYPE)
968            || combination.value_types.contains_key(&atomic.get_id())
969        {
970            return;
971        }
972
973        let Some(symbol_type) = codebase.symbols.get_kind(fq_class_name) else {
974            combination.value_types.insert(atomic.get_id(), atomic);
975            return;
976        };
977
978        if !matches!(symbol_type, SymbolKind::Class | SymbolKind::Enum | SymbolKind::Interface) {
979            combination.value_types.insert(atomic.get_id(), atomic);
980            return;
981        }
982
983        let is_class = matches!(symbol_type, SymbolKind::Class);
984        let is_interface = matches!(symbol_type, SymbolKind::Interface);
985
986        let mut types_to_remove: Vec<Atom> = Vec::new();
987
988        for (key, existing_type) in &combination.value_types {
989            if let TAtomic::Object(TObject::Named(existing_object)) = &existing_type {
990                let existing_name = existing_object.get_name();
991
992                if intersection_types.is_some() || existing_object.has_intersection_types() {
993                    if object_comparator::is_shallowly_contained_by(
994                        codebase,
995                        existing_type,
996                        &atomic,
997                        false,
998                        &mut ComparisonResult::new(),
999                    ) {
1000                        types_to_remove.push(existing_name);
1001                        continue;
1002                    }
1003
1004                    if object_comparator::is_shallowly_contained_by(
1005                        codebase,
1006                        &atomic,
1007                        existing_type,
1008                        false,
1009                        &mut ComparisonResult::new(),
1010                    ) {
1011                        return;
1012                    }
1013
1014                    continue;
1015                }
1016
1017                let Some(existing_symbol_kind) = codebase.symbols.get_kind(existing_object.get_name()) else {
1018                    continue;
1019                };
1020
1021                if matches!(existing_symbol_kind, SymbolKind::Class) {
1022                    // remove subclasses
1023                    if codebase.is_instance_of(&existing_name, &fq_class_name) {
1024                        types_to_remove.push(*key);
1025                        continue;
1026                    }
1027
1028                    if is_class {
1029                        // if covered by a parent class
1030                        if codebase.class_extends(&fq_class_name, &existing_name) {
1031                            return;
1032                        }
1033                    } else if is_interface {
1034                        // if covered by a parent class
1035                        if codebase.class_implements(&fq_class_name, &existing_name) {
1036                            return;
1037                        }
1038                    }
1039                } else if matches!(existing_symbol_kind, SymbolKind::Interface) {
1040                    if codebase.class_implements(&existing_name, &fq_class_name) {
1041                        types_to_remove.push(existing_name);
1042                        continue;
1043                    }
1044
1045                    if (is_class || is_interface) && codebase.class_implements(&fq_class_name, &existing_name) {
1046                        return;
1047                    }
1048                }
1049            }
1050        }
1051
1052        combination.value_types.insert(atomic.get_id(), atomic);
1053
1054        for type_key in types_to_remove {
1055            combination.value_types.remove(&type_key);
1056        }
1057
1058        return;
1059    }
1060
1061    if let TAtomic::Scalar(TScalar::Generic) = atomic {
1062        combination.literal_strings.clear();
1063        combination.integers.clear();
1064        combination.literal_floats.clear();
1065        combination.value_types.retain(|k, _| {
1066            k != "string"
1067                && k != "bool"
1068                && k != "false"
1069                && k != "true"
1070                && k != "float"
1071                && k != "numeric"
1072                && k != "array-key"
1073        });
1074
1075        combination.value_types.insert(atomic.get_id(), atomic);
1076        return;
1077    }
1078
1079    if let TAtomic::Scalar(TScalar::ArrayKey) = atomic {
1080        if combination.value_types.contains_key(&*ATOM_SCALAR) {
1081            return;
1082        }
1083
1084        combination.literal_strings.clear();
1085        combination.integers.clear();
1086        combination.value_types.retain(|k, _| k != &*ATOM_STRING && k != &*ATOM_INT);
1087        combination.value_types.insert(atomic.get_id(), atomic);
1088
1089        return;
1090    }
1091
1092    if let TAtomic::Scalar(TScalar::String(_) | TScalar::Integer(_)) = atomic
1093        && (combination.value_types.contains_key(&*ATOM_SCALAR)
1094            || combination.value_types.contains_key(&*ATOM_ARRAY_KEY))
1095    {
1096        return;
1097    }
1098
1099    if let TAtomic::Scalar(TScalar::Float(_) | TScalar::Integer(_)) = atomic
1100        && (combination.value_types.contains_key(&*ATOM_NUMERIC) || combination.value_types.contains_key(&*ATOM_SCALAR))
1101    {
1102        return;
1103    }
1104
1105    if let TAtomic::Scalar(TScalar::String(mut string_scalar)) = atomic {
1106        if let Some(existing_string_type) = combination.value_types.get_mut(&*ATOM_STRING) {
1107            if let TAtomic::Scalar(TScalar::String(existing_string_type)) = existing_string_type {
1108                if let Some(lit_atom) = string_scalar.get_known_literal_atom() {
1109                    let lit_value = lit_atom.as_str();
1110                    let is_incompatible = (existing_string_type.is_numeric && !str_is_numeric(lit_value))
1111                        || (existing_string_type.is_truthy && (lit_value.is_empty() || lit_value == "0"))
1112                        || (existing_string_type.is_non_empty && lit_value.is_empty())
1113                        || (existing_string_type.is_lowercase() && lit_value.chars().any(char::is_uppercase))
1114                        || (existing_string_type.is_uppercase() && lit_value.chars().any(char::is_lowercase));
1115
1116                    if is_incompatible {
1117                        // Check threshold before adding literal string
1118                        if combination.literal_strings.len() >= options.string_combination_threshold as usize {
1119                            // Exceeded threshold - just merge into the base string type
1120                            *existing_string_type = combine_string_scalars(existing_string_type, string_scalar);
1121                        } else {
1122                            combination.literal_strings.insert(lit_atom);
1123                        }
1124                    } else {
1125                        *existing_string_type = combine_string_scalars(existing_string_type, string_scalar);
1126                    }
1127                } else {
1128                    *existing_string_type = combine_string_scalars(existing_string_type, string_scalar);
1129                }
1130            }
1131        } else if let Some(atom) = string_scalar.get_known_literal_atom() {
1132            // Check threshold before adding literal string
1133            if combination.literal_strings.len() >= options.string_combination_threshold as usize {
1134                // Exceeded threshold - generalize to base string type
1135                combination.literal_strings.clear();
1136                combination.value_types.insert(*ATOM_STRING, TAtomic::Scalar(TScalar::string()));
1137            } else {
1138                combination.literal_strings.insert(atom);
1139            }
1140        } else {
1141            // When we have a constrained string type (like numeric-string) and literals,
1142            // we need to decide whether to merge them or keep them separate.
1143            // If the non-literal is numeric-string, keep non-numeric literals separate.
1144            let mut literals_to_keep = AtomSet::default();
1145
1146            if string_scalar.is_truthy
1147                || string_scalar.is_non_empty
1148                || string_scalar.is_numeric
1149                || !string_scalar.casing.is_unspecified()
1150            {
1151                for value in &combination.literal_strings {
1152                    if value.is_empty() {
1153                        string_scalar.is_non_empty = false;
1154                        string_scalar.is_truthy = false;
1155                        string_scalar.is_numeric = false;
1156                        break;
1157                    } else if value == "0" {
1158                        string_scalar.is_truthy = false;
1159                    }
1160
1161                    // If the string is numeric but the literal is not, keep the literal separate
1162                    if string_scalar.is_numeric && !str_is_numeric(value) {
1163                        literals_to_keep.insert(*value);
1164                    } else {
1165                        string_scalar.is_numeric = string_scalar.is_numeric && str_is_numeric(value);
1166                    }
1167
1168                    string_scalar.casing = match string_scalar.casing {
1169                        TStringCasing::Lowercase if value.chars().all(|c| c.is_lowercase()) => TStringCasing::Lowercase,
1170                        TStringCasing::Uppercase if value.chars().all(|c| c.is_uppercase()) => TStringCasing::Uppercase,
1171                        _ => TStringCasing::Unspecified,
1172                    };
1173                }
1174            }
1175
1176            combination.value_types.insert(*ATOM_STRING, TAtomic::Scalar(TScalar::String(string_scalar)));
1177
1178            std::mem::swap(&mut combination.literal_strings, &mut literals_to_keep);
1179        }
1180
1181        return;
1182    }
1183
1184    if let TAtomic::Scalar(TScalar::Integer(integer)) = &atomic {
1185        // If we already have the base int type, no need to track literals
1186        if combination.value_types.contains_key(&*ATOM_INT) {
1187            return;
1188        }
1189
1190        // Check if adding this integer would exceed the threshold
1191        if integer.is_literal() && combination.integers.len() >= options.integer_combination_threshold as usize {
1192            // Exceeded threshold - generalize to base int type
1193            combination.integers.clear();
1194            combination.value_types.insert(*ATOM_INT, TAtomic::Scalar(TScalar::int()));
1195            return;
1196        }
1197
1198        combination.integers.push(*integer);
1199
1200        return;
1201    }
1202
1203    if let TAtomic::Scalar(TScalar::Float(float_scalar)) = &atomic {
1204        if combination.value_types.contains_key(&*ATOM_FLOAT) {
1205            return;
1206        }
1207
1208        if let TFloat::Literal(literal_value) = float_scalar {
1209            // Check if adding this float would exceed the threshold (using string threshold for floats)
1210            if combination.literal_floats.len() >= options.string_combination_threshold as usize {
1211                // Exceeded threshold - generalize to base float type
1212                combination.literal_floats.clear();
1213                combination.value_types.insert(*ATOM_FLOAT, TAtomic::Scalar(TScalar::float()));
1214                return;
1215            }
1216            combination.literal_floats.push(*literal_value);
1217        } else {
1218            combination.literal_floats.clear();
1219            combination.value_types.insert(*ATOM_FLOAT, atomic);
1220        }
1221
1222        return;
1223    }
1224
1225    combination.value_types.insert(atomic.get_id(), atomic);
1226}
1227
1228/// Widens known items in a sealed array with the generic value type from parameters.
1229/// This is needed when combining a sealed array with a parametric one, the parametric
1230/// array's generic string keys could overwrite any of the sealed array's known keys.
1231fn widen_known_items_with_params(
1232    known_items: Option<BTreeMap<ArrayKey, (bool, TUnion)>>,
1233    params: &Option<(TUnion, TUnion)>,
1234    codebase: &CodebaseMetadata,
1235    options: CombinerOptions,
1236) -> Option<BTreeMap<ArrayKey, (bool, TUnion)>> {
1237    let mut items = known_items?;
1238
1239    if let Some((key_param, value_param)) = params {
1240        let key_param_accepts_int;
1241        let key_param_accepts_string;
1242        if key_param.has_mixed() || key_param.has_mixed_template() {
1243            key_param_accepts_int = true;
1244            key_param_accepts_string = true;
1245        } else {
1246            let mut accepts_int = false;
1247            let mut accepts_string = false;
1248            for part in key_param.types.as_ref() {
1249                if accepts_int && accepts_string {
1250                    break;
1251                }
1252
1253                match part {
1254                    TAtomic::Scalar(TScalar::ArrayKey) => {
1255                        accepts_int = true;
1256                        accepts_string = true;
1257                    }
1258                    TAtomic::Scalar(TScalar::Integer(_)) => accepts_int = true,
1259                    TAtomic::Scalar(TScalar::String(_)) => accepts_string = true,
1260                    _ => {
1261                        accepts_int = true;
1262                        accepts_string = true;
1263                    }
1264                }
1265            }
1266
1267            key_param_accepts_int = accepts_int;
1268            key_param_accepts_string = accepts_string;
1269        }
1270
1271        if !key_param_accepts_int && !key_param_accepts_string {
1272            return Some(items);
1273        }
1274
1275        for (key, (_, entry_type)) in items.iter_mut() {
1276            if entry_type == value_param {
1277                continue;
1278            }
1279
1280            let key_compatible = match key {
1281                ArrayKey::Integer(_) => key_param_accepts_int,
1282                ArrayKey::String(_) => key_param_accepts_string,
1283                ArrayKey::ClassLikeConstant { .. } => key_param_accepts_int || key_param_accepts_string,
1284            };
1285
1286            if !key_compatible {
1287                continue;
1288            }
1289
1290            *entry_type = combine_union_types(entry_type, value_param, codebase, options);
1291        }
1292    }
1293
1294    Some(items)
1295}
1296
1297fn adjust_keyed_array_parameters(
1298    existing_value_param: &mut TUnion,
1299    entry_type: &TUnion,
1300    codebase: &CodebaseMetadata,
1301    options: CombinerOptions,
1302    key: &ArrayKey,
1303    existing_key_param: &mut TUnion,
1304) {
1305    *existing_value_param = combine_union_types(existing_value_param, entry_type, codebase, options);
1306    let new_key_type = key.to_union();
1307    *existing_key_param = combine_union_types(existing_key_param, &new_key_type, codebase, options);
1308}
1309
1310fn flush_sealed_keyed_arrays_into_combination(
1311    combination: &mut TypeCombination,
1312    codebase: &CodebaseMetadata,
1313    options: CombinerOptions,
1314) {
1315    let sealed = std::mem::take(&mut combination.sealed_arrays);
1316    let mut any_keyed = false;
1317    let mut put_back = Vec::new();
1318
1319    for array in sealed {
1320        let TArray::Keyed(keyed) = array else {
1321            put_back.push(array);
1322            continue;
1323        };
1324
1325        any_keyed = true;
1326        let TKeyedArray { known_items, parameters, non_empty } = keyed;
1327
1328        if non_empty {
1329            combination.flags.insert(CombinationFlags::KEYED_ARRAY_SOMETIMES_FILLED);
1330        } else {
1331            combination.flags.remove(CombinationFlags::KEYED_ARRAY_ALWAYS_FILLED);
1332        }
1333
1334        if let Some(known_items) = known_items {
1335            for (candidate_item_name, (candidate_optional, candidate_item_type)) in known_items {
1336                if let Some((existing_optional, existing_type)) =
1337                    combination.keyed_array_entries.get_mut(&candidate_item_name)
1338                {
1339                    if candidate_optional {
1340                        *existing_optional = true;
1341                    }
1342                    if &candidate_item_type != existing_type {
1343                        *existing_type = combine_union_types(existing_type, &candidate_item_type, codebase, options);
1344                    }
1345                } else {
1346                    let inserted = if let Some((ref mut existing_key_param, ref mut existing_value_param)) =
1347                        combination.keyed_array_parameters
1348                    {
1349                        adjust_keyed_array_parameters(
1350                            existing_value_param,
1351                            &candidate_item_type,
1352                            codebase,
1353                            options,
1354                            &candidate_item_name,
1355                            existing_key_param,
1356                        );
1357                        None
1358                    } else {
1359                        Some((true, candidate_item_type.clone()))
1360                    };
1361
1362                    if let Some(entry) = inserted {
1363                        combination.keyed_array_entries.insert(candidate_item_name, entry);
1364                    }
1365                }
1366            }
1367        }
1368
1369        combination.keyed_array_parameters = match (combination.keyed_array_parameters.take(), parameters) {
1370            (None, None) => None,
1371            (Some(existing_types), None) => Some(existing_types),
1372            (None, Some(params)) => Some(((*params.0).clone(), (*params.1).clone())),
1373            (Some(existing_types), Some(params)) => Some((
1374                combine_union_types(&existing_types.0, &params.0, codebase, options),
1375                combine_union_types(&existing_types.1, &params.1, codebase, options),
1376            )),
1377        };
1378    }
1379
1380    if any_keyed {
1381        combination.flags.insert(CombinationFlags::HAS_KEYED_ARRAY);
1382    }
1383
1384    combination.sealed_arrays = put_back;
1385}
1386
1387const COMBINER_KEY_STACK_BUF: usize = 256;
1388
1389fn get_combiner_key(name: Atom, type_params: &[TUnion], codebase: &CodebaseMetadata) -> Atom {
1390    let covariants = if let Some(class_like_metadata) = codebase.get_class_like(&name) {
1391        &class_like_metadata.template_variance
1392    } else {
1393        return name;
1394    };
1395
1396    let name_str = name.as_str();
1397    let mut estimated_len = name_str.len() + 2; // name + "<" + ">"
1398    for (i, tunion) in type_params.iter().enumerate() {
1399        if i > 0 {
1400            estimated_len += 2; // ", "
1401        }
1402
1403        if covariants.get(&i) == Some(&Variance::Covariant) {
1404            estimated_len += 1; // "*"
1405        } else {
1406            estimated_len += tunion.get_id().len();
1407        }
1408    }
1409
1410    if estimated_len <= COMBINER_KEY_STACK_BUF {
1411        let mut buffer = [0u8; COMBINER_KEY_STACK_BUF];
1412        let mut pos = 0;
1413
1414        buffer[pos..pos + name_str.len()].copy_from_slice(name_str.as_bytes());
1415        pos += name_str.len();
1416
1417        buffer[pos] = b'<';
1418        pos += 1;
1419
1420        for (i, tunion) in type_params.iter().enumerate() {
1421            if i > 0 {
1422                buffer[pos..pos + 2].copy_from_slice(b", ");
1423                pos += 2;
1424            }
1425            let param_str =
1426                if covariants.get(&i) == Some(&Variance::Covariant) { "*" } else { tunion.get_id().as_str() };
1427            buffer[pos..pos + param_str.len()].copy_from_slice(param_str.as_bytes());
1428            pos += param_str.len();
1429        }
1430
1431        buffer[pos] = b'>';
1432        pos += 1;
1433
1434        // SAFETY: We only write valid UTF-8 (ASCII characters and valid UTF-8 from Atom strings)
1435        return atom(unsafe { std::str::from_utf8_unchecked(&buffer[..pos]) });
1436    }
1437
1438    let mut result = String::with_capacity(estimated_len);
1439    result.push_str(name_str);
1440    result.push('<');
1441    for (i, tunion) in type_params.iter().enumerate() {
1442        if i > 0 {
1443            result.push_str(", ");
1444        }
1445        if covariants.get(&i) == Some(&Variance::Covariant) {
1446            result.push('*');
1447        } else {
1448            result.push_str(tunion.get_id().as_str());
1449        }
1450    }
1451    result.push('>');
1452    atom(&result)
1453}
1454
1455fn combine_string_scalars(s1: &TString, s2: TString) -> TString {
1456    TString {
1457        literal: match (&s1.literal, s2.literal) {
1458            (Some(TStringLiteral::Value(v1)), Some(TStringLiteral::Value(v2))) => {
1459                if v1 == &v2 {
1460                    Some(TStringLiteral::Value(v2))
1461                } else {
1462                    Some(TStringLiteral::Unspecified)
1463                }
1464            }
1465            (Some(TStringLiteral::Unspecified), Some(_)) | (Some(_), Some(TStringLiteral::Unspecified)) => {
1466                Some(TStringLiteral::Unspecified)
1467            }
1468            _ => None,
1469        },
1470        is_numeric: s1.is_numeric && s2.is_numeric,
1471        is_truthy: s1.is_truthy && s2.is_truthy,
1472        is_non_empty: s1.is_non_empty && s2.is_non_empty,
1473        is_callable: s1.is_callable && s2.is_callable,
1474        casing: match (s1.casing, s2.casing) {
1475            (TStringCasing::Lowercase, TStringCasing::Lowercase) => TStringCasing::Lowercase,
1476            (TStringCasing::Uppercase, TStringCasing::Uppercase) => TStringCasing::Uppercase,
1477            _ => TStringCasing::Unspecified,
1478        },
1479    }
1480}
1481
1482#[cfg(test)]
1483mod tests {
1484    use std::collections::BTreeMap;
1485
1486    use super::*;
1487
1488    use crate::ttype::atomic::TAtomic;
1489    use crate::ttype::atomic::array::list::TList;
1490    use crate::ttype::atomic::scalar::TScalar;
1491
1492    #[test]
1493    fn test_combine_scalars() {
1494        let types = vec![
1495            TAtomic::Scalar(TScalar::string()),
1496            TAtomic::Scalar(TScalar::int()),
1497            TAtomic::Scalar(TScalar::float()),
1498            TAtomic::Scalar(TScalar::bool()),
1499        ];
1500
1501        let combined =
1502            combine(types, &CodebaseMetadata::default(), CombinerOptions::default().with_overwrite_empty_array());
1503
1504        assert_eq!(combined.len(), 1);
1505        assert!(matches!(combined[0], TAtomic::Scalar(TScalar::Generic)));
1506    }
1507
1508    #[test]
1509    fn test_combine_boolean_lists() {
1510        let types = vec![
1511            TAtomic::Array(TArray::List(TList::from_known_elements(BTreeMap::from_iter([
1512                (0, (false, TUnion::from_atomic(TAtomic::Scalar(TScalar::r#false())))),
1513                (1, (false, TUnion::from_atomic(TAtomic::Scalar(TScalar::r#true())))),
1514            ])))),
1515            TAtomic::Array(TArray::List(TList::from_known_elements(BTreeMap::from_iter([
1516                (0, (false, TUnion::from_atomic(TAtomic::Scalar(TScalar::r#true())))),
1517                (1, (false, TUnion::from_atomic(TAtomic::Scalar(TScalar::r#false())))),
1518            ])))),
1519        ];
1520
1521        let combined =
1522            combine(types, &CodebaseMetadata::default(), CombinerOptions::default().with_overwrite_empty_array());
1523
1524        assert_eq!(combined.len(), 2);
1525        assert!(matches!(combined[0], TAtomic::Array(TArray::List(_))));
1526        assert!(matches!(combined[1], TAtomic::Array(TArray::List(_))));
1527    }
1528
1529    #[test]
1530    fn test_combine_integer_lists() {
1531        let types = vec![
1532            TAtomic::Array(TArray::List(TList::from_known_elements(BTreeMap::from_iter([
1533                (0, (false, TUnion::from_atomic(TAtomic::Scalar(TScalar::Integer(TInteger::literal(1)))))),
1534                (1, (false, TUnion::from_atomic(TAtomic::Scalar(TScalar::Integer(TInteger::literal(2)))))),
1535            ])))),
1536            TAtomic::Array(TArray::List(TList::from_known_elements(BTreeMap::from_iter([
1537                (0, (false, TUnion::from_atomic(TAtomic::Scalar(TScalar::Integer(TInteger::literal(2)))))),
1538                (1, (false, TUnion::from_atomic(TAtomic::Scalar(TScalar::Integer(TInteger::literal(1)))))),
1539            ])))),
1540        ];
1541
1542        let combined =
1543            combine(types, &CodebaseMetadata::default(), CombinerOptions::default().with_overwrite_empty_array());
1544
1545        assert_eq!(combined.len(), 2);
1546        assert!(matches!(combined[0], TAtomic::Array(TArray::List(_))));
1547        assert!(matches!(combined[1], TAtomic::Array(TArray::List(_))));
1548    }
1549
1550    #[test]
1551    fn test_combine_string_lists() {
1552        let types = vec![
1553            TAtomic::Array(TArray::List(TList::from_known_elements(BTreeMap::from_iter([
1554                (0, (false, TUnion::from_atomic(TAtomic::Scalar(TScalar::String(TString::known_literal("a".into())))))),
1555                (1, (false, TUnion::from_atomic(TAtomic::Scalar(TScalar::String(TString::known_literal("b".into())))))),
1556            ])))),
1557            TAtomic::Array(TArray::List(TList::from_known_elements(BTreeMap::from_iter([
1558                (0, (false, TUnion::from_atomic(TAtomic::Scalar(TScalar::String(TString::known_literal("b".into())))))),
1559                (1, (false, TUnion::from_atomic(TAtomic::Scalar(TScalar::String(TString::known_literal("a".into())))))),
1560            ])))),
1561        ];
1562
1563        let combined =
1564            combine(types, &CodebaseMetadata::default(), CombinerOptions::default().with_overwrite_empty_array());
1565
1566        assert_eq!(combined.len(), 2);
1567        assert!(matches!(combined[0], TAtomic::Array(TArray::List(_))));
1568        assert!(matches!(combined[1], TAtomic::Array(TArray::List(_))));
1569    }
1570
1571    #[test]
1572    fn test_combine_mixed_literal_lists() {
1573        let types = vec![
1574            TAtomic::Array(TArray::List(TList::from_known_elements(BTreeMap::from_iter([
1575                (0, (false, TUnion::from_atomic(TAtomic::Scalar(TScalar::Integer(TInteger::literal(1)))))),
1576                (1, (false, TUnion::from_atomic(TAtomic::Scalar(TScalar::String(TString::known_literal("a".into())))))),
1577            ])))),
1578            TAtomic::Array(TArray::List(TList::from_known_elements(BTreeMap::from_iter([
1579                (0, (false, TUnion::from_atomic(TAtomic::Scalar(TScalar::String(TString::known_literal("b".into())))))),
1580                (1, (false, TUnion::from_atomic(TAtomic::Scalar(TScalar::Integer(TInteger::literal(2)))))),
1581            ])))),
1582        ];
1583
1584        let combined =
1585            combine(types, &CodebaseMetadata::default(), CombinerOptions::default().with_overwrite_empty_array());
1586
1587        assert_eq!(combined.len(), 2);
1588        assert!(matches!(combined[0], TAtomic::Array(TArray::List(_))));
1589        assert!(matches!(combined[1], TAtomic::Array(TArray::List(_))));
1590    }
1591
1592    #[test]
1593    fn test_combine_list_with_generic_list() {
1594        let types = vec![
1595            TAtomic::Array(TArray::List(TList::from_known_elements(BTreeMap::from_iter([
1596                (0, (false, TUnion::from_atomic(TAtomic::Scalar(TScalar::Integer(TInteger::literal(1)))))),
1597                (1, (false, TUnion::from_atomic(TAtomic::Scalar(TScalar::Integer(TInteger::literal(2)))))),
1598            ])))),
1599            TAtomic::Array(TArray::List(TList::new(Arc::new(TUnion::from_atomic(TAtomic::Scalar(TScalar::int())))))), // list<int>
1600        ];
1601
1602        let combined =
1603            combine(types, &CodebaseMetadata::default(), CombinerOptions::default().with_overwrite_empty_array());
1604
1605        // Expecting list{1,2} and list<int> = list<int>
1606        assert_eq!(combined.len(), 1);
1607
1608        let TAtomic::Array(TArray::List(list_type)) = &combined[0] else {
1609            panic!("Expected a list type");
1610        };
1611
1612        let Some(known_elements) = &list_type.known_elements else {
1613            panic!("Expected known elements");
1614        };
1615
1616        assert!(!list_type.is_non_empty());
1617        assert!(list_type.known_count.is_none());
1618        assert!(list_type.element_type.is_int());
1619
1620        assert_eq!(known_elements.len(), 2);
1621        assert!(known_elements.contains_key(&0));
1622        assert!(known_elements.contains_key(&1));
1623
1624        let Some(first_element) = known_elements.get(&0) else {
1625            panic!("Expected first element");
1626        };
1627
1628        let Some(second_element) = known_elements.get(&1) else {
1629            panic!("Expected second element");
1630        };
1631
1632        assert!(first_element.1.is_int());
1633        assert!(second_element.1.is_int());
1634    }
1635}