#[macro_export] stops macro's documentation tests from working

b064169
Opened by Binero at 2024-09-03 08:53:07

Adding #[macro_export] to a macro stops it from working in documentation tests. Here's a few examples:

/// Test macro
///
/// #Examples
/// ```
/// test_macro!(TestStructure);
/// ```
#[macro_export]
macro_rules! test_macro {
    ($expression:ident) => (struct $expression);
}
#[macro_export]
/// Test macro
///
/// #Examples
/// ```
/// test_macro!(TestStructure);
/// ```
macro_rules! test_macro {
    ($expression:ident) => (struct $expression);
}

They both will yield output similar to this (using cargo):

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured

   Doc-tests macro_doc

running 1 test
test test_macro!_0 ... FAILED

failures:

---- test_macro!_0 stdout ----
    <anon>:2:5: 2:15 error: macro undefined: 'test_macro!'
<anon>:2     test_macro!(TestStructure);
             ^~~~~~~~~~
error: aborting due to previous error


failures:
    test_macro!_0

test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured

thread '<unnamed>' panicked at 'Some tests failed', ../src/libtest/lib.rs:252

Removing the export makes it work fine:

/// Test macro
///
/// #Examples
/// ```
/// test_macro!(TestStructure);
/// ```
macro_rules! test_macro {
    ($expression:ident) => (struct $expression);
}
  1. The bug here is that rustdoc doesn't inject extern crate foo with the #[macro_use] attribute, and macros that aren't exported don't have their docs tested.

    Alex Crichton at 2015-10-25 17:34:36

  2. Triage: not entirely sure this is a bug, though it is a footgun for sure.

    Steve Klabnik at 2019-12-25 17:19:08