"在此范围内找不到值'a`"在Rust宏

时间:2018-04-12 19:56:00

标签: macros rust

我使用proc-macro-hack创建了用于打印的宏 然后发生了这个错误,虽然我已经定义了a

以下是代码。

在decl crate上,

proc_macro_expr_decl! {
    /// Function for printing to the standard output.
    ///
    /// First argument can be literal or not literal.
    gprint! => gprint_impl
}

关于impl crate,

use syn::{Expr, ExprTuple, parse_str};
use quote::ToTokens;
fn _print_impl(input: &str, print_name: &str) -> String {
    let mut input_with_parens = String::with_capacity(input.len() + 2);
    input_with_parens.push('(');
    input_with_parens.push_str(input);
    input_with_parens.push(')');
    let tuple = parse_str::<ExprTuple>(&input_with_parens)
        .unwrap_or_else(|_| panic!("expected arguments is expressions separated by comma, found {}", input))
    let mut arg_iter = tuple.elems.iter();
    let first = arg_iter.next();
    if first.is_none() {
        return "()".to_string();
    }
    let first = first.unwrap();
    let mut s = String::new();
    if let &Expr::Lit(ref lit) = first {
        s.push_str(print_name);
        s.push('(');
        s.push_str(&lit.into_tokens().to_string());
    } else {
        s.push_str(print_name);
        s.push_str("(\"{}\", ");
        s.push_str(&first.into_tokens().to_string());
    }
    for arg in arg_iter {
        s.push_str(", ");
        s.push_str(&arg.into_tokens().to_string());
    }
    s.push(')');
    s
}

proc_macro_expr_impl! {
    pub fn gprint_impl(input: &str) -> String {
        _print_impl(input, "print!")
    }
}

尝试使用此宏,

fn main() {
    let a = 0;
    gprint!(a);
}
发生

错误:

error[E0425]: cannot find value `a` in this scope

为什么?

0 个答案:

没有答案