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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
//! Passes for generating dts.

#![allow(incomplete_features)]
#![feature(box_syntax)]
#![feature(box_patterns)]
#![feature(specialization)]
use fxhash::FxHashSet;
use rnode::{NodeId, Visit, VisitMut, VisitMutWith, VisitWith};
use stc_ts_ast_rnode::{
    RArrayPat, RAssignPat, RBlockStmt, RClass, RClassDecl, RClassMember, RClassProp, RDecl, RExportDecl, RExportDefaultExpr, RExpr,
    RFnDecl, RIdent, RImportDecl, RImportSpecifier, RMemberExpr, RMemberProp, RModuleDecl, RModuleItem, RNamedExport, RParamOrTsParamProp,
    RPat, RPrivateName, RPrivateProp, RPropName, RStmt, RTsEntityName, RTsEnumDecl, RTsIndexSignature, RTsInterfaceDecl, RTsKeywordType,
    RTsModuleDecl, RTsParamProp, RTsParamPropParam, RTsPropertySignature, RTsType, RTsTypeAliasDecl, RTsTypeAnn, RVarDecl, RVarDeclarator,
};
use stc_ts_types::{Id, ModuleTypeData};
use stc_ts_utils::{find_ids_in_pat, MapWithMut};
use swc_common::DUMMY_SP;
use swc_ecma_ast::*;

use self::{
    ambient::RealImplRemover,
    dce::{get_used, DceForDts},
};
pub use crate::mutations::apply_mutations;

mod ambient;
mod dce;
mod mutations;

/// Make `module` suitable for .d.ts file.
///
/// - Removes function body
pub fn cleanup_module_for_dts(module: &mut Vec<RModuleItem>, type_data: &ModuleTypeData) {
    let is_module = module.iter().any(|item| match item {
        RModuleItem::ModuleDecl(_) => true,
        RModuleItem::Stmt(_) => false,
    });

    module.visit_mut_with(&mut RealImplRemover::default());

    let (used_types, used_vars) = {
        let mut v = TypeUsageCollector {
            phase: CollectorPhase::SearchExports,
            is_module,
            in_module_item: false,
            used_types: Default::default(),
            used_vars: Default::default(),
        };
        module.visit_with(&mut v);

        v.phase = CollectorPhase::AddTypes;
        module.visit_with(&mut v);
        (v.used_types, v.used_vars)
    };

    module.visit_mut_with(&mut Dts {
        preserve_stmt: false,
        used_types,
        used_vars,
    });

    module.visit_mut_with(&mut DceForDts {
        used: get_used(type_data),
        info: type_data,
        current_class: None,
        in_declare: false,
        top_level: true,
        forced_module: false,
        prevent_empty_export: false,
    })
}

enum CollectorPhase {
    SearchExports,
    AddTypes,
}

struct TypeUsageCollector {
    phase: CollectorPhase,
    is_module: bool,
    in_module_item: bool,
    /// This includes types **only** used in public interface.
    used_types: FxHashSet<Id>,
    used_vars: FxHashSet<Id>,
}

impl Visit<RDecl> for TypeUsageCollector {
    fn visit(&mut self, decl: &RDecl) {
        match self.phase {
            CollectorPhase::SearchExports => {
                if self.is_module && !self.in_module_item {
                    return;
                }
            }
            CollectorPhase::AddTypes => {
                if self.is_module {
                    match decl {
                        RDecl::Class(RClassDecl { ident, .. })
                        | RDecl::Fn(RFnDecl { ident, .. })
                        | RDecl::TsInterface(box RTsInterfaceDecl { id: ident, .. })
                        | RDecl::TsTypeAlias(box RTsTypeAliasDecl { id: ident, .. })
                        | RDecl::TsEnum(box RTsEnumDecl { id: ident, .. }) => {
                            if !self.used_types.contains(&ident.into()) {
                                return;
                            }
                        }
                        RDecl::Var(var) => {
                            let ids: Vec<Id> = find_ids_in_pat(&var.decls);

                            for id in ids {
                                if self.used_types.contains(&id) {
                                    decl.visit_children_with(self);
                                    return;
                                }
                            }
                            return;
                        }
                        RDecl::TsModule(_) => {}
                    }
                }
            }
        }

        decl.visit_children_with(self)
    }
}

impl Visit<RExportDecl> for TypeUsageCollector {
    fn visit(&mut self, export: &RExportDecl) {
        let old = self.in_module_item;
        self.in_module_item = true;
        export.decl.visit_with(self);
        self.in_module_item = old;
    }
}

impl Visit<RExportDefaultExpr> for TypeUsageCollector {
    fn visit(&mut self, export: &RExportDefaultExpr) {
        if let RExpr::Ident(i) = &*export.expr {
            self.used_vars.insert(i.into());
        }
    }
}

impl Visit<RClass> for TypeUsageCollector {
    fn visit(&mut self, class: &RClass) {
        class.visit_children_with(self);

        fn left_most(e: &RExpr) -> Option<Id> {
            match e {
                RExpr::Ident(i) => Some(i.into()),
                RExpr::Member(RMemberExpr {
                    obj: e,
                    prop: RMemberProp::Ident(..) | RMemberProp::PrivateName(..),
                    ..
                }) => left_most(e),
                _ => None,
            }
        }

        if let Some(e) = &class.super_class {
            if let Some(id) = left_most(e) {
                self.used_types.insert(id.clone());
                self.used_vars.insert(id);
            }
        }
    }
}

impl Visit<RTsEntityName> for TypeUsageCollector {
    fn visit(&mut self, n: &RTsEntityName) {
        match n {
            RTsEntityName::TsQualifiedName(_) => {
                n.visit_children_with(self);
            }
            RTsEntityName::Ident(i) => {
                let id = Id::from(i);
                // Exports may refer to module-private types.
                self.used_types.insert(id);
            }
        }
    }
}

impl Visit<Option<RBlockStmt>> for TypeUsageCollector {
    fn visit(&mut self, _: &Option<RBlockStmt>) {}
}

struct Dts {
    preserve_stmt: bool,
    used_types: FxHashSet<Id>,
    used_vars: FxHashSet<Id>,
}

impl VisitMut<RClassMember> for Dts {
    fn visit_mut(&mut self, m: &mut RClassMember) {
        if let RClassMember::Method(method) = m {
            if let Some(Accessibility::Private) = method.accessibility {
                // Converts a private method to a private property without type.
                *m = RClassMember::ClassProp(RClassProp {
                    node_id: NodeId::invalid(),
                    span: method.span,
                    key: method.key.clone(),
                    value: None,
                    type_ann: None,
                    is_static: method.is_static,
                    decorators: Default::default(),
                    accessibility: Some(Accessibility::Private),
                    is_abstract: false,
                    is_optional: method.is_optional,
                    readonly: false,
                    declare: false,
                    definite: false,
                    is_override: false,
                });
                return;
            }
        }
        m.visit_mut_children_with(self);
    }
}

impl VisitMut<RTsPropertySignature> for Dts {
    fn visit_mut(&mut self, ps: &mut RTsPropertySignature) {
        if ps.type_ann.is_none() {
            ps.type_ann = Some(box RTsTypeAnn {
                node_id: NodeId::invalid(),
                span: DUMMY_SP,
                type_ann: box RTsType::TsKeywordType(RTsKeywordType {
                    span: DUMMY_SP,
                    kind: TsKeywordTypeKind::TsAnyKeyword,
                }),
            });
        }
    }
}

impl VisitMut<Vec<RVarDeclarator>> for Dts {
    fn visit_mut(&mut self, decls: &mut Vec<RVarDeclarator>) {
        decls.visit_mut_children_with(self);

        // Flatten var declarations
        for decl in decls.take() {
            match decl.name {
                RPat::Array(RArrayPat {
                    span,
                    elems,
                    type_ann:
                        Some(box RTsTypeAnn {
                            type_ann: box RTsType::TsTupleType(..),
                            ..
                        }),
                    ..
                }) => {
                    //
                    for name in elems.into_iter().flatten() {
                        decls.push(RVarDeclarator {
                            node_id: NodeId::invalid(),
                            span,
                            name,
                            init: None,
                            definite: false,
                        })
                    }
                }
                // TODO
                //  RPat::Object(obj) => {}
                _ => decls.push(decl),
            }
        }
    }
}

impl VisitMut<RTsParamProp> for Dts {
    fn visit_mut(&mut self, p: &mut RTsParamProp) {
        p.visit_mut_children_with(self);

        if p.accessibility == Some(Accessibility::Private) {
            p.accessibility = None;
        }
    }
}

impl VisitMut<RClassProp> for Dts {
    fn visit_mut(&mut self, prop: &mut RClassProp) {
        prop.visit_mut_children_with(self);

        if let Some(Accessibility::Private) = prop.accessibility {
            prop.type_ann = None;
        }

        prop.value = None;
    }
}

impl VisitMut<RPrivateProp> for Dts {
    fn visit_mut(&mut self, prop: &mut RPrivateProp) {
        prop.visit_mut_children_with(self);

        prop.value = None;
    }
}

impl VisitMut<Option<RBlockStmt>> for Dts {
    fn visit_mut(&mut self, value: &mut Option<RBlockStmt>) {
        *value = None;
    }
}

impl VisitMut<RTsModuleDecl> for Dts {
    fn visit_mut(&mut self, _: &mut RTsModuleDecl) {}
}

impl VisitMut<Vec<RModuleItem>> for Dts {
    fn visit_mut(&mut self, items: &mut Vec<RModuleItem>) {
        items.retain(|item| {
            match item {
                RModuleItem::ModuleDecl(decl) => match decl {
                    RModuleDecl::ExportNamed(export @ RNamedExport { src: None, .. }) if export.specifiers.is_empty() => return false,
                    _ => {}
                },
                RModuleItem::Stmt(stmt) => match stmt {
                    RStmt::Decl(..) => {}
                    _ => return false,
                },
            }

            // Let's be conservative
            true
        });

        let is_module = items.iter().any(|item| match item {
            RModuleItem::ModuleDecl(_) => true,
            RModuleItem::Stmt(_) => false,
        });
        self.preserve_stmt |= !is_module;

        items.visit_mut_children_with(self);

        if is_module {
            items.retain(|item| match item {
                RModuleItem::ModuleDecl(_) => true,
                RModuleItem::Stmt(RStmt::Decl(decl)) => match decl {
                    RDecl::Class(RClassDecl { ident, .. })
                    | RDecl::Fn(RFnDecl { ident, .. })
                    | RDecl::TsEnum(box RTsEnumDecl { id: ident, .. })
                    | RDecl::TsTypeAlias(box RTsTypeAliasDecl { id: ident, .. })
                    | RDecl::TsInterface(box RTsInterfaceDecl { id: ident, .. }) => self.used_types.contains(&Id::from(ident)),
                    // Handled by `visit_mut_var_decl`
                    RDecl::Var(decl) => !decl.decls.is_empty(),
                    RDecl::TsModule(_) => true,
                },
                _ => false,
            });
        }

        items.retain(|item| match item {
            RModuleItem::ModuleDecl(RModuleDecl::Import(RImportDecl { specifiers, .. })) => !specifiers.is_empty(),
            RModuleItem::Stmt(RStmt::Empty(..)) => false,
            _ => true,
        });
    }
}

impl VisitMut<Vec<RImportSpecifier>> for Dts {
    fn visit_mut(&mut self, specifiers: &mut Vec<RImportSpecifier>) {
        specifiers.retain(|specifier| match specifier {
            RImportSpecifier::Named(specifier) => self.used_types.contains(&Id::from(&specifier.local)),
            RImportSpecifier::Default(specifier) => self.used_types.contains(&Id::from(&specifier.local)),
            RImportSpecifier::Namespace(specifier) => self.used_types.contains(&Id::from(&specifier.local)),
        });
    }
}

impl VisitMut<RExportDecl> for Dts {
    fn visit_mut(&mut self, export: &mut RExportDecl) {
        let old = self.preserve_stmt;
        self.preserve_stmt = true;
        export.decl.visit_mut_with(self);
        self.preserve_stmt = old;
    }
}

impl VisitMut<RVarDecl> for Dts {
    fn visit_mut(&mut self, decl: &mut RVarDecl) {
        decl.visit_mut_children_with(self);
        decl.declare = true;

        if self.preserve_stmt {
            return;
        }

        decl.decls.retain(|decl| {
            let ids: Vec<Id> = find_ids_in_pat(&decl.name);
            for id in ids {
                if self.used_vars.contains(&id) {
                    return true;
                }
            }

            false
        });
    }
}

impl VisitMut<RFnDecl> for Dts {
    fn visit_mut(&mut self, decl: &mut RFnDecl) {
        decl.declare = true;

        decl.visit_mut_children_with(self);
    }
}

impl VisitMut<RClassDecl> for Dts {
    fn visit_mut(&mut self, decl: &mut RClassDecl) {
        decl.declare = true;

        decl.visit_mut_children_with(self);
    }
}

impl VisitMut<RTsTypeAliasDecl> for Dts {
    fn visit_mut(&mut self, decl: &mut RTsTypeAliasDecl) {
        decl.declare = true;

        decl.visit_mut_children_with(self);
    }
}

impl VisitMut<RTsEnumDecl> for Dts {
    fn visit_mut(&mut self, decl: &mut RTsEnumDecl) {
        decl.declare = true;

        decl.visit_mut_children_with(self);
    }
}

impl VisitMut<RPat> for Dts {
    fn visit_mut(&mut self, pat: &mut RPat) {
        pat.visit_mut_children_with(self);

        if let RPat::Assign(assign) = pat {
            *pat = assign.left.take();
            match pat {
                RPat::Ident(pat) => pat.id.optional = true,
                RPat::Array(pat) => pat.optional = true,
                RPat::Object(pat) => pat.optional = true,
                _ => {}
            }
        }
    }
}

impl VisitMut<Vec<RClassMember>> for Dts {
    fn visit_mut(&mut self, members: &mut Vec<RClassMember>) {
        // Remove empty members.
        members.retain(|member| !matches!(member, RClassMember::Empty(..)));

        members.visit_mut_children_with(self);

        members.map_with_mut(|members| {
            let mut props = Vec::with_capacity(members.len() + 6);
            let mut buf = Vec::with_capacity(members.len());
            //
            let mut has_private = false;

            for mut m in members {
                match m {
                    RClassMember::Constructor(ref mut c) => {
                        for p in c.params.iter_mut() {
                            if let RParamOrTsParamProp::TsParamProp(ref mut p) = p {
                                if p.accessibility.is_some() || p.readonly {
                                    props.push(RClassMember::ClassProp(RClassProp {
                                        node_id: NodeId::invalid(),
                                        span: Default::default(),
                                        declare: false,
                                        key: match &p.param {
                                            RTsParamPropParam::Ident(p) => RPropName::Ident(p.id.clone()),
                                            RTsParamPropParam::Assign(p) => match &p.left {
                                                //
                                                box RPat::Ident(i) => RPropName::Ident(i.id.clone()),
                                                _ => unreachable!("binding pattern in property initializer"),
                                            },
                                        },
                                        value: None,
                                        type_ann: None,
                                        is_static: false,
                                        decorators: vec![],
                                        accessibility: p.accessibility,
                                        is_abstract: false,
                                        is_optional: false,
                                        readonly: p.readonly,
                                        definite: false,
                                        is_override: false,
                                    }));
                                }

                                p.accessibility = None;
                                p.readonly = false;

                                match &mut p.param {
                                    RTsParamPropParam::Ident(_) => {}
                                    RTsParamPropParam::Assign(RAssignPat {
                                        left: box RPat::Ident(i), ..
                                    }) => {
                                        // Original pattern has default value, so it should be
                                        // option
                                        i.id.optional = true;
                                        p.param = RTsParamPropParam::Ident(i.clone());
                                    }
                                    _ => {}
                                }
                            }
                        }
                    }
                    RClassMember::Method(ref mut m) => {
                        if let Some(Accessibility::Public) = m.accessibility {
                            m.accessibility = None;
                        }

                        if let RPropName::Computed(e) = &m.key {
                            if let RExpr::Bin(..) = &*e.expr {
                                continue;
                            }
                        }
                    }

                    RClassMember::PrivateMethod(..) | RClassMember::PrivateProp(..) => {
                        has_private = true;
                        continue;
                    }
                    _ => {}
                }

                buf.push(m);
            }

            if has_private {
                props.insert(
                    0,
                    RClassMember::PrivateProp(RPrivateProp {
                        node_id: NodeId::invalid(),
                        span: DUMMY_SP,
                        key: RPrivateName {
                            node_id: NodeId::invalid(),
                            span: DUMMY_SP,
                            id: RIdent::new("private".into(), DUMMY_SP),
                        },
                        value: None,
                        type_ann: None,
                        is_static: false,
                        decorators: Default::default(),
                        accessibility: None,
                        is_optional: false,
                        readonly: false,
                        definite: false,
                        is_override: false,
                    }),
                );
            }

            props.extend(buf);

            props
        })
    }
}

impl VisitMut<RTsIndexSignature> for Dts {
    fn visit_mut(&mut self, sig: &mut RTsIndexSignature) {
        sig.visit_mut_children_with(self);

        if sig.type_ann.is_none() {
            sig.type_ann = Some(box RTsTypeAnn {
                node_id: NodeId::invalid(),
                span: DUMMY_SP,
                type_ann: box RTsType::TsKeywordType(RTsKeywordType {
                    span: DUMMY_SP,
                    kind: TsKeywordTypeKind::TsAnyKeyword,
                }),
            });
        }
    }
}