As of Rust 1.30, the language supports user-defined function-like procedural macros. However these can only be invoked in item position, not in statements or expressions.
This crate implements an alternative type of procedural macro that can be invoked in statement or expression position.
This approach works with any stable or nightly Rust version 1.30+.
Two crates are required to define a procedural macro.
This crate must contain nothing but procedural macros. Private helper functions and private modules are fine but nothing can be public.
> example of an implementation crate
Just like you would use a #[procmacro] attribute to define a natively supported procedural macro, use proc-macro-hack's #[procmacro_hack] attribute to define a procedural macro that works in expression position. The function signature is the same as for ordinary function-like procedural macros.
```rust extern crate proc_macro;
use procmacro::TokenStream; use procmacrohack::procmacrohack; use quote::quote; use syn::{parsemacro_input, Expr};
/// Add one to an expression.
pub fn addone(input: TokenStream) -> TokenStream { let expr = parsemacro_input!(input as Expr); TokenStream::from(quote! { 1 + (#expr) }) } ```
This crate is allowed to contain other public things if you need, for example traits or functions or ordinary macros.
> example of a declaration crate
Within the declaration crate there needs to be a re-export of your procedural macro from the implementation crate. The re-export also carries a #[procmacrohack] attribute.
```rust use procmacrohack::procmacrohack;
/// Add one to an expression.
pub use demohackimpl::add_one; ```
Both crates depend on proc-macro-hack
:
toml
[dependencies]
proc-macro-hack = "0.5"
Additionally, your implementation crate (but not your declaration crate) is a proc macro crate:
toml
[lib]
proc-macro = true
Users of your crate depend on your declaration crate (not your implementation crate), then use your procedural macros as usual.
> example of a downstream crate
```rust use demohack::addone;
fn main() { let two = 2; let nine = addone!(two) + addone!(2 + 3); println!("nine = {}", nine); } ```
Only proc macros in expression position are supported. Proc macros in type position ([#10]) or pattern position ([#20]) are not supported.
By default, nested invocations are not supported i.e. the code emitted by a
proc-macro-hack macro invocation cannot contain recursive calls to the same
proc-macro-hack macro nor calls to any other proc-macro-hack macros. Use
[proc-macro-nested
] if you require support for nested invocations.
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 this hack by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.