Crate macro_magic

source ·
Expand description

Macro Magic đŸȘ„

Build Status GitHub Crates.io docs.rs

This crate provides two powerful proc macros, #[export_tokens] and import_tokens!. When used in tandem, these two macros allow you to mark items in other files (and even in other crates, as long as you can modify the source code) for export. The tokens of these items can then be imported by the import_tokens! macro using the path to an item you have exported.

Two advanced macros, import_tokens_indirect! and read_namespace! are also provided when the “indirect” feature is enabled. These macros are capable of going across crate boundaries without complicating your dependencies and can return collections of tokens based on a shared common prefix.

Among other things, the patterns introduced by Macro Magic, and in particular by the “indirect” feature be used to implement safe and efficient coordination and communication between macro invocations in the same file, and even across different files and different crates. This crate officially supercedes my previous effort at achieving this, macro_state, which was designed to allow for building up and making use of state information across multiple macro invocations. All of the things you can do with macro_state you can also achieve with this crate, albeit with slightly different patterns.

macro_magic is designed to work with stable Rust.

Modules

  • Contains the internal code behind the macro_magic macros in a re-usable and extensible form, including the ability to make custom macros that behave like #[export_tokens] and import_tokens_indirect!. This module obeys the “indirect” / “indirect-read” “indirect-write” feature conventions so make sure the proper features are enabled if you are trying to access anything involving indirect exports/imports.

Macros

  • This macro is the primary way to bring exported tokens into scope in your proc macros (though it can also be used in non-proc-macro contexts, and is based on TokenStream2 for this purpose).
  • This macro allows you to import tokens across crate boundaries without strict dependency requirements and to use advanced features such as namespacing.
  • This convenient macro can be used to publicly re-export an item that has been exported via #[export_tokens] when doing direct imports.
  • This macro allows you to group a number of #[export_tokens] calls and collect them into a Result<Vec<(String, TokenStream2)>>.

Attribute Macros

  • This attribute can be attached to any [syn::Item]-compatible source code item without specifying any arguments, with the exception of ForeignMod, Impl, Macro (except when it has a defined [syn::Ident]), Use, and Verbatim which all require a disambiguation path to be specified as an argument. Attaching to an item will “export” that item so that it can be imported elsewhere by name via the import_tokens! macro.