Skip to content

Commit 7eefbc8

Browse files
authored
Turn block into a closure in test macro (#27)
The `doc_test!` macro defines two local variables (`entries` and `doc`), which are then accessed from the provided `block`. However, this only compiled due to a bug in rustc: substituted metavariables cannot refer to names defined within the macro body. For example, the following ode does not compile: ```rust macro_rules! foo { ($block:expr) => { let mut bar = false; $block } } fn main() { foo!({bar = true}); } ``` In this case, the `doc_test!` macro was incorrectly allowed to compile due to the presence of the `#[tokio::test]` macro on the enclosing function. When the underlying compiler bug is fixed in rust-lang/rust#75800, this macro will stop compiling.
1 parent 18c58a1 commit 7eefbc8

File tree

1 file changed

+7
-6
lines changed

1 file changed

+7
-6
lines changed

src/tests.rs

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -56,15 +56,15 @@ impl DocFileLoader for TestLoader {
5656
}
5757

5858
macro_rules! doc_test {
59-
( $name:ident, $source:expr; $block:block ) => {
59+
( $name:ident, $source:expr; $block:expr ) => {
6060
doc_test!($name, $source, false; $block);
6161
};
6262

63-
( $name:ident, $source:expr, private; $block:block ) => {
63+
( $name:ident, $source:expr, private; $block:expr ) => {
6464
doc_test!($name, $source, true; $block);
6565
};
6666

67-
( $name:ident, $source:expr, $private:expr; $block:block ) => {
67+
( $name:ident, $source:expr, $private:expr; $block:expr ) => {
6868
#[tokio::test]
6969
async fn $name() {
7070
use swc_ecmascript::parser::Syntax;
@@ -83,7 +83,8 @@ macro_rules! doc_test {
8383
#[allow(unused_variables)]
8484
let doc = DocPrinter::new(&entries, false, private).to_string();
8585

86-
$block
86+
#[allow(clippy::redundant_closure_call)]
87+
($block)(entries, doc)
8788
}
8889
};
8990
}
@@ -101,7 +102,7 @@ macro_rules! contains_test {
101102

102103
( $name:ident, $source:expr, $private:expr;
103104
$( $contains:expr ),* $( ; $( $notcontains:expr ),* )? ) => {
104-
doc_test!($name, $source, $private; {
105+
doc_test!($name, $source, $private; |_entries, doc: String| {
105106
$(
106107
assert!(doc.contains($contains));
107108
)*
@@ -124,7 +125,7 @@ macro_rules! json_test {
124125
};
125126

126127
( $name:ident, $source:expr, $private:expr; $json:tt ) => {
127-
doc_test!($name, $source, $private; {
128+
doc_test!($name, $source, $private; |entries, _doc| {
128129
let actual = serde_json::to_value(&entries).unwrap();
129130
let expected_json = json!($json);
130131
assert_eq!(actual, expected_json);

0 commit comments

Comments
 (0)