Skip to main content

mir_types/
generalize.rs

1//! Widening of types that keep growing: loop fixed points and the global size guard.
2
3use std::sync::Arc;
4
5use crate::atomic::{ArrayKey, Atomic};
6use crate::union::{combine_generic_arrays, Type};
7
8/// Array nesting kept before deeper levels collapse to `array<array-key, mixed>`.
9pub const MAX_ARRAY_DEPTH: usize = 8;
10
11/// Union members before generalizing; literal strings and ints (`int-mask-of`) have own limits and don't count.
12pub const MAX_UNION_MEMBERS: usize = 30;
13
14/// Array levels [`Type::generalized`] keeps below the top one.
15const LOOP_WIDENING_DEPTH: usize = 1;
16
17impl Type {
18    /// Deepest array nesting in this type: `int` is 0, `list<int>` 1, `array{0: list<int>}` 2.
19    pub fn array_depth(&self) -> usize {
20        self.types.iter().map(atomic_array_depth).max().unwrap_or(0)
21    }
22
23    /// Literals to base types, shapes to generic arrays, values two levels down to `mixed`; idempotent.
24    pub fn generalized(&self) -> Type {
25        self.generalized_to(LOOP_WIDENING_DEPTH)
26    }
27
28    fn generalized_to(&self, depth: usize) -> Type {
29        let mut out = Type::empty();
30        out.possibly_undefined = self.possibly_undefined;
31        out.from_docblock = self.from_docblock;
32        out.falsy_stripped = self.falsy_stripped;
33        out.possibly_absent_offset = self.possibly_absent_offset;
34        // One generic array per kind keeps the form canonical across loop passes.
35        let mut folded: Vec<Atomic> = Vec::with_capacity(self.types.len());
36        for atomic in &self.types {
37            let mut general = generalize_atomic(atomic, depth);
38            if let Some((i, combined)) = folded
39                .iter()
40                .enumerate()
41                .find_map(|(i, f)| combine_generic_arrays(f, &general).map(|c| (i, c)))
42            {
43                folded.swap_remove(i);
44                general = combined;
45            }
46            folded.push(general);
47        }
48        for atomic in folded {
49            out.add_type(atomic);
50        }
51        out
52    }
53}
54
55fn atomic_array_depth(atomic: &Atomic) -> usize {
56    let mut deepest = 0;
57    let is_array = any_array_child(atomic, |ty| {
58        deepest = deepest.max(ty.array_depth());
59        false
60    });
61    is_array.map_or(0, |_| 1 + deepest)
62}
63
64/// Whether `f` holds for a value type nested in array `atomic`; `None` for a non-array.
65fn any_array_child(atomic: &Atomic, mut f: impl FnMut(&Type) -> bool) -> Option<bool> {
66    match atomic {
67        Atomic::TArray { value, .. }
68        | Atomic::TNonEmptyArray { value, .. }
69        | Atomic::TList { value }
70        | Atomic::TNonEmptyList { value } => Some(f(value)),
71        Atomic::TKeyedArray { properties, .. } => Some(
72            properties.values().any(|p| f(&p.ty)) || properties.remainder.as_ref().is_some_and(f),
73        ),
74        _ => None,
75    }
76}
77
78/// Whether `atomic` nests arrays more than `limit` levels deep.
79pub(crate) fn exceeds_array_depth(atomic: &Atomic, limit: usize) -> bool {
80    any_array_child(atomic, |ty| {
81        limit == 0 || ty.types.iter().any(|a| exceeds_array_depth(a, limit - 1))
82    })
83    .unwrap_or(false)
84}
85
86/// `atomic` with arrays nested past [`MAX_ARRAY_DEPTH`] levels generalized away.
87pub fn cap_array_depth(atomic: Atomic) -> Atomic {
88    if exceeds_array_depth(&atomic, MAX_ARRAY_DEPTH) {
89        truncate_depth(&atomic, MAX_ARRAY_DEPTH)
90    } else {
91        atomic
92    }
93}
94
95fn truncate_depth(atomic: &Atomic, limit: usize) -> Atomic {
96    if limit <= 1 {
97        return generalize_atomic(atomic, 0);
98    }
99    let inner = |ty: &Type| {
100        let mut out = ty.clone();
101        out.types = ty
102            .types
103            .iter()
104            .map(|a| truncate_depth(a, limit - 1))
105            .collect();
106        out
107    };
108    map_array_values(atomic, inner).unwrap_or_else(|| atomic.clone())
109}
110
111/// `atomic` with `f` applied to its nested value types, keeping its kind.
112fn map_array_values(atomic: &Atomic, mut f: impl FnMut(&Type) -> Type) -> Option<Atomic> {
113    Some(match atomic {
114        Atomic::TArray { key, value } => Atomic::TArray {
115            key: key.clone(),
116            value: Box::new(f(value)),
117        },
118        Atomic::TNonEmptyArray { key, value } => Atomic::TNonEmptyArray {
119            key: key.clone(),
120            value: Box::new(f(value)),
121        },
122        Atomic::TList { value } => Atomic::TList {
123            value: Box::new(f(value)),
124        },
125        Atomic::TNonEmptyList { value } => Atomic::TNonEmptyList {
126            value: Box::new(f(value)),
127        },
128        Atomic::TKeyedArray {
129            properties,
130            is_open,
131            is_list,
132        } => Atomic::TKeyedArray {
133            properties: Arc::new(properties.map_types(f)),
134            is_open: *is_open,
135            is_list: *is_list,
136        },
137        _ => return None,
138    })
139}
140
141/// Whether [`generalize_atomic`] would change `atomic` at the top level.
142pub(crate) fn is_generalizable(atomic: &Atomic) -> bool {
143    match atomic {
144        Atomic::TKeyedArray { properties, .. } => !properties.is_empty(),
145        Atomic::TLiteralInt(_)
146        | Atomic::TIntRange { .. }
147        | Atomic::TPositiveInt
148        | Atomic::TNegativeInt
149        | Atomic::TNonNegativeInt
150        | Atomic::TLiteralString(_)
151        | Atomic::TLiteralFloat(..)
152        | Atomic::TTrue
153        | Atomic::TFalse => true,
154        _ => false,
155    }
156}
157
158/// Generalizes `atomic`, keeping `depth` array levels below it before values become `mixed`.
159pub(crate) fn generalize_atomic(atomic: &Atomic, depth: usize) -> Atomic {
160    let value_of = |ty: &Type| -> Box<Type> {
161        Box::new(if depth == 0 {
162            Type::mixed()
163        } else {
164            ty.generalized_to(depth - 1)
165        })
166    };
167    match atomic {
168        Atomic::TLiteralInt(_)
169        | Atomic::TIntRange { .. }
170        | Atomic::TPositiveInt
171        | Atomic::TNegativeInt
172        | Atomic::TNonNegativeInt => Atomic::TInt,
173        Atomic::TLiteralString(_) => Atomic::TString,
174        Atomic::TLiteralFloat(..) => Atomic::TFloat,
175        Atomic::TTrue | Atomic::TFalse => Atomic::TBool,
176        Atomic::TArray { key, value } => Atomic::TArray {
177            key: Box::new(key.generalized_to(0)),
178            value: value_of(value),
179        },
180        Atomic::TNonEmptyArray { key, value } => Atomic::TNonEmptyArray {
181            key: Box::new(key.generalized_to(0)),
182            value: value_of(value),
183        },
184        Atomic::TList { value } => Atomic::TList {
185            value: value_of(value),
186        },
187        Atomic::TNonEmptyList { value } => Atomic::TNonEmptyList {
188            value: value_of(value),
189        },
190        Atomic::TKeyedArray { properties, .. } if properties.is_empty() => atomic.clone(),
191        Atomic::TKeyedArray {
192            properties,
193            is_open,
194            is_list,
195        } => {
196            if *is_open && properties.remainder.is_none() {
197                return Atomic::TArray {
198                    key: Box::new(Type::array_key()),
199                    value: Box::new(Type::mixed()),
200                };
201            }
202            let mut values = Type::empty();
203            for ty in properties
204                .values()
205                .map(|p| &p.ty)
206                .chain(properties.remainder.as_ref())
207            {
208                values.merge_with(ty);
209            }
210            let value = value_of(&values);
211            let non_empty = properties.values().any(|p| !p.optional);
212            if *is_list {
213                return if non_empty {
214                    Atomic::TNonEmptyList { value }
215                } else {
216                    Atomic::TList { value }
217                };
218            }
219            let has_int = properties.keys().any(|k| matches!(k, ArrayKey::Int(_)));
220            let has_string = properties.keys().any(|k| matches!(k, ArrayKey::String(_)));
221            let key = Box::new(match (has_int, has_string) {
222                (true, false) => Type::int(),
223                (false, true) => Type::string(),
224                _ => Type::array_key(),
225            });
226            if non_empty {
227                Atomic::TNonEmptyArray { key, value }
228            } else {
229                Atomic::TArray { key, value }
230            }
231        }
232        _ => atomic.clone(),
233    }
234}
235
236#[cfg(test)]
237mod tests {
238    use super::*;
239    use crate::atomic::KeyedProperty;
240
241    fn list_of(ty: Type) -> Type {
242        let mut props = crate::KeyedProperties::default();
243        props.insert(
244            ArrayKey::Int(0),
245            KeyedProperty {
246                ty,
247                optional: false,
248            },
249        );
250        Type::single(Atomic::TKeyedArray {
251            properties: Arc::new(props),
252            is_open: false,
253            is_list: true,
254        })
255    }
256
257    #[test]
258    fn generalizing_a_recursive_shape_reaches_a_fixed_point() {
259        let mut ty = Type::single(Atomic::TLiteralInt(0));
260        ty.merge_with(&list_of(list_of(Type::single(Atomic::TLiteralInt(0)))));
261        let step = |w: &Type| {
262            let mut next = w.clone();
263            next.merge_with(&list_of(w.clone()));
264            next.generalized()
265        };
266        let mut widened = ty.generalized();
267        for _ in 0..2 {
268            widened = step(&widened);
269        }
270        assert_eq!(step(&widened), widened);
271        assert!(widened.array_depth() <= LOOP_WIDENING_DEPTH + 1);
272    }
273
274    #[test]
275    fn depth_cap_bounds_nesting() {
276        let mut ty = Type::int();
277        for _ in 0..20 {
278            ty = list_of(ty);
279        }
280        let capped = cap_array_depth(ty.types[0].clone());
281        assert_eq!(Type::single(capped).array_depth(), MAX_ARRAY_DEPTH);
282    }
283
284    #[test]
285    fn merging_deep_shapes_caps_their_depth() {
286        let mut ty = Type::int();
287        for _ in 0..20 {
288            let mut next = Type::empty();
289            next.merge_with(&list_of(ty.clone()));
290            next.merge_with(&ty);
291            ty = next;
292        }
293        assert!(ty.array_depth() <= MAX_ARRAY_DEPTH);
294    }
295
296    #[test]
297    fn wide_union_generalizes_literals() {
298        let mut ty = Type::empty();
299        for n in 0..100 {
300            ty.merge_with(&Type::single(Atomic::TLiteralFloat(n, 0)));
301        }
302        assert!(ty.types.len() <= MAX_UNION_MEMBERS + 1, "{ty:?}");
303        assert!(ty.types.contains(&Atomic::TFloat));
304    }
305}