我正在写一个玩具虚拟机,我需要在其中解码指令。我有一个 Instruction
特性,有一些方法和具体指令实现了这个特性。另外,我有一个解码函数,它只接受一个字节并匹配它以返回与给定字节对应的特定指令。
pub struct FirstInstruction { ... }
pub struct SecondInstruction { ... }
pub struct ThirdInstruction { ... }
pub fn decode(byte: u8) -> Box<dyn Instruction> {
match byte {
0x1 => Box::new(FirstInstruction::new()),
0x2 => Box::new(SecondInstruction::new()),
0x3 => Box::new(ThirdInstruction::new()),
}
}
我想知道如何编写一个允许我自动生成解码函数的程序宏。同时,它将在其参数中获取匹配的字节,如下所示:
#[instruction(0x1)]
pub struct FirstInstruction { ... }
#[instruction(0x2)]
pub struct SecondInstruction { ... }
#[instruction(0x3)]
pub struct ThirdInstruction { ... }
pub fn decode(byte: u8) -> Box<dyn Instruction> {
// Autogenerated
}
我明白,从实际的角度来看,这整件事可能毫无用处。我只是好奇如何使用宏来实现它,如果可能的话。
我试图阅读有关如何编写过程宏的信息,但我不明白如何积累有关具有特定属性的所有结构的信息,然后生成一个全新的函数。