1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
use syn::{
parenthesized,
parse::{Parse, ParseStream},
punctuated::Punctuated,
token, Attribute, Error, Ident, LitInt, Result, Token,
};
mod kw {
syn::custom_keyword!(opcode);
syn::custom_keyword!(subopcode);
syn::custom_keyword!(operands);
}
#[derive(Clone)]
pub struct Attrs<'a> {
pub insn: Vec<InsnAttr<'a>>,
}
impl<'a> Attrs<'a> {
pub fn get(input: &'a [Attribute]) -> Result<Attrs<'a>> {
let mut attrs = Attrs { insn: Vec::new() };
for attr in input {
if attr.path.is_ident("insn") {
parse_insn_attr(&mut attrs, attr)?;
}
}
Ok(attrs)
}
}
#[derive(Clone)]
pub struct InsnAttr<'a> {
pub original: &'a Attribute,
pub opcode: Option<u8>,
pub subopcode: Option<u8>,
pub operands: Option<Vec<Ident>>,
}
fn parse_insn_attr<'a>(attrs: &mut Attrs<'a>, attr: &'a Attribute) -> Result<()> {
attrs.insn.push(InsnAttr {
original: attr,
opcode: None,
subopcode: None,
operands: None,
});
let insn = attrs.insn.last_mut().unwrap();
attr.parse_args_with(|input: ParseStream| {
let mut first = true;
while !input.is_empty() {
if !first {
input.parse::<Token![,]>()?;
}
let look = input.lookahead1();
if look.peek(kw::opcode) {
if insn.opcode.is_some() {
return Err(Error::new_spanned(
attr,
"duplicate #[insn(opcode)] attribute found",
));
}
let AttrWrapper::<kw::opcode, LitInt> { value, .. } = input.parse()?;
insn.opcode = Some(value.base10_parse()?);
} else if look.peek(kw::subopcode) {
if insn.subopcode.is_some() {
return Err(Error::new_spanned(
attr,
"duplicate #[insn(subopcode)] attribute found",
));
}
let AttrWrapper::<kw::subopcode, LitInt> { value, .. } = input.parse()?;
insn.subopcode = Some(value.base10_parse()?);
} else if look.peek(kw::operands) {
if insn.operands.is_some() {
return Err(Error::new_spanned(
attr,
"duplicate #[insn(operands)] attribute found",
));
}
input.parse::<kw::operands>()?;
let content;
parenthesized!(content in input);
let value: Punctuated<Ident, Token![,]> = content.parse_terminated(Ident::parse)?;
insn.operands = Some(value.into_iter().collect());
} else {
return Err(look.error());
}
first = false;
}
Ok(())
})
}
#[allow(unused)]
struct AttrWrapper<K: Parse, V: Parse> {
pub ident: K,
pub value: V,
}
impl<K: Parse, V: Parse> Parse for AttrWrapper<K, V> {
fn parse(input: ParseStream) -> Result<Self> {
let ident = input.parse()?;
let value = if input.peek(token::Paren) {
let value;
parenthesized!(value in input);
value.parse()?
} else {
input.parse::<Token![=]>()?;
input.parse()?
};
Ok(AttrWrapper { ident, value })
}
}