nade
English | 简体中文
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:
// some_crate/src/lib.rs
pub use *;
use nade;
]
b: u32,
c: u32,
d: u32
)
it will be expanded to:
// some_crate/src/lib.rs
// ⓵
pub use *;
use nade;
// ⓶
Then, when you call the macro foo like this:
use ;
foo!;
it will be expanded to:
use ;
foo;
Note
As you can see in How it works, there are 3 things to be aware of in the code generated by #[nade].
-
⓵, ⓷
nade_helperis a declarative macro used to generate function call expressions based on arguments, parameters, and function path.Its path defaults is
$crate::nade_helper, so you need to import the macro in the root of crate usingpub use nade::base::*;orpub use nade::base::nade_helper;.Also you can customize the path of
nade_helper.use nade; -
⓶
macro_vis an attribute macro that makes the visibility of the declarative macro the same as the function. see macro-v for details.Its path defaults is
::nade::__internal::macro_v.Also you can customize the path of
macro_v.use nade;
Limitations
-
When you call the macro
foo, you must use theusestatement to bring the macro into scope.// Good use ; foo!; // Bad use one; foo!;Because the attribute macro
#[nade]will generate a macro with the same name as the function, and the macro use the function in an unhygienic way, so you must use theusestatement to bring the macro and the function into scope. -
The default argument expression must be imported into the scope of the macro call.
// Good use ; foo!; // Bad use foo; foo!;Because the default argument expression is evaluated after the
foomacro is expanded, so it must be imported into the scope of the macro call.
How to bypass the limitations
-
You can pass a module path starting with
$cratefor the#[nade]attribute macro on the function.// <--- here ] b: u32, c: u32, d: u32 )it will be expanded to:
Then, you can not use the
usestatement to bring the macro and the function into scope, like this:use one; foo!; -
In the
#[nade]attribute 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:use foo; foo!;
Credits
This crate is inspired by these crates: