| Expand `macro_rules!` rather than translating it to a Nim template 04eb29f nandithebull 9h ago | 1 | // A `macro_rules!` is expanded at the call site, not translated into a Nim |
| 2 | // template. The shape-level correspondence is real -- a single-rule macro *is* |
| 3 | // a Nim template -- but a template body is untyped, and this lowering is |
| 4 | // type-directed throughout: it needs a type to choose `div` over `/`, to size |
| 5 | // a `cast`, to pick a literal's width. Expanding gives ordinary Rust in a |
| 6 | // context where those types are known. |
| 7 | |
| 8 | macro_rules! square { |
| 9 | ($x:expr) => { |
| 10 | $x * $x |
| 11 | }; |
| 12 | } |
| 13 | |
| 14 | macro_rules! clamp_to { |
| 15 | ($v:expr, $lo:expr, $hi:expr) => { |
| 16 | if $v < $lo { $lo } else if $v > $hi { $hi } else { $v } |
| 17 | }; |
| 18 | } |
| 19 | |
| 20 | macro_rules! first_of { |
| 21 | ($a:expr, $b:expr) => { |
| 22 | if $a != 0 { $a } else { $b } |
| 23 | }; |
| 24 | } |
| 25 | |
| 26 | fn main() { |
| 27 | // Precedence is preserved: `square!(2 + 3)` is 25, not 11. |
| 28 | println!("{} {}", square!(4), square!(2 + 3)); |
| 29 | |
| 30 | let a: i32 = 5; |
| 31 | println!("{}", square!(a)); |
| 32 | |
| 33 | println!("{} {} {}", clamp_to!(15, 0, 10), clamp_to!(-4, 0, 10), clamp_to!(7, 0, 10)); |
| 34 | println!("{} {}", first_of!(0, 9), first_of!(3, 9)); |
| 35 | |
| 36 | // Nested, and with the macro's own type context. |
| 37 | let w: u8 = 200; |
| 38 | println!("{}", clamp_to!(w, 0u8, 100u8)); |
| 39 | println!("{}", square!(3i64) + square!(4i64)); |
| 40 | } |