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
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
use crate::{
    pass::Pass,
    util::{prepend_stmts, var::VarCollector, ExprFactory},
};
use fxhash::FxHashMap;
use swc_atoms::js_word;
use swc_common::{util::move_map::MoveMap, Fold, FoldWith, Spanned, Visit, VisitWith, DUMMY_SP};
use swc_ecma_ast::*;
use swc_ecma_utils::Id;

/// Strips type annotations out.
pub fn strip() -> impl Pass {
    Strip::default()
}

#[derive(Default)]
struct Strip {
    non_top_level: bool,
    scope: Scope,
    phase: Phase,

    was_side_effect_import: bool,
}

#[derive(Debug, Clone, Copy)]
enum Phase {
    ///
    ///  - analyze ident usages
    ///  - remove type annotations
    Analysis,
    ///
    ///  - remove type-only imports
    DropImports,
}
impl Default for Phase {
    fn default() -> Self {
        Phase::Analysis
    }
}

#[derive(Default)]
struct Scope {
    decls: FxHashMap<Id, DeclInfo>,
    imported_idents: FxHashMap<Id, DeclInfo>,
}

#[derive(Debug, Default)]
struct DeclInfo {
    /// interface / type alias
    has_type: bool,
    /// Var, Fn, Class
    has_concrete: bool,
}

impl Strip {
    fn handle_decl(&mut self, decl: &Decl) {
        // We don't care about stuffs which cannot be exported
        if self.non_top_level {
            return;
        }

        macro_rules! store {
            ($sym:expr, $ctxt:expr, $concrete:expr) => {{
                let entry = self.scope.decls.entry(($sym.clone(), $ctxt)).or_default();

                if $concrete {
                    entry.has_concrete = true
                } else {
                    entry.has_type = true;
                }
            }};
        }
        match *decl {
            Decl::Class(ClassDecl { ref ident, .. }) | Decl::Fn(FnDecl { ref ident, .. }) => {
                store!(ident.sym, ident.span.ctxt(), true);
            }

            Decl::Var(ref var) => {
                let mut names = vec![];
                var.decls.visit_with(&mut VarCollector { to: &mut names });

                for name in names {
                    store!(name.0, name.1, true);
                }
            }

            Decl::TsEnum(TsEnumDecl { ref id, .. })
            | Decl::TsInterface(TsInterfaceDecl { ref id, .. })
            | Decl::TsModule(TsModuleDecl {
                id: TsModuleName::Ident(ref id),
                ..
            })
            | Decl::TsTypeAlias(TsTypeAliasDecl { ref id, .. }) => {
                store!(id.sym, id.span.ctxt(), false)
            }

            Decl::TsModule(TsModuleDecl {
                id:
                    TsModuleName::Str(Str {
                        ref value, span, ..
                    }),
                ..
            }) => store!(value, span.ctxt(), false),
        }
    }
}

impl Fold<Constructor> for Strip {
    fn fold(&mut self, c: Constructor) -> Constructor {
        let c = c.fold_children(self);

        let mut stmts = vec![];

        let params = c.params.move_map(|param| match param {
            PatOrTsParamProp::Pat(..) => param,
            PatOrTsParamProp::TsParamProp(param) => {
                let (ident, param) = match param.param {
                    TsParamPropParam::Ident(i) => (i.clone(), Pat::Ident(i)),
                    TsParamPropParam::Assign(AssignPat {
                        span,
                        left: box Pat::Ident(i),
                        right,
                        ..
                    }) => (
                        i.clone(),
                        Pat::Assign(AssignPat {
                            span,
                            left: box Pat::Ident(i),
                            right,
                            type_ann: None,
                        }),
                    ),
                    _ => unreachable!("destructuring pattern inside TsParameterProperty"),
                };
                stmts.push(
                    AssignExpr {
                        span: DUMMY_SP,
                        left: PatOrExpr::Expr(
                            box ThisExpr { span: DUMMY_SP }.member(ident.clone()),
                        ),
                        op: op!("="),
                        right: box Expr::Ident(ident),
                    }
                    .into_stmt(),
                );

                PatOrTsParamProp::Pat(param)
            }
        });

        let body = match c.body {
            Some(mut body) => {
                prepend_stmts(&mut body.stmts, stmts.into_iter());
                Some(body)
            }
            None => None,
        };

        Constructor { params, body, ..c }
    }
}

impl Fold<Vec<ClassMember>> for Strip {
    fn fold(&mut self, members: Vec<ClassMember>) -> Vec<ClassMember> {
        let members = members.fold_children(self);

        members.move_flat_map(|member| match member {
            ClassMember::Constructor(Constructor { body: None, .. }) => None,
            ClassMember::Method(ClassMethod {
                is_abstract: true, ..
            })
            | ClassMember::Method(ClassMethod {
                function: Function { body: None, .. },
                ..
            })
            | ClassMember::ClassProp(ClassProp { value: None, .. }) => None,

            _ => Some(member),
        })
    }
}

impl Fold<Vec<Pat>> for Strip {
    fn fold(&mut self, pats: Vec<Pat>) -> Vec<Pat> {
        let mut pats = pats.fold_children(self);

        // Remove this from parameter list
        pats.retain(|pat| match *pat {
            Pat::Ident(Ident {
                sym: js_word!("this"),
                ..
            }) => false,
            _ => true,
        });

        pats
    }
}

impl Fold<Vec<ModuleItem>> for Strip {
    fn fold(&mut self, items: Vec<ModuleItem>) -> Vec<ModuleItem> {
        // First pass
        let items = items.fold_children(self);

        let old = self.phase;
        self.phase = Phase::DropImports;

        // Second pass
        let mut stmts = Vec::with_capacity(items.len());
        for item in items {
            self.was_side_effect_import = false;
            match item {
                ModuleItem::Stmt(Stmt::Empty(..))
                | ModuleItem::ModuleDecl(ModuleDecl::Import(ImportDecl {
                    type_only: true, ..
                }))
                | ModuleItem::ModuleDecl(ModuleDecl::ExportNamed(NamedExport {
                    type_only: true,
                    ..
                })) => continue,

                ModuleItem::ModuleDecl(ModuleDecl::Import(i)) => {
                    let i = i.fold_with(self);

                    if self.was_side_effect_import || !i.specifiers.is_empty() {
                        stmts.push(ModuleItem::ModuleDecl(ModuleDecl::Import(i)));
                    }
                }

                ModuleItem::ModuleDecl(ModuleDecl::ExportDecl(ExportDecl {
                    decl: Decl::TsEnum(e),
                    ..
                })) => {
                    stmts.push(ModuleItem::ModuleDecl(ModuleDecl::ExportDecl(ExportDecl {
                        span: e.span,
                        decl: Decl::Var(VarDecl {
                            span: DUMMY_SP,
                            kind: VarDeclKind::Var,
                            declare: false,
                            decls: vec![VarDeclarator {
                                span: e.span,
                                name: Pat::Ident(e.id.clone()),
                                definite: false,
                                init: None,
                            }],
                        }),
                    })));
                    self.handle_enum(e, &mut stmts)
                }
                ModuleItem::Stmt(Stmt::Decl(Decl::TsEnum(e))) => {
                    // var Foo;
                    // (function (Foo) {
                    //     Foo[Foo["a"] = 0] = "a";
                    // })(Foo || (Foo = {}));

                    stmts.push(
                        Stmt::Decl(Decl::Var(VarDecl {
                            span: DUMMY_SP,
                            kind: VarDeclKind::Var,
                            declare: false,
                            decls: vec![VarDeclarator {
                                span: e.span,
                                name: Pat::Ident(e.id.clone()),
                                definite: false,
                                init: None,
                            }],
                        }))
                        .into(),
                    );
                    self.handle_enum(e, &mut stmts)
                }

                ModuleItem::Stmt(Stmt::Decl(Decl::Fn(FnDecl {
                    function: Function { body: None, .. },
                    ..
                })))
                | ModuleItem::Stmt(Stmt::Decl(Decl::TsInterface(..)))
                | ModuleItem::Stmt(Stmt::Decl(Decl::TsModule(..)))
                | ModuleItem::Stmt(Stmt::Decl(Decl::TsTypeAlias(..)))
                | ModuleItem::ModuleDecl(ModuleDecl::ExportDecl(ExportDecl {
                    decl: Decl::TsInterface(..),
                    ..
                }))
                | ModuleItem::ModuleDecl(ModuleDecl::ExportDecl(ExportDecl {
                    decl: Decl::TsModule(..),
                    ..
                }))
                | ModuleItem::ModuleDecl(ModuleDecl::ExportDecl(ExportDecl {
                    decl: Decl::TsTypeAlias(..),
                    ..
                }))
                | ModuleItem::ModuleDecl(ModuleDecl::ExportDecl(ExportDecl {
                    decl:
                        Decl::Fn(FnDecl {
                            function: Function { body: None, .. },
                            ..
                        }),
                    ..
                }))
                | ModuleItem::ModuleDecl(ModuleDecl::ExportDefaultDecl(ExportDefaultDecl {
                    decl:
                        DefaultDecl::Fn(FnExpr {
                            function: Function { body: None, .. },
                            ..
                        }),
                    ..
                }))
                | ModuleItem::ModuleDecl(ModuleDecl::ExportDefaultDecl(ExportDefaultDecl {
                    decl: DefaultDecl::TsInterfaceDecl(..),
                    ..
                }))
                | ModuleItem::ModuleDecl(ModuleDecl::TsNamespaceExport(..)) => continue,

                ModuleItem::ModuleDecl(ModuleDecl::TsImportEquals(import)) => {
                    if !import.is_export {
                        continue;
                    }

                    stmts.push(ModuleItem::ModuleDecl(ModuleDecl::ExportDecl(ExportDecl {
                        span: DUMMY_SP,
                        decl: Decl::Var(VarDecl {
                            span: DUMMY_SP,
                            kind: VarDeclKind::Var,
                            decls: vec![VarDeclarator {
                                span: DUMMY_SP,
                                name: Pat::Ident(import.id),
                                init: Some(box module_ref_to_expr(import.module_ref)),
                                definite: false,
                            }],
                            declare: false,
                        }),
                    })));
                }

                ModuleItem::ModuleDecl(ModuleDecl::TsExportAssignment(export)) => {
                    stmts.push(ModuleItem::ModuleDecl(
                        ModuleDecl::ExportDefaultExpr(ExportDefaultExpr {
                            span: export.span(),
                            expr: export.expr,
                        })
                        .fold_with(self),
                    ))
                }
                ModuleItem::ModuleDecl(ModuleDecl::ExportNamed(mut export)) => {
                    // if specifier become empty, we remove export statement.

                    export.specifiers.retain(|s| match *s {
                        ExportSpecifier::Named(NamedExportSpecifier { ref orig, .. }) => {
                            if let Some(e) =
                                self.scope.decls.get(&(orig.sym.clone(), orig.span.ctxt()))
                            {
                                e.has_concrete
                            } else {
                                true
                            }
                        }
                        _ => true,
                    });
                    if export.specifiers.is_empty() {
                        continue;
                    }

                    stmts.push(ModuleItem::ModuleDecl(ModuleDecl::ExportNamed(
                        NamedExport { ..export },
                    )))
                }

                _ => stmts.push(item.fold_with(self)),
            };
        }
        self.phase = old;

        stmts
    }
}

impl Strip {
    fn handle_enum(&mut self, e: TsEnumDecl, stmts: &mut Vec<ModuleItem>) {
        let id = e.id;
        stmts.push(
            CallExpr {
                span: DUMMY_SP,
                callee: FnExpr {
                    ident: None,
                    function: Function {
                        span: DUMMY_SP,
                        decorators: Default::default(),
                        is_async: false,
                        is_generator: false,
                        type_params: Default::default(),
                        params: vec![Pat::Ident(id.clone())],
                        body: Some(BlockStmt {
                            span: DUMMY_SP,
                            stmts: e
                                .members
                                .into_iter()
                                .enumerate()
                                .map(|(i, m)| {
                                    let value = match m.id {
                                        TsEnumMemberId::Str(s) => s,
                                        TsEnumMemberId::Ident(i) => Str {
                                            span: i.span,
                                            value: i.sym,
                                            has_escape: false,
                                        },
                                    };

                                    // Foo[Foo["a"] = 0] = "a";
                                    AssignExpr {
                                        span: DUMMY_SP,
                                        left: PatOrExpr::Expr(box Expr::Member(MemberExpr {
                                            obj: id.clone().as_obj(),
                                            span: DUMMY_SP,
                                            computed: true,

                                            // Foo["a"] = 0
                                            prop: box Expr::Assign(AssignExpr {
                                                span: DUMMY_SP,
                                                left: PatOrExpr::Expr(box Expr::Member(
                                                    MemberExpr {
                                                        span: DUMMY_SP,
                                                        obj: id.clone().as_obj(),
                                                        prop: m.init.unwrap_or_else(|| {
                                                            box Expr::Lit(Lit::Str(value.clone()))
                                                        }),
                                                        computed: true,
                                                    },
                                                )),
                                                op: op!("="),
                                                right: box Expr::Lit(Lit::Num(Number {
                                                    span: DUMMY_SP,
                                                    value: i as _,
                                                })),
                                            }),
                                        })),
                                        op: op!("="),
                                        right: box Expr::Lit(Lit::Str(Str {
                                            span: DUMMY_SP,
                                            value: value.value,
                                            has_escape: false,
                                        })),
                                    }
                                    .into_stmt()
                                })
                                .collect(),
                        }),
                        return_type: Default::default(),
                    },
                }
                .as_callee(),
                args: vec![BinExpr {
                    span: DUMMY_SP,
                    left: box Expr::Ident(id.clone()),
                    op: op!("||"),
                    right: box Expr::Assign(AssignExpr {
                        span: DUMMY_SP,
                        left: PatOrExpr::Pat(Pat::Ident(id.clone()).into()),
                        op: op!("="),
                        right: box Expr::Object(ObjectLit {
                            span: DUMMY_SP,
                            props: vec![],
                        }),
                    }),
                }
                .as_arg()],
                type_args: Default::default(),
            }
            .into_stmt()
            .into(),
        )
    }
}

impl Fold<ImportDecl> for Strip {
    fn fold(&mut self, mut import: ImportDecl) -> ImportDecl {
        match self.phase {
            Phase::Analysis => {
                macro_rules! store {
                    ($i:expr) => {{
                        self.scope
                            .imported_idents
                            .insert(($i.sym.clone(), $i.span.ctxt()), Default::default());
                    }};
                }
                for s in &import.specifiers {
                    match *s {
                        ImportSpecifier::Default(ref import) => store!(import.local),
                        ImportSpecifier::Specific(ref import) => store!(import.local),
                        ImportSpecifier::Namespace(..) => {}
                    }
                }

                import
            }
            Phase::DropImports => {
                self.was_side_effect_import = import.specifiers.is_empty();

                import.specifiers.retain(|s| match *s {
                    ImportSpecifier::Default(ImportDefault { ref local, .. })
                    | ImportSpecifier::Specific(ImportSpecific { ref local, .. }) => {
                        let entry = self
                            .scope
                            .imported_idents
                            .get(&(local.sym.clone(), local.span.ctxt()));
                        match entry {
                            Some(&DeclInfo {
                                has_type: true,
                                has_concrete: false,
                            }) => false,
                            _ => true,
                        }
                    }
                    _ => true,
                });

                import
            }
        }
    }
}

impl Fold<Ident> for Strip {
    fn fold(&mut self, i: Ident) -> Ident {
        self.scope
            .imported_idents
            .entry((i.sym.clone(), i.span.ctxt()))
            .and_modify(|v| v.has_concrete = true);

        Ident {
            optional: false,
            ..i.fold_children(self)
        }
    }
}

impl Visit<TsEntityName> for Strip {
    fn visit(&mut self, name: &TsEntityName) {
        assert!(match self.phase {
            Phase::Analysis => true,
            _ => false,
        });

        match *name {
            TsEntityName::Ident(ref i) => {
                self.scope
                    .imported_idents
                    .entry((i.sym.clone(), i.span.ctxt()))
                    .and_modify(|v| v.has_type = true);
            }
            TsEntityName::TsQualifiedName(..) => name.visit_children(self),
        }
    }
}

impl Fold<Decl> for Strip {
    fn fold(&mut self, decl: Decl) -> Decl {
        let decl = validate!(decl);
        self.handle_decl(&decl);

        let old = self.non_top_level;
        self.non_top_level = true;
        let decl = decl.fold_children(self);
        self.non_top_level = old;
        validate!(decl)
    }
}

impl Fold<Stmt> for Strip {
    fn fold(&mut self, stmt: Stmt) -> Stmt {
        let stmt = stmt.fold_children(self);

        match stmt {
            Stmt::Decl(decl) => match decl {
                Decl::TsInterface(..) | Decl::TsModule(..) | Decl::TsTypeAlias(..) => {
                    let span = decl.span();
                    Stmt::Empty(EmptyStmt { span })
                }
                _ => Stmt::Decl(decl),
            },
            _ => stmt,
        }
    }
}

macro_rules! type_to_none {
    ($T:ty) => {
        impl Fold<Option<$T>> for Strip {
            fn fold(&mut self, node: Option<$T>) -> Option<$T> {
                node.visit_with(self);

                None
            }
        }
    };
    ($T:ty,) => {
        type_to_none!($T);
    };
    ($T:ty, $($rest:tt)+) => {
        type_to_none!($T);
        type_to_none!($($rest)*);
    };
}

impl Fold<Option<Accessibility>> for Strip {
    fn fold(&mut self, _: Option<Accessibility>) -> Option<Accessibility> {
        None
    }
}

type_to_none!(TsType, TsTypeAnn, TsTypeParamDecl, TsTypeParamInstantiation);

impl Fold<Expr> for Strip {
    fn fold(&mut self, expr: Expr) -> Expr {
        let expr = match expr {
            Expr::Member(MemberExpr {
                span,
                obj,
                prop,
                computed,
            }) => Expr::Member(MemberExpr {
                span,
                obj: obj.fold_with(self),
                prop: if computed { prop.fold_with(self) } else { prop },
                computed,
            }),
            _ => expr.fold_children(self),
        };

        match expr {
            Expr::TsAs(TsAsExpr { expr, .. }) => validate!(*expr),
            Expr::TsNonNull(TsNonNullExpr { expr, .. }) => validate!(*expr),
            Expr::TsTypeAssertion(TsTypeAssertion { expr, .. }) => validate!(*expr),
            Expr::TsConstAssertion(TsConstAssertion { expr, .. }) => validate!(*expr),
            Expr::TsTypeCast(TsTypeCastExpr { expr, .. }) => validate!(*expr),
            _ => validate!(expr),
        }
    }
}

impl Fold<Module> for Strip {
    fn fold(&mut self, node: Module) -> Module {
        let node = validate!(node);

        validate!(node.fold_children(self))
    }
}

fn module_ref_to_expr(r: TsModuleRef) -> Expr {
    match r {
        TsModuleRef::TsEntityName(name) => ts_entity_name_to_expr(name),
        _ => unimplemented!("export import A = B where B != TsEntityName\nB: {:?}", r),
    }
}

fn ts_entity_name_to_expr(n: TsEntityName) -> Expr {
    match n {
        TsEntityName::Ident(i) => i.into(),
        TsEntityName::TsQualifiedName(box TsQualifiedName { left, right }) => MemberExpr {
            span: DUMMY_SP,
            obj: ExprOrSuper::Expr(box ts_entity_name_to_expr(left)),
            prop: box right.into(),
            computed: false,
        }
        .into(),
    }
}