Skip to content

Commit

Permalink
Add a section on recursive macros
Browse files Browse the repository at this point in the history
  • Loading branch information
Keegan McAllister committed Feb 25, 2015
1 parent 0bd1565 commit 65e1e6b
Showing 1 changed file with 39 additions and 0 deletions.
39 changes: 39 additions & 0 deletions src/doc/trpl/macros.md
Expand Up @@ -357,6 +357,45 @@ fn main() {

[items]: ../reference.html#items

# Recursive macros

A macro's expansion can include more macro invocations, including invocations
of the very same macro being expanded. These recursive macros are useful for
processing tree-structured input, as illustrated by this (simplistic) HTML
shorthand:

```rust
# #![allow(unused_must_use)]
macro_rules! write_html {
($w:expr, ) => (());

($w:expr, $e:tt) => (write!($w, "{}", $e));

($w:expr, $tag:ident [ $($inner:tt)* ] $($rest:tt)*) => {{
write!($w, "<{}>", stringify!($tag));
write_html!($w, $($inner)*);
write!($w, "</{}>", stringify!($tag));
write_html!($w, $($rest)*);
}};
}

fn main() {
# // FIXME(#21826)
use std::fmt::Write;
let mut out = String::new();

write_html!(&mut out,
html[
head[title["Macros guide"]]
body[h1["Macros are the best!"]]
]);

assert_eq!(out,
"<html><head><title>Macros guide</title></head>\
<body><h1>Macros are the best!</h1></body></html>");
}
```

# Further reading

The [advanced macros chapter][] goes into more detail about macro syntax. It
Expand Down

0 comments on commit 65e1e6b

Please sign in to comment.