-
-
Save durka/d13945528c596746d696ba0fac49fa7e to your computer and use it in GitHub Desktop.
Hygiene-based ident generator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#![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