Crate quote
This crate provides the [quote!] macro for turning Rust syntax tree data
structures into tokens of source code.
Procedural macros in Rust receive a stream of tokens as input, execute arbitrary Rust code to determine how to manipulate those tokens, and produce a stream of tokens to hand back to the compiler to compile into the caller's crate. Quasi-quoting is a solution to one piece of that — producing tokens to return to the compiler.
The idea of quasi-quoting is that we write code that we treat as data.
Within the quote! macro, we can write what looks like code to our text
editor or IDE. We get all the benefits of the editor's brace matching,
syntax highlighting, indentation, and maybe autocompletion. But rather than
compiling that as code into the current crate, we can treat it as data, pass
it around, mutate it, and eventually hand it back to the compiler as tokens
to compile into the macro caller's crate.
This crate is motivated by the procedural macro use case, but is a general-purpose Rust quasi-quoting library and is not specific to procedural macros.
[dependencies]
quote = "1.0"
Example
The following quasi-quoted block of code is something you might find in a
procedural macro having to do with data structure serialization. The #var
syntax performs interpolation of runtime variables into the quoted tokens.
Check out the documentation of the [quote!] macro for more detail about
the syntax. See also the [quote_spanned!] macro which is important for
implementing hygienic procedural macros.
# use quote;
#
# let generics = "";
# let where_clause = "";
# let field_ty = "";
# let item_ty = "";
# let path = "";
# let value = "";
#
let tokens = quote! ;
Non-macro code generators
When using quote in a build.rs or main.rs and writing the output out to a
file, consider having the code generator pass the tokens through
prettyplease before writing. This way if an error occurs in the generated
code it is convenient for a human to read and debug.
Traits
-
IdentFragment
Specialized formatting trait used by
format_ident!. -
ToTokens
Types that can be interpolated inside a
quote!invocation. - TokenStreamExt TokenStream extension trait with methods for appending tokens.
Macros
-
format_ident
Formatting macro for constructing
Idents. - quote The whole point.
-
quote_spanned
Same as
quote!, but applies a given span to all tokens originating within the macro invocation.