standalone_quote/lib.rs
1//! This crate provides the [`quote!`] macro for turning Rust syntax tree data
2//! structures into tokens of source code.
3//!
4//! [`quote!`]: macro.quote.html
5//!
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.
11//!
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.
19//!
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
22//! macros.
23//!
24//! *Version requirement: Quote supports any compiler version back to Rust's
25//! very first support for procedural macros in Rust 1.15.0.*
26//!
27//! ```toml
28//! [dependencies]
29//! quote = "0.4"
30//! ```
31//!
32//! ```
33//! #[macro_use]
34//! extern crate quote;
35//! #
36//! # fn main() {}
37//! ```
38//!
39//! # Example
40//!
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.
47//!
48//! [a]: https://serde.rs/
49//! [`quote_spanned!`]: macro.quote_spanned.html
50//!
51//! ```
52//! # #[macro_use]
53//! # extern crate quote;
54//! #
55//! # fn main() {
56//! # let generics = "";
57//! # let where_clause = "";
58//! # let field_ty = "";
59//! # let item_ty = "";
60//! # let path = "";
61//! # let value = "";
62//! #
63//! let tokens = quote! {
64//! struct SerializeWith #generics #where_clause {
65//! value: &'a #field_ty,
66//! phantom: ::std::marker::PhantomData<#item_ty>,
67//! }
68//!
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
72//! {
73//! #path(self.value, s)
74//! }
75//! }
76//!
77//! SerializeWith {
78//! value: #value,
79//! phantom: ::std::marker::PhantomData::<#item_ty>,
80//! }
81//! };
82//! #
83//! # }
84//! ```
85//!
86//! ## Recursion limit
87//!
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.
92
93// Quote types in rustdoc of other crates get linked to here.
94#![doc(html_root_url = "https://docs.rs/quote/0.4.2")]
95
96extern crate proc_macro2;
97#[cfg(feature = "proc-macro")]
98extern crate proc_macro;
99
100mod tokens;
101pub use tokens::Tokens;
102
103mod to_tokens;
104pub use to_tokens::ToTokens;
105
106// Not public API.
107#[doc(hidden)]
108pub mod __rt {
109 // Not public API.
110 pub use proc_macro2::*;
111
112 // Not public API.
113 pub fn parse(tokens: &mut ::Tokens, span: Span, s: &str) {
114 let s: TokenStream = s.parse().expect("invalid token stream");
115 tokens.append_all(s.into_iter().map(|mut t| {
116 t.span = span;
117 t
118 }));
119 }
120
121 // Not public API.
122 pub fn append_kind(tokens: &mut ::Tokens, span: Span, kind: TokenNode) {
123 tokens.append(TokenTree {
124 span: span,
125 kind: kind,
126 })
127 }
128}
129
130/// The whole point.
131///
132/// Performs variable interpolation against the input and produces it as
133/// [`Tokens`]. For returning tokens to the compiler in a procedural macro, use
134/// `into()` to build a `TokenStream`.
135///
136/// [`Tokens`]: struct.Tokens.html
137///
138/// # Interpolation
139///
140/// Variable interpolation is done with `#var` (similar to `$var` in
141/// `macro_rules!` macros). This grabs the `var` variable that is currently in
142/// scope and inserts it in that location in the output tokens. The variable
143/// must implement the [`ToTokens`] trait.
144///
145/// [`ToTokens`]: trait.ToTokens.html
146///
147/// Repetition is done using `#(...)*` or `#(...),*` again similar to
148/// `macro_rules!`. This iterates through the elements of any variable
149/// interpolated within the repetition and inserts a copy of the repetition body
150/// for each one. The variables in an interpolation may be anything that
151/// implements `IntoIterator`, including `Vec` or a pre-existing iterator.
152///
153/// - `#(#var)*` — no separators
154/// - `#(#var),*` — the character before the asterisk is used as a separator
155/// - `#( struct #var; )*` — the repetition can contain other tokens
156/// - `#( #k => println!("{}", #v), )*` — even multiple interpolations
157///
158/// # Hygiene
159///
160/// Any interpolated tokens preserve the `Span` information provided by their
161/// `ToTokens` implementation. Tokens that originate within the `quote!`
162/// invocation are spanned with [`Span::def_site()`].
163///
164/// [`Span::def_site()`]: https://docs.rs/proc-macro2/0.2/proc_macro2/struct.Span.html#method.def_site
165///
166/// A different span can be provided through the [`quote_spanned!`] macro.
167///
168/// [`quote_spanned!`]: macro.quote_spanned.html
169///
170/// # Example
171///
172/// ```
173/// # #[cfg(feature = "proc-macro")]
174/// extern crate proc_macro;
175///
176/// #[macro_use]
177/// extern crate quote;
178///
179/// # #[cfg(feature = "proc-macro")]
180/// use proc_macro::TokenStream;
181///
182/// # const IGNORE_TOKENS: &'static str = stringify! {
183/// #[proc_macro_derive(HeapSize)]
184/// # };
185/// # #[cfg(feature = "proc-macro")]
186/// pub fn derive_heap_size(input: TokenStream) -> TokenStream {
187/// // Parse the input and figure out what implementation to generate...
188/// # const IGNORE_TOKENS: &'static str = stringify! {
189/// let name = /* ... */;
190/// let expr = /* ... */;
191/// # };
192/// #
193/// # let name = 0;
194/// # let expr = 0;
195///
196/// let expanded = quote! {
197/// // The generated impl.
198/// impl ::heapsize::HeapSize for #name {
199/// fn heap_size_of_children(&self) -> usize {
200/// #expr
201/// }
202/// }
203/// };
204///
205/// // Hand the output tokens back to the compiler.
206/// expanded.into()
207/// }
208/// #
209/// # fn main() {}
210/// ```
211#[macro_export]
212macro_rules! quote {
213 ($($tt:tt)*) => (quote_spanned!($crate::__rt::Span::def_site()=> $($tt)*));
214}
215
216/// Same as `quote!`, but applies a given span to all tokens originating within
217/// the macro invocation.
218///
219/// # Syntax
220///
221/// A span expression of type [`Span`], followed by `=>`, followed by the tokens
222/// to quote. The span expression should be brief -- use a variable for anything
223/// more than a few characters. There should be no space before the `=>` token.
224///
225/// [`Span`]: https://docs.rs/proc-macro2/0.2/proc_macro2/struct.Span.html
226///
227/// ```
228/// # #[macro_use]
229/// # extern crate quote;
230/// # extern crate proc_macro2;
231/// #
232/// # use proc_macro2::Span;
233/// #
234/// # fn main() {
235/// # const IGNORE_TOKENS: &'static str = stringify! {
236/// let span = /* ... */;
237/// # };
238/// # let span = Span::call_site();
239/// # let init = 0;
240///
241/// // On one line, use parentheses.
242/// let tokens = quote_spanned!(span=> Box::into_raw(Box::new(#init)));
243///
244/// // On multiple lines, place the span at the top and use braces.
245/// let tokens = quote_spanned! {span=>
246/// Box::into_raw(Box::new(#init))
247/// };
248/// # }
249/// ```
250///
251/// # Hygiene
252///
253/// Any interpolated tokens preserve the `Span` information provided by their
254/// `ToTokens` implementation. Tokens that originate within the `quote_spanned!`
255/// invocation are spanned with the given span argument.
256///
257/// # Example
258///
259/// The following procedural macro code uses `quote_spanned!` to assert that a
260/// particular Rust type implements the [`Sync`] trait so that references can be
261/// safely shared between threads.
262///
263/// [`Sync`]: https://doc.rust-lang.org/std/marker/trait.Sync.html
264///
265/// ```
266/// # #[macro_use]
267/// # extern crate quote;
268/// # extern crate proc_macro2;
269/// #
270/// # use quote::{Tokens, ToTokens};
271/// # use proc_macro2::Span;
272/// #
273/// # struct Type;
274/// #
275/// # impl Type {
276/// # fn span(&self) -> Span {
277/// # Span::call_site()
278/// # }
279/// # }
280/// #
281/// # impl ToTokens for Type {
282/// # fn to_tokens(&self, _tokens: &mut Tokens) {}
283/// # }
284/// #
285/// # fn main() {
286/// # let ty = Type;
287/// # let def_site = Span::def_site();
288/// #
289/// let ty_span = ty.span().resolved_at(def_site);
290/// let assert_sync = quote_spanned! {ty_span=>
291/// struct _AssertSync where #ty: Sync;
292/// };
293/// # }
294/// ```
295///
296/// If the assertion fails, the user will see an error like the following. The
297/// input span of their type is hightlighted in the error.
298///
299/// ```text
300/// error[E0277]: the trait bound `*const (): std::marker::Sync` is not satisfied
301/// --> src/main.rs:10:21
302/// |
303/// 10 | static ref PTR: *const () = &();
304/// | ^^^^^^^^^ `*const ()` cannot be shared between threads safely
305/// ```
306///
307/// In this example it is important for the where-clause to be spanned with the
308/// line/column information of the user's input type so that error messages are
309/// placed appropriately by the compiler. But it is also incredibly important
310/// that `Sync` resolves at the macro definition site and not the macro call
311/// site. If we resolve `Sync` at the same span that the user's type is going to
312/// be resolved, then they could bypass our check by defining their own trait
313/// named `Sync` that is implemented for their type.
314#[macro_export]
315macro_rules! quote_spanned {
316 ($span:expr=> $($tt:tt)*) => {
317 {
318 let mut _s = $crate::Tokens::new();
319 let _span = $span;
320 quote_each_token!(_s _span $($tt)*);
321 _s
322 }
323 };
324}
325
326// Extract the names of all #metavariables and pass them to the $finish macro.
327//
328// in: pounded_var_names!(then () a #b c #( #d )* #e)
329// out: then!(() b d e)
330#[macro_export]
331#[doc(hidden)]
332macro_rules! pounded_var_names {
333 ($finish:ident ($($found:ident)*) # ( $($inner:tt)* ) $($rest:tt)*) => {
334 pounded_var_names!($finish ($($found)*) $($inner)* $($rest)*)
335 };
336
337 ($finish:ident ($($found:ident)*) # [ $($inner:tt)* ] $($rest:tt)*) => {
338 pounded_var_names!($finish ($($found)*) $($inner)* $($rest)*)
339 };
340
341 ($finish:ident ($($found:ident)*) # { $($inner:tt)* } $($rest:tt)*) => {
342 pounded_var_names!($finish ($($found)*) $($inner)* $($rest)*)
343 };
344
345 ($finish:ident ($($found:ident)*) # $first:ident $($rest:tt)*) => {
346 pounded_var_names!($finish ($($found)* $first) $($rest)*)
347 };
348
349 ($finish:ident ($($found:ident)*) ( $($inner:tt)* ) $($rest:tt)*) => {
350 pounded_var_names!($finish ($($found)*) $($inner)* $($rest)*)
351 };
352
353 ($finish:ident ($($found:ident)*) [ $($inner:tt)* ] $($rest:tt)*) => {
354 pounded_var_names!($finish ($($found)*) $($inner)* $($rest)*)
355 };
356
357 ($finish:ident ($($found:ident)*) { $($inner:tt)* } $($rest:tt)*) => {
358 pounded_var_names!($finish ($($found)*) $($inner)* $($rest)*)
359 };
360
361 ($finish:ident ($($found:ident)*) $ignore:tt $($rest:tt)*) => {
362 pounded_var_names!($finish ($($found)*) $($rest)*)
363 };
364
365 ($finish:ident ($($found:ident)*)) => {
366 $finish!(() $($found)*)
367 };
368}
369
370// in: nested_tuples_pat!(() a b c d e)
371// out: ((((a b) c) d) e)
372//
373// in: nested_tuples_pat!(() a)
374// out: a
375#[macro_export]
376#[doc(hidden)]
377macro_rules! nested_tuples_pat {
378 (()) => {
379 &()
380 };
381
382 (() $first:ident $($rest:ident)*) => {
383 nested_tuples_pat!(($first) $($rest)*)
384 };
385
386 (($pat:pat) $first:ident $($rest:ident)*) => {
387 nested_tuples_pat!((($pat, $first)) $($rest)*)
388 };
389
390 (($done:pat)) => {
391 $done
392 };
393}
394
395// in: multi_zip_expr!(() a b c d e)
396// out: a.into_iter().zip(b).zip(c).zip(d).zip(e)
397//
398// in: multi_zip_iter!(() a)
399// out: a
400#[macro_export]
401#[doc(hidden)]
402macro_rules! multi_zip_expr {
403 (()) => {
404 &[]
405 };
406
407 (() $single:ident) => {
408 $single
409 };
410
411 (() $first:ident $($rest:ident)*) => {
412 multi_zip_expr!(($first.into_iter()) $($rest)*)
413 };
414
415 (($zips:expr) $first:ident $($rest:ident)*) => {
416 multi_zip_expr!(($zips.zip($first)) $($rest)*)
417 };
418
419 (($done:expr)) => {
420 $done
421 };
422}
423
424#[macro_export]
425#[doc(hidden)]
426macro_rules! quote_each_token {
427 ($tokens:ident $span:ident) => {};
428
429 ($tokens:ident $span:ident # ! $($rest:tt)*) => {
430 quote_each_token!($tokens $span #);
431 quote_each_token!($tokens $span !);
432 quote_each_token!($tokens $span $($rest)*);
433 };
434
435 ($tokens:ident $span:ident # ( $($inner:tt)* ) * $($rest:tt)*) => {
436 for pounded_var_names!(nested_tuples_pat () $($inner)*)
437 in pounded_var_names!(multi_zip_expr () $($inner)*) {
438 quote_each_token!($tokens $span $($inner)*);
439 }
440 quote_each_token!($tokens $span $($rest)*);
441 };
442
443 ($tokens:ident $span:ident # ( $($inner:tt)* ) $sep:tt * $($rest:tt)*) => {
444 for (_i, pounded_var_names!(nested_tuples_pat () $($inner)*))
445 in pounded_var_names!(multi_zip_expr () $($inner)*).into_iter().enumerate() {
446 if _i > 0 {
447 quote_each_token!($tokens $span $sep);
448 }
449 quote_each_token!($tokens $span $($inner)*);
450 }
451 quote_each_token!($tokens $span $($rest)*);
452 };
453
454 ($tokens:ident $span:ident # [ $($inner:tt)* ] $($rest:tt)*) => {
455 quote_each_token!($tokens $span #);
456 $crate::__rt::append_kind(&mut $tokens,
457 $span,
458 $crate::__rt::TokenNode::Group(
459 $crate::__rt::Delimiter::Bracket,
460 quote_spanned!($span=> $($inner)*).into()
461 ));
462 quote_each_token!($tokens $span $($rest)*);
463 };
464
465 ($tokens:ident $span:ident # $first:ident $($rest:tt)*) => {
466 $crate::ToTokens::to_tokens(&$first, &mut $tokens);
467 quote_each_token!($tokens $span $($rest)*);
468 };
469
470 ($tokens:ident $span:ident ( $($first:tt)* ) $($rest:tt)*) => {
471 $crate::__rt::append_kind(&mut $tokens,
472 $span,
473 $crate::__rt::TokenNode::Group(
474 $crate::__rt::Delimiter::Parenthesis,
475 quote_spanned!($span=> $($first)*).into()
476 ));
477 quote_each_token!($tokens $span $($rest)*);
478 };
479
480 ($tokens:ident $span:ident [ $($first:tt)* ] $($rest:tt)*) => {
481 $crate::__rt::append_kind(&mut $tokens,
482 $span,
483 $crate::__rt::TokenNode::Group(
484 $crate::__rt::Delimiter::Bracket,
485 quote_spanned!($span=> $($first)*).into()
486 ));
487 quote_each_token!($tokens $span $($rest)*);
488 };
489
490 ($tokens:ident $span:ident { $($first:tt)* } $($rest:tt)*) => {
491 $crate::__rt::append_kind(&mut $tokens,
492 $span,
493 $crate::__rt::TokenNode::Group(
494 $crate::__rt::Delimiter::Brace,
495 quote_spanned!($span=> $($first)*).into()
496 ));
497 quote_each_token!($tokens $span $($rest)*);
498 };
499
500 ($tokens:ident $span:ident $first:tt $($rest:tt)*) => {
501 // TODO: this seems slow... special case some `:tt` arguments?
502 $crate::__rt::parse(&mut $tokens, $span, stringify!($first));
503 quote_each_token!($tokens $span $($rest)*);
504 };
505}