在上一个章节中,我们学习了许多跟文字格式化有关的宏。在这个章节,我们将会更深入地了解宏到底是什么东西,以及实作宏的方式。
Rust 编程语言的宏,很像是函数,但是它比函数还要更有弹性,而且复杂很多。「宏」是一个用代码产生代码的方式,又称为「元编程」(Metaprogramming),妥善运用可以大量地减少我们需要撰写的代码。当然我们如果能用函数解决的问题就尽量使用函数,因为过度使用宏通常会使得程序不易阅读。
在早期版本的 Rust,要引用宏,必须使用 extern crate 叙述并加上 #[macro_use] 属性来引用才行。但现在的宏和函数一样,可以直接透过路径或是 use 关键字来使用。举例来说:
use serde::{Deserialize, Serialize};
以上程序会将 serde 这个 crate 中的 Deserialize 和 Serialize 宏引用进目前程序的 scope 中,它们可以被用在 #[derive()] 属性的参数中,属于「进程式宏」(Procedural Macros)。在之前的章节中经常使用的 println! 宏可以用像是函数一样的方式来调用,属于「声明式宏」(Declarative Macro)。
声明式宏
声明式宏的用途比进程式宏还要广泛,我们可以使用 macro_rules! 宏来定义并实作新的声明式宏。例如:
macro_rules! hello {
() => {
println!("Hello!");
};
}
以上程序,实作了一个 hello! 宏,它在不传入任何的参数时,会再去调用 println! 宏在屏幕上显示出 Hello! 文字。
完整程序如下:
macro_rules! hello {
() => {
println!("Hello!");
};
}
fn main() {
hello!();
}
macro_rules! 宏的语法格式有点像是 match 关键字,而事实上,编译器在遇到声明式宏的时候,也会如 match 关键字那样去做类似型样匹配的动作。例如以上程序,我们用 hello!() 这个程序叙述来调用 hello! 宏。由于 hello!() 没有加入任何的参数,因此 macro_rules! 宏中定义的 () 这条 arm 就会被匹配到。
编译器会在进进程式编译前,先去匹配并「解开」声明式宏内撰写的代码。拿以上的例子来说,编译器会将程序第 8 行的 hello! 宏解开,变成如下的代码:
macro_rules! hello {
() => {
println!("Hello!");
};
}
fn main() {
println!("Hello!");
}
所以程序运行后会在屏幕上显示出 Hello! 文字。
我们可以再将 hello! 宏进行如下的改写,加入新的 arm,使其能同时支持不传入任何参数和传入一个 world 参数的调用方式。
macro_rules! hello {
() => {
println!("Hello!");
};
(world) => {
println!("Hello, world!");
};
}
这边另外要注意的是,在 macro_rules! 宏的 arm 与 arm 之间,要用分号 ; 隔开,而且 arm 的匹配顺序是从上到下的。
当我们使用 hello!(world) 来调用 hello! 宏时,屏幕上就会显示出 Hello, world! 文字,而不是 Hello! 文字。完整程序如下:
macro_rules! hello {
() => {
println!("Hello!");
};
(world) => {
println!("Hello, world!");
};
}
fn main() {
hello!(world);
}
所以我们传给 hello! 宏的 world 到底是什么东西?一个变量吗?其实它可以是变量也可以不是变量。例如以下程序:
macro_rules! hello {
() => {
println!("Hello!");
};
(world) => {
println!("Hello, world!");
};
}
fn main() {
let world = "Magic Len";
hello!(world);
}
我们真的在调用 hello! 宏前先声明了一个 world 变量。这个程序虽然可以通过编译,但是编译器会提示程序第 11 行声明的 world 变量并没有被用到。
这是怎么回事?所以程序第 13 行的 world 是什么?在这个程序中,第 13 行的 world 其实就如同 hello! 宏的一部份,它既不是变量、不是类型、也不是字符串。当编译器看到 hello!(world) 时,首先会去看它有没有办法与 () 这条 arm 匹配,在这边很显然是不能的,所以又会去看它能不能与 (world) 这条 arm 匹配,由于它们的参数都是 world,因此匹配成功。
声明式宏并不会去区分到底是用小括号 ()、中括号 [] 还是大括号 {} 来传递参数。例如:
macro_rules! hello {
[] => {
println!("Hello!");
};
{world} => {
println!("Hello, world!");
};
}
fn main() {
hello!();
hello![];
hello! {};
hello!(world);
hello![world];
hello! {world};
}
以上程序的运行结果如下:
Hello!
Hello!
Hello, world!
Hello, world!
Hello, world!
虽然声明式宏并没有区分括号版本,但是习惯上,我们写在 macro_rules! 宏的 arm 的匹配样本都是使用小括号。在调用宏时,则是依据传入参数的类型来决定要使用哪种括号。如果是要如函数那样传入参数的话,就使用小括号 ();如果是要如数组那样传入好几个元素的话,就使用中括号 [];如果是要传入等等会提到的多种记号(token)的话,就使用大括号 {}。
我们可以再将 hello! 宏进行如下的改写,加入新的 arm,使其能再支持更多的调用方式。
macro_rules! hello {
() => {
println!("Hello!");
};
(world) => {
println!("Hello, world!");
};
(web: MagicLen) => {
println!("Hello, magiclen.org!");
};
}
同样地,当我们使用 hello!(web: MagicLen) 来调用 hello! 宏时,屏幕上就会显示出 Hello, magiclen.org! 文字。完整程序如下:
macro_rules! hello {
() => {
println!("Hello!");
};
(world) => {
println!("Hello, world!");
};
(web: MagicLen) => {
println!("Hello, magiclen.org!");
};
}
fn main() {
hello!(web: MagicLen);
}
事实上,就算我们在调用 hello! 宏时,把 web: MagicLen 的空格 省略掉,程序也还是可以通过编译。如下:
macro_rules! hello {
() => {
println!("Hello!");
};
(world) => {
println!("Hello, world!");
};
(web: MagicLen) => {
println!("Hello, magiclen.org!");
};
}
fn main() {
hello!(web:MagicLen);
}
这是因为声明式宏会将传入的参数拆解成好几个记号(token),来做型样匹配,因此不论是 web: MagicLen 或 web:MagicLen 都会被拆解为 web、: 和 MagicLen,不用管空格到底有多少个。
那它是怎么把 web: 拆成 web 和 : 两个记号的?怎么不就是一个 web: 记号呢?除了底线、英文字母和数字外,其余的字符皆是记号的分界,但是重复的字符不会被分界。像是 a1B_,只会被拆解为 a1B_;a1B.c 会被拆解为 a1B、. 和 c;a1B..c 会被拆解为 a1B、.. 和 c。
如果我们要把写在 macro_rules! 宏的 arm 的匹配样本内的参数当变量来用的话,该参数名称必须要以 $ 为开头,而且其后还要使用 : 语法来定义参数的类型。如下:
macro_rules! hello {
() => {
println!("Hello!");
};
($target:expr) => {
println!("Hello, {}!", $target);
};
}
在 hello! 宏的第二个 arm 中,我们定义了一个类型为 expr 的 $target 参数。这个 $target 不是用来直接匹配 $ 和 target 这两个记号,而是用来匹配任意的表达式。
例如以下程序:
macro_rules! hello {
() => {
println!("Hello!");
};
($target:expr) => {
println!("Hello, {}!", $target);
};
}
fn main() {
hello!();
let world = "world";
hello!(world);
}
运行结果如下:
Hello, world!
在这个程序中,hello!(world) 中的 world 就是变量了,而不是宏的一部份。
声明式宏参数的类型
以下分别说明与举例参数可以使用的类型:
literal
literal 用来匹配一个定数。
macro_rules! hello {
($target:literal) => {
println!("Hello, {}!", $target);
};
}
fn main() {
hello!("world");
}
expr
expr 用来匹配一个表达式。
macro_rules! hello {
($target:expr) => {
println!("Hello, {}!", $target);
};
}
fn main() {
hello!("world");
}
ident
ident 用来匹配一个变量、函数、常数、类型名称。
macro_rules! wrapper {
($name:ident) => {
struct $name<T> {
data: T,
}
impl<T> From<T> for $name<T> {
fn from(data: T) -> Self {
Self { data }
}
}
};
}
wrapper!(Wrapper);
fn main() {
let _wrapper = Wrapper::from(String::new());
}
ty
ty 用来匹配一个类型,包含泛型。
macro_rules! wrapper {
($name:ident, $typ: ty) => {
struct $name {
data: $typ,
}
impl From<$typ> for $name {
fn from(data: $typ) -> Self {
Self { data }
}
}
};
}
wrapper!(StringWrapper, String);
fn main() {
let string_wrapper = StringWrapper::from(String::new());
}
lifetime
lifetime 用来匹配一个生命周期,例如 'static、'a。
macro_rules! wrapper {
($name:ident, & $lt: lifetime $typ: ty) => {
struct $name {
data: & $lt $typ
}
impl $name {
fn from(data: & $lt $typ) -> Self {
Self {
data
}
}
}
};
}
wrapper!(StringWrapper, &'static str);
fn main() {
let string_wrapper = StringWrapper::from("123");
}
tt
tt 用来匹配一个记号。
macro_rules! declare {
($keyword: tt, $name: ident, $typ: ty, $value: expr) => {
$keyword $name: $typ = $value;
};
}
declare!(static, A, i32, 1);
fn main() {
println!("{A}");
}
item
item 用来匹配一个结构体、枚举、函数、模块。
macro_rules! basic_derive {
($item: item) => {
#[derive(Debug, Clone, Default)]
$item
};
}
basic_derive!(
struct MyStruct {
name: String,
}
);
fn main() {
let a = MyStruct { name: "name".to_string() };
println!("{a:?}");
}
item 的匹配范围其实也有包含该项目的属性和文档注解。
macro_rules! basic {
($item: item) => {
$item
};
}
basic! {
#[derive(Debug, Clone, Default)]
struct MyStruct {
name: String
}
}
fn main() {
let a = MyStruct { name: "name".to_string() };
println!("{a:?}");
}
block
block 用来匹配一个程序区块。
macro_rules! validated_string {
($name: ident, $data: ident, $handler:block, $err: ty) => {
struct $name(String);
impl $name {
fn from_string($data: String) -> Result<Self, $err> {
let s = match $handler {
Ok(s) => s,
Err(e) => return Err(e),
};
Ok(Self(s))
}
}
};
}
#[derive(Debug)]
enum Errors {
IncorrectFormat,
}
validated_string!(
HelloString,
data,
{
if data.starts_with("Hello") {
Ok(data)
} else {
Err(Errors::IncorrectFormat)
}
},
Errors
);
fn main() {
let validated_string = HelloString::from_string("Hello!".to_string()).unwrap();
}
stmt
stmt 用来匹配一个程序叙述。
macro_rules! one_statement_function {
($name: ident, $do: stmt) => {
fn $name() {
$do
}
};
}
one_statement_function!(hello, println!("Hello!"));
fn main() {
hello();
}
pat
pat 用来匹配 match 关键字的匹配样本。
macro_rules! match_one {
($v: expr, $p: pat, $b: block) => {
match $v {
$p => $b
_ => unimplemented!()
}
};
}
fn main() {
let v = Some(50);
match_one!(v, Some(a), {
println!("{a}");
});
}
path
path 用来匹配一个路径。
macro_rules! hello {
($p: path) => {
use $p::{hello};
hello();
};
}
mod hello {
pub mod a {
pub fn hello() {
println!("Hello!");
}
}
pub mod b {
pub fn hello() {
println!("Hello.");
}
}
}
fn main() {
hello!(hello::a);
}
注意以上程序的第 3 行,要在声明式宏中使用类型为 path 的参数,若要在路径后再添加其它路径,需要使用 use 关键字搭配大括号 {} 语法将其引入。下面再举一个例子:
macro_rules! hello {
($p: path) => {
use $p::{b};
b::hello();
};
}
mod hello {
pub mod a {
pub mod b {
pub fn hello() {
println!("Hello!");
}
}
}
}
fn main() {
hello!(hello::a);
}
meta
meta 用来匹配属性或是其中的一个参数。
macro_rules! item_with_derive {
($item: item, $meta: meta) => {
#[derive($meta)]
$item
};
}
item_with_derive!(
struct MyStruct {
name: String,
},
Debug
);
fn main() {
let a = MyStruct { name: "name".to_string() };
println!("{a:?}");
}
meta 经常会写成 $(#[$attr: meta])*,来匹配所有属性和文档注解。
macro_rules! struct_with_meta {
($(#[$attr: meta])* struct $($t:tt)*) => {
$(#[$attr])*
struct $($t)*
};
}
struct_with_meta! {
/// My struct!!
#[derive(Debug)]
struct MyStruct {
name: String
}
}
fn main() {
let a = MyStruct { name: "name".to_string() };
println!("{a:?}");
}
vis
vis 用来匹配一个如 pub、pub(crate) 等的关键字。vis 也可以完全不匹配任何字符,表示要使用预设的可见度。
macro_rules! wrapper {
($v:vis $name:ident, $typ: ty) => {
$v struct $name {
data: $typ
}
impl From<$typ> for $name {
fn from(data: $typ) -> Self {
Self {
data
}
}
}
};
}
wrapper!(pub StringWrapper, String);
fn main() {
let string_wrapper = StringWrapper::from(String::new());
}
多次匹配
利用 $() 语法,将想要进行多次匹配的部份括起来,接着再接上星号 * 或加号 + 来表示要进行任意次数的匹配还是至少一次的匹配。在读取时,也是用同样的语法,将要多次使用的部份括起来。
直接给个例子会比较清楚:
macro_rules! item_with_derives {
($item: item $(, $meta: meta)+ ) => {
#[derive( $($meta,)+ )]
$item
};
}
item_with_derives!(
struct MyStruct {
name: String,
},
Debug,
Clone
);
fn main() {
let a = MyStruct { name: "name".to_string() };
println!("{a:?}");
}
在使用 $() 语法来匹配时,其实也可以在 $() 和星号 * 或加号 + 之间再加上一个记号,作为分隔参数的记号。例如:
macro_rules! item_with_derives {
($item: item, $($meta: meta),+ ) => {
#[derive( $($meta,)+ )]
$item
};
}
item_with_derives!(
struct MyStruct {
name: String,
},
Debug,
Clone
);
fn main() {
let a = MyStruct { name: "name".to_string() };
println!("{a:?}");
}
不过上述的两种分隔方式,均无法成功匹配参数最后又多了一个分隔记号的情形。例如:
macro_rules! item_with_derives {
($item: item, $($meta: meta),+) => {
#[derive( $($meta,)+ )]
$item
};
}
item_with_derives!(
struct MyStruct {
name: String,
},
Debug,
Clone,
);
fn main() {
let a = MyStruct { name: "name".to_string() };
println!("{a:?}");
}
以上程序会编译失败,因为程序第 13 行多了一个逗号 ,。
为了解决这个问题,我们可以将匹配样本改成这样:
macro_rules! item_with_derives {
($item: item, $($meta: meta),+ $(,)*) => {
#[derive( $($meta,)+ )]
$item
};
}
item_with_derives!(struct MyStruct {
name: String
},
Debug,
Clone,,,,,
);
fn main() {
let a = MyStruct { name: "name".to_string() };
println!("{a:?}");
}
如此一来要加几个逗号都不是问题!
可有可无的匹配
利用 $() 语法,将想要进行选用而不强制匹配的部份括起来,接着再接上问号 ?。在读取时,也是用同样的语法,将要选用的部份括起来。例如:
macro_rules! declare {
($keyword: tt, $name: ident $(: $typ: ty)?, $value: expr) => {
$keyword $name $(: $typ)? = $value;
};
}
fn main() {
declare!(let, a: i32, 1);
declare!(let, b, 2);
println!("{a} {b}");
}
前面提到的结尾逗号的问题,也可以用这种匹配方式来解决。如下:
macro_rules! item_with_derives {
($item: item, $($meta: meta),+ $(,)?) => {
#[derive( $($meta,)+ )]
$item
};
}
item_with_derives!(
struct MyStruct {
name: String,
},
Debug,
Clone,
);
fn main() {
let a = MyStruct { name: "name".to_string() };
println!("{a:?}");
}
将声明式宏公开出去
如果要让我们实作的声明式宏能够在模块之外甚至是 crate 之外被使用的话,必须替其加上 #[macro_export] 属性来暴露(export)。如下:
#[macro_export]
macro_rules! hello {
() => {
println!("Hello!");
};
($target:expr) => {
println!("Hello, {}!", $target);
};
}
如此一来,当外部的 crate 想要引用到我们这个 hello! 宏时,早期的 Rust 版本要在 extern crate 叙述的左方或是上方加上 #[macro_use] 属性或是 #[macro_use(hello)] 属性,前者表示要使用整个 crate 公开出去的宏,后者则表示只需使用 hello! 这个宏(如果要引用多个宏,用逗号隔开)。如下:
#[macro_use]
extern crate example;
fn main() {
hello!();
}
而现在的 Rust 只需要使用一般函数的调用方式来使用宏即可,如下:
use example::hello;
fn main() {
hello!();
}
或是:
fn main() {
example::hello!();
}
用 #[macro_export] 属性公开出去的声明式宏,不管是在哪个模块中被定义与实作的,宏的路径都会直接被放在 crate 下。但如果我们只想让声明式宏在同一个 crate 下公开的话,那就不能够使用 #[macro_export] 属性,而是要使用 use 关键字搭配 pub 关键字来设置权限。
如下:
mod m {
macro_rules! hello {
() => {
println!("Hello!");
};
($target:expr) => {
println!("Hello, {}!", $target);
};
}
pub(crate) use hello;
}
使用 use 关键字来公开没有被加上 #[macro_export] 属性的声明式宏,其最广的权限只能够使用 pub(crate) 来设置。
在声明式宏中使用其它的声明式宏
我们其实已经看过在声明式宏中使用其它的声明式宏的例子了。如下:
macro_rules! hello {
() => {
println!("Hello!");
};
}
所以这样的写法还有什么要注意的吗?
上面这个 hello! 宏之所以能正常使用,是因为 Rust 会自动引用标准函数库的 println! 宏,使我们不需要预先在 extern crate 关键字引入某个 crate 时,使用 #[macro_use] 属性来说明要引用 println! 宏。
换句话说,在不使用路径调用的前提下,在声明式宏中使用其它的声明式宏时,该宏必须要事先被引用至目前的 scope 下。
如果我们在自己实作的声明式宏中,又去调用同样的宏的话,如下:
macro_rules! hello {
() => {
hello!("world");
};
($target:expr) => {
println!("Hello, {}!", $target);
};
}
当 hello! 宏公开于 crate 外时,如果外面的 crate 是在 extern crate 叙述加上 #[macro_use] 属性来引用 hello! 宏,不会有任何问题。但如果没有使用 #[macro_use] 属性,而是用路径的方式来直接使用 xxx::hello!(),那么 hello! 宏里面的 hello!("world"); 叙述会因为不知道 hello! 宏是哪个宏,而编译失败。
例如以下这段程序:
fn main() {
xxx::hello!();
}
在编译时宏会被解开,变成:
fn main() {
hello!("world");
}
以至于编译器不知道 hello! 是什么宏。
用 $crate 关键字来表示宏所在的 crate
一般而言,在公开的声明式宏中用到的不会自动被 Rust 引用的项目,最好都明确地写上其路径,避免使用到这个宏的开发者,还要另外用 use 关键字和 #[macro_use] 属性引用一堆有的没的项目到要调用这个宏的 scope 下。
我们可以在 macro_rules! 宏中利用 $crate 关键字,来表示其所在的 crate。所以,刚才提到的 hello! 宏的例子,最好还是改写成以下这样:
#[macro_export]
macro_rules! hello {
() => {
$crate::hello!("world");
};
($target:expr) => {
println!("Hello, {}!", $target);
};
}
如此一来,外部的 crate 就算不使用 #[macro_use] 属性,也还是可以正常地用路径去调用 hello! 宏。
在公开的声明式宏中使用其它的声明式宏
那如果我们在自己实作的公开的声明式宏中,调用同样也是我们自己实作,但是是不同的宏,又是怎么样的一个状况呢?如下:
macro_rules! hello_inner {
($target:expr) => {
println!("Hello, {}!", $target);
};
}
#[macro_export]
macro_rules! hello {
() => {
$crate::hello_inner!("world");
};
}
虽然我们有把 hello! 宏加上 #[macro_export] 属性,但是 hello_inner! 宏并没有加上,因为我们不想要公开 hello_inner! 宏。可是这样一来,就会导致外部 crate 在调用 hello! 宏的时候无法去调用到 hello_inner! 宏。
为了解决这个问题,我们也还是得去公开 hello_inner! 宏,只不过除了替它加上 #[macro_export] 属性之外,还可以再加上 #[doc(hidden)] 属性,使其不会出现在 API 文档上。如下:
#[doc(hidden)]
#[macro_export]
macro_rules! hello_inner {
($target:expr) => {
println!("Hello, {}!", $target);
};
}
#[macro_export]
macro_rules! hello {
() => {
$crate::hello_inner!("world");
};
}
自动替声明式宏中用到的声明式宏都加上 $crate 关键字
macro_rules! 宏还提供了一个古怪,但是很方便的用法,那就是它可以自动替声明式宏中直接用到(不透过路径)的声明式宏都加上 $crate 关键字。在替我们的宏加上 #[macro_export] 属性时,可以再加上 local_inner_macros 参数,使其变成 #[macro_export(local_inner_macros)]。如下:
#[macro_export(local_inner_macros)]
macro_rules! hello {
() => {
hello!("world");
};
($target:expr) => {
println!("Hello, {}!", $target);
};
}
不过以上程序会编译失败,因为 println! 宏并不在 $crate 下。所以 println! 宏必须要改用路径的方式来调用,如下:
#[macro_export(local_inner_macros)]
macro_rules! hello {
() => {
hello!("world");
};
($target:expr) => {
::std::println!("Hello, {}!", $target);
};
}
进程式宏
进程式宏更像是函数,它允许输入 Rust 的代码,对这个代码做处理来产生出新的代码,不像是声明式宏只能利用型样匹配来透过一些参数和已经写好的代码范本来产生代码。当然,进程式宏的实作方式也会比声明式宏复杂许多。先前我们使用过的 #[derive(Debug)] 就是一种进程式宏的用法。我们可以把任意的特性当作进程式宏来使用,举例来说:
trait HelloWorld {
fn hello_world();
}
#[derive(HelloWorld)]
struct Pineapple;
#[derive(HelloWorld)]
struct Durian;
fn main() {
Pineapple::hello_world();
Durian::hello_world();
}
我们希望以上代码可以输出:
Hello, world! My name is `Durian`.
为了要让 HelloWorld 特性可以作为进程式宏来使用,我们必须将它另外使用一个独立的 crate 来实作。我们可以创建一个名为 hello_world_derive 的函数库项目,接着修改该项目的 Cargo.toml,添加以下内容:
[lib]
proc-macro = true
[dependencies]
syn = { version = "2", features = ["full"] }
quote = "1"
# proc-macro2 = "1"
syn 和 quote 这两个套件可以帮助我们处理 Rust 的代码,等等会用到。syn 的 full 特色建议激活,免得有些还算常用的结构体不能用。
至于 proc_macro2 套件,虽然它是 syn 和 quote 内部使用的套件,但在一些情况下我们会需要直接使用它,稍后会提到。
[lib] 区块中的 proc-macro 设置项目可以设置这个程序项目是否为进程式宏的项目。
接着在 lib.rs 文件中,撰写以下程序:
use proc_macro::TokenStream;
use quote::quote;
use syn::{
parse::{Parse, ParseStream},
parse_macro_input, DeriveInput,
};
#[proc_macro_derive(HelloWorld)]
pub fn hello_world_derive(input: TokenStream) -> TokenStream {
struct MyDeriveInput {
ast: DeriveInput,
}
impl Parse for MyDeriveInput {
fn parse(input: ParseStream) -> Result<Self, syn::Error> {
let ast = input.parse::<DeriveInput>()?;
Ok(MyDeriveInput { ast })
}
}
// Parse the token stream
let derive_input = parse_macro_input!(input as MyDeriveInput);
// Get the identifier of the type.
let name = &derive_input.ast.ident;
// Build the code
let expanded = quote! {
impl HelloWorld for #name {
fn hello_world() {
println!("Hello, world! My name is `{}`.", stringify!(#name));
}
}
};
expanded.into()
}
以上程序是用于 derive 属性的进程式宏的基本代码模板。
proc_macro 这个套件是 Rust 编程语言内置的 crate,它可以将 Rust 的代码转成字符串,这样我就可以撰写程序产生新的 Rust 代码字符串,再交给 proc_macro 将字符串转成 Rust 的代码让 Rust 编译。
syn 套件可以解析 Rust 的代码字符串,将其转换成特定的结构体,方便我们写程序去处理 Rust 的代码。
quote 套件可以接受 syn 套件转出来的结构实体,将其转回 Rust 的代码字符串。
程序第 10 行,proc_macro_derive 这个属性可以在属性的参数定义某个名称,这个名称即为外面在使用时要放入 derive 属性的名称,如果是要实作某个特性,这个名称最好与该特性的名称一样或是改成 -ize(……化)型态。例如我们的这个进程式宏是为了要快速替结构体实作 HelloWorld 特性,所以属性应该要写成 #[proc_macro_derive(HelloWorld)]。被加上 proc_macro_derive 属性的函数即为 Rust 代码的处理程序,这个函数必须要有 pub 权限,而函数名称则可以随意取,自己看得懂就好。
程序第 12 行,我们定义了一个 MyDeriveInput 结构体,它将被用来处理我们要解析的 Rust 代码,并保存之后要产生 Rust 代码的时候需要用到的信息。
程序第 16 行,替 MyDeriveInput 实作 Parse 特性,并在其 parse 函数中撰写解析代码的程序。有了 Parse 特性便可以使用 syn 的 parse_macro_input! 宏将 TokenStream 转成该结构体。
程序第 18 行,将 Rust 的代码转成 DeriveInput 结构实体。
程序第 20 行,将 DeriveInput 结构实体交给 MyDeriveInput 结构实体来保存。
程序第 28 行,取得当前使用了 derive 属性的结构体或是枚举的名称,如果是 Pineapple 结构体使用了 derive 属性,解析出来的名称就会是 Pineapple。
程序第 31 行到第 37 行,利用 quote! 宏,将要产生出来的 Rust 代码写在这个宏的程序叙述区块内。
在 quote! 宏的程序叙述区块中,可以直接使用井字号 # 接上外面的变量名称,就可以用外面的变量名称所保存的值,来取代 quote! 宏的程序叙述区块中的 # 接上变量名称所形成的空格。
程序第 34 行,stringify! 宏是 Rust 编程语言的标准函数库提供的,可以在程序编译阶段直接将 Rust 的表达式直接转成字符串定数,而不会去运行它。
程序第 39 行,利用 quote! 宏回传的实体所提供的 into 方法,来将该实体转为 TokenStream 结构实体。
将 hello_world_derive 函数库项目的程序写好之后,就可以使用我们原本的可运行程序项目来引用啦!改写后的程序如下:
use hello_world_derive::HelloWorld;
trait HelloWorld {
fn hello_world();
}
#[derive(HelloWorld)]
struct Pineapple;
#[derive(HelloWorld)]
struct Durian;
fn main() {
Pineapple::hello_world();
Durian::hello_world();
}
程序在编译阶段时,有用到进程式宏的部份会被展开成:
trait HelloWorld {
fn hello_world();
}
struct Pineapple;
impl HelloWorld for Pineapple {
fn hello_world() {
println!("Hello, world! My name is `{}`.", stringify!(Pineapple));
}
}
struct Durian;
impl HelloWorld for Durian {
fn hello_world() {
println!("Hello, world! My name is `{}`.", stringify!(Durian));
}
}
fn main() {
Pineapple::hello_world();
Durian::hello_world();
}
程序运行结果如下:
Hello, world! My name is `Durian`.
不过如果我们加上 #[derive(HelloWorld)] 属性的结构体或是枚举有用到泛型的话,编译时就会出问题。
例如:
use hello_world_derive::HelloWorld;
trait HelloWorld {
fn hello_world();
}
#[derive(HelloWorld)]
struct Fruit<'a>(&'a str);
fn main() {
Fruit::hello_world();
}
这是因为在 quote! 宏中撰写 impl 区块时,并没有去处理当要实作的结构体或是枚举有泛型的情形。我们可以利用 DeriveInput 结构实体的 generics 字段保存的实体,其提供的 split_for_impl 方法,将泛型的代码转为撰写 impl 区块时会用到的各个部份。程序修改如下:
use proc_macro::TokenStream;
use quote::quote;
use syn::{
parse::{Parse, ParseStream},
parse_macro_input, DeriveInput,
};
#[proc_macro_derive(HelloWorld)]
pub fn hello_world_derive(input: TokenStream) -> TokenStream {
struct MyDeriveInput {
ast: DeriveInput,
}
impl Parse for MyDeriveInput {
fn parse(input: ParseStream) -> Result<Self, syn::Error> {
let ast = input.parse::<DeriveInput>()?;
Ok(MyDeriveInput { ast })
}
}
// Parse the token stream
let derive_input = parse_macro_input!(input as MyDeriveInput);
// Get the identifier of the type.
let name = &derive_input.ast.ident;
let (impl_generics, ty_generics, where_clause) = derive_input.ast.generics.split_for_impl();
// Build the code
let expanded = quote! {
impl #impl_generics HelloWorld for #name #ty_generics #where_clause {
fn hello_world() {
println!("Hello, world! My name is `{}`.", stringify!(#name));
}
}
};
expanded.into()
}
如此一来,#[derive(HelloWorld)] 属性就可以同时支持有泛型或是没泛型的结构体或是枚举。
替属性添加额外的元数据(meta)参数
如果我们想要更进一步的控制 #[derive(HelloWorld)] 属性,可以让其允许从元数据中输入参数。
好比说,我们可以替结构体再加上 #[helloWorld(target = "xxx")] 属性,来控制 hello_world 关联函数印出来的文字为 Hello, xxx!。如下:
use hello_world_derive::HelloWorld;
trait HelloWorld {
fn hello_world();
}
#[derive(HelloWorld)]
#[helloWorld(target = "MagicLen")]
struct Fruit<'a>(&'a str);
fn main() {
Fruit::hello_world();
}
当然,以上程序目前是无法编译的,因为我们还没有实作这个功能嘛!
DeriveInput 结构实体的 attrs 字段可以用来取得该项目用到的所有属性,我们可以针对 helloWorld 这个属性名称(元数据名称)来进行处理。程序改写如下:
use proc_macro::TokenStream;
use quote::quote;
use syn::{
parse::{Parse, ParseStream},
parse_macro_input,
spanned::Spanned,
DeriveInput, Expr, Lit, Meta, MetaNameValue,
};
#[proc_macro_derive(HelloWorld, attributes(helloWorld))]
pub fn hello_world_derive(input: TokenStream) -> TokenStream {
struct MyDeriveInput {
ast: DeriveInput,
target: Option<String>,
}
impl Parse for MyDeriveInput {
fn parse(input: ParseStream) -> Result<Self, syn::Error> {
let ast = input.parse::<DeriveInput>()?;
let mut target: Option<String> = None;
for attr in ast.attrs.iter() {
if attr.path().is_ident("helloWorld") {
match &attr.meta {
Meta::List(list) => {
let named_value: MetaNameValue = list.parse_args()?;
if named_value.path.is_ident("target") {
match named_value.value {
Expr::Lit(lit) => match lit.lit {
Lit::Str(s) => {
target = Some(s.value());
},
lit => {
return Err(syn::Error::new(
lit.span(),
"the value of `target` should be a string literal",
));
},
},
expr => {
return Err(syn::Error::new(
expr.span(),
"the value of `target` should be a string literal",
));
},
}
}
},
meta => {
return Err(syn::Error::new(
meta.span(),
"the `helloWorld` attribute should have a list item",
));
},
}
}
}
Ok(MyDeriveInput { ast, target })
}
}
// Parse the token stream
let derive_input = parse_macro_input!(input as MyDeriveInput);
// Get the identifier of the type.
let name = &derive_input.ast.ident;
let (impl_generics, ty_generics, where_clause) = derive_input.ast.generics.split_for_impl();
// Build the code
let expanded = match derive_input.target {
Some(target) => {
quote! {
impl #impl_generics HelloWorld for #name #ty_generics #where_clause {
fn hello_world() {
println!("Hello, {}! My name is {}.", #target, stringify!(#name));
}
}
}
},
None => {
quote! {
impl #impl_generics HelloWorld for #name #ty_generics #where_clause {
fn hello_world() {
println!("Hello, world! My name is {}.", stringify!(#name));
}
}
}
},
};
expanded.into()
}
proc_macro_derive 这个属性可以在属性的参数定义某个名称,第二个参数则可以再传入 attributes 这个属性,来创建新的属性(在这个程序中创建的新属性即为 helloWorld)。
我们在 MyDeriveInput 结构体添加了一个 target 字段,先去解析 helloWorld 属性是否属于 MetaList,List 代表一个 attribute_name(parameters) 这样可传入多个属性或是定数作为参数的属性。如果 helloWorld 属性是 List 的话再解析它的参数是否为 MetaNameValue,NameValue 代表一个 attribute_name = value 这样的属性。如果参数是 NameValue 的话,就去看它是否为名为 target 的 NameValue 属性,如果是的话就去检查它的值是否为字符串定数。最终即可把抓出的字符串定数存进 target 变量。
在使用 quote! 宏产生 Rust 的代码字符串的时候,先去判断是否有设置 target 参数,有的话就使用它。
在设计进程式宏的时候,应回传 syn::Error 结构实体(如果需要自行使用 syn::Error::new 创建出来,必须传入正确的 Span 结构实体),将错误交给 parse_macro_input! 宏来处理,而不要直接使用 panic! 宏。这样做的目的是要让编译器能够明确地知道发生编译错误的宏位置在哪,以此来增加进程式宏函数库的易用性。
此外,对于没有定义的属性用法,应该全都找出来并回传错误消息,避免应用到我们的宏函数库的开发者不小心用错却全然不知。所以以上的程序,还可以再做如下的加强:
use proc_macro::TokenStream;
use quote::quote;
use syn::{
parse::{Parse, ParseStream},
parse_macro_input,
spanned::Spanned,
DeriveInput, Expr, Lit, Meta, MetaNameValue,
};
#[proc_macro_derive(HelloWorld, attributes(helloWorld))]
pub fn hello_world_derive(input: TokenStream) -> TokenStream {
struct MyDeriveInput {
ast: DeriveInput,
target: Option<String>,
}
impl Parse for MyDeriveInput {
fn parse(input: ParseStream) -> Result<Self, syn::Error> {
let ast = input.parse::<DeriveInput>()?;
let mut target: Option<String> = None;
for attr in ast.attrs.iter() {
if attr.path().is_ident("helloWorld") {
match &attr.meta {
Meta::List(list) => {
let named_value: MetaNameValue = list.parse_args()?;
if named_value.path.is_ident("target") {
match named_value.value {
Expr::Lit(lit) => match lit.lit {
Lit::Str(s) => {
target = Some(s.value());
},
lit => {
return Err(syn::Error::new(
lit.span(),
"the value of `target` should be a string literal",
));
},
},
expr => {
return Err(syn::Error::new(
expr.span(),
"the value of `target` should be a string literal",
));
},
}
} else {
return Err(syn::Error::new(
named_value.span(),
"unknown attribute",
));
}
},
meta => {
return Err(syn::Error::new(
meta.span(),
"the `helloWorld` attribute should have a list item",
));
},
}
}
}
Ok(MyDeriveInput { ast, target })
}
}
// Parse the token stream
let derive_input = parse_macro_input!(input as MyDeriveInput);
// Get the identifier of the type.
let name = &derive_input.ast.ident;
let (impl_generics, ty_generics, where_clause) = derive_input.ast.generics.split_for_impl();
// Build the code
let expanded = match derive_input.target {
Some(target) => {
quote! {
impl #impl_generics HelloWorld for #name #ty_generics #where_clause {
fn hello_world() {
println!("Hello, {}! My name is {}.", #target, stringify!(#name));
}
}
}
},
None => {
quote! {
impl #impl_generics HelloWorld for #name #ty_generics #where_clause {
fn hello_world() {
println!("Hello, world! My name is {}.", stringify!(#name));
}
}
}
},
};
expanded.into()
}
替结构体或是枚举的字段加上属性
接着要把 hello_world 关联函数改为方法来说明。
先看看以下代码:
use proc_macro::TokenStream;
use quote::quote;
use syn::{
parse::{Parse, ParseStream},
parse_macro_input, DeriveInput,
};
#[proc_macro_derive(HelloWorld)]
pub fn hello_world_derive(input: TokenStream) -> TokenStream {
struct MyDeriveInput {
ast: DeriveInput,
}
impl Parse for MyDeriveInput {
fn parse(input: ParseStream) -> Result<Self, syn::Error> {
let ast = input.parse::<DeriveInput>()?;
Ok(MyDeriveInput { ast })
}
}
// Parse the token stream
let derive_input = parse_macro_input!(input as MyDeriveInput);
// Get the identifier of the type.
let name = &derive_input.ast.ident;
let (impl_generics, ty_generics, where_clause) = derive_input.ast.generics.split_for_impl();
// Build the code
let expanded = quote! {
impl #impl_generics HelloWorld for #name #ty_generics #where_clause {
fn hello_world(&self) {
println!("Hello, world! My name is `{}`.", stringify!(#name));
}
}
};
expanded.into()
}
use hello_world_derive::HelloWorld;
trait HelloWorld {
fn hello_world(&self);
}
#[derive(HelloWorld)]
struct Fruit<'a>(&'a str);
fn main() {
let apple = Fruit("apple");
apple.hello_world();
}
我们希望可以替使用了 #[derive(HelloWorld)] 属性的结构体或是枚举的某个字符串字段加上 #[helloWorld(target)] 属性,使该字符串字段可以在调用 hello_world 方法时被显示出来。如下:
use hello_world_derive::HelloWorld;
trait HelloWorld {
fn hello_world(&self);
}
#[derive(HelloWorld)]
struct Fruit<'a>(#[helloWorld(target)] &'a str);
fn main() {
let apple = Fruit("apple");
apple.hello_world();
}
DeriveInput 结构实体的 data 字段可以用来取得结构体或是枚举的主体(它也可以用来取得联合体的主体,不过在本系列文章中并不谈联合体)。程序可先改写如下:
use proc_macro::TokenStream;
use quote::{quote, ToTokens};
use syn::{
parse::{Parse, ParseStream},
parse_macro_input,
spanned::Spanned,
Data, DeriveInput, Fields, Index, Meta, Path,
};
#[proc_macro_derive(HelloWorld, attributes(helloWorld))]
pub fn hello_world_derive(input: TokenStream) -> TokenStream {
enum Target {
Struct(proc_macro2::TokenStream),
}
struct MyDeriveInput {
ast: DeriveInput,
target: Option<Target>,
}
impl Parse for MyDeriveInput {
fn parse(input: ParseStream) -> Result<Self, syn::Error> {
let ast = input.parse::<DeriveInput>()?;
let mut target: Option<Target> = None;
match &ast.data {
Data::Struct(struct_data) => match &struct_data.fields {
Fields::Unnamed(unnamed_fields) => {
for (index, unnamed_field) in unnamed_fields.unnamed.iter().enumerate() {
for attr in unnamed_field.attrs.iter() {
if attr.path().is_ident("helloWorld") {
match &attr.meta {
Meta::List(list) => {
let path: Path = list.parse_args()?;
if path.is_ident("target") {
if target.is_some() {
return Err(syn::Error::new(
path.span(),
"`target` has been set before",
));
}
let field = Index::from(index).into_token_stream();
target = Some(Target::Struct(field));
} else {
return Err(syn::Error::new(
path.span(),
"should only be `target`",
));
}
},
meta => {
return Err(syn::Error::new(
meta.span(),
"the `helloWorld` attribute should have a list item",
));
},
}
}
}
}
},
_ => return Err(syn::Error::new(ast.span(), "unsupported type")),
},
_ => return Err(syn::Error::new(ast.span(), "unsupported type")),
}
Ok(MyDeriveInput { ast, target })
}
}
// Parse the token stream
let derive_input = parse_macro_input!(input as MyDeriveInput);
// Get the identifier of the type.
let name = &derive_input.ast.ident;
let (impl_generics, ty_generics, where_clause) = derive_input.ast.generics.split_for_impl();
// Build the code
let expanded = match derive_input.target {
Some(target) => match target {
Target::Struct(field) => {
quote! {
impl #impl_generics HelloWorld for #name #ty_generics #where_clause {
fn hello_world(&self) {
println!("Hello, {}! My name is {}.", self.#field, stringify!(#name));
}
}
}
},
},
None => {
quote! {
impl #impl_generics HelloWorld for #name #ty_generics #where_clause {
fn hello_world(&self) {
println!("Hello, world! My name is {}.", stringify!(#name));
}
}
}
},
};
expanded.into()
}
利用 match 关键字来做 DeriveInput 结构实体的 data 字段的型样匹配,可针对不同的类型的结构体和枚举创建出不同的 MyDeriveInput 结构实体,以产生出不同的 Rust 代码。
以上程序目前还只支持元组结构体,等等会再加强它,使它支持有字段名称的结构体以及枚举。在继续加强之前,还有一个地方必须要注意,就是在以上程序中,我们有去使用 proc_macro2::TokenStream 来避免需要用太多 syn 提供的结构体来区分代码的类型,所以在 Cargo.toml 的 [dependencies] 区块中要去引用 proc-macro2 这个 crate。
当我们熟悉了以上程序之后,就继续来加强它吧!程序如下:
use std::str::FromStr;
use proc_macro::TokenStream;
use quote::{quote, ToTokens};
use syn::{
parse::{Parse, ParseStream},
parse_macro_input,
spanned::Spanned,
Data, DeriveInput, Fields, Ident, Index, Meta, Path,
};
#[proc_macro_derive(HelloWorld, attributes(helloWorld))]
pub fn hello_world_derive(input: TokenStream) -> TokenStream {
enum Target {
Struct(proc_macro2::TokenStream),
EnumUnnamedFields { variant_ident: Ident, pat_tuple: proc_macro2::TokenStream },
EnumNamedFields { variant_ident: Ident, ident: Ident },
}
struct MyDeriveInput {
ast: DeriveInput,
target: Option<Target>,
}
impl Parse for MyDeriveInput {
fn parse(input: ParseStream) -> Result<Self, syn::Error> {
let ast = input.parse::<DeriveInput>()?;
let mut target: Option<Target> = None;
match &ast.data {
Data::Struct(struct_data) => match &struct_data.fields {
Fields::Unnamed(unnamed_fields) => {
for (index, unnamed_field) in unnamed_fields.unnamed.iter().enumerate() {
for attr in unnamed_field.attrs.iter() {
if attr.path().is_ident("helloWorld") {
match &attr.meta {
Meta::List(list) => {
let path: Path = list.parse_args()?;
if path.is_ident("target") {
if target.is_some() {
return Err(syn::Error::new(
path.span(),
"`target` has been set before",
));
}
let field = Index::from(index).into_token_stream();
target = Some(Target::Struct(field));
} else {
return Err(syn::Error::new(
path.span(),
"should only be `target`",
));
}
},
meta => {
return Err(syn::Error::new(
meta.span(),
"the `helloWorld` attribute should have a list item",
));
},
}
}
}
}
},
Fields::Named(named_fields) => {
for named_field in named_fields.named.iter() {
for attr in named_field.attrs.iter() {
if attr.path().is_ident("helloWorld") {
match &attr.meta {
Meta::List(list) => {
let path: Path = list.parse_args()?;
if path.is_ident("target") {
if target.is_some() {
return Err(syn::Error::new(
path.span(),
"`target` has been set before",
));
}
let field =
named_field.ident.clone().into_token_stream();
target = Some(Target::Struct(field));
} else {
return Err(syn::Error::new(
path.span(),
"should only be `target`",
));
}
},
meta => {
return Err(syn::Error::new(
meta.span(),
"the `helloWorld` attribute should have a list item",
));
},
}
}
}
}
},
Fields::Unit => (),
},
Data::Enum(enum_data) => {
for variant in enum_data.variants.iter() {
for (index, field) in variant.fields.iter().enumerate() {
for attr in field.attrs.iter() {
if attr.path().is_ident("helloWorld") {
match &attr.meta {
Meta::List(list) => {
let path: Path = list.parse_args()?;
if path.is_ident("target") {
if target.is_some() {
return Err(syn::Error::new(
path.span(),
"`target` has been set before",
));
}
let variant_ident = variant.ident.clone();
match field.ident.as_ref() {
Some(ident) => {
target = Some(Target::EnumNamedFields {
variant_ident,
ident: ident.clone(),
});
},
None => {
// to form a pattern tuple like (_, _, _, ..., _, v, ..)
let mut pat_tuple = String::from("(");
for _ in 0..index {
pat_tuple.push_str("_,");
}
pat_tuple.push_str("v,..)");
let pat_tuple =
proc_macro2::TokenStream::from_str(
pat_tuple.as_str(),
)?;
target = Some(Target::EnumUnnamedFields {
variant_ident,
pat_tuple,
});
},
}
} else {
return Err(syn::Error::new(
path.span(),
"should only be `target`",
));
}
},
meta => {
return Err(syn::Error::new(
meta.span(),
"the `helloWorld` attribute should have a list item",
));
},
}
}
}
}
}
},
_ => return Err(syn::Error::new(ast.span(), "unsupported type")),
}
Ok(MyDeriveInput { ast, target })
}
}
// Parse the token stream
let derive_input = parse_macro_input!(input as MyDeriveInput);
// Get the identifier of the type.
let name = &derive_input.ast.ident;
let (impl_generics, ty_generics, where_clause) = derive_input.ast.generics.split_for_impl();
// Build the code
let expanded = match derive_input.target {
Some(target) => match target {
Target::Struct(field) => {
quote! {
impl #impl_generics HelloWorld for #name #ty_generics #where_clause {
fn hello_world(&self) {
println!("Hello, {}! My name is {}.", self.#field, stringify!(#name));
}
}
}
},
Target::EnumUnnamedFields { variant_ident, pat_tuple } => {
quote! {
impl #impl_generics HelloWorld for #name #ty_generics #where_clause {
fn hello_world(&self) {
match self {
#name::#variant_ident #pat_tuple => {
println!("Hello, {}! My name is `{}`.", v, stringify!(#name));
}
_ => unreachable!()
}
}
}
}
},
Target::EnumNamedFields { variant_ident, ident } => {
quote! {
impl #impl_generics HelloWorld for #name #ty_generics #where_clause {
fn hello_world(&self) {
match self {
#name::#variant_ident{#ident, ..} => {
println!("Hello, {}! My name is `{}`.", #ident, stringify!(#name));
}
_ => unreachable!()
}
}
}
}
},
},
None => {
quote! {
impl #impl_generics HelloWorld for #name #ty_generics #where_clause {
fn hello_world(&self) {
println!("Hello, world! My name is {}.", stringify!(#name));
}
}
}
},
};
expanded.into()
}
虽然进程式宏写起来有点费工夫,但就是属于一次功,完成之后就有很方便的进程式宏可以用了!
function-like 进程式宏
进程式宏除了能够用在定义结构体、枚举时使用外,它还可以如声明式宏那样做成用法像是函数的宏。只要将 proc_macro_derive 属性替换成 proc_macro 属性就可以了!举个简单的例子:
use proc_macro::TokenStream;
use quote::quote;
use syn::{parse_macro_input, LitStr};
#[proc_macro]
pub fn hello(input: TokenStream) -> TokenStream {
// Parse the token stream
let input = parse_macro_input!(input as LitStr);
let s = input.value();
let output_sentence = format!("Hello, world! My name is `{s}`.");
// Build the code
let expanded = quote! {
#output_sentence
};
expanded.into()
}
上面这个程序创建了一个进程式宏,宏名称为函数名称,即 hello,它的功能非常近似于:
macro_rules! hello {
($s:literal) => {
concat!("Hello, world! My name is `", $s, "`.")
};
}
concat 是 Rust 内置的宏,可以把输入的任意数量的定数全部串接成字符串定数。
进程式宏 hello 的用法如下:
fn main() {
println!(hello_world_macro::hello!("Pineapple"));
}
如果宏的参数数量固定是 1 个,可以直接像上面的例子这样使用 syn 这个 crate 提供的 parse_macro_input! 宏和 syn 内置的 LitStr 等结构体或是枚举来解析 token。而如果宏的参数数量超过 1 个或是有使用记号的话,最好自行创建一个结构体,并实作 syn::parse::Parse 特性,再搭配 parse_macro_input! 宏来用。
写法如下:
use proc_macro::TokenStream;
use quote::quote;
use syn::{
parse::{Parse, ParseStream},
parse_macro_input, LitStr, Token,
};
#[proc_macro]
pub fn hello(input: TokenStream) -> TokenStream {
struct MyInput {
v: Vec<String>,
}
impl Parse for MyInput {
fn parse(input: ParseStream) -> Result<Self, syn::Error> {
let mut v: Vec<String> = vec![];
loop {
if input.is_empty() {
break;
}
v.push(input.parse::<LitStr>()?.value());
if input.is_empty() {
break;
}
input.parse::<Token!(,)>()?;
}
Ok(MyInput { v })
}
}
// Parse the token stream
let input = parse_macro_input!(input as MyInput);
let output_sentence = format!("Hello, world! List: {:?}.", input.v);
// Build the code
let expanded = quote! {
#output_sentence
};
expanded.into()
}
不然的话,parse_macro_input! 宏要改成如以下的写法,但比较不自由。
use proc_macro::TokenStream;
use quote::quote;
use syn::{parse_macro_input, punctuated::Punctuated, LitStr, Token};
#[proc_macro]
pub fn hello(input: TokenStream) -> TokenStream {
// Parse the token stream
let input = parse_macro_input!(input with Punctuated::<LitStr, Token![,]>::parse_terminated);
let output_sentence = format!(
"Hello, world! List: {:?}.",
input.into_iter().map(|s| s.value()).collect::<Vec<String>>()
);
// Build the code
let expanded = quote! {
#output_sentence
};
expanded.into()
}
用于 derive 属性外的进程式宏
上面介绍的用于属性的进程式宏必须要搭配 derive 属性一起使用,但其实我们也可以创建出独立于 derive 属性的属性,可以被用在任何的项目上,不限于结构体、枚举和联合体,只是这种进程式宏比较少会需要自己制作,通常是自行开发框架(framework)才会需要。它的撰写方式如下:
use std::str::FromStr;
use proc_macro::TokenStream;
use quote::quote;
use syn::{
parse::{Parse, ParseStream},
parse_macro_input, Ident, ItemFn,
};
#[proc_macro_attribute]
pub fn hello(attr: TokenStream, item: TokenStream) -> TokenStream {
struct MyAttrInput {
uppercase: bool,
}
impl Parse for MyAttrInput {
fn parse(input: ParseStream) -> Result<Self, syn::Error> {
let mut uppercase = false;
if !input.is_empty() {
let ident = input.parse::<Ident>()?;
if ident == "uppercase" {
uppercase = true;
} else {
return Err(syn::Error::new(input.span(), "should use `uppercase`"));
}
}
Ok(MyAttrInput { uppercase })
}
}
// backup the item token stream
let item2: proc_macro2::TokenStream = item.clone().into();
// Parse the attr token stream
let attr_input = parse_macro_input!(attr as MyAttrInput);
// Parse the item token stream
let fn_input = parse_macro_input!(item as ItemFn);
let mut name = fn_input.sig.ident.to_string();
let hello_ident =
proc_macro2::TokenStream::from_str(format!("{}_hello", name).as_str()).unwrap();
if attr_input.uppercase {
name = name.to_uppercase();
}
let expanded = quote! {
fn #hello_ident() {
println!("Hello {}!", #name);
}
#item2
};
expanded.into()
}
以上程序创建了一个 hello 属性,可以作用在函数上,加上后会自动实作出一个名为 函数名称_hello 的函数,这个新函数可以印出 Hello 消息。hello 属性也可以在第一个参数传入 uppercase,来让印出的消息中的函数名称变成大写。
这个 hello 属性的用法如下:
use hello_world_attribute::hello;
#[hello(uppercase)]
fn main() {
main_hello();
}
以上程序的运行结果如下:
结论
Rust 的宏功能十分强大,可以替我们省下不少撰写相同或是相似的程序的时间。虽然会大大地增加代码的复杂度,但是如果有提供良好的文档的话,用到这些宏的开发者们即便完全不知道这些宏背后到底是怎么实作的也没关系。在 Rust 生态圈中,许多框架都会应用强大的宏功能,有兴趣想要更加熟悉用大量宏来开发程序的这种风格的话,可以自行到 crates.io 上翻翻看。
下一章节,我们要来学习 Rust 编程语言的不安全设计方式!
下一章:不安全的 Rust。
