swc_core

Macro quote

source
macro_rules! quote {
    ($($tt:tt)*) => { ... };
}
Available on crate feature ecma_quote only.
Expand description

§Supported output types

  • Expr

  • Pat

  • Stmt

  • ModuleItem

  • Option where T is supported type

  • Box where T is supported type

For example, Box<Expr> and Option<Box<Expr>> are supported.

§Variable substitution

If an identifier starts with $, it is substituted with the value of the parameter passed.

e.g.

use swc_common::DUMMY_SP;
use swc_ecma_ast::Ident;
use swc_ecma_quote::quote;

// This will return ast for `const ref = 4;`
let _stmt = quote!("const $name = 4;" as Stmt, name = Ident::new("ref".into(), DUMMY_SP));

// Tip: Use private_ident!("ref") for real identifiers.

§Typed variables

As this macro generates static AST, it can’t substitute variables if an ideitifier is not allowed in such position. In other words, this macro only supports substituting

  • Ident
  • Expr
  • Pat

You can use it like

use swc_common::DUMMY_SP;
use swc_ecma_ast::Ident;
use swc_ecma_quote::quote;

// This will return ast for `const ref = 4;`
let _stmt = quote!(
                "const $name = $val;" as Stmt,
                name = Ident::new("ref".into(), DUMMY_SP),
                val: Expr = 4.into(),
            );

§Examples

§Quote a variable declaration

use swc_common::DUMMY_SP;
use swc_ecma_ast::Ident;
use swc_ecma_quote::quote;

// This will return ast for `const ref = 4;`
let _stmt = quote!("const $name = 4;" as Stmt, name =
Ident::new("ref".into(), DUMMY_SP));

// Tip: Use private_ident!("ref") for real identifiers.