#macros #inline #macro #patterns #define

defmac

A macro to define lambda-like macros inline

4 releases

0.1.3 Nov 4, 2017
0.1.2 Jul 28, 2017
0.1.1 Jan 21, 2017
0.1.0 Oct 5, 2016
Download history 90/week @ 2018-05-27 165/week @ 2018-06-03 79/week @ 2018-06-10 186/week @ 2018-06-17 264/week @ 2018-06-24 223/week @ 2018-07-01 176/week @ 2018-07-08 107/week @ 2018-07-15 130/week @ 2018-07-22 139/week @ 2018-07-29 122/week @ 2018-08-05 84/week @ 2018-08-12 105/week @ 2018-08-19

153 downloads per month
Used in 5 crates (3 directly)

Apache-2.0/MIT

7KB
60 lines

defmac

Please read the API documentation here__

__ https://docs.rs/defmac

|build_status|_ |crates|_

.. |build_status| image:: https://travis-ci.org/bluss/defmac.svg .. _build_status: https://travis-ci.org/bluss/defmac

.. |crates| image:: http://meritbadge.herokuapp.com/defmac .. _crates: https://crates.io/crates/defmac

Recent Changes

  • 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.

Supports up to four arguments.

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]);
}

No runtime deps