1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
extern crate proc_macro; use proc_macro::TokenStream; use proc_macro::TokenTree; use proc_macro_hack::proc_macro_hack; use std::str::FromStr; #[proc_macro_hack] pub fn error_message(input: TokenStream) -> TokenStream { let mut tokens = input.into_iter().peekable(); let mut description; let mut source; if let Some(TokenTree::Literal(t)) = tokens.next() { description = format!("{}", t); } else { panic!("first param of error! should be a string") } if description.chars().last().unwrap() != '"' { panic!("first param of error! should be a string") } description.pop(); println!("{}", file!()); if let None = tokens.peek() { return TokenStream::from_str(&format!( "Err(no_error::NoError::Message(({}\\0\",\"\\0\")))", description )) .unwrap(); } if let Some(TokenTree::Punct(p)) = tokens.next() { if p.as_char() != ',' { panic!("expected , in error!") } } if let Some(TokenTree::Literal(t)) = tokens.next() { source = format!("{}", t); } else { panic!("second param of error! should be a string") } if source.chars().last().unwrap() != '"' { panic!("second param of error! should be a string") } source.pop(); return TokenStream::from_str(&format!( "Err(no_error::NoError::Message(({}\\0\",{}\\0\")))", description, source )) .unwrap(); }