Et tu `macro_rules!`

Acme Design is a full service design agency.

— Swarnim Arun

Every programmer is an author.
But why can't the program be one too?

– Somebody somewhere someplace

Hygiene is an important concept for macros.

 

It describes the ability for a macro to work in its own syntax context, not affecting nor being affected by its surroundings.

 

In other words this means that a syntax extension should be invocable anywhere without interfering with its surrounding context.

what's hygiene?

macro_rules!

macro_rules! hello {
    ($e:literal) => { println!("Hello, {}!", $e); };
}

rustc provides a number of tools to debug general syntax extensions, as well as some more specific ones tailored towards declarative and procedural macros respectively.

 

Sometimes, it is what the extension expands to that proves problematic as you do not usually see the expanded code. Fortunately rustc offers the ability to look at the expanded code via the unstable -Zunpretty=expanded argument.

debug it!

debugging!

rustc +nightly -Zunpretty=expanded hello.rs
fn foo() {
    {
        ::std::io::_print(format_args!("Hello, {0}!\n", "world"));
    };
}
fn foo() {
  hello!("world");
}
  • Callback
  • TT munch'in
  • Internal "rules"
  • Push-Down Accumulation

Some patterns

TT Muncher & Internal Rules

Just the important ones

#[macro_export]
macro_rules! foo {
    (@as_expr $e:expr) => {$e};

    ($($tts:tt)*) => {
        foo!(@as_expr $($tts)*)
    };
}

Live Demo

Resources

Thank You!

reachout at:

@swarnimarun

Made with Slides.com