Last active
March 19, 2020 22:47
-
-
Save alexnoz/9e3f2f79ea4df23fe2f73c1de96e5ce9 to your computer and use it in GitHub Desktop.
Rust macro for evaluation of postfix expressions
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
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