#patterns #macros #inline #macro #define

defmac

A macro to define lambda-like macros inline

5 releases

0.2.0 Nov 19, 2018
0.1.3 Nov 4, 2017
0.1.2 Jul 28, 2017
0.1.1 Jan 21, 2017
0.1.0 Oct 5, 2016

#50 in Rust patterns

Download history 233/week @ 2018-10-11 297/week @ 2018-10-18 372/week @ 2018-10-25 546/week @ 2018-11-01 357/week @ 2018-11-08 340/week @ 2018-11-15 524/week @ 2018-11-22 373/week @ 2018-11-29 428/week @ 2018-12-06 366/week @ 2018-12-13 382/week @ 2018-12-20 300/week @ 2018-12-27 340/week @ 2019-01-03

1,627 downloads per month
Used in 6 crates (3 directly)

Apache-2.0/MIT

8KB
68 lines

defmac

Please read the API documentation here

build_status crates

Recent Changes

  • 0.2.0

    • New implementation that is general and variadic: defmac now supports making macros with arbitrarily many parameters!

    • Requires Rust 1.20

  • 0.1.3

    • Update docs with another example and a tip about syntactical variable capture.

License

Dual-licensed to be compatible with the Rust project.

Licensed under the Apache License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0 or the MIT license http://opensource.org/licenses/MIT, at your option. This file may not be copied, modified, or distributed except according to those terms.


lib.rs:

A macro to define lambda-like macros inline.

Syntax:

defmac!( name [ pattern [, pattern ... ]] => expression )

name is the name of the new macro, followed by 0 or more patterns separated by comma. A pattern can be just an argument name like x or a pattern like ref value, (x, y) etc. Note that there is no comma between the name and the first pattern.

Example

#[macro_use] extern crate defmac;

fn main() {
    defmac!(mkvec iter => iter.into_iter().collect::<Vec<_>>());

    let v = mkvec!((0..10).map(|x| x * 2));

    defmac!(repeat ref s, n => (0..n).map(|_| &s[..]).collect::<String>());

    let text = String::from("abc");
    let s = repeat!(text, 10);
    let t = repeat!("-", s.len());
    println!("{}", s);
    println!("{}", t);

}

Did you know that macros can “capture” variables that they have in scope? The capture is by name instead of by reference, so we can use defmac where we cannot use closures. See the example below:

#[macro_use] extern crate defmac;

fn main() {
    let mut result = Vec::new();
    let mut sum = 0.;
    let input = "2 2 ^ 7 b ^";

    defmac!(push elem => result.push(elem));
    defmac!(double => *result.last_mut().unwrap() *= 2);

    for ch in input.chars() {
        match ch {
            '^' => double!(),
            '0'...'9' => push!(ch as u32 - '0' as u32),
            'a'...'z' => push!(ch as u32 - 'a' as u32),
            _ => { }
        }
    }

    assert_eq!(
        result,
        vec![2, 4, 7, 2]);
}

Rust Version

This crate requires Rust 1.20 or later.

No runtime deps