swc_ecma_transforms_proposal/decorators/legacy/
metadata.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
use swc_atoms::{js_word, JsWord};
use swc_common::{
    collections::AHashMap,
    util::{move_map::MoveMap, take::Take},
    Spanned, DUMMY_SP,
};
use swc_ecma_ast::*;
use swc_ecma_transforms_base::helper;
use swc_ecma_utils::{quote_ident, undefined, ExprFactory};
use swc_ecma_visit::{VisitMut, VisitMutWith};

use super::EnumKind;

/// https://github.com/leonardfactory/babel-plugin-transform-typescript-metadata/blob/master/src/parameter/parameterVisitor.ts
pub(super) struct ParamMetadata;

impl VisitMut for ParamMetadata {
    fn visit_mut_class(&mut self, mut cls: &mut Class) {
        cls.visit_mut_children_with(self);

        let mut decorators = cls.decorators.take();

        cls.body = cls.body.take().move_map(|m| match m {
            ClassMember::Constructor(mut c) => {
                for (idx, param) in c.params.iter_mut().enumerate() {
                    //
                    match param {
                        ParamOrTsParamProp::TsParamProp(p) => {
                            for decorator in p.decorators.drain(..) {
                                let new_dec = self.create_param_decorator(idx, decorator.expr);
                                decorators.push(new_dec);
                            }
                        }
                        ParamOrTsParamProp::Param(param) => {
                            for decorator in param.decorators.drain(..) {
                                let new_dec = self.create_param_decorator(idx, decorator.expr);
                                decorators.push(new_dec);
                            }
                        }
                    }
                }

                ClassMember::Constructor(c)
            }
            _ => m,
        });
        cls.decorators = decorators;
    }

    fn visit_mut_class_method(&mut self, m: &mut ClassMethod) {
        for (idx, param) in m.function.params.iter_mut().enumerate() {
            for decorator in param.decorators.drain(..) {
                let new_dec = self.create_param_decorator(idx, decorator.expr);
                m.function.decorators.push(new_dec);
            }
        }
    }
}

impl ParamMetadata {
    fn create_param_decorator(&self, param_index: usize, decorator_expr: Box<Expr>) -> Decorator {
        Decorator {
            span: DUMMY_SP,
            expr: Box::new(Expr::Call(CallExpr {
                span: decorator_expr.span(),
                callee: helper!(ts, ts_param, "__param"),
                args: vec![param_index.as_arg(), decorator_expr.as_arg()],
                type_args: Default::default(),
            })),
        }
    }
}

/// https://github.com/leonardfactory/babel-plugin-transform-typescript-metadata/blob/master/src/metadata/metadataVisitor.ts
pub(super) struct Metadata<'a> {
    pub(super) enums: &'a AHashMap<JsWord, EnumKind>,

    pub(super) class_name: Option<&'a Ident>,
}

impl VisitMut for Metadata<'_> {
    fn visit_mut_class(&mut self, c: &mut Class) {
        c.visit_mut_children_with(self);

        if c.decorators.is_empty() {
            return;
        }

        let constructor = c.body.iter().find_map(|m| match m {
            ClassMember::Constructor(c) => Some(c),
            _ => None,
        });
        if constructor.is_none() {
            return;
        }

        {
            let dec = self
                .create_metadata_design_decorator("design:type", quote_ident!("Function").as_arg());
            c.decorators.push(dec);
        }
        {
            let dec = self.create_metadata_design_decorator(
                "design:paramtypes",
                ArrayLit {
                    span: DUMMY_SP,
                    elems: constructor
                        .as_ref()
                        .unwrap()
                        .params
                        .iter()
                        .map(|v| match v {
                            ParamOrTsParamProp::TsParamProp(p) => {
                                let ann = match &p.param {
                                    TsParamPropParam::Ident(i) => i.type_ann.as_deref(),
                                    TsParamPropParam::Assign(a) => get_type_ann_of_pat(&a.left),
                                };
                                Some(serialize_type(self.class_name, ann).as_arg())
                            }
                            ParamOrTsParamProp::Param(p) => Some(
                                serialize_type(self.class_name, get_type_ann_of_pat(&p.pat))
                                    .as_arg(),
                            ),
                        })
                        .collect(),
                }
                .as_arg(),
            );
            c.decorators.push(dec);
        }
    }

    fn visit_mut_class_method(&mut self, m: &mut ClassMethod) {
        if m.function.decorators.is_empty() {
            return;
        }

        {
            let dec = self
                .create_metadata_design_decorator("design:type", quote_ident!("Function").as_arg());
            m.function.decorators.push(dec);
        }
        {
            let dec = self.create_metadata_design_decorator(
                "design:paramtypes",
                ArrayLit {
                    span: DUMMY_SP,
                    elems: m
                        .function
                        .params
                        .iter()
                        .map(|v| {
                            Some(
                                serialize_type(self.class_name, get_type_ann_of_pat(&v.pat))
                                    .as_arg(),
                            )
                        })
                        .collect(),
                }
                .as_arg(),
            );
            m.function.decorators.push(dec);
        }
    }

    fn visit_mut_class_prop(&mut self, p: &mut ClassProp) {
        if p.decorators.is_empty() {
            return;
        }

        if p.type_ann.is_none() {
            return;
        }
        if let Some(name) = p
            .type_ann
            .as_ref()
            .map(|ty| &ty.type_ann)
            .and_then(|type_ann| match &**type_ann {
                TsType::TsTypeRef(r) => Some(r),
                _ => None,
            })
            .and_then(|r| match &r.type_name {
                TsEntityName::TsQualifiedName(_) => None,
                TsEntityName::Ident(i) => Some(i),
            })
        {
            if let Some(kind) = self.enums.get(&name.sym) {
                let dec = self.create_metadata_design_decorator(
                    "design:type",
                    match kind {
                        EnumKind::Mixed => quote_ident!("Object").as_arg(),
                        EnumKind::Str => quote_ident!("String").as_arg(),
                        EnumKind::Num => quote_ident!("Number").as_arg(),
                    },
                );
                p.decorators.push(dec);
                return;
            }
        }

        let dec = self.create_metadata_design_decorator(
            "design:type",
            serialize_type(self.class_name, p.type_ann.as_deref()).as_arg(),
        );
        p.decorators.push(dec);
    }
}

impl Metadata<'_> {
    fn create_metadata_design_decorator(&self, design: &str, type_arg: ExprOrSpread) -> Decorator {
        Decorator {
            span: DUMMY_SP,
            expr: Box::new(Expr::Call(CallExpr {
                span: DUMMY_SP,
                callee: helper!(ts, ts_metadata, "__metadata"),
                args: vec![design.as_arg(), type_arg],
                type_args: Default::default(),
            })),
        }
    }
}

fn serialize_type(class_name: Option<&Ident>, param: Option<&TsTypeAnn>) -> Expr {
    fn check_object_existed(expr: Box<Expr>) -> Box<Expr> {
        match *expr {
            Expr::Member(ref member_expr) => {
                let obj_expr = member_expr.obj.clone();
                Box::new(Expr::Bin(BinExpr {
                    span: DUMMY_SP,
                    left: check_object_existed(obj_expr),
                    op: op!("||"),
                    right: Box::new(Expr::Bin(BinExpr {
                        span: DUMMY_SP,
                        left: Box::new(Expr::Unary(UnaryExpr {
                            span: DUMMY_SP,
                            op: op!("typeof"),
                            arg: expr,
                        })),
                        op: op!("==="),
                        right: Box::new(Expr::Lit(Lit::Str(Str {
                            span: DUMMY_SP,
                            value: "undefined".into(),
                            raw: None,
                        }))),
                    })),
                }))
            }
            _ => Box::new(Expr::Bin(BinExpr {
                span: DUMMY_SP,
                left: Box::new(Expr::Unary(UnaryExpr {
                    span: DUMMY_SP,
                    op: op!("typeof"),
                    arg: expr,
                })),
                op: op!("==="),
                right: Box::new(Expr::Lit(Lit::Str(Str {
                    span: DUMMY_SP,
                    value: "undefined".into(),
                    raw: None,
                }))),
            })),
        }
    }

    fn serialize_type_ref(class_name: &str, ty: &TsTypeRef) -> Expr {
        match &ty.type_name {
            // We should omit references to self (class) since it will throw a ReferenceError at
            // runtime due to babel transpile output.
            TsEntityName::Ident(i) if &*i.sym == class_name => {
                return quote_ident!("Object").into()
            }
            _ => {}
        }

        let member_expr = ts_entity_to_member_expr(&ty.type_name);

        // We don't know if type is just a type (interface, etc.) or a concrete value
        // (class, etc.)
        //
        // `typeof` operator allows us to use the expression even if it is not defined,
        // fallback is just `Object`.

        Expr::Cond(CondExpr {
            span: DUMMY_SP,
            test: check_object_existed(Box::new(member_expr.clone())),
            cons: Box::new(quote_ident!("Object").into()),
            alt: Box::new(member_expr),
        })
    }

    fn serialize_type_list(class_name: &str, types: &[Box<TsType>]) -> Expr {
        let mut u = None;
        for ty in types {
            // Skip parens if need be
            let ty = match &**ty {
                TsType::TsParenthesizedType(ty) => &ty.type_ann,
                _ => ty,
            };
            match &**ty {
                // Always elide `never` from the union/intersection if possible
                TsType::TsKeywordType(TsKeywordType {
                    kind: TsKeywordTypeKind::TsNeverKeyword,
                    ..
                }) => {
                    continue;
                }

                // Elide null and undefined from unions for metadata, just like what we did prior to
                // the implementation of strict null checks
                TsType::TsKeywordType(TsKeywordType {
                    kind: TsKeywordTypeKind::TsNullKeyword,
                    ..
                })
                | TsType::TsKeywordType(TsKeywordType {
                    kind: TsKeywordTypeKind::TsUndefinedKeyword,
                    ..
                }) => {
                    return quote_ident!("Object").into();
                }

                _ => {}
            }

            let item = serialize_type_node(class_name, ty);

            // One of the individual is global object, return immediately
            if let Expr::Ident(Ident {
                sym: js_word!("Object"),
                ..
            }) = item
            {
                return item;
            }

            // If there exists union that is not void 0 expression, check if the
            // the common type is identifier. anything more complex
            // and we will just default to Object

            //
            match &u {
                None => {
                    u = Some(item);
                }

                Some(prev) => {
                    // Check for different types
                    match prev {
                        Expr::Ident(prev) => match &item {
                            Expr::Ident(item) if prev.sym == item.sym => {}
                            _ => return quote_ident!("Object").into(),
                        },

                        _ => return quote_ident!("Object").into(),
                    }
                }
            }
        }

        match u {
            Some(i) => i,
            _ => quote_ident!("Object").into(),
        }
    }

    fn serialize_type_node(class_name: &str, ty: &TsType) -> Expr {
        let span = ty.span();
        match ty {
            TsType::TsKeywordType(TsKeywordType {
                kind: TsKeywordTypeKind::TsVoidKeyword,
                ..
            })
            | TsType::TsKeywordType(TsKeywordType {
                kind: TsKeywordTypeKind::TsUndefinedKeyword,
                ..
            })
            | TsType::TsKeywordType(TsKeywordType {
                kind: TsKeywordTypeKind::TsNullKeyword,
                ..
            })
            | TsType::TsKeywordType(TsKeywordType {
                kind: TsKeywordTypeKind::TsNeverKeyword,
                ..
            }) => *undefined(span),

            TsType::TsParenthesizedType(ty) => serialize_type_node(class_name, &ty.type_ann),

            TsType::TsFnOrConstructorType(_) => quote_ident!("Function").into(),

            TsType::TsArrayType(_) | TsType::TsTupleType(_) => quote_ident!("Array").into(),

            TsType::TsLitType(TsLitType {
                lit: TsLit::Bool(..),
                ..
            })
            | TsType::TsTypePredicate(_)
            | TsType::TsKeywordType(TsKeywordType {
                kind: TsKeywordTypeKind::TsBooleanKeyword,
                ..
            }) => quote_ident!("Boolean").into(),

            ty if is_str(ty) => quote_ident!("String").into(),

            TsType::TsKeywordType(TsKeywordType {
                kind: TsKeywordTypeKind::TsObjectKeyword,
                ..
            }) => quote_ident!("Object").into(),

            TsType::TsLitType(TsLitType {
                lit: TsLit::Number(..),
                ..
            })
            | TsType::TsKeywordType(TsKeywordType {
                kind: TsKeywordTypeKind::TsNumberKeyword,
                ..
            }) => quote_ident!("Number").into(),

            TsType::TsKeywordType(TsKeywordType {
                kind: TsKeywordTypeKind::TsBigIntKeyword,
                ..
            }) => Expr::Cond(CondExpr {
                span: DUMMY_SP,
                test: check_object_existed(quote_ident!("BigInt").into()),
                cons: quote_ident!("Object").into(),
                alt: quote_ident!("BigInt").into(),
            }),

            TsType::TsLitType(ty) => {
                // TODO: Proper error reporting
                panic!("Bad type for decoration: {:?}", ty);
            }

            TsType::TsKeywordType(TsKeywordType {
                kind: TsKeywordTypeKind::TsSymbolKeyword,
                ..
            }) => quote_ident!("Symbol").into(),

            TsType::TsTypeQuery(_)
            | TsType::TsTypeOperator(_)
            | TsType::TsIndexedAccessType(_)
            | TsType::TsTypeLit(_)
            | TsType::TsMappedType(_)
            | TsType::TsKeywordType(TsKeywordType {
                kind: TsKeywordTypeKind::TsAnyKeyword,
                ..
            })
            | TsType::TsKeywordType(TsKeywordType {
                kind: TsKeywordTypeKind::TsUnknownKeyword,
                ..
            })
            | TsType::TsThisType(..) => quote_ident!("Object").into(),

            TsType::TsUnionOrIntersectionType(ty) => match ty {
                TsUnionOrIntersectionType::TsUnionType(ty) => {
                    serialize_type_list(class_name, &ty.types)
                }
                TsUnionOrIntersectionType::TsIntersectionType(ty) => {
                    serialize_type_list(class_name, &ty.types)
                }
            },

            TsType::TsConditionalType(ty) => {
                serialize_type_list(class_name, &[ty.true_type.clone(), ty.false_type.clone()])
            }

            TsType::TsTypeRef(ty) => serialize_type_ref(class_name, ty),

            _ => panic!("Bad type for decorator: {:?}", ty),
        }
    }

    let param = match param {
        Some(v) => &v.type_ann,
        None => return *undefined(DUMMY_SP),
    };

    serialize_type_node(class_name.map(|v| &*v.sym).unwrap_or(""), param)
}

fn ts_entity_to_member_expr(type_name: &TsEntityName) -> Expr {
    match type_name {
        TsEntityName::TsQualifiedName(q) => {
            let obj = ts_entity_to_member_expr(&q.left);

            Expr::Member(MemberExpr {
                span: DUMMY_SP,
                obj: obj.into(),
                prop: MemberProp::Ident(q.right.clone()),
            })
        }
        TsEntityName::Ident(i) => Expr::Ident(i.clone()),
    }
}

fn get_type_ann_of_pat(p: &Pat) -> Option<&TsTypeAnn> {
    match p {
        Pat::Ident(p) => p.type_ann.as_deref(),
        Pat::Array(p) => p.type_ann.as_deref(),
        Pat::Rest(p) => p.type_ann.as_deref(),
        Pat::Object(p) => p.type_ann.as_deref(),
        Pat::Assign(p) => {
            return p
                .type_ann
                .as_deref()
                .or_else(|| get_type_ann_of_pat(&p.left));
        }
        Pat::Invalid(_) => None,
        Pat::Expr(_) => None,
    }
}

fn is_str(ty: &TsType) -> bool {
    match ty {
        TsType::TsLitType(TsLitType {
            lit: TsLit::Str(..),
            ..
        })
        | TsType::TsKeywordType(TsKeywordType {
            kind: TsKeywordTypeKind::TsStringKeyword,
            ..
        }) => true,

        TsType::TsUnionOrIntersectionType(TsUnionOrIntersectionType::TsUnionType(u)) => {
            u.types.iter().all(|ty| is_str(ty))
        }

        _ => false,
    }
}