[][src]Function syn::parse

pub fn parse<T: Parse>(tokens: TokenStream) -> Result<T>

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.

This function is available if Syn is built with both the "parsing" and "proc-macro" features.

Examples

extern crate proc_macro;

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

# const IGNORE_TOKENS: &str = stringify! {
#[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()
}