From 65e1e6bb942701a061f6772507141ea9f8e920e2 Mon Sep 17 00:00:00 2001 From: Keegan McAllister Date: Fri, 20 Feb 2015 12:12:25 -0800 Subject: [PATCH] Add a section on recursive macros --- src/doc/trpl/macros.md | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/src/doc/trpl/macros.md b/src/doc/trpl/macros.md index ce6fa3ce949..d0fa735b1df 100644 --- a/src/doc/trpl/macros.md +++ b/src/doc/trpl/macros.md @@ -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, + "Macros guide\ +

Macros are the best!

"); +} +``` + # Further reading The [advanced macros chapter][] goes into more detail about macro syntax. It