nandi/rustnimpublic Fork 0
main
Commits
Clone
git clone https://git.rickub.com/nandi/rustnim.git
git clone ssh://git@rickub.com/nandi/rustnim.git

Host key fingerprint (ed25519): SHA256:iycHnxEyq0Q7uyVpB7JlznP0G7JrTPXLYRcAU5CSLhc — verify it before your first connect.

037-macro-rules.rs · 40 lines · 1.2 KBRust Blame HistoryRaw
Expand `macro_rules!` rather than translating it to a Nim template 04eb29f nandithebull 10h ago1// 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
8macro_rules! square {
9 ($x:expr) => {
10 $x * $x
11 };
12}
13
14macro_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
20macro_rules! first_of {
21 ($a:expr, $b:expr) => {
22 if $a != 0 { $a } else { $b }
23 };
24}
25
26fn 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}