|
|
<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta name="generator" content="rustdoc"><meta name="description" content="API documentation for the Rust `quote` macro in crate `quote`."><meta name="keywords" content="rust, rustlang, rust-lang, quote"><title>quote::quote - Rust</title><link rel="stylesheet" type="text/css" href="../normalize.css"><link rel="stylesheet" type="text/css" href="../rustdoc.css" id="mainThemeStyle"><link rel="stylesheet" type="text/css" href="../dark.css"><link rel="stylesheet" type="text/css" href="../light.css" id="themeStyle"><script src="../storage.js"></script><noscript><link rel="stylesheet" href="../noscript.css"></noscript><link rel="shortcut icon" href="../favicon.ico"><style type="text/css">#crate-search{background-image:url("../down-arrow.svg");}</style></head><body class="rustdoc macro"><!--[if lte IE 8]><div class="warning">This old browser is unsupported and will most likely display funky things.</div><![endif]--><nav class="sidebar"><div class="sidebar-menu">☰</div><a href='../quote/index.html'><div class='logo-container'><img src='../rust-logo.png' alt='logo'></div></a><div class="sidebar-elems"><p class='location'><a href='index.html'>quote</a></p><script>window.sidebarCurrent = {name: 'quote', ty: 'macro', relpath: ''};</script><script defer src="sidebar-items.js"></script></div></nav><div class="theme-picker"><button id="theme-picker" aria-label="Pick another theme!"><img src="../brush.svg" width="18" alt="Pick another theme!"></button><div id="theme-choices"></div></div><script src="../theme.js"></script><nav class="sub"><form class="search-form js-only"><div class="search-container"><div><select id="crate-search"><option value="All crates">All crates</option></select><input class="search-input" name="search" autocomplete="off" spellcheck="false" placeholder="Click or press ‘S’ to search, ‘?’ for more options…" type="search"></div><a id="settings-menu" href="../settings.html"><img src="../wheel.svg" width="18" alt="Change settings"></a></div></form></nav><section id="main" class="content"><h1 class='fqn'><span class='out-of-band'><span id='render-detail'><a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs">[<span class='inner'>−</span>]</a></span><a class='srclink' href='../src/quote/lib.rs.html#335-339' title='goto source code'>[src]</a></span><span class='in-band'>Macro <a href='index.html'>quote</a>::<wbr><a class="macro" href=''>quote</a></span></h1><div class="docblock type-decl hidden-by-usual-hider"><div class="example-wrap"><pre class="rust macro">
|
|
|
<span class="macro">macro_rules</span><span class="macro">!</span> <span class="ident">quote</span> {
|
|
|
($(<span class="macro-nonterminal">$</span><span class="macro-nonterminal">tt</span>:<span class="ident">tt</span>)<span class="kw-2">*</span>) <span class="op">=</span><span class="op">></span> { ... };
|
|
|
}</pre></div>
|
|
|
</div><div class='docblock'><p>The whole point.</p>
|
|
|
<p>Performs variable interpolation against the input and produces it as
|
|
|
<a href="https://docs.rs/proc-macro2/0.4/proc_macro2/struct.TokenStream.html"><code>TokenStream</code></a>. For returning tokens to the compiler in a procedural macro, use
|
|
|
<code>into()</code> to build a <code>TokenStream</code>.</p>
|
|
|
<h1 id="interpolation" class="section-header"><a href="#interpolation">Interpolation</a></h1>
|
|
|
<p>Variable interpolation is done with <code>#var</code> (similar to <code>$var</code> in
|
|
|
<code>macro_rules!</code> macros). This grabs the <code>var</code> variable that is currently in
|
|
|
scope and inserts it in that location in the output tokens. Any type
|
|
|
implementing the <a href="trait.ToTokens.html"><code>ToTokens</code></a> trait can be interpolated. This includes most
|
|
|
Rust primitive types as well as most of the syntax tree types from the <a href="https://github.com/dtolnay/syn">Syn</a>
|
|
|
crate.</p>
|
|
|
<p>Repetition is done using <code>#(...)*</code> or <code>#(...),*</code> again similar to
|
|
|
<code>macro_rules!</code>. This iterates through the elements of any variable
|
|
|
interpolated within the repetition and inserts a copy of the repetition body
|
|
|
for each one. The variables in an interpolation may be anything that
|
|
|
implements <code>IntoIterator</code>, including <code>Vec</code> or a pre-existing iterator.</p>
|
|
|
<ul>
|
|
|
<li><code>#(#var)*</code> — no separators</li>
|
|
|
<li><code>#(#var),*</code> — the character before the asterisk is used as a separator</li>
|
|
|
<li><code>#( struct #var; )*</code> — the repetition can contain other tokens</li>
|
|
|
<li><code>#( #k => println!("{}", #v), )*</code> — even multiple interpolations</li>
|
|
|
</ul>
|
|
|
<p>There are two limitations around interpolations in a repetition:</p>
|
|
|
<ul>
|
|
|
<li>
|
|
|
<p>Every interpolation inside of a repetition must be a distinct variable.
|
|
|
That is, <code>#(#a #a)*</code> is not allowed. Work around this by collecting <code>a</code>
|
|
|
into a vector and taking references <code>a1 = &a</code> and <code>a2 = &a</code> which you use
|
|
|
inside the repetition: <code>#(#a1 #a2)*</code>. Where possible, use meaningful names
|
|
|
that indicate the distinct role of each copy.</p>
|
|
|
</li>
|
|
|
<li>
|
|
|
<p>Every interpolation inside of a repetition must be iterable. If we have
|
|
|
<code>vec</code> which is a vector and <code>ident</code> which is a single identifier,
|
|
|
<code>#(#ident #vec)*</code> is not allowed. Work around this by using
|
|
|
<code>std::iter::repeat(ident)</code> to produce an iterable that can be used from
|
|
|
within the repetition.</p>
|
|
|
</li>
|
|
|
</ul>
|
|
|
<h1 id="hygiene" class="section-header"><a href="#hygiene">Hygiene</a></h1>
|
|
|
<p>Any interpolated tokens preserve the <code>Span</code> information provided by their
|
|
|
<code>ToTokens</code> implementation. Tokens that originate within the <code>quote!</code>
|
|
|
invocation are spanned with <a href="https://docs.rs/proc-macro2/0.4/proc_macro2/struct.Span.html#method.call_site"><code>Span::call_site()</code></a>.</p>
|
|
|
<p>A different span can be provided through the <a href="macro.quote_spanned.html"><code>quote_spanned!</code></a> macro.</p>
|
|
|
<h1 id="return-type" class="section-header"><a href="#return-type">Return type</a></h1>
|
|
|
<p>The macro evaluates to an expression of type <code>proc_macro2::TokenStream</code>.
|
|
|
Meanwhile Rust procedural macros are expected to return the type
|
|
|
<code>proc_macro::TokenStream</code>.</p>
|
|
|
<p>The difference between the two types is that <code>proc_macro</code> types are entirely
|
|
|
specific to procedural macros and cannot ever exist in code outside of a
|
|
|
procedural macro, while <code>proc_macro2</code> types may exist anywhere including
|
|
|
tests and non-macro code like main.rs and build.rs. This is why even the
|
|
|
procedural macro ecosystem is largely built around <code>proc_macro2</code>, because
|
|
|
that ensures the libraries are unit testable and accessible in non-macro
|
|
|
contexts.</p>
|
|
|
<p>There is a <a href="https://doc.rust-lang.org/std/convert/trait.From.html"><code>From</code></a>-conversion in both directions so returning the output of
|
|
|
<code>quote!</code> from a procedural macro usually looks like <code>tokens.into()</code> or
|
|
|
<code>proc_macro::TokenStream::from(tokens)</code>.</p>
|
|
|
<h1 id="examples" class="section-header"><a href="#examples">Examples</a></h1><h2 id="procedural-macro" class="section-header"><a href="#procedural-macro">Procedural macro</a></h2>
|
|
|
<p>The structure of a basic procedural macro is as follows. Refer to the <a href="https://github.com/dtolnay/syn">Syn</a>
|
|
|
crate for further useful guidance on using <code>quote!</code> as part of a procedural
|
|
|
macro.</p>
|
|
|
<pre><code class="language-edition2018"># #[cfg(any())]
|
|
|
extern crate proc_macro;
|
|
|
# use proc_macro2 as proc_macro;
|
|
|
|
|
|
use proc_macro::TokenStream;
|
|
|
use quote::quote;
|
|
|
|
|
|
# const IGNORE_TOKENS: &'static str = stringify! {
|
|
|
#[proc_macro_derive(HeapSize)]
|
|
|
# };
|
|
|
pub fn derive_heap_size(input: TokenStream) -> TokenStream {
|
|
|
// Parse the input and figure out what implementation to generate...
|
|
|
# const IGNORE_TOKENS: &'static str = stringify! {
|
|
|
let name = /* ... */;
|
|
|
let expr = /* ... */;
|
|
|
# };
|
|
|
#
|
|
|
# let name = 0;
|
|
|
# let expr = 0;
|
|
|
|
|
|
let expanded = quote! {
|
|
|
// The generated impl.
|
|
|
impl heapsize::HeapSize for #name {
|
|
|
fn heap_size_of_children(&self) -> usize {
|
|
|
#expr
|
|
|
}
|
|
|
}
|
|
|
};
|
|
|
|
|
|
// Hand the output tokens back to the compiler.
|
|
|
TokenStream::from(expanded)
|
|
|
}
|
|
|
</code></pre>
|
|
|
<h2 id="combining-quoted-fragments" class="section-header"><a href="#combining-quoted-fragments">Combining quoted fragments</a></h2>
|
|
|
<p>Usually you don't end up constructing an entire final <code>TokenStream</code> in one
|
|
|
piece. Different parts may come from different helper functions. The tokens
|
|
|
produced by <code>quote!</code> themselves implement <code>ToTokens</code> and so can be
|
|
|
interpolated into later <code>quote!</code> invocations to build up a final result.</p>
|
|
|
<pre><code class="language-edition2018"># use quote::quote;
|
|
|
#
|
|
|
let type_definition = quote! {...};
|
|
|
let methods = quote! {...};
|
|
|
|
|
|
let tokens = quote! {
|
|
|
#type_definition
|
|
|
#methods
|
|
|
};
|
|
|
</code></pre>
|
|
|
<h2 id="constructing-identifiers" class="section-header"><a href="#constructing-identifiers">Constructing identifiers</a></h2>
|
|
|
<p>Suppose we have an identifier <code>ident</code> which came from somewhere in a macro
|
|
|
input and we need to modify it in some way for the macro output. Let's
|
|
|
consider prepending the identifier with an underscore.</p>
|
|
|
<p>Simply interpolating the identifier next to an underscore will not have the
|
|
|
behavior of concatenating them. The underscore and the identifier will
|
|
|
continue to be two separate tokens as if you had written <code>_ x</code>.</p>
|
|
|
<pre><code class="language-edition2018"># use proc_macro2::{self as syn, Span};
|
|
|
# use quote::quote;
|
|
|
#
|
|
|
# let ident = syn::Ident::new("i", Span::call_site());
|
|
|
#
|
|
|
// incorrect
|
|
|
quote! {
|
|
|
let mut _#ident = 0;
|
|
|
}
|
|
|
# ;
|
|
|
</code></pre>
|
|
|
<p>The solution is to perform token-level manipulations using the APIs provided
|
|
|
by Syn and proc-macro2.</p>
|
|
|
<pre><code class="language-edition2018"># use proc_macro2::{self as syn, Span};
|
|
|
# use quote::quote;
|
|
|
#
|
|
|
# let ident = syn::Ident::new("i", Span::call_site());
|
|
|
#
|
|
|
let concatenated = format!("_{}", ident);
|
|
|
let varname = syn::Ident::new(&concatenated, ident.span());
|
|
|
quote! {
|
|
|
let mut #varname = 0;
|
|
|
}
|
|
|
# ;
|
|
|
</code></pre>
|
|
|
<h2 id="making-method-calls" class="section-header"><a href="#making-method-calls">Making method calls</a></h2>
|
|
|
<p>Let's say our macro requires some type specified in the macro input to have
|
|
|
a constructor called <code>new</code>. We have the type in a variable called
|
|
|
<code>field_type</code> of type <code>syn::Type</code> and want to invoke the constructor.</p>
|
|
|
<pre><code class="language-edition2018"># use quote::quote;
|
|
|
#
|
|
|
# let field_type = quote!(...);
|
|
|
#
|
|
|
// incorrect
|
|
|
quote! {
|
|
|
let value = #field_type::new();
|
|
|
}
|
|
|
# ;
|
|
|
</code></pre>
|
|
|
<p>This works only sometimes. If <code>field_type</code> is <code>String</code>, the expanded code
|
|
|
contains <code>String::new()</code> which is fine. But if <code>field_type</code> is something
|
|
|
like <code>Vec<i32></code> then the expanded code is <code>Vec<i32>::new()</code> which is invalid
|
|
|
syntax. Ordinarily in handwritten Rust we would write <code>Vec::<i32>::new()</code>
|
|
|
but for macros often the following is more convenient.</p>
|
|
|
<pre><code class="language-edition2018"># use quote::quote;
|
|
|
#
|
|
|
# let field_type = quote!(...);
|
|
|
#
|
|
|
quote! {
|
|
|
let value = <#field_type>::new();
|
|
|
}
|
|
|
# ;
|
|
|
</code></pre>
|
|
|
<p>This expands to <code><Vec<i32>>::new()</code> which behaves correctly.</p>
|
|
|
<p>A similar pattern is appropriate for trait methods.</p>
|
|
|
<pre><code class="language-edition2018"># use quote::quote;
|
|
|
#
|
|
|
# let field_type = quote!(...);
|
|
|
#
|
|
|
quote! {
|
|
|
let value = <#field_type as core::default::Default>::default();
|
|
|
}
|
|
|
# ;
|
|
|
</code></pre>
|
|
|
</div></section><section id="search" class="content hidden"></section><section class="footer"></section><aside id="help" class="hidden"><div><h1 class="hidden">Help</h1><div class="shortcuts"><h2>Keyboard Shortcuts</h2><dl><dt><kbd>?</kbd></dt><dd>Show this help dialog</dd><dt><kbd>S</kbd></dt><dd>Focus the search field</dd><dt><kbd>↑</kbd></dt><dd>Move up in search results</dd><dt><kbd>↓</kbd></dt><dd>Move down in search results</dd><dt><kbd>↹</kbd></dt><dd>Switch tab</dd><dt><kbd>⏎</kbd></dt><dd>Go to active search result</dd><dt><kbd>+</kbd></dt><dd>Expand all sections</dd><dt><kbd>-</kbd></dt><dd>Collapse all sections</dd></dl></div><div class="infos"><h2>Search Tricks</h2><p>Prefix searches with a type followed by a colon (e.g., <code>fn:</code>) to restrict the search to a given type.</p><p>Accepted types are: <code>fn</code>, <code>mod</code>, <code>struct</code>, <code>enum</code>, <code>trait</code>, <code>type</code>, <code>macro</code>, and <code>const</code>.</p><p>Search functions by type signature (e.g., <code>vec -> usize</code> or <code>* -> vec</code>)</p><p>Search multiple things at once by splitting your query with comma (e.g., <code>str,u8</code> or <code>String,struct:Vec,test</code>)</p></div></div></aside><script>window.rootPath = "../";window.currentCrate = "quote";</script><script src="../aliases.js"></script><script src="../main.js"></script><script defer src="../search-index.js"></script></body></html> |