nandi/rustnimpublic Fork 0
d4592812fae6b652d94be442f5b3a408d3ab21b6
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.

Expand `macro_rules!` rather than translating it to a Nim template 04eb29f · on d4592812fae6b652d94be442f5b3a408d3ab21b6 · nandithebull · 7h ago
037-macro-rules.rs · 40 lines · 1.2 KBRust Blame HistoryRaw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
// 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));
}