Hacker News new | past | comments | ask | show | jobs | submit login
Show HN: macro_magic – access foreign item tokens in Rust proc/attribute macros (crates.io)
4 points by sam0x17 6 months ago | hide | past | favorite | 2 comments



Crate author here, macro_magic takes an extremely tricky to implement (and thus rare in the wild) pattern for accessing the tokens of foreign items in Rust within proc/attribute macros by path, the decl macro callback pattern, and makes it easy to use and fully accessible for people who want to leverage this superpower in their proc and attribute macros.

This approach enables some very exotic functionality that is normally impossible in rust proc macros, where you can decorate an item _anywhere_ with your attribute macro, and that item's tokens will become accessible when referenced by path as part of the input to any macro_magic-amplified proc or attribute macro.

macro_magic is able to do all of this without violating the golden principle of proc macros (that they must be a pure function of their inputs), and without relying on improper methods such as IO bookkeeping or global state. It is purely based on decl macro callbacks calling each other and is perfectly valid, pure rust.

Some crates/ecosystems making use of macro_magic already include:

- https://crates.io/crates/supertrait (enables default associated types in stable rust)

- https://github.com/paritytech/polkadot-sdk

Happy to answer any questions anyone may have about macro_magic!

Also worth noting, I am on the job market looking for my next Rust and/or CTO position :) -- info in bio


related: this approach also gives rise to eager expansion, which is supposed to be completely impossible in stable rust. The caveat is this eager expansion can _only_ work within a proc macro crate, so it is only useful in very specific circumstances.

Here is the first place such a thing was seen in the wild: https://github.com/paritytech/polkadot-sdk/blob/d0fd2660031b...




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: