swc_ecma_quote_macros/ast/
lit.rs

1use proc_macro2::Span;
2use swc_atoms::{Atom, Wtf8Atom};
3use swc_ecma_ast::*;
4use syn::{parse_quote, ExprLit, LitBool, LitByteStr, LitFloat};
5
6use super::ToCode;
7use crate::{builder::Builder, ctxt::Ctx};
8
9fail_todo!(BigInt);
10fail_todo!(JSXText);
11
12impl ToCode for Str {
13    fn to_code(&self, cx: &crate::ctxt::Ctx) -> syn::Expr {
14        if let Some(var_name) = self.value.as_str() {
15            if let Some(var_name) = var_name.strip_prefix('$') {
16                if let Some(var) = cx.var(crate::ctxt::VarPos::Str, var_name) {
17                    return var.get_expr();
18                }
19            }
20        }
21
22        let mut builder = Builder::new("Str");
23        builder.add("span", ToCode::to_code(&self.span, cx));
24        builder.add("value", ToCode::to_code(&self.value, cx));
25        builder.add("raw", ToCode::to_code(&self.raw, cx));
26        syn::Expr::Struct(builder.build())
27    }
28}
29impl_struct!(Bool, [span, value]);
30impl_struct!(Null, [span]);
31impl_struct!(Number, [span, value, raw]);
32impl_struct!(Regex, [span, exp, flags]);
33
34impl ToCode for Atom {
35    fn to_code(&self, _: &Ctx) -> syn::Expr {
36        let val = &**self;
37        parse_quote!(swc_core::atoms::atom!(#val))
38    }
39}
40
41impl ToCode for Wtf8Atom {
42    fn to_code(&self, _: &Ctx) -> syn::Expr {
43        let bytes_literal = LitByteStr::new(self.as_bytes(), Span::call_site());
44        parse_quote!(unsafe { swc_atoms::Wtf8Atom::from_bytes_unchecked(#bytes_literal) })
45    }
46}
47
48impl ToCode for bool {
49    fn to_code(&self, _: &Ctx) -> syn::Expr {
50        syn::Expr::Lit(ExprLit {
51            attrs: Default::default(),
52            lit: syn::Lit::Bool(LitBool::new(*self, Span::call_site())),
53        })
54    }
55}
56
57impl ToCode for f64 {
58    fn to_code(&self, _: &Ctx) -> syn::Expr {
59        syn::Expr::Lit(ExprLit {
60            attrs: Default::default(),
61            lit: syn::Lit::Float(LitFloat::new(&format!("{self}f64"), Span::call_site())),
62        })
63    }
64}