I want to directly execute the content of any string from user input in runtime, just like the eval or Function in javascript:
fn main() { let args :Vec<String> = env::args().collect(); let input = &args[1]; // if input content is "aaa()", expect running: // aaa(); // if input content is "aaa::bbb::ccc()", expect running: // aaa::bbb::ccc(); // execute by macro_rules: run!(input); // or execute by proc_macro_attribute: #[run(input)] fn run_input(args :&String) {}; run_input(input); }
Now I can parse the string to ast in macro_rules
, proc_macro
, proc_macro_attribute
or proc_macro_hack
, like following:
// parse in macro_rules: #[macro_export] macro_rules! run { ($input :expr) => { let val = syn::parse_str::<syn::Expr>($input); if let syn::Result::Ok(ast) = val { // parse input ok // want to execute the TokenStream of ast at here } else { // parse input error }; } }
// parse in proc_macro_attribute: #[proc_macro_attribute] pub fn run( input :TokenStream, func :TokenStream, ) -> TokenStream { let output = quote! { fn run_input(args :&String) { let val = syn::parse_str::<syn::Expr>(args); if let syn::Result::Ok(ast) = val { // parse ok // want to execute the TokenStream of ast at here } else { // parse error }; } }; output.into() }
But I can't run any TokenStream of ast in runtime. So what should I do?