1 //! This crate provides the [`quote!`] macro for turning Rust syntax tree data
2 //! structures into tokens of source code.
4 //! [`quote!`]: macro.quote.html
6 //! Procedural macros in Rust receive a stream of tokens as input, execute
7 //! arbitrary Rust code to determine how to manipulate those tokens, and produce
8 //! a stream of tokens to hand back to the compiler to compile into the caller's
9 //! crate. Quasi-quoting is a solution to one piece of that -- producing tokens
10 //! to return to the compiler.
12 //! The idea of quasi-quoting is that we write *code* that we treat as *data*.
13 //! Within the `quote!` macro, we can write what looks like code to our text
14 //! editor or IDE. We get all the benefits of the editor's brace matching,
15 //! syntax highlighting, indentation, and maybe autocompletion. But rather than
16 //! compiling that as code into the current crate, we can treat it as data, pass
17 //! it around, mutate it, and eventually hand it back to the compiler as tokens
18 //! to compile into the macro caller's crate.
20 //! This crate is motivated by the procedural macro use case, but is a
21 //! general-purpose Rust quasi-quoting library and is not specific to procedural
24 //! *Version requirement: Quote supports any compiler version back to Rust's
25 //! very first support for procedural macros in Rust 1.15.0.*
34 //! extern crate quote;
41 //! The following quasi-quoted block of code is something you might find in [a]
42 //! procedural macro having to do with data structure serialization. The `#var`
43 //! syntax performs interpolation of runtime variables into the quoted tokens.
44 //! Check out the documentation of the [`quote!`] macro for more detail about
45 //! the syntax. See also the [`quote_spanned!`] macro which is important for
46 //! implementing hygienic procedural macros.
48 //! [a]: https://serde.rs/
49 //! [`quote_spanned!`]: macro.quote_spanned.html
53 //! # extern crate quote;
56 //! # let generics = "";
57 //! # let where_clause = "";
58 //! # let field_ty = "";
59 //! # let item_ty = "";
63 //! let tokens = quote! {
64 //! struct SerializeWith #generics #where_clause {
65 //! value: &'a #field_ty,
66 //! phantom: ::std::marker::PhantomData<#item_ty>,
69 //! impl #generics serde::Serialize for SerializeWith #generics #where_clause {
70 //! fn serialize<S>(&self, s: &mut S) -> Result<(), S::Error>
71 //! where S: serde::Serializer
73 //! #path(self.value, s)
79 //! phantom: ::std::marker::PhantomData::<#item_ty>,
86 //! ## Recursion limit
88 //! The `quote!` macro relies on deep recursion so some large invocations may
89 //! fail with "recursion limit reached" when you compile. If it fails, bump up
90 //! the recursion limit by adding `#![recursion_limit = "128"]` to your crate.
91 //! An even higher limit may be necessary for especially large invocations.
93 // Quote types in rustdoc of other crates get linked to here.
94 #![doc(html_root_url = "https://docs.rs/quote/0.4.2")]
96 extern crate proc_macro2
;
97 extern crate proc_macro
;
100 pub use tokens
::Tokens
;
103 pub use to_tokens
::ToTokens
;
109 pub use proc_macro2
::*;
112 pub fn parse(tokens
: &mut ::Tokens
, span
: Span
, s
: &str) {
113 let s
: TokenStream
= s
.parse().expect("invalid token stream");
114 tokens
.append_all(s
.into_iter().map(|mut t
| {
121 pub fn append_kind(tokens
: &mut ::Tokens
, span
: Span
, kind
: TokenNode
) {
122 tokens
.append(TokenTree
{
131 /// Performs variable interpolation against the input and produces it as
132 /// [`Tokens`]. For returning tokens to the compiler in a procedural macro, use
133 /// `into()` to build a `TokenStream`.
135 /// [`Tokens`]: struct.Tokens.html
139 /// Variable interpolation is done with `#var` (similar to `$var` in
140 /// `macro_rules!` macros). This grabs the `var` variable that is currently in
141 /// scope and inserts it in that location in the output tokens. The variable
142 /// must implement the [`ToTokens`] trait.
144 /// [`ToTokens`]: trait.ToTokens.html
146 /// Repetition is done using `#(...)*` or `#(...),*` again similar to
147 /// `macro_rules!`. This iterates through the elements of any variable
148 /// interpolated within the repetition and inserts a copy of the repetition body
149 /// for each one. The variables in an interpolation may be anything that
150 /// implements `IntoIterator`, including `Vec` or a pre-existing iterator.
152 /// - `#(#var)*` — no separators
153 /// - `#(#var),*` — the character before the asterisk is used as a separator
154 /// - `#( struct #var; )*` — the repetition can contain other tokens
155 /// - `#( #k => println!("{}", #v), )*` — even multiple interpolations
159 /// Any interpolated tokens preserve the `Span` information provided by their
160 /// `ToTokens` implementation. Tokens that originate within the `quote!`
161 /// invocation are spanned with [`Span::def_site()`].
163 /// [`Span::def_site()`]: https://docs.rs/proc-macro2/0.2/proc_macro2/struct.Span.html#method.def_site
165 /// A different span can be provided through the [`quote_spanned!`] macro.
167 /// [`quote_spanned!`]: macro.quote_spanned.html
172 /// extern crate proc_macro;
175 /// extern crate quote;
177 /// use proc_macro::TokenStream;
179 /// # const IGNORE_TOKENS: &'static str = stringify! {
180 /// #[proc_macro_derive(HeapSize)]
182 /// pub fn derive_heap_size(input: TokenStream) -> TokenStream {
183 /// // Parse the input and figure out what implementation to generate...
184 /// # const IGNORE_TOKENS: &'static str = stringify! {
185 /// let name = /* ... */;
186 /// let expr = /* ... */;
192 /// let expanded = quote! {
193 /// // The generated impl.
194 /// impl ::heapsize::HeapSize for #name {
195 /// fn heap_size_of_children(&self) -> usize {
201 /// // Hand the output tokens back to the compiler.
209 ($
($tt
:tt
)*) => (quote_spanned
!($
crate::__rt
::Span
::def_site()=> $
($tt
)*));
212 /// Same as `quote!`, but applies a given span to all tokens originating within
213 /// the macro invocation.
217 /// A span expression of type [`Span`], followed by `=>`, followed by the tokens
218 /// to quote. The span expression should be brief -- use a variable for anything
219 /// more than a few characters. There should be no space before the `=>` token.
221 /// [`Span`]: https://docs.rs/proc-macro2/0.2/proc_macro2/struct.Span.html
225 /// # extern crate quote;
226 /// # extern crate proc_macro2;
228 /// # use proc_macro2::Span;
231 /// # const IGNORE_TOKENS: &'static str = stringify! {
232 /// let span = /* ... */;
234 /// # let span = Span::call_site();
237 /// // On one line, use parentheses.
238 /// let tokens = quote_spanned!(span=> Box::into_raw(Box::new(#init)));
240 /// // On multiple lines, place the span at the top and use braces.
241 /// let tokens = quote_spanned! {span=>
242 /// Box::into_raw(Box::new(#init))
249 /// Any interpolated tokens preserve the `Span` information provided by their
250 /// `ToTokens` implementation. Tokens that originate within the `quote_spanned!`
251 /// invocation are spanned with the given span argument.
255 /// The following procedural macro code uses `quote_spanned!` to assert that a
256 /// particular Rust type implements the [`Sync`] trait so that references can be
257 /// safely shared between threads.
259 /// [`Sync`]: https://doc.rust-lang.org/std/marker/trait.Sync.html
263 /// # extern crate quote;
264 /// # extern crate proc_macro2;
266 /// # use quote::{Tokens, ToTokens};
267 /// # use proc_macro2::Span;
272 /// # fn span(&self) -> Span {
273 /// # Span::call_site()
277 /// # impl ToTokens for Type {
278 /// # fn to_tokens(&self, _tokens: &mut Tokens) {}
283 /// # let def_site = Span::def_site();
285 /// let ty_span = ty.span().resolved_at(def_site);
286 /// let assert_sync = quote_spanned! {ty_span=>
287 /// struct _AssertSync where #ty: Sync;
292 /// If the assertion fails, the user will see an error like the following. The
293 /// input span of their type is hightlighted in the error.
296 /// error[E0277]: the trait bound `*const (): std::marker::Sync` is not satisfied
297 /// --> src/main.rs:10:21
299 /// 10 | static ref PTR: *const () = &();
300 /// | ^^^^^^^^^ `*const ()` cannot be shared between threads safely
303 /// In this example it is important for the where-clause to be spanned with the
304 /// line/column information of the user's input type so that error messages are
305 /// placed appropriately by the compiler. But it is also incredibly important
306 /// that `Sync` resolves at the macro definition site and not the macro call
307 /// site. If we resolve `Sync` at the same span that the user's type is going to
308 /// be resolved, then they could bypass our check by defining their own trait
309 /// named `Sync` that is implemented for their type.
311 macro_rules
! quote_spanned
{
312 ($span
:expr
=> $
($tt
:tt
)*) => {
314 let mut _s
= $
crate::Tokens
::new();
316 quote_each_token
!(_s _span $
($tt
)*);
322 // Extract the names of all #metavariables and pass them to the $finish macro.
324 // in: pounded_var_names!(then () a #b c #( #d )* #e)
325 // out: then!(() b d e)
328 macro_rules
! pounded_var_names
{
329 ($finish
:ident ($
($found
:ident
)*) # ( $($inner:tt)* ) $($rest:tt)*) => {
330 pounded_var_names
!($
finish ($
($found
)*) $
($inner
)* $
($rest
)*)
333 ($finish
:ident ($
($found
:ident
)*) # [ $($inner:tt)* ] $($rest:tt)*) => {
334 pounded_var_names
!($
finish ($
($found
)*) $
($inner
)* $
($rest
)*)
337 ($finish
:ident ($
($found
:ident
)*) # { $($inner:tt)* } $($rest:tt)*) => {
338 pounded_var_names
!($
finish ($
($found
)*) $
($inner
)* $
($rest
)*)
341 ($finish
:ident ($
($found
:ident
)*) # $first:ident $($rest:tt)*) => {
342 pounded_var_names
!($
finish ($
($found
)* $first
) $
($rest
)*)
345 ($finish
:ident ($
($found
:ident
)*) ( $
($inner
:tt
)* ) $
($rest
:tt
)*) => {
346 pounded_var_names
!($
finish ($
($found
)*) $
($inner
)* $
($rest
)*)
349 ($finish
:ident ($
($found
:ident
)*) [ $
($inner
:tt
)* ] $
($rest
:tt
)*) => {
350 pounded_var_names
!($
finish ($
($found
)*) $
($inner
)* $
($rest
)*)
353 ($finish
:ident ($
($found
:ident
)*) { $($inner:tt)* } $
($rest
:tt
)*) => {
354 pounded_var_names
!($
finish ($
($found
)*) $
($inner
)* $
($rest
)*)
357 ($finish
:ident ($
($found
:ident
)*) $ignore
:tt $
($rest
:tt
)*) => {
358 pounded_var_names
!($
finish ($
($found
)*) $
($rest
)*)
361 ($finish
:ident ($
($found
:ident
)*)) => {
362 $finish
!(() $
($found
)*)
366 // in: nested_tuples_pat!(() a b c d e)
367 // out: ((((a b) c) d) e)
369 // in: nested_tuples_pat!(() a)
373 macro_rules
! nested_tuples_pat
{
378 (() $first
:ident $
($rest
:ident
)*) => {
379 nested_tuples_pat
!(($first
) $
($rest
)*)
382 (($pat
:pat
) $first
:ident $
($rest
:ident
)*) => {
383 nested_tuples_pat
!((($pat
, $first
)) $
($rest
)*)
391 // in: multi_zip_expr!(() a b c d e)
392 // out: a.into_iter().zip(b).zip(c).zip(d).zip(e)
394 // in: multi_zip_iter!(() a)
398 macro_rules
! multi_zip_expr
{
403 (() $single
:ident
) => {
407 (() $first
:ident $
($rest
:ident
)*) => {
408 multi_zip_expr
!(($first
.into_iter()) $
($rest
)*)
411 (($zips
:expr
) $first
:ident $
($rest
:ident
)*) => {
412 multi_zip_expr
!(($zips
.zip($first
)) $
($rest
)*)
422 macro_rules
! quote_each_token
{
423 ($tokens
:ident $span
:ident
) => {}
;
425 ($tokens
:ident $span
:ident
# ! $($rest:tt)*) => {
426 quote_each_token
!($tokens $span
#);
427 quote_each_token
!($tokens $span
!);
428 quote_each_token
!($tokens $span $
($rest
)*);
431 ($tokens
:ident $span
:ident
# ( $($inner:tt)* ) * $($rest:tt)*) => {
432 for pounded_var_names
!(nested_tuples_pat () $
($inner
)*)
433 in pounded_var_names
!(multi_zip_expr () $
($inner
)*) {
434 quote_each_token
!($tokens $span $
($inner
)*);
436 quote_each_token
!($tokens $span $
($rest
)*);
439 ($tokens
:ident $span
:ident
# ( $($inner:tt)* ) $sep:tt * $($rest:tt)*) => {
440 for (_i
, pounded_var_names
!(nested_tuples_pat () $
($inner
)*))
441 in pounded_var_names
!(multi_zip_expr () $
($inner
)*).into_iter().enumerate() {
443 quote_each_token
!($tokens $span $sep
);
445 quote_each_token
!($tokens $span $
($inner
)*);
447 quote_each_token
!($tokens $span $
($rest
)*);
450 ($tokens
:ident $span
:ident
# [ $($inner:tt)* ] $($rest:tt)*) => {
451 quote_each_token
!($tokens $span
#);
452 $
crate::__rt
::append_kind(&mut $tokens
,
454 $
crate::__rt
::TokenNode
::Group(
455 $
crate::__rt
::Delimiter
::Bracket
,
456 quote_spanned
!($span
=> $
($inner
)*).into()
458 quote_each_token
!($tokens $span $
($rest
)*);
461 ($tokens
:ident $span
:ident
# $first:ident $($rest:tt)*) => {
462 $
crate::ToTokens
::to_tokens(&$first
, &mut $tokens
);
463 quote_each_token
!($tokens $span $
($rest
)*);
466 ($tokens
:ident $span
:ident ( $
($first
:tt
)* ) $
($rest
:tt
)*) => {
467 $
crate::__rt
::append_kind(&mut $tokens
,
469 $
crate::__rt
::TokenNode
::Group(
470 $
crate::__rt
::Delimiter
::Parenthesis
,
471 quote_spanned
!($span
=> $
($first
)*).into()
473 quote_each_token
!($tokens $span $
($rest
)*);
476 ($tokens
:ident $span
:ident
[ $
($first
:tt
)* ] $
($rest
:tt
)*) => {
477 $
crate::__rt
::append_kind(&mut $tokens
,
479 $
crate::__rt
::TokenNode
::Group(
480 $
crate::__rt
::Delimiter
::Bracket
,
481 quote_spanned
!($span
=> $
($first
)*).into()
483 quote_each_token
!($tokens $span $
($rest
)*);
486 ($tokens
:ident $span
:ident { $($first:tt)* } $
($rest
:tt
)*) => {
487 $
crate::__rt
::append_kind(&mut $tokens
,
489 $
crate::__rt
::TokenNode
::Group(
490 $
crate::__rt
::Delimiter
::Brace
,
491 quote_spanned
!($span
=> $
($first
)*).into()
493 quote_each_token
!($tokens $span $
($rest
)*);
496 ($tokens
:ident $span
:ident $first
:tt $
($rest
:tt
)*) => {
497 // TODO: this seems slow... special case some `:tt` arguments?
498 $
crate::__rt
::parse(&mut $tokens
, $span
, stringify
!($first
));
499 quote_each_token
!($tokens $span $
($rest
)*);