1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
use rnode::{Fold, FoldWith, Visit, VisitWith};
use stc_ts_ast_rnode::{RBool, RNumber, RStr, RTsLit};
use stc_ts_base_type_ops::is_str_lit_or_union;
use stc_ts_types::{
    Array, Class, ClassProperty, Conditional, Function, IndexedAccessType, Interface, KeywordType, KeywordTypeMetadata, LitType, Ref,
    RestType, TplType, Tuple, Type, TypeLit, Union,
};
use stc_utils::ext::TypeVecExt;
use swc_ecma_ast::TsKeywordTypeKind;

pub use self::metadata::prevent_generalize;

mod metadata;

pub struct LitGeneralizer;

impl Fold<Ref> for LitGeneralizer {
    fn fold(&mut self, mut r: Ref) -> Ref {
        r.type_name = r.type_name.fold_with(self);

        r
    }
}

impl Fold<Union> for LitGeneralizer {
    fn fold(&mut self, mut u: Union) -> Union {
        u = u.fold_children_with(self);

        u.types.dedup_type();

        u
    }
}

impl Fold<Tuple> for LitGeneralizer {
    fn fold(&mut self, mut tuple: Tuple) -> Tuple {
        tuple = tuple.fold_children_with(self);

        let has_rest = tuple
            .elems
            .iter()
            .map(|element| &element.ty)
            .any(|ty| matches!(&**ty, Type::Rest(..)));

        if has_rest {
            // Handle rest
            let mut rest_ty = None;

            // Remove types after `...boolean[]`
            tuple.elems.retain(|element| {
                match element.ty.normalize() {
                    Type::Rest(RestType {
                        ty: box Type::Array(Array { elem_type, .. }),
                        ..
                    }) => {
                        rest_ty = Some(elem_type.clone());
                    }
                    _ => {
                        if let Some(_rest_ty) = &rest_ty {
                            return false;
                        }
                    }
                }

                true
            });
        }

        tuple
    }
}

impl Fold<Type> for LitGeneralizer {
    fn fold(&mut self, mut ty: Type) -> Type {
        {
            let mut checker = LitChecker { found: false };
            ty.visit_with(&mut checker);

            if !checker.found {
                return ty;
            }
        }

        ty.normalize_mut();

        match &ty {
            Type::IndexedAccessType(IndexedAccessType { index_type, .. }) if is_str_lit_or_union(index_type) => {
                return ty;
            }
            _ => {}
        }

        ty = ty.fold_children_with(self);

        match ty {
            Type::Lit(LitType {
                span, ref lit, metadata, ..
            }) => {
                if metadata.common.prevent_generalization {
                    return ty;
                }

                Type::Keyword(KeywordType {
                    span,
                    kind: match *lit {
                        RTsLit::Bool(RBool { .. }) => TsKeywordTypeKind::TsBooleanKeyword,
                        RTsLit::Number(RNumber { .. }) => TsKeywordTypeKind::TsNumberKeyword,
                        RTsLit::Str(RStr { .. }) => TsKeywordTypeKind::TsStringKeyword,
                        RTsLit::Tpl(..) => TsKeywordTypeKind::TsStringKeyword,
                        RTsLit::BigInt(..) => TsKeywordTypeKind::TsBigIntKeyword,
                    },
                    metadata: KeywordTypeMetadata {
                        common: metadata.common,
                        ..Default::default()
                    },
                    tracker: Default::default(),
                })
            }
            Type::Tpl(TplType { span, metadata, .. }) => Type::Keyword(KeywordType {
                span,
                kind: TsKeywordTypeKind::TsStringKeyword,
                metadata: KeywordTypeMetadata {
                    common: metadata.common,
                    ..Default::default()
                },
                tracker: Default::default(),
            }),
            _ => ty,
        }
    }
}

impl Fold<Function> for LitGeneralizer {
    fn fold(&mut self, node: Function) -> Function {
        node
    }
}

impl Fold<Interface> for LitGeneralizer {
    fn fold(&mut self, node: Interface) -> Interface {
        node
    }
}

impl Fold<Class> for LitGeneralizer {
    fn fold(&mut self, node: Class) -> Class {
        node
    }
}

impl Fold<ClassProperty> for LitGeneralizer {
    fn fold(&mut self, node: ClassProperty) -> ClassProperty {
        if node.readonly {
            return node;
        }
        node.fold_children_with(self)
    }
}

impl Fold<TypeLit> for LitGeneralizer {
    fn fold(&mut self, node: TypeLit) -> TypeLit {
        if node.metadata.specified {
            return node;
        }
        node.fold_children_with(self)
    }
}

impl Fold<Conditional> for LitGeneralizer {
    fn fold(&mut self, n: Conditional) -> Conditional {
        n
    }
}

struct LitChecker {
    found: bool,
}

impl Visit<Type> for LitChecker {
    fn visit(&mut self, ty: &Type) {
        if self.found {
            return;
        }

        if let Type::Lit(LitType { metadata, .. }) = ty.normalize() {
            if metadata.common.prevent_generalization {
                return;
            }

            self.found = true;
            return;
        }
        if let Type::Tpl(TplType { metadata, .. }) = ty.normalize() {
            if metadata.common.prevent_generalization {
                return;
            }

            self.found = true;
            return;
        }

        ty.visit_children_with(self);
    }
}