Function syn::parse

source ·
pub fn parse<T: Parse>(tokens: TokenStream) -> Result<T>
Expand description

Parse tokens of source code into the chosen syntax tree node.

This is preferred over parsing a string because tokens are able to preserve information about where in the user’s code they were originally written (the “span” of the token), possibly allowing the compiler to produce better error messages.

This function parses a proc_macro::TokenStream which is the type used for interop with the compiler in a procedural macro. To parse a proc_macro2::TokenStream, use syn::parse2 instead.

Examples

use proc_macro::TokenStream;
use quote::quote;
use syn::DeriveInput;

#[proc_macro_derive(MyMacro)]
pub fn my_macro(input: TokenStream) -> TokenStream {
    // Parse the tokens into a syntax tree
    let ast: DeriveInput = syn::parse(input).unwrap();

    // Build the output, possibly using quasi-quotation
    let expanded = quote! {
        /* ... */
    };

    // Convert into a token stream and return it
    expanded.into()
}