#macro-rules #proc-macro #pattern-matching #deno #procedural #syntax #emulation

deno-proc-macro-rules

Deno fork of proc-macro-rules. Emulate macro-rules pattern matching in procedural macros

3 releases

0.3.2 Jun 24, 2023
0.3.1 Jun 24, 2023
0.3.0 Jun 24, 2023

#459 in Procedural macros

Download history 2069/week @ 2024-08-15 2384/week @ 2024-08-22 1981/week @ 2024-08-29 2704/week @ 2024-09-05 1991/week @ 2024-09-12 2256/week @ 2024-09-19 2726/week @ 2024-09-26 2132/week @ 2024-10-03 1603/week @ 2024-10-10 2130/week @ 2024-10-17 2604/week @ 2024-10-24 2073/week @ 2024-10-31 1937/week @ 2024-11-07 2268/week @ 2024-11-14 1963/week @ 2024-11-21 1493/week @ 2024-11-28

8,089 downloads per month

Apache-2.0/MIT

19KB
359 lines

proc-macro-rules

macro_rules-style syntax matching for procedural macros.

This crate is work-in-progress, incomplete, and probably buggy!

Example:

rules!(tokens => {
    ($finish:ident ($($found:ident)*) # [ $($inner:tt)* ] $($rest:tt)*) => {
        for f in found {
            do_something(finish, f, inner, rest[0]);
        }
    }
    (foo $($bar:expr)?) => {
        match bar {
            Some(e) => foo_with_expr(e),
            None => foo_no_expr(),
        }
    }
});

Using proc-macro-rules

Add proc-macro-rules = "0.3.0" (or proc-macro-rules = "0.2.1" for versions between 1.31 and 1.56) to your Cargo.toml.

Import the rules macro with use proc_macro_rules::rules, then use with rules!(tokens => { branches }); where tokens is an expression which evaluates to a TokenStream (such as the argument in the definition of a procedural macro).

Each branch in branches should have the form ( pattern ) => { body } where pattern is a macro-rules-style pattern (using all the same syntax for meta-variables, AST nodes, repetition, etc.) and body is rust code executed when the pattern is matched. Within body, any meta-variables in the pattern are bound to variables of an appropriate type from either the proc_macro2 or syn crates. Where a meta-variable is inside a repetition or option clause, it will be wrapped in a Vec or Option, respectively.

For example, in the first branch in the above example ident has type syn::Ident and inner has type Vec<proc_macro2::TokenTree>.

Building and testing

Use cargo build to build, cargo test --all to test.

Contributing

Contributions are very welcome! It would be great to know things which are missing or incorrect (in general we should have the same behaviour as macro_rules, so anything different is incorrect). Issues, code, docs, tests, and corrections are all welcome.

Dependencies

~230–690KB
~16K SLoC