swc_core/quote.rs
1/// # Supported output types
2///
3/// - `Expr`
4/// - `Pat`
5/// - `Stmt`
6/// - `ModuleItem`
7///
8/// - Option<T> where T is supported type
9/// - Box<T> where T is supported type
10///
11/// For example, `Box<Expr>` and `Option<Box<Expr>>` are supported.
12///
13/// # Variable substitution
14///
15/// If an identifier starts with `$`, it is substituted with the value of the
16/// parameter passed.
17///
18/// e.g.
19///
20/// ```rust
21/// use swc_common::DUMMY_SP;
22/// use swc_ecma_ast::Ident;
23/// use swc_ecma_quote::quote;
24///
25/// // This will return ast for `const ref = 4;`
26/// let _stmt = quote!("const $name = 4;" as Stmt, name = Ident::new("ref".into(), DUMMY_SP));
27///
28/// // Tip: Use private_ident!("ref") for real identifiers.
29/// ```
30///
31/// ## Typed variables
32///
33/// As this macro generates static AST, it can't substitute variables if an
34/// ideitifier is not allowed in such position. In other words, this macro only
35/// supports substituting
36///
37/// - Ident
38/// - Expr
39/// - Pat
40///
41/// You can use it like
42///
43/// ```rust
44/// use swc_common::DUMMY_SP;
45/// use swc_ecma_ast::Ident;
46/// use swc_ecma_quote::quote;
47///
48/// // This will return ast for `const ref = 4;`
49/// let _stmt = quote!(
50/// "const $name = $val;" as Stmt,
51/// name = Ident::new("ref".into(), DUMMY_SP),
52/// val: Expr = 4.into(),
53/// );
54/// ```
55///
56/// # Examples
57///
58/// ## Quote a variable declaration
59/// ```rust
60/// use swc_common::DUMMY_SP;
61/// use swc_ecma_ast::Ident;
62/// use swc_ecma_quote::quote;
63///
64/// // This will return ast for `const ref = 4;`
65/// let _stmt = quote!("const $name = 4;" as Stmt, name =
66/// Ident::new("ref".into(), DUMMY_SP));
67///
68/// // Tip: Use private_ident!("ref") for real identifiers.
69/// ```
70#[macro_export]
71macro_rules! quote {
72 ($($tt:tt)*) => {{
73 $crate::swc_ecma_quote_macros::internal_quote!($($tt)*)
74 }};
75}
76
77/// Creates a `Box<Expr>` from the source code.
78///
79/// This is an alias for [quote], but without `as Box<Expr>`.
80#[macro_export]
81macro_rules! quote_expr {
82 ($src:tt) => {{
83 $crate::quote!($src as Box<Expr>)
84 }};
85
86 ($src:tt, $($tt2:tt)*) => {{
87 $crate::quote!($src as Box<Expr>, $($tt2)*)
88
89 }};
90}
91
92/// Noop
93pub trait ImplicitClone: Clone {
94 fn clone_quote_var(&self) -> Self {
95 self.clone()
96 }
97}
98
99impl<T: Clone> ImplicitClone for T {}