#proc-macro #macro #export #reflection #macro-magic

no-std mini-macro-magic

Export tokens to other modules and crates. Now with 100% less proc macros!

4 stable releases

2.0.2 Dec 16, 2023
1.0.0 Jun 28, 2023

#618 in Rust patterns

MIT/Apache

22KB
207 lines

Version Crates.io docs.rs Crates.io

::mini-macro-magic 🪄

Export tokens to other modules or crates. Now with 100% less proc macros!

See the integration tests for examples that show why you would want to use export.

This crate provides the export macro which allows exporting tokens. The concept is similar to that used by the inspiration for this crate macro_magic. Namely, a macro_rules! is generated. This macro_rules! will invoke a passed macro with the exported tokens.

The difference to macro_magic is that this crate does it all with one macro_rules! macro. No more need to poll in a set of proc macros if you don't need the full power of macro_magic. Instead use export to generate a macro you or a dependant crate can use. Also, a dependant crate doesn't need to know about mini_macro_magic to use the generated macro_rules!. They are fully self contained.

The export macro allows for a form of reflection. Reflection over the definition of items by inspecting the tokens of the definition. macro_rules (and Rust macros in general) have no way to eagerly expand their input. As a result export creates a macro that you pass another macro call for it to expand into.

use mini_macro_magic::{export, emit};

// Export the definition of `MyStruct`.
// Note without using `emit!()` `MyStruct` isn't actually created in this scope.
export!(
    #[export(my_struct$)]
    {
        struct MyStruct;
    }
);

// An example macro that can parse a struct definition and get the name
// of the struct as a string.
macro_rules! name_of_struct {
    {{
        $(#[$($attr:tt)*])*
        $vis:vis struct $name:ident;
    }} => {
        stringify!($name)
    };
}

// Invoke `name_of_struct` with the definition of `MyStruct`.
assert_eq!(my_struct!(name_of_struct!()), "MyStruct");

#![no_std]

mini_macro_magic is #![no_std], it can be used anywhere Rust can.

Minimum Supported Rust Version

Requires Rust 1.56.0.

This crate follows the "Latest stable Rust" policy. The listed MSRV won't be changed unless needed. However, updating the MSRV anywhere up to the latest stable at time of release is allowed.


License

Licensed under either of Apache License, Version 2.0 or MIT license at your option.
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in mini-macro-rules by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

No runtime deps