首页 文章

如何查看导致编译错误的扩展宏代码?

提问于
浏览
35

我有一个涉及宏的编译错误:

<mdo macros>:6:19: 6:50 error: cannot move out of captured outer variable in an `FnMut` closure
<mdo macros>:6 bind ( $ e , move | $ p | mdo ! { $ ( $ t ) * } ) ) ; (
                                 ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
<mdo macros>:1:1: 14:36 note: in expansion of mdo!
<mdo macros>:6:27: 6:50 note: expansion site
<mdo macros>:1:1: 14:36 note: in expansion of mdo!
<mdo macros>:6:27: 6:50 note: expansion site
<mdo macros>:1:1: 14:36 note: in expansion of mdo!
src/parser.rs:30:42: 37:11 note: expansion site
error: aborting due to previous error

不幸的是,宏是递归的,因此很难弄清楚编译器在抱怨什么,而且看起来线号是针对扩展宏而不是我的代码 .

如何查看扩展的宏?是否有一面旗帜可以传递给rustc(甚至更好的货物)来解决这个问题?

(这个宏来自rust-mdo,虽然我认为不重要 . )

2 回答

  • 34

    是的,您可以将特殊标志传递给 rustc ,名为 --pretty=expanded

    % cat test.rs
    fn main() {
        println!("Hello world");
    }
    % rustc -Z unstable-options --pretty=expanded test.rs
    #![feature(no_std)]
    #![no_std]
    #[prelude_import]
    use std::prelude::v1::*;
    #[macro_use]
    extern crate "std" as std;
    fn main() {
        ::std::old_io::stdio::println_args(::std::fmt::Arguments::new_v1({
                                                                             static __STATIC_FMTSTR:
                                                                                    &'static [&'static str]
                                                                                    =
                                                                                 &["Hello world"];
                                                                             __STATIC_FMTSTR
                                                                         },
                                                                         &match ()
                                                                              {
                                                                              ()
                                                                              =>
                                                                              [],
                                                                          }));
    }
    

    但是,您需要先通过 -Z unstable-options 来允许它 .

    从Rust 1.1开始,您可以将这些参数传递给Cargo,如下所示:

    cargo rustc -- -Z unstable-options --pretty=expanded
    
  • 41

    cargo rustc -- -Zunstable-options --pretty=expanded 的更简洁的替代是cargo-expand箱子 . 它提供了一个Cargo子命令 cargo expand ,用于打印宏扩展的结果 . 它还通过rustfmt传递扩展代码,这通常导致代码比rustc的默认输出更易读 .

    通过运行 cargo install cargo-expand 进行安装 .

相关问题