// A `macro_rules!` is expanded at the call site, not translated into a Nim // template. The shape-level correspondence is real -- a single-rule macro *is* // a Nim template -- but a template body is untyped, and this lowering is // type-directed throughout: it needs a type to choose `div` over `/`, to size // a `cast`, to pick a literal's width. Expanding gives ordinary Rust in a // context where those types are known. macro_rules! square { ($x:expr) => { $x * $x }; } macro_rules! clamp_to { ($v:expr, $lo:expr, $hi:expr) => { if $v < $lo { $lo } else if $v > $hi { $hi } else { $v } }; } macro_rules! first_of { ($a:expr, $b:expr) => { if $a != 0 { $a } else { $b } }; } fn main() { // Precedence is preserved: `square!(2 + 3)` is 25, not 11. println!("{} {}", square!(4), square!(2 + 3)); let a: i32 = 5; println!("{}", square!(a)); println!("{} {} {}", clamp_to!(15, 0, 10), clamp_to!(-4, 0, 10), clamp_to!(7, 0, 10)); println!("{} {}", first_of!(0, 9), first_of!(3, 9)); // Nested, and with the macro's own type context. let w: u8 = 200; println!("{}", clamp_to!(w, 0u8, 100u8)); println!("{}", square!(3i64) + square!(4i64)); }