[英]How can I create multiple items in a Rust procedural macro?
我正在尝试创建一个宏,当像这样使用时:
foo!()
扩展为两个项目,静态项目和功能。 像这样的东西:
static x: uint = 5;
fn bar() -> uint { x + 1 }
我已经向我指出, MacResult
的make_items
方法支持这一点,所以我只需要创建一个正确实现它的类型。 我这样做了:
struct MacItems {
items: Vec<::std::gc::Gc<Item>>,
}
impl MacResult for MacItems {
fn make_def(&self) -> Option<::syntax::ext::base::MacroDef> { None }
fn make_expr(&self) -> Option<::std::gc::Gc<ast::Expr>> { None }
fn make_pat(&self) -> Option<::std::gc::Gc<ast::Pat>> { None }
fn make_stmt(&self) -> Option<::std::gc::Gc<ast::Stmt>> { None }
fn make_items(&self) -> Option<::syntax::util::small_vector::SmallVector<::std::gc::Gc<Item>>> {
Some(::syntax::util::small_vector::SmallVector::many(self.items.clone()))
}
}
我试图使用quote_item!
宏,但这个宏显然移动了ExtCtxt
,使得它不可能连续两次使用它。 这是我的代码:
#[plugin_registrar]
pub fn plugin_registrar(reg: &mut Registry) {
reg.register_macro("foo", expand);
}
fn expand(cx: &mut ExtCtxt, sp: codemap::Span, _: &[ast::TokenTree]) -> Box<MacResult> {
let mut v = vec!();
v.push( quote_item!(cx, static x: uint = 5;).unwrap() );
v.push( quote_item!(cx, fn bar() -> uint { x + 1 }).unwrap() );
box MacItems { items: v } as Box<MacResult>
}
这是错误:
test.rs:37:13: 37:57 error: use of moved value: `cx`
test.rs:37 v.push( quote_item!(cx, fn bar() -> uint { x + 1 }).unwrap() );
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
note: in expansion of quote_item!
test.rs:37:13: 37:57 note: expansion site
test.rs:36:13: 36:50 note: `cx` moved here because it has type `&mut syntax::ext::base::ExtCtxt<'_>`, which is moved by default (use `ref` to override)
test.rs:36 v.push( quote_item!(cx, static x: uint = 5;).unwrap() );
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
note: in expansion of quote_item!
test.rs:36:13: 36:50 note: expansion site
error: aborting due to previous error
我怎样才能做到这一点? 我试图使用AstBuilder::item_static
来创建静态项目,但我无法确定Ty_
哪个变体对应于uint
。 (这只是一个玩具示例,我真正的静态声明是&'static str
,所以我需要构建该项目)。
我这样做完全错了吗? 怎么能实现这一目标?
您需要手动将cx
重新借用到临时&mut ExtCtxt
。 编译器通常可以自动插入reborrows,但quote_*
宏不会扩展为适合此的东西。
那是,
quote_item!(&mut *cx, ...)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.