Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions code/examples/misc_7.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ macro_rules! transform {
}

fn main() {
let x = capture!(2 + 3);
println!("{}", x); // what this will print?
}
// what will be output of this macro calls
dbg!(capture!(2 + 3));
dbg!(transform!(2 + 3));
}
2 changes: 2 additions & 0 deletions code/examples/stderr/misc_7.stderr
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
[examples/misc_7.rs:18:5] capture!(2 + 3) = 5
[examples/misc_7.rs:19:5] transform!(2 + 3) = 6
9 changes: 7 additions & 2 deletions src/misc/7.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,14 @@
<details>
<summary>Solution</summary>

It will prints `5`.
The actual output will be:

Once a token is captured as an expression (`:expr`), it becomes opaque to macro pattern matching and cannot be destructured into its component tokens.
```
[src/main.rs:17:5] capture!(2 + 3) = 5
[src/main.rs:18:5] transform!(2 + 3) = 6
```
Comment on lines +14 to +17
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
```
[src/main.rs:17:5] capture!(2 + 3) = 5
[src/main.rs:18:5] transform!(2 + 3) = 6
```
```text
{{#include ../../code/examples/stderr/misc_7.stderr}}
```


Because once a token is captured as an expression (`:expr`), it becomes opaque to macro pattern matching and cannot be destructured into its component tokens.

When `capture!(2 + 3)` is invoked, the `$e:expr` matcher captures `2 + 3` as a single expression token tree. This captured expression is then passed to `transform!($e)`, which attempts to match it against the pattern `$a:tt + $b:tt`.

Expand Down