swc_estree_compat/babelify/
lit.rs1use serde::{Deserialize, Serialize};
2use swc_atoms::atom;
3use swc_ecma_ast::{BigInt, Bool, Lit, Null, Number, Regex, Str};
4use swc_estree_ast::{
5 BigIntLiteral, BooleanLiteral, JSXText as BabelJSXText, Literal, NullLiteral, NumericLiteral,
6 RegExpLiteral, StringLiteral,
7};
8
9use crate::babelify::{Babelify, Context};
10
11#[derive(Debug, Clone, Serialize, Deserialize)]
12pub enum LitOutput {
13 Lit(Literal),
14 JSX(BabelJSXText),
15}
16
17impl Babelify for Lit {
18 type Output = LitOutput;
19
20 fn babelify(self, ctx: &Context) -> Self::Output {
21 match self {
22 Lit::Str(s) => LitOutput::Lit(Literal::String(s.babelify(ctx))),
23 Lit::Bool(b) => LitOutput::Lit(Literal::Boolean(b.babelify(ctx))),
24 Lit::Null(n) => LitOutput::Lit(Literal::Null(n.babelify(ctx))),
25 Lit::Num(n) => LitOutput::Lit(Literal::Numeric(n.babelify(ctx))),
26 Lit::BigInt(i) => LitOutput::Lit(Literal::BigInt(i.babelify(ctx))),
27 Lit::Regex(r) => LitOutput::Lit(Literal::RegExp(r.babelify(ctx))),
28 Lit::JSXText(t) => LitOutput::JSX(t.babelify(ctx)),
29 #[cfg(swc_ast_unknown)]
30 _ => panic!("unable to access unknown nodes"),
31 }
32 }
33}
34
35impl Babelify for Str {
36 type Output = StringLiteral;
37
38 fn babelify(self, ctx: &Context) -> Self::Output {
39 StringLiteral {
40 base: ctx.base(self.span),
41 value: self.value,
42 raw: match self.raw {
44 Some(value) => value,
45 _ => swc_atoms::atom!(""),
46 },
47 }
48 }
49}
50
51impl Babelify for Bool {
52 type Output = BooleanLiteral;
53
54 fn babelify(self, ctx: &Context) -> Self::Output {
55 BooleanLiteral {
56 base: ctx.base(self.span),
57 value: self.value,
58 }
59 }
60}
61
62impl Babelify for Null {
63 type Output = NullLiteral;
64
65 fn babelify(self, ctx: &Context) -> Self::Output {
66 NullLiteral {
67 base: ctx.base(self.span),
68 }
69 }
70}
71
72impl Babelify for Number {
73 type Output = NumericLiteral;
74
75 fn babelify(self, ctx: &Context) -> Self::Output {
76 NumericLiteral {
77 base: ctx.base(self.span),
78 value: self.value,
79 }
80 }
81}
82
83impl Babelify for BigInt {
84 type Output = BigIntLiteral;
85
86 fn babelify(self, ctx: &Context) -> Self::Output {
87 BigIntLiteral {
88 base: ctx.base(self.span),
89 value: self.value.to_string(),
90 raw: match self.raw {
92 Some(value) => value,
93 _ => atom!(""),
94 },
95 }
96 }
97}
98
99impl Babelify for Regex {
100 type Output = RegExpLiteral;
101
102 fn babelify(self, ctx: &Context) -> Self::Output {
103 RegExpLiteral {
104 base: ctx.base(self.span),
105 pattern: self.exp,
106 flags: self.flags,
107 }
108 }
109}