[−][src]Macro genco::quote
quote!() { /* proc-macro */ }
Quotes the specified expression as a stream of tokens for use with genco.
Mechanisms
- Elements are interpolated using
#
, so to include the variabletest
, you could write#test
. Returned elements must implement FormatTokens. #
can be escaped by repeating it twice in case it's needed in the target language. So##
would produce a single#
.- Inline statements can be evaluated using
#(<stmt>)
. They can also be suffixed with<stmt>,*
to treat the statement as an iterator, and add the specified separator (,
here) between each element.- Example:
#("test".quoted())
can be used to quote a string.
- Example:
- The register functionality of Tokens is available by prefixing an
expression with
#@
as#@<stmt>
.- Example:
#@only_imports
will register the variableonly_imports
.
- Example:
- Expressions can be repeated. It is then expected that they evaluate to an
iterator. Expressions are repeated by adding the
<token>*
suffix. Thewill then be used as a separator between each element, and a spacing will be added after it. - Example:
#var,*
will treatvar
as an iterator and add,
and a spacing between each element. - Example with explicit iterator:
#(vec![1, 2, 3].into_iter()),*
.
- Example:
- Scoped expressions using
#{<binding> => { <block> }}
, giving mutable and scoped access to the token stream being built. This can be used with the [quote_in!] macro for improved flow control. The<binding>
is provided through a mutable borrow. If the<binding>
already is mutably borrowed you probably want to perform a reborrow. This can be done with*<binding>
. See the borrowing seciton in [quote_in!] for more details.- Example:
quote!(#{tokens => /* */})
. - Example with reborrowing:
quote_in!(&mut tokens => #{*tokens => { /* */ }})
.
- Example:
Examples
use genco::prelude::*; let tokens: rust::Tokens = quote!(#[test]); assert_eq!("#[test]", tokens.to_string().unwrap()); let tokens: rust::Tokens = quote!(#{t => { quote_in!(t => #[test]) }}); assert_eq!("#[test]", tokens.to_string().unwrap());
Bigger example:
use genco::prelude::*; // Import the LittleEndian item, without referencing it through the last // module component it is part of. let little_endian = rust::imported("byteorder", "LittleEndian").qualified(); let big_endian = rust::imported("byteorder", "BigEndian"); // This is a trait, so only import it into the scope (unless we intent to // implement it). let write_bytes_ext = rust::imported("byteorder", "WriteBytesExt").alias("_"); let tokens: rust::Tokens = quote! { #@write_bytes_ext let mut wtr = vec![]; wtr.write_u16::<#little_endian>(517).unwrap(); wtr.write_u16::<#big_endian>(768).unwrap(); assert_eq!(wtr, vec![#(0..10),*]); }; println!("{}", tokens.to_file_string().unwrap());