Skip to content

Instantly share code, notes, and snippets.

@kmcallister
Created March 12, 2014 20:26
Show Gist options
  • Select an option

  • Save kmcallister/9515601 to your computer and use it in GitHub Desktop.

Select an option

Save kmcallister/9515601 to your computer and use it in GitHub Desktop.
macro sadness
#[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