Created
March 12, 2014 20:26
-
-
Save kmcallister/9515601 to your computer and use it in GitHub Desktop.
macro sadness
This file contains hidden or 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(macro_rules)]; | |
| // Shorthand for state-machine actions. | |
| macro_rules! one ( | |
| ( inc ) => ( self.counter += 1; ); | |
| ( print ) => ( println!("counter is {:d}", self.counter); ); | |
| ) | |
| // A DSL for sequencing shorthand actions. | |
| macro_rules! go ( | |
| ( $a:tt ; $($rest:tt)* ) => ({ one!($a); go!($($rest)*); }); | |
| ( $($cmd:tt)+ ) => ( one!($($cmd)+); ); | |
| () => (()); | |
| ) | |
| // Conditional action. | |
| macro_rules! match_counter ( ( 0 ( $($eq0:tt)+ ) else ( $($ne0:tt)+ ) ) => ( | |
| match self.counter { | |
| 0 => go!($($eq0)+), | |
| _ => go!($($ne0)+), | |
| } | |
| )) | |
| struct Machine { | |
| counter: int, | |
| } | |
| impl Machine { | |
| fn run(&mut self) { | |
| go!(inc; inc; print); | |
| // works | |
| match_counter!( | |
| 0 (inc) | |
| else (print) | |
| ); | |
| // foo.rs:31:22: 31:23 error: Local ambiguity: multiple parsing options: built-in NTs tt ('eq0') or 1 other options. | |
| // foo.rs:31 0 (inc) | |
| // ^ | |
| } | |
| } | |
| fn main() { | |
| let mut m = Machine { counter: 0 }; | |
| m.run(); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment