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
130
131
132
133
134
135
136
137
138
139
use proc_macro2::TokenStream;
use syn;
use syn::parse::{Parse, ParseStream, Parser, Result as ParseResult};
#[derive(Debug)]
pub struct Bitflags {
attrs: Vec<syn::Attribute>,
vis: syn::Visibility,
struct_token: Token![struct],
name: syn::Ident,
colon_token: Token![:],
repr: syn::Type,
flags: Flags,
}
impl Bitflags {
pub fn expand(&self) -> (syn::ItemStruct, syn::ItemImpl) {
let Bitflags {
ref attrs,
ref vis,
ref name,
ref repr,
ref flags,
..
} = *self;
let struct_ = parse_quote! {
#(#attrs)*
#vis struct #name {
bits: #repr,
}
};
let consts = flags.expand(name);
let impl_ = parse_quote! {
impl #name {
#consts
}
};
(struct_, impl_)
}
}
impl Parse for Bitflags {
fn parse(input: ParseStream) -> ParseResult<Self> {
Ok(Self {
attrs: input.call(syn::Attribute::parse_outer)?,
vis: input.parse()?,
struct_token: input.parse()?,
name: input.parse()?,
colon_token: input.parse()?,
repr: input.parse()?,
flags: input.parse()?,
})
}
}
#[derive(Debug)]
struct Flag {
attrs: Vec<syn::Attribute>,
const_token: Token![const],
name: syn::Ident,
equals_token: Token![=],
value: syn::Expr,
semicolon_token: Token![;],
}
impl Flag {
fn expand(&self, struct_name: &syn::Ident) -> TokenStream {
let Flag {
ref attrs,
ref name,
ref value,
..
} = *self;
quote! {
#(#attrs)*
pub const #name : #struct_name = #struct_name { bits: #value };
}
}
}
impl Parse for Flag {
fn parse(input: ParseStream) -> ParseResult<Self> {
Ok(Self {
attrs: input.call(syn::Attribute::parse_outer)?,
const_token: input.parse()?,
name: input.parse()?,
equals_token: input.parse()?,
value: input.parse()?,
semicolon_token: input.parse()?,
})
}
}
#[derive(Debug)]
struct Flags(Vec<Flag>);
impl Parse for Flags {
fn parse(input: ParseStream) -> ParseResult<Self> {
let content;
let _ = braced!(content in input);
let mut flags = vec![];
while !content.is_empty() {
flags.push(content.parse()?);
}
Ok(Flags(flags))
}
}
impl Flags {
fn expand(&self, struct_name: &syn::Ident) -> TokenStream {
let mut ts = quote! {};
for flag in &self.0 {
ts.extend(flag.expand(struct_name));
}
ts
}
}
pub fn parse(tokens: TokenStream) -> ParseResult<Bitflags> {
let parser = Bitflags::parse;
parser.parse2(tokens)
}