Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"cannot find macro" error in the macro's own doc test

Tags:

rust

I am trying to add documentation tests to a Rust macro that I'm exporting. Something like this:

/// Usage:
///
/// ```
/// let x = addone!(100);
/// ```
#[macro_export]
macro_rules! addone {
    ($x:expr) => ($x + 1)
}

If I run cargo test on this, I get

failures:

---- src/lib.rs - addone (line 3) stdout ----
    error: cannot find macro `addone!` in this scope
 --> src/lib.rs:2:9
  |
2 | let x = addone!(100);
  |         ^^^^^^

I can't think of a legal way of adding macro_use inside the doc test, so no luck there.

The macros in Rust's standard library follow the same format as the code above, so I was expecting it to work.

like image 888
Gustav Larsson Avatar asked Jul 27 '15 02:07

Gustav Larsson


1 Answers

Doc tests automatically wrap the code block in extern crate foo; fn main() { … } if they don’t find these elements in the code, but to get an exported macro you need the #[macro_use] attribute on the extern crate foo;.

Thus, you should write this:

/// Usage:
///
/// ```
/// # #[macro_use] extern crate foo; fn main() {
/// let x = addone!(100);
/// # }
/// ```
#[macro_export]
macro_rules! addone {
    ($x:expr) => ($x + 1)
}

(The lines prefixed with get hidden in the output, but included, sans the marker, in the code that gets compiled for the doc test.)

This is covered in The Rust Programming Language, first edition.

As for std, there is an implied #[macro_use] extern crate std; in all crates that lack the #![no_std] crate attribute, so its macros immediately work.

like image 53
Chris Morgan Avatar answered Oct 09 '22 12:10

Chris Morgan