swc_typescript/fast_dts/
function.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
use std::mem;

use swc_atoms::Atom;
use swc_common::{Span, Spanned, DUMMY_SP};
use swc_ecma_ast::{
    AssignPat, Decl, ExportDecl, Function, ModuleDecl, ModuleItem, Param, Pat, Script, Stmt,
    TsKeywordTypeKind, TsType, TsTypeAnn, TsUnionOrIntersectionType, TsUnionType,
};

use super::{
    type_ann,
    util::types::{any_type_ann, ts_keyword_type},
    FastDts,
};

impl FastDts {
    pub(crate) fn transform_fn(&mut self, func: &mut Function, ident_span: Option<Span>) {
        self.transform_fn_return_type(func);
        if func.return_type.is_none() {
            self.function_must_have_explicit_return_type(
                ident_span.unwrap_or_else(|| Span::new(func.span_lo(), func.body.span_lo())),
            );
        }
        self.transform_fn_params(&mut func.params);
        func.is_async = false;
        func.is_generator = false;
        func.body = None
    }

    pub(crate) fn transform_fn_return_type(&mut self, func: &mut Function) {
        if func.return_type.is_none() && !func.is_async && !func.is_generator {
            func.return_type = self.infer_function_return_type(func);
        }
    }

    pub(crate) fn transform_fn_params(&mut self, params: &mut [Param]) {
        // If there is required param after current param.
        let mut is_required = false;
        for param in params.iter_mut().rev() {
            is_required |= match &param.pat {
                Pat::Ident(binding_ident) => !binding_ident.optional,
                Pat::Array(array_pat) => !array_pat.optional,
                Pat::Object(object_pat) => !object_pat.optional,
                Pat::Assign(_) | Pat::Invalid(_) | Pat::Expr(_) | Pat::Rest(_) => false,
            };
            self.transform_fn_param(param, is_required);
        }
    }

    pub(crate) fn transform_fn_param(&mut self, param: &mut Param, is_required: bool) {
        // 1. Check assign pat type
        if let Pat::Assign(assign_pat) = &mut param.pat {
            if self.check_assign_pat_param(assign_pat) {
                self.parameter_must_have_explicit_type(param.span);
                return;
            }
        }

        // 2. Infer type annotation
        let (type_ann, should_add_undefined) = match &mut param.pat {
            Pat::Ident(ident) => {
                if ident.type_ann.is_none() {
                    self.parameter_must_have_explicit_type(param.span);
                }
                let is_none = ident.type_ann.is_none();
                (ident.type_ann.as_mut(), is_none)
            }
            Pat::Array(arr_pat) => {
                if arr_pat.type_ann.is_none() {
                    self.parameter_must_have_explicit_type(param.span);
                }
                let is_none = arr_pat.type_ann.is_none();
                (arr_pat.type_ann.as_mut(), is_none)
            }
            Pat::Object(obj_pat) => {
                if obj_pat.type_ann.is_none() {
                    self.parameter_must_have_explicit_type(param.span);
                }
                let is_none = obj_pat.type_ann.is_none();
                (obj_pat.type_ann.as_mut(), is_none)
            }
            Pat::Assign(assign_pat) => {
                if !self.transform_assign_pat(assign_pat, is_required) {
                    self.parameter_must_have_explicit_type(param.span);
                }

                (
                    match assign_pat.left.as_mut() {
                        Pat::Ident(ident) => ident.type_ann.as_mut(),
                        Pat::Array(array_pat) => array_pat.type_ann.as_mut(),
                        Pat::Object(object_pat) => object_pat.type_ann.as_mut(),
                        Pat::Assign(_) | Pat::Rest(_) | Pat::Invalid(_) | Pat::Expr(_) => return,
                    },
                    true,
                )
            }
            Pat::Rest(_) | Pat::Expr(_) | Pat::Invalid(_) => (None, false),
        };

        // 3. Add undefined type if needed
        if let Some(type_ann) = type_ann {
            if is_required && should_add_undefined && self.add_undefined_type_for_param(type_ann) {
                self.implicitly_adding_undefined_to_type(param.span);
            }
        }

        // 4. Flat param pat
        let pat = mem::take(&mut param.pat);
        param.pat = match pat {
            Pat::Assign(assign_pat) => *assign_pat.left,
            _ => pat,
        };
    }

    pub(crate) fn transform_assign_pat(
        &mut self,
        assign_pat: &mut AssignPat,
        is_required: bool,
    ) -> bool {
        // We can only infer types from the right expr of assign pat
        let left_type_ann = match assign_pat.left.as_mut() {
            Pat::Ident(ident) => {
                ident.optional |= !is_required;
                &mut ident.type_ann
            }
            Pat::Array(array_pat) => {
                array_pat.optional |= !is_required;
                &mut array_pat.type_ann
            }
            Pat::Object(object_pat) => {
                object_pat.optional |= !is_required;
                &mut object_pat.type_ann
            }
            // These are illegal
            Pat::Assign(_) | Pat::Rest(_) | Pat::Invalid(_) | Pat::Expr(_) => return true,
        };

        let mut has_expclicit_type = true;
        if left_type_ann.is_none() {
            *left_type_ann = self
                .infer_type_from_expr(&assign_pat.right)
                .map(type_ann)
                .or_else(|| {
                    has_expclicit_type = false;
                    Some(any_type_ann())
                });
        }
        has_expclicit_type
    }

    pub(crate) fn check_assign_pat_param(&mut self, assign_pat: &AssignPat) -> bool {
        assign_pat
            .left
            .as_array()
            .map(|array_pat| array_pat.type_ann.is_none())
            .unwrap_or(false)
            || assign_pat
                .left
                .as_object()
                .map(|object_pat| object_pat.type_ann.is_none())
                .unwrap_or(false)
    }

    pub(crate) fn add_undefined_type_for_param(&mut self, type_ann: &mut TsTypeAnn) -> bool {
        if type_ann.type_ann.is_ts_type_ref() {
            return true;
        }

        if !is_maybe_undefined(&type_ann.type_ann) {
            type_ann.type_ann = Box::new(TsType::TsUnionOrIntersectionType(
                TsUnionOrIntersectionType::TsUnionType(TsUnionType {
                    span: DUMMY_SP,
                    types: vec![
                        type_ann.type_ann.clone(),
                        ts_keyword_type(TsKeywordTypeKind::TsUndefinedKeyword),
                    ],
                }),
            ))
        }

        false
    }

    pub(crate) fn remove_function_overloads_in_module(items: &mut Vec<ModuleItem>) {
        let mut last_function_name: Option<Atom> = None;
        let mut is_export_default_function_overloads = false;

        items.retain(|item| match item {
            ModuleItem::Stmt(Stmt::Decl(Decl::Fn(fn_decl)))
            | ModuleItem::ModuleDecl(ModuleDecl::ExportDecl(ExportDecl {
                decl: Decl::Fn(fn_decl),
                ..
            })) => {
                if fn_decl.function.body.is_some() {
                    if last_function_name
                        .as_ref()
                        .is_some_and(|last_name| last_name == &fn_decl.ident.sym)
                    {
                        return false;
                    }
                } else {
                    last_function_name = Some(fn_decl.ident.sym.clone());
                }
                true
            }
            ModuleItem::ModuleDecl(ModuleDecl::ExportDefaultDecl(export)) => {
                if let Some(fn_expr) = export.decl.as_fn_expr() {
                    if is_export_default_function_overloads && fn_expr.function.body.is_some() {
                        is_export_default_function_overloads = false;
                        false
                    } else {
                        is_export_default_function_overloads = true;
                        true
                    }
                } else {
                    is_export_default_function_overloads = false;
                    true
                }
            }
            _ => true,
        });
    }

    pub(crate) fn remove_function_overloads_in_script(script: &mut Script) {
        let mut last_function_name: Option<Atom> = None;
        script.body.retain(|stmt| {
            if let Some(fn_decl) = stmt.as_decl().and_then(|decl| decl.as_fn_decl()) {
                if fn_decl.function.body.is_some() {
                    if last_function_name
                        .as_ref()
                        .is_some_and(|last_name| last_name == &fn_decl.ident.sym)
                    {
                        return false;
                    }
                } else {
                    last_function_name = Some(fn_decl.ident.sym.clone());
                }
            }
            true
        });
    }
}

fn is_maybe_undefined(ts_type: &TsType) -> bool {
    match ts_type {
        TsType::TsKeywordType(keyword_type) => matches!(
            keyword_type.kind,
            TsKeywordTypeKind::TsAnyKeyword
                | TsKeywordTypeKind::TsUndefinedKeyword
                | TsKeywordTypeKind::TsUnknownKeyword
        ),
        TsType::TsUnionOrIntersectionType(TsUnionOrIntersectionType::TsUnionType(union_type)) => {
            union_type.types.iter().any(|ty| is_maybe_undefined(ty))
        }
        _ => false,
    }
}