Skip to content

Instantly share code, notes, and snippets.

@alexnoz
Last active March 19, 2020 22:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexnoz/9e3f2f79ea4df23fe2f73c1de96e5ce9 to your computer and use it in GitHub Desktop.
Save alexnoz/9e3f2f79ea4df23fe2f73c1de96e5ce9 to your computer and use it in GitHub Desktop.
Rust macro for evaluation of postfix expressions
macro_rules! postfix {
// Terminating rule
(() -> ($res:expr)) => {$res};
// Addition
((+ $($rest:tt)*) -> ($a:tt $b:tt $($stack:tt)*)) => {
postfix!(($($rest)*) -> (($b + $a) $($stack)*))
};
// Subtraction
((- $($rest:tt)*) -> ($a:tt $b:tt $($stack:tt)*)) => {
postfix!(($($rest)*) -> (($b - $a) $($stack)*))
};
// Multiplication
((* $($rest:tt)*) -> ($a:tt $b:tt $($stack:tt)*)) => {
postfix!(($($rest)*) -> (($b * $a) $($stack)*))
};
// Divison
((/ $($rest:tt)*) -> ($a:tt $b:tt $($stack:tt)*)) => {
postfix!(($($rest)*) -> (($b / $a) $($stack)*))
};
// Push operands onto the stack
(($d:tt $($rest:tt)+) -> ($($stack:tt)*)) => {
postfix!(($($rest)+) -> ($d $($stack)*))
};
// Start
($($ops:tt)+) => {
postfix!(($($ops)+) -> ())
};
}
fn main() {
let res = postfix!(15 7 1 1 + - / 3 * 2 1 1 + + -);
println!("{}", res);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment