Skip to content

Commit

Permalink
feat(es/quote): Allow using Str as a var (#6797)
Browse files Browse the repository at this point in the history
  • Loading branch information
kdy1 committed Jan 12, 2023
1 parent be0af3f commit 224eff9
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 6 deletions.
25 changes: 21 additions & 4 deletions crates/swc_ecma_quote/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,12 +46,13 @@ mod clone;
/// ## 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
/// identifier is not allowed in such position. In other words, this macro only
/// supports substituting
///
/// - Ident
/// - Expr
/// - Pat
/// - [swc_ecma_ast::Ident]
/// - [swc_ecma_ast::Expr]
/// - [swc_ecma_ast::Pat]
/// - [swc_ecma_ast::Str]
///
/// You can use it like
///
Expand Down Expand Up @@ -82,6 +83,22 @@ mod clone;
///
/// // Tip: Use private_ident!("ref") for real identifiers.
/// ```
///
/// ## Using `Str`
///
/// The grammar is `"$var_name"`.
///
/// ```rust
/// use swc_common::DUMMY_SP;
/// use swc_ecma_ast::Str;
/// use swc_ecma_quote::quote;
///
/// // This will return ast for `import thing from "foo";`
/// let _stmt = quote!(
/// "import thing from \"$thing\";" as ModuleItem,
/// thing: Str = "foo".into(),
/// );
/// ```
#[macro_export]
macro_rules! quote {
($($tt:tt)*) => {{
Expand Down
18 changes: 16 additions & 2 deletions crates/swc_ecma_quote_macros/src/ast/lit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,26 @@ use swc_ecma_ast::*;
use syn::{ExprLit, LitBool, LitFloat};

use super::ToCode;
use crate::ctxt::Ctx;
use crate::{builder::Builder, ctxt::Ctx};

fail_todo!(BigInt);
fail_todo!(JSXText);

impl_struct!(Str, [span, value, raw]);
impl ToCode for Str {
fn to_code(&self, cx: &crate::ctxt::Ctx) -> syn::Expr {
if let Some(var_name) = self.value.strip_prefix('$') {
if let Some(var) = cx.var(crate::ctxt::VarPos::Str, var_name) {
return var.get_expr();
}
}

let mut builder = Builder::new("Str");
builder.add("span", ToCode::to_code(&self.span, cx));
builder.add("value", ToCode::to_code(&self.value, cx));
builder.add("raw", ToCode::to_code(&self.raw, cx));
syn::Expr::Struct(builder.build())
}
}
impl_struct!(Bool, [span, value]);
impl_struct!(Null, [span]);
impl_struct!(Number, [span, value, raw]);
Expand Down
2 changes: 2 additions & 0 deletions crates/swc_ecma_quote_macros/src/ctxt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ pub enum VarPos {
Ident,
Expr,
Pat,
Str,
}

#[derive(Debug)]
Expand Down Expand Up @@ -137,6 +138,7 @@ pub(super) fn prepare_vars(
VarPos::Ident => "Ident",
VarPos::Expr => "Expr",
VarPos::Pat => "Pat",
VarPos::Str => "Str",
},
call_site(),
);
Expand Down

0 comments on commit 224eff9

Please sign in to comment.