This crate provides quasi-quoting macros like quote.
This crate has backward-compatibility with original quote!
macro and also provides
new template-engine like syntax.
This crate is get some inspiration from proc-quote.
This crate is useful for developing proc-macro. Usually an proc-macro crate using template_quote is placed with following Cargo.toml
:
```Cargo.toml [package] name = "yourcratename" version = "0.0.0" edition = "2021"
[lib] proc-macro = true
[dependencies] template-quote = "0.2" proc-macro2 = "1.0" ```
and with following src/lib.rs
code:
```lib.rs extern crate procmacro; extern crate procmacro2; extern crate template_quote;
use templatequote::quote; use procmacro::TokenStream; use proc_macro2::TokenStream as TokenStream2;
pub fn mymacro(: TokenStream) -> TokenStream { quote! { /* something here */ }.into() } ```
then you will be able to use it like:
```rust extern crate yourcratename; use yourcratename::my_macro;
my_macro!() ```
Original quote!
macro syntax is fully supported. See quote's doc.
template_quote supports if
, else
, else if
, for .. in ..
, while ..
, while let ...
, loop
syntax like following:
rust
let tokens = quote! {
#(
#(if v >= &10){
#v
}
#(else){
-#v
}
)*
};
assert_eq!("-1i32 10i32 -2i32 13i32 -4i32 19i32", tokens.to_string());
You can also set an separater for for
, while
, loop
, placing a separater between #(..)
and {..}
.
You can use inline expression by syntax #{ ... }
.
rust
let v = vec![1, 2, 3];
let tokens = quote! {
#(
#v => #{ format!("{}", v).as_str() }
)*
};
assert_eq!(
"1i32 => \"1\" 2i32 => \"2\" 3i32 => \"3\"",
tokens.to_string()
);
#{ ... }
within traditional repetition syntax #( .. )*
does not work.Spacing::Join
, then the emitting punct also has same spacing, whether the '#' token is processed by the macro or not.