Skip to content

Instantly share code, notes, and snippets.

Created October 30, 2017 20:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save anonymous/89fd24baf9a253e91b28316cc6ba5eee to your computer and use it in GitHub Desktop.
Save anonymous/89fd24baf9a253e91b28316cc6ba5eee to your computer and use it in GitHub Desktop.
Rust code shared from the playground
#![feature(trace_macros)] trace_macros!(true);
/// Given N tokens, recurses N times to generate N unique identifiers
/// then calls you back at the given macro
macro_rules! idents {
// finished recursing, do the callback
(@rec [] -> $ids:tt $mac:ident!($($params:tt)*)) => {
$mac!($($params)* $ids)
};
// consume one token and generate one identifier
(@rec [$tok:tt $($toks:tt)*] -> [$($id:ident)*] $($thru:tt)*) => {
idents!(@rec [$($toks)*] -> [$($id)* id] $($thru)*)
};
// entry point
([$($toks:tt)*] $mac:ident!$params:tt) => {
idents!(@rec [$($toks)*] -> [] $mac!$params)
}
}
macro_rules! foo {
// callback rule: when idents! finishes recursing, we come back here
(@cb [$($num:tt)*], [$($id:ident)*]) => {
$(let $id = $num;)*
println!("{:?}", [$($id),*]);
};
// macro entry point
($($num:tt)*) => {
idents!([$($num)*] foo!(@cb [$($num)*],))
// ^ callback specification
// ^ tokens for counting the recursion
}
}
fn main() {
foo!(1 2 3);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment