Macro syn::parse_macro_input
source · [−]macro_rules! parse_macro_input {
($tokenstream:ident as $ty:ty) => { ... };
($tokenstream:ident with $parser:path) => { ... };
($tokenstream:ident) => { ... };
}
Expand description
Parse the input TokenStream of a macro, triggering a compile error if the tokens fail to parse.
Refer to the parse
module documentation for more details about parsing
in Syn.
Intended usage
This macro must be called from a function that returns
proc_macro::TokenStream
. Usually this will be your proc macro entry point,
the function that has the #[proc_macro] / #[proc_macro_derive] /
#[proc_macro_attribute] attribute.
use proc_macro::TokenStream;
use syn::{parse_macro_input, Result};
use syn::parse::{Parse, ParseStream};
struct MyMacroInput {
/* ... */
}
impl Parse for MyMacroInput {
fn parse(input: ParseStream) -> Result<Self> {
/* ... */
}
}
#[proc_macro]
pub fn my_macro(tokens: TokenStream) -> TokenStream {
let input = parse_macro_input!(tokens as MyMacroInput);
/* ... */
}
Usage with Parser
This macro can also be used with the Parser
trait for types that have
multiple ways that they can be parsed.
impl MyMacroInput {
fn parse_alternate(input: ParseStream) -> Result<Self> {
/* ... */
}
}
#[proc_macro]
pub fn my_macro(tokens: TokenStream) -> TokenStream {
let input = parse_macro_input!(tokens with MyMacroInput::parse_alternate);
/* ... */
}
Expansion
parse_macro_input!($variable as $Type)
expands to something like:
match syn::parse::<$Type>($variable) {
Ok(syntax_tree) => syntax_tree,
Err(err) => return proc_macro::TokenStream::from(err.to_compile_error()),
}