/
strip.rs
2701 lines (2435 loc) · 97.1 KB
/
strip.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
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
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::mem::take;
use serde::{Deserialize, Serialize};
use swc_atoms::{js_word, JsWord};
use swc_common::{
chain,
collections::{AHashMap, AHashSet},
comments::{Comments, NoopComments},
sync::Lrc,
util::{move_map::MoveMap, take::Take},
Mark, SourceMap, Span, Spanned, SyntaxContext, DUMMY_SP,
};
use swc_ecma_ast::*;
use swc_ecma_transforms_react::{parse_expr_for_jsx, JsxDirectives};
use swc_ecma_utils::{
alias_ident_for, constructor::inject_after_super, is_literal, prepend_stmt, private_ident,
prop_name_to_expr, var::VarCollector, ExprFactory,
};
use swc_ecma_visit::{
as_folder, noop_visit_mut_type, visit_obj_and_computed, Fold, Visit, VisitMut, VisitMutWith,
VisitWith,
};
use crate::{
import_export_assign::import_export_assign,
inline_enum::{inline_enum, TSEnumLit},
};
/// Value does not contain TsLit::Bool
type EnumValues = AHashMap<JsWord, Option<TsLit>>;
#[derive(Debug, Serialize, Deserialize)]
#[non_exhaustive]
pub enum ImportsNotUsedAsValues {
#[serde(rename = "remove")]
Remove,
#[serde(rename = "preserve")]
Preserve,
}
#[deprecated = "ImportNotUsedAsValues is renamed to ImportsNotUsedAsValues"]
pub type ImportNotUsedAsValues = ImportsNotUsedAsValues;
/// This value defaults to `Remove`
impl Default for ImportsNotUsedAsValues {
fn default() -> Self {
Self::Remove
}
}
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct Config {
#[serde(default)]
pub import_not_used_as_values: ImportsNotUsedAsValues,
/// Align the semantics of TS class fields with TC39 class fields. Defaults
/// to `false`.
///
/// See https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#the-usedefineforclassfields-flag-and-the-declare-property-modifier.
///
/// When running `tsc` with configuration `"target": "ESNext",
/// "useDefineForClassFields": true`, TS class fields are preserved as JS
/// class fields. We target ESNext, so this our behavior with
/// `use_define_for_class_fields: true`.
///
/// When running `tsc` with configuration `"target": "<ES6-ES2020>",
/// "useDefineForClassFields": true`, TS class fields are transformed to
/// `Object.defineProperty()` statements. You must additionally apply the
/// `swc_ecmascript::transforms::compat::es2022::class_properties()` pass to
/// get this backward-compatible output.
#[serde(default)]
pub use_define_for_class_fields: bool,
/// Don't create `export {}`.
/// By default, strip creates `export {}` for modules to preserve module
/// context.
///
/// https://github.com/swc-project/swc/issues/1698
#[serde(default)]
pub no_empty_export: bool,
/// Note: this pass handle jsx directives in comments
#[serde(default)]
pub pragma: Option<String>,
/// Note: this pass handle jsx directives in comments
#[serde(default)]
pub pragma_frag: Option<String>,
#[serde(default)]
pub ts_enum_config: TsEnumConfig,
#[serde(default)]
pub import_export_assign_config: TsImportExportAssignConfig,
}
#[derive(Clone, Copy, Debug, Default, Serialize, Deserialize)]
pub struct TsEnumConfig {
/// Note: `const enum` will be inlined if this is false(default)
/// All `const enum` *should be* inlined since it's align to tsc behavior.
/// This option exists to allow you to roll back the old behavior of swc.
#[serde(default)]
pub treat_const_enum_as_enum: bool,
/// Config from `assumptions`
/// Note: If this is true, all enums will be inlined when possible
/// whether or not you use `enum` or `const enum`.
#[serde(default)]
pub ts_enum_is_readonly: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum TsImportExportAssignConfig {
/// - Rewrite `import foo = require("foo")` to `var foo = require("foo")`
/// - Rewrite `export =` to `module.exports = `
/// Note: This option is deprecated as all CJS/AMD/UMD can handle it
/// themselves.
Classic,
/// preserve for CJS/AMD/UMD
Preserve,
/// Rewrite `import foo = require("foo")` to
/// ```javascript
/// import { createRequire as _createRequire } from "module";
/// const __require = _createRequire(import.meta.url);
/// const foo = __require("foo");
/// ```
///
/// Report error for `export =`
NodeNext,
/// Both `import =` and `export =` are disabled.
/// An error will be reported if an import/export assignment is found.
EsNext,
}
impl Default for TsImportExportAssignConfig {
fn default() -> Self {
Self::Classic
}
}
impl TsEnumConfig {
pub fn should_collect_enum(&self, is_const: bool) -> bool {
self.ts_enum_is_readonly || (!self.treat_const_enum_as_enum && is_const)
}
}
pub fn strip_with_config(config: Config, top_level_mark: Mark) -> impl Fold + VisitMut {
let ts_enum_lit = TSEnumLit::default();
let ts_enum_config = config.ts_enum_config;
chain!(
as_folder(Strip {
config,
comments: NoopComments,
jsx: None,
top_level_ctxt: SyntaxContext::empty().apply_mark(top_level_mark),
ts_enum_lit: ts_enum_lit.clone(),
non_top_level: Default::default(),
scope: Default::default(),
is_side_effect_import: Default::default(),
is_type_only_export: Default::default(),
decl_names: Default::default(),
in_var_pat: Default::default(),
keys: Default::default()
}),
inline_enum(ts_enum_lit, ts_enum_config)
)
}
/// Strips type annotations out.
///
/// See the `examples` directory of the crate to see how you can transpile a
/// typescript file to a javascript file.
pub fn strip(top_level_mark: Mark) -> impl Fold + VisitMut {
strip_with_config(Default::default(), top_level_mark)
}
/// [strip], but aware of jsx.
///
/// If you are using jsx, you should use this before jsx pass.
pub fn strip_with_jsx<C>(
cm: Lrc<SourceMap>,
config: Config,
comments: C,
top_level_mark: Mark,
) -> impl Fold + VisitMut
where
C: Comments,
{
let pragma = parse_expr_for_jsx(
&cm,
"pragma",
config
.pragma
.clone()
.unwrap_or_else(|| "React.createElement".to_string()),
top_level_mark,
);
let pragma_frag = parse_expr_for_jsx(
&cm,
"pragma",
config
.pragma_frag
.clone()
.unwrap_or_else(|| "React.Fragment".to_string()),
top_level_mark,
);
let pragma_id = id_for_jsx(&pragma);
let pragma_frag_id = id_for_jsx(&pragma_frag);
let ts_enum_lit = TSEnumLit::default();
let ts_enum_config = config.ts_enum_config;
chain!(
as_folder(Strip {
config,
comments,
jsx: Some(JsxData {
cm,
top_level_mark,
pragma_id,
pragma_frag_id,
}),
top_level_ctxt: SyntaxContext::empty().apply_mark(top_level_mark),
ts_enum_lit: ts_enum_lit.clone(),
non_top_level: Default::default(),
scope: Default::default(),
is_side_effect_import: Default::default(),
is_type_only_export: Default::default(),
decl_names: Default::default(),
in_var_pat: Default::default(),
keys: Default::default(),
}),
inline_enum(ts_enum_lit, ts_enum_config)
)
}
/// Get an [Id] which will used by expression.
///
/// For `React#1.createElement`, this returns `React#1`.
fn id_for_jsx(e: &Expr) -> Id {
match e {
Expr::Ident(i) => i.to_id(),
Expr::Member(MemberExpr { obj, .. }) => id_for_jsx(obj),
_ => {
panic!("failed to determine top-level Id for jsx expression")
}
}
}
struct JsxData {
cm: Lrc<SourceMap>,
top_level_mark: Mark,
pragma_id: Id,
pragma_frag_id: Id,
}
struct Strip<C>
where
C: Comments,
{
config: Config,
comments: C,
jsx: Option<JsxData>,
non_top_level: bool,
top_level_ctxt: SyntaxContext,
scope: Scope,
is_side_effect_import: bool,
is_type_only_export: bool,
ts_enum_lit: TSEnumLit,
/// Names of declarations.
/// This is used to prevent emitting a variable with same name multiple
/// name.
///
/// If an identifier is in this list, the [VisitMut] impl should not add a
/// variable with it.
///
/// This field is filled by [Visit] impl and [VisitMut] impl.
decl_names: AHashSet<Id>,
in_var_pat: bool,
keys: Vec<VarDeclarator>,
}
impl<C> Strip<C>
where
C: Comments,
{
/// If we found required jsx directives, we returns true.
fn parse_jsx_directives(&mut self, span: Span) -> bool {
let jsx_data = match &mut self.jsx {
Some(v) => v,
None => return false,
};
let cm = jsx_data.cm.clone();
let top_level_mark = jsx_data.top_level_mark;
let mut found = false;
let directives = self.comments.with_leading(span.lo, |comments| {
JsxDirectives::from_comments(&cm, span, comments, top_level_mark)
});
let JsxDirectives {
pragma,
pragma_frag,
..
} = directives;
if let Some(pragma) = pragma {
found = true;
jsx_data.pragma_id = id_for_jsx(&pragma);
}
if let Some(pragma_frag) = pragma_frag {
found = true;
jsx_data.pragma_frag_id = id_for_jsx(&pragma_frag);
}
found
}
}
impl<C> Strip<C>
where
C: Comments,
{
/// Creates an uninitialized variable if `name` is not in scope.
fn create_uninit_var(&mut self, span: Span, name: Id) -> Option<VarDeclarator> {
if !self.decl_names.insert(name.clone()) {
return None;
}
Some(VarDeclarator {
span,
name: Ident::new(name.0, DUMMY_SP.with_ctxt(name.1)).into(),
init: None,
definite: false,
})
}
}
#[derive(Default)]
struct Scope {
decls: AHashMap<Id, DeclInfo>,
referenced_idents: AHashMap<Id, DeclInfo>,
}
#[derive(Debug, Default)]
struct DeclInfo {
/// Var, Fn, Class
has_concrete: bool,
/// In `import foo = bar.baz`, `foo`'s dependency is `bar`. This means that
/// when setting `has_concrete` for `foo`, it must also be set for
/// `bar`.
maybe_dependency: Option<Ident>,
}
impl<C> Strip<C>
where
C: Comments,
{
fn store(&mut self, sym: JsWord, ctxt: SyntaxContext, concrete: bool) {
let entry = self.scope.decls.entry((sym, ctxt)).or_default();
if concrete {
entry.has_concrete = true
}
}
fn handle_decl(&mut self, decl: &Decl) {
// We don't care about stuffs which cannot be exported
if self.non_top_level {
return;
}
match &decl {
Decl::Class(ClassDecl { ref ident, .. }) | Decl::Fn(FnDecl { ref ident, .. }) => {
self.store(ident.sym.clone(), ident.span.ctxt, true);
}
Decl::Var(ref var) => {
let mut names: Vec<Id> = vec![];
var.decls.visit_with(&mut VarCollector { to: &mut names });
for name in names {
self.store(name.0.clone(), name.1, true);
}
}
Decl::TsEnum(e) => {
// Currently swc cannot remove constant enums
self.store(e.id.sym.clone(), e.id.span.ctxt, true);
self.store(e.id.sym.clone(), e.id.span.ctxt, false);
}
Decl::TsInterface(v) => self.store(v.id.sym.clone(), v.id.span.ctxt, false),
Decl::TsTypeAlias(v) => self.store(v.id.sym.clone(), v.id.span.ctxt, false),
Decl::TsModule(m) => match &m.id {
TsModuleName::Ident(id) => self.store(id.sym.clone(), id.span.ctxt, false),
TsModuleName::Str(Str {
ref value, span, ..
}) => self.store(value.clone(), span.ctxt, false),
},
}
}
}
impl<C> Strip<C>
where
C: Comments,
{
/// Returns [Some] if the method should be called again.
fn handle_expr<'a>(&mut self, n: &'a mut Expr) -> Vec<&'a mut Expr> {
match n {
Expr::Bin(BinExpr { left, right, .. }) => return vec![&mut **left, &mut **right],
// Remove types
Expr::TsAs(TsAsExpr { expr, .. })
| Expr::TsNonNull(TsNonNullExpr { expr, .. })
| Expr::TsTypeAssertion(TsTypeAssertion { expr, .. })
| Expr::TsConstAssertion(TsConstAssertion { expr, .. })
| Expr::TsInstantiation(TsInstantiation { expr, .. })
| Expr::TsSatisfies(TsSatisfiesExpr { expr, .. }) => {
expr.visit_mut_with(self);
let expr = *expr.take();
*n = expr;
}
Expr::Member(MemberExpr { obj, prop, .. }) => {
obj.visit_mut_with(self);
match prop {
MemberProp::Ident(i) => i.optional = false,
MemberProp::Computed(c) => c.visit_mut_with(self),
_ => (),
}
}
Expr::SuperProp(SuperPropExpr { prop, .. }) => match prop {
SuperProp::Ident(i) => i.optional = false,
SuperProp::Computed(c) => c.visit_mut_with(self),
},
Expr::Class(class) => {
let key_len = self.keys.len();
class.visit_mut_with(self);
let mut exprs: Vec<Box<Expr>> = self
.keys
.iter_mut()
.skip(key_len)
.map(|key| {
let value = key.init.take().unwrap();
let key = key.name.clone();
Box::new(Expr::Assign(AssignExpr {
span: DUMMY_SP,
left: PatOrExpr::Pat(key.into()),
op: op!("="),
right: value,
}))
})
.collect();
if !exprs.is_empty() {
exprs.push(Box::new(Expr::Class(class.take())));
*n = Expr::Seq(SeqExpr {
span: DUMMY_SP,
exprs,
})
}
}
_ => {
n.visit_mut_children_with(self);
}
}
vec![]
}
/// Returns `(var_decl, init)`.
#[allow(clippy::boxed_local)]
fn handle_enum(
&mut self,
e: Box<TsEnumDecl>,
module_name: Option<&Ident>,
) -> (Option<Decl>, Stmt) {
/// Called only for enums.
///
/// If both of the default value and the initialization is None, this
/// method returns [Err].
fn compute(
e: &TsEnumDecl,
span: Span,
values: &mut EnumValues,
default: Option<i64>,
init: Option<&Expr>,
) -> Result<TsLit, ()> {
fn compute_bin(
e: &TsEnumDecl,
span: Span,
values: &mut EnumValues,
expr: &BinExpr,
) -> Result<TsLit, ()> {
let l = compute(e, span, values, None, Some(&expr.left))?;
let r = compute(e, span, values, None, Some(&expr.right))?;
Ok(match (l, r) {
(
TsLit::Number(Number { value: l, .. }),
TsLit::Number(Number { value: r, .. }),
) => {
TsLit::Number(Number {
span,
value: match expr.op {
op!(bin, "+") => l + r,
op!(bin, "-") => l - r,
op!("*") => l * r,
op!("/") => l / r,
// TODO
op!("&") => ((l.round() as i64) & (r.round() as i64)) as _,
op!("|") => ((l.round() as i64) | (r.round() as i64)) as _,
op!("^") => ((l.round() as i64) ^ (r.round() as i64)) as _,
op!("<<") => ((l.round() as i64) << (r.round() as i64)) as _,
op!(">>") => ((l.round() as i64) >> (r.round() as i64)) as _,
// TODO: Verify this
op!(">>>") => ((l.round() as u64) >> (r.round() as u64)) as _,
_ => return Err(()),
},
raw: None,
})
}
(TsLit::Str(l), TsLit::Str(r)) if expr.op == op!(bin, "+") => {
let value = format!("{}{}", l.value, r.value);
TsLit::Str(Str {
span,
raw: None,
value: value.into(),
})
}
(TsLit::Number(l), TsLit::Str(r)) if expr.op == op!(bin, "+") => {
let value = format!("{}{}", l.value, r.value);
TsLit::Str(Str {
span,
raw: None,
value: value.into(),
})
}
(TsLit::Str(l), TsLit::Number(r)) if expr.op == op!(bin, "+") => {
let value = format!("{}{}", l.value, r.value);
TsLit::Str(Str {
span,
raw: None,
value: value.into(),
})
}
_ => return Err(()),
})
}
if let Some(expr) = init {
match expr {
Expr::Lit(Lit::Str(s)) => return Ok(TsLit::Str(s.clone())),
Expr::Lit(Lit::Num(s)) => return Ok(TsLit::Number(s.clone())),
Expr::Bin(ref bin) => return compute_bin(e, span, values, bin),
Expr::Paren(ref paren) => {
return compute(e, span, values, default, Some(&paren.expr))
}
Expr::Ident(ref id) => {
if let Some(Some(v)) = values.get(&id.sym) {
return Ok(v.clone());
}
return Err(());
}
Expr::Unary(ref expr) => {
let v = compute(e, span, values, None, Some(&expr.arg))?;
match v {
TsLit::BigInt(BigInt { .. }) => {}
TsLit::Number(Number { value: v, .. }) => {
return Ok(TsLit::Number(Number {
span,
value: match expr.op {
op!(unary, "+") => v,
op!(unary, "-") => -v,
op!("!") => {
if v == 0.0f64 {
0.0
} else {
1.0
}
}
op!("~") => (!(v as i32)) as f64,
_ => return Err(()),
},
raw: None,
}))
}
TsLit::Str(_) => {}
TsLit::Bool(_) => {}
TsLit::Tpl(_) => {}
}
}
Expr::Tpl(ref t) if t.exprs.is_empty() => {
if let Some(v) = &t.quasis[0].cooked {
return Ok(TsLit::Str(Str {
span,
raw: None,
value: JsWord::from(&**v),
}));
}
}
_ => {}
}
} else if let Some(value) = default {
return Ok(TsLit::Number(Number {
span,
value: value as _,
raw: None,
}));
}
Err(())
}
// let Foo;
// (function (Foo) {
// Foo[Foo["a"] = 0] = "a";
// })(Foo || (Foo = {}));
let var = self.create_uninit_var(e.span, e.id.to_id()).map(|var| {
VarDecl {
span: DUMMY_SP,
kind: if e.id.span.ctxt != self.top_level_ctxt {
VarDeclKind::Let
} else {
VarDeclKind::Var
},
declare: false,
decls: vec![var],
}
.into()
});
let id = e.id.clone();
let mut default = 0;
let mut values = Default::default();
let members = e
.members
.clone()
.into_iter()
.map(|m| -> Result<_, ()> {
let id_span = m.id.span();
let val = compute(&e, id_span, &mut values, Some(default), m.init.as_deref())
.map(|val| {
if let TsLit::Number(ref n) = val {
default = n.value as i64 + 1;
}
values.insert(m.id.as_ref().clone(), Some(val.clone()));
match val {
TsLit::Number(v) => Expr::Lit(Lit::Num(v)),
TsLit::Str(v) => Expr::Lit(Lit::Str(v)),
TsLit::Bool(v) => Expr::Lit(Lit::Bool(v)),
TsLit::Tpl(v) => {
let value = v.quasis.into_iter().next().unwrap().raw;
Expr::Lit(Lit::Str(Str {
span: v.span,
raw: None,
value: JsWord::from(&*value),
}))
}
TsLit::BigInt(v) => Expr::Lit(Lit::BigInt(v)),
}
})
.or_else(|err| match &m.init {
None => Err(err),
Some(v) => {
let mut v = *v.clone();
let mut visitor = EnumValuesVisitor {
previous: &values,
ident: &id,
};
visitor.visit_mut_expr(&mut v);
values.insert(m.id.as_ref().clone(), None);
Ok(v)
}
})?;
Ok((m, val))
})
.collect::<Result<Vec<_>, _>>()
.unwrap_or_else(|_| panic!("invalid value for enum is detected"));
let contains_lit = members.iter().any(|(_, v)| matches!(v, Expr::Lit(..)));
let should_collect = self.config.ts_enum_config.should_collect_enum(e.is_const);
if should_collect && contains_lit {
let mut enums = self.ts_enum_lit.borrow_mut();
let k_v = enums.entry(e.id.to_id()).or_default();
members
.iter()
.filter(|(_, v)| matches!(v, Expr::Lit(..)))
.for_each(|(m, e)| {
let member_key = m.id.as_ref().clone();
let value = e.clone().expect_lit();
k_v.insert(member_key, value);
})
}
let init = CallExpr {
span: DUMMY_SP,
callee: Function {
span: DUMMY_SP,
decorators: Default::default(),
is_async: false,
is_generator: false,
type_params: Default::default(),
params: vec![Param {
span: id.span,
decorators: vec![],
pat: id.clone().into(),
}],
body: Some(BlockStmt {
span: DUMMY_SP,
stmts: members
.into_iter()
.map(|(m, val)| {
let no_init_required = matches!(val, Expr::Lit(Lit::Str(..)));
let rhs_should_be_name = match &val {
Expr::Lit(Lit::Str(s)) => m.id.as_ref() == &s.value,
_ => true,
};
let value = match m.id {
TsEnumMemberId::Str(s) => s,
TsEnumMemberId::Ident(i) => Str {
span: i.span,
raw: None,
value: i.sym,
},
};
let prop = if no_init_required {
Box::new(Expr::Lit(Lit::Str(value.clone())))
} else {
Box::new(Expr::Assign(AssignExpr {
span: DUMMY_SP,
left: PatOrExpr::Expr(Box::new(Expr::Member(MemberExpr {
span: DUMMY_SP,
obj: Box::new(Expr::Ident(id.clone())),
prop: MemberProp::Computed(ComputedPropName {
span: DUMMY_SP,
expr: Box::new(Expr::Lit(Lit::Str(value.clone()))),
}),
}))),
op: op!("="),
right: Box::new(val.clone()),
}))
};
// Foo[Foo["a"] = 0] = "a";
AssignExpr {
span: DUMMY_SP,
left: PatOrExpr::Expr(Box::new(Expr::Member(MemberExpr {
obj: Box::new(Expr::Ident(id.clone())),
span: DUMMY_SP,
// Foo["a"] = 0
prop: MemberProp::Computed(ComputedPropName {
span: DUMMY_SP,
expr: prop,
}),
}))),
op: op!("="),
right: if rhs_should_be_name {
Box::new(Expr::Lit(Lit::Str(value)))
} else if m.init.is_some() {
Box::new(val)
} else {
Box::new(Expr::Lit(Lit::Str(value)))
},
}
.into_stmt()
})
.collect(),
}),
return_type: Default::default(),
}
.as_callee(),
args: vec![self.get_namespace_or_enum_init_arg(e.span, &id, module_name)],
type_args: Default::default(),
}
.into_stmt();
(var, init)
}
/// Returns `(var_decl, init)`.
#[allow(clippy::boxed_local)]
fn handle_ts_module(
&mut self,
module: Box<TsModuleDecl>,
parent_module_name: Option<&Ident>,
) -> Option<(Option<Decl>, Stmt)> {
if module.global || module.declare {
return None;
}
let module_span = module.span;
let module_name = match module.id {
TsModuleName::Ident(i) => i,
TsModuleName::Str(_) => return None,
};
let body = module.body?;
let private_name = private_ident!(module_name.sym.clone());
let body_stmts = match body {
TsNamespaceBody::TsModuleBlock(block) => {
self.handle_ts_module_block(block, &private_name)
}
TsNamespaceBody::TsNamespaceDecl(decl) => {
self.handle_ts_namespace_decl(decl, &private_name)
}
}?;
let var = self.create_uninit_var(module_name.span, module_name.to_id());
self.get_namespace_var_decl_and_call_expr(
var,
body_stmts,
module.span,
parent_module_name,
&module_name,
&private_name,
)
.map(|(mut var, stmt)| {
if let Some(var) = var.as_mut() {
// for comments
var.span = module_span;
// ensure it's a var if top level
if module_name.span.ctxt == self.top_level_ctxt {
var.kind = VarDeclKind::Var;
}
}
(var.map(Decl::from), stmt)
})
}
fn handle_ts_namespace_decl(
&mut self,
decl: TsNamespaceDecl,
parent_private_name: &Ident,
) -> Option<Vec<Stmt>> {
let private_name = private_ident!(decl.id.sym.clone());
// we'll always create a variable in this scenario
let var_id = Ident::new(decl.id.sym.clone(), DUMMY_SP.with_ctxt(decl.id.span.ctxt));
let var = VarDeclarator {
span: DUMMY_SP,
name: var_id.into(),
init: None,
definite: false,
};
let body_stmts = match *decl.body {
TsNamespaceBody::TsModuleBlock(block) => {
self.handle_ts_module_block(block, &private_name)
}
TsNamespaceBody::TsNamespaceDecl(decl) => {
self.handle_ts_namespace_decl(decl, &private_name)
}
}?;
let (var_decl, init_stmt) = self.get_namespace_var_decl_and_call_expr(
Some(var),
body_stmts,
decl.span,
Some(parent_private_name),
&decl.id,
&private_name,
)?;
let mut stmts = Vec::new();
stmts.extend(var_decl.map(Stmt::from));
stmts.push(init_stmt);
Some(stmts)
}
fn get_namespace_var_decl_and_call_expr(
&self,
var: Option<VarDeclarator>,
body_stmts: Vec<Stmt>,
decl_span: Span,
parent_module_name: Option<&Ident>,
module_name: &Ident,
private_name: &Ident,
) -> Option<(Option<VarDecl>, Stmt)> {
let init_fn_expr: FnExpr = Function {
params: vec![Param {
span: DUMMY_SP,
decorators: Default::default(),
pat: private_name.clone().into(),
}],
decorators: Default::default(),
span: DUMMY_SP,
body: Some(BlockStmt {
span: DUMMY_SP,
stmts: body_stmts,
}),
is_generator: false,
is_async: false,
type_params: Default::default(),
return_type: Default::default(),
}
.into();
let initializer = Box::new(Expr::Call(CallExpr {
span: DUMMY_SP,
callee: init_fn_expr.as_callee(),
args: vec![self.get_namespace_or_enum_init_arg(
decl_span,
module_name,
parent_module_name,
)],
type_args: Default::default(),
}));
Some((
var.map(|var| VarDecl {
span: DUMMY_SP,
kind: if module_name.span.ctxt != self.top_level_ctxt {
VarDeclKind::Let
} else {
VarDeclKind::Var
},
declare: false,
decls: vec![var],
}),
Stmt::Expr(ExprStmt {
span: DUMMY_SP,
expr: initializer,
}),
))
}
fn handle_ts_module_block(
&mut self,
block: TsModuleBlock,
private_module_name: &Ident,
) -> Option<Vec<Stmt>> {
let stmts = self.handle_module_items(block.body, Some(private_module_name));
if stmts.is_empty() {
None
} else {
Some(
stmts
.into_iter()
.filter_map(|item| {
match item {
ModuleItem::Stmt(stmt) => Some(stmt),
_ => None, // do not emit these as they are not valid in a module block
}
})
.collect(),
)
}
}
fn handle_module_items(
&mut self,
items: Vec<ModuleItem>,
parent_module_name: Option<&Ident>,