nade
nade is a attribute macro that adds named and default arguments to Rust functions.
Usage
// some_crate/src/lib.rs
pub use *;
use nade;
] b: u32,
/// Default value of u32
c: u32,
d: u32
)
assert_eq!; // foo(1, 2, 3, 4)
assert_eq!; // foo(42, one(), Default::default(), 2)
assert_eq!; // foo(1, 3, 2, 4)
How it works
If you write a function like this:
]
b: u32,
c: u32,
d: u32
)
it will be expanded to:
The attribute macro #[macro_v(pub)] make the visibility of the declarative macro the same as the function. When the visibility of the function is pub(crate), #[macro_v(pub(crate))] is also generated. see macro-v for details.
Then, when you call the macro foo like this:
foo!;
it will be expanded to:
foo;
Note
As you can see in How it works, the code generated by #[nade] contains calls to the macros #[crate::macro_v(pub)] and $crate::nade_helper!(..), so you have to import them in the root of crate, because the declarative macro foo may be used in other crate so it is recommended to use the pub use statement.
// recommend
pub use *;
// or expand glob import
pub use ;
Limitations
-
When you call the macro
foo, you must use theusestatement to bring the macro into scope.// Good use foo; foo!; // Bad foo!;Because the attribute macro
nadewill generate a macro with the same name as the function, and the macro use the function, so you must use theusestatement to bring the macro and the function into scope. -
The default argument expression must be declared in the scope of the macro call.
// Good use one; foo!; // Bad foo!;Because the default argument expression is evaluated after the macro is expanded, so it must be declared in the scope of the macro call.
How to bypass the limitations
-
You can pass a module path starting with
$cratefor thenadeattribute macro on the function.] b: u32, c: u32, d: u32 )it will be expanded to:
Then, you can not use the
usestatement to bring the macro into scope, like this:foo!; -
In the
nadeattribute macro on the parameter, you can specify the default argument expression using the full path, either$crate::a::expr, or::a::b::expr. In fact, when you use#[nade]on an parameter, you are using#[nade(::core::default::Default::default())].pub static PATH: &str = "a"; ] a: T1, b: T2, c: T3, d: T4 )it will be expanded to:
Then, you can not use the
usestatement to bring default argument expressions into scope, like this:foo!;
Credits
This crate is inspired by these crates: