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
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
#![recursion_limit="2048"]
extern crate proc_macro;
extern crate syn;
#[macro_use]
extern crate quote;
use syn::{Body, Ident, MacroInput, Variant};
use quote::Tokens;
use proc_macro::TokenStream;

#[proc_macro_derive(EnumFlags, attributes(EnumFlags))]
pub fn derive_enum_flags(input: TokenStream) -> TokenStream {
    let input = input.to_string();
    let ast = syn::parse_macro_input(&input).unwrap();

    let quote_tokens = match ast.body {
        Body::Enum(ref data) => gen_enumflags(&ast.ident, &ast, data),
        _ => panic!("`derive(EnumFlags)` may only be applied to enums"),
    };

    // println!("{:?}", quote_tokens);
    quote_tokens.parse().unwrap()
}

fn max_value_of(ty: &str) -> Option<usize> {
    match ty {
        "u8" => Some(u8::max_value() as usize),
        "u16" => Some(u16::max_value() as usize),
        "u32" => Some(u32::max_value() as usize),
        "u64" => Some(u64::max_value() as usize),
        _ => None,
    }
}

fn gen_enumflags(ident: &Ident, item: &MacroInput, data: &Vec<Variant>) -> Tokens {
    let variants: Vec<_> = data.iter().map(|v| v.ident.clone()).collect();
    let variants_ref = &variants;
    let flag_values: Vec<_> = data.iter()
        .filter_map(|v| {
            if let Some(syn::ConstExpr::Lit(syn::Lit::Int(flag, _))) = v.discriminant {
                Some(flag)
            } else {
                None
            }
        })
        .collect();
    let flag_values_ref1 = &flag_values;
    let flag_value_names: &Vec<_> =
        &flag_values.iter().map(|val| Ident::new(format!("{}", val))).collect();
    let names: Vec<_> = flag_values.iter().map(|_| ident.clone()).collect();
    let names_ref = &names;
    assert!(variants.len() == flag_values.len(),
            "At least one variant was not initialized explicity with a value.");
    let ty_attr = item.attrs
        .iter()
        .filter_map(|a| {
            if let syn::MetaItem::List(ref ident, ref items) = a.value {
                if ident.as_ref() == "repr" {
                    return items.iter().filter_map(|mi| {
                        if let &syn::NestedMetaItem::MetaItem(syn::MetaItem::Word(ref ident)) = mi {
                                return Some(Ident::new(ident.clone()));
                        }
                        None
                    }).nth(0);
                }
            }
            None
        })
        .nth(0);
    let ty = ty_attr.unwrap_or(Ident::new("usize"));
    let max_flag_value = flag_values.iter().max().unwrap();
    let max_allowed_value = max_value_of(ty.as_ref()).expect(&format!("{} is not supported", ty));
    assert!(*max_flag_value as usize <= max_allowed_value,
            format!("Value '0b{val:b}' is too big for an {ty}",
                    val = max_flag_value,
                    ty = ty));
    let wrong_flag_values: &Vec<_> = &flag_values.iter()
        .enumerate()
        .map(|(i, &val)| {
            (i,
             flag_values.iter().enumerate().fold(0u32, |acc, (other_i, &other_val)| {
                if other_i == i || other_val > 0 && other_val & val == 0 {
                    acc
                } else {
                    acc + 1
                }
            }))
        })
        .filter(|&(_, count)| count > 0)
        .map(|(index, _)| {
            format!("{name}::{variant} = 0b{value:b}",
                    name = ident,
                    variant = variants_ref[index],
                    value = flag_values[index])
        })
        .collect();
    assert!(wrong_flag_values.len() == 0,
            format!("The following flags are not unique: {data:?}",
                     data = wrong_flag_values));
    let inner_name = Ident::new(format!("Inner{}", ident));
    quote!{
        #[derive(Copy, Clone, Eq, PartialEq, Hash)]
        pub struct #inner_name(#ty);

        impl ::std::ops::BitOr for #inner_name{
            type Output = Self;
            fn bitor(self, other: Self) -> Self{
                #inner_name(self.0 | other.0)
            }
        }

        impl ::std::ops::BitAnd for #inner_name{
            type Output = Self;
            fn bitand(self, other: Self) -> Self{
                #inner_name(self.0 & other.0)
            }
        }

        impl ::std::ops::BitXor for #inner_name{
            type Output = Self;
            fn bitxor(self, other: Self) -> Self{
                #inner_name(self.0 ^ other.0)
            }
        }

        impl ::std::ops::Not for #inner_name{
            type Output = Self;
            fn not(self) -> Self{
                #inner_name(!self.0)
            }
        }

        impl ::enumflags::InnerBitFlags for #inner_name{
            type Type = #ty;
            fn all() -> Self {
               let val = (#(#flag_values_ref1)|*) as #ty;
               #inner_name(val)
            }

            fn empty() -> Self {
                #inner_name(0)
            }

            fn is_empty(self) -> bool {
                self == Self::empty()
            }

            fn is_all(self) -> bool {
                self == Self::all()
            }

            fn bits(self) -> Self::Type {
                self.0
            }

            fn intersects(self, other: Self) -> bool{
                (self & other).0 > 0
            }

            fn contains(self, other: Self) -> bool{
                (self & other) == other
            }

            fn not(self) -> Self {
                #inner_name(!self.0)
            }

            fn from_bits(bits: #ty) -> Option<Self> {
                println!("{:?}", #inner_name(bits) & Self::all().not());
                if #inner_name(bits) & Self::all().not() == Self::empty(){
                    Some(#inner_name(bits))
                }
                else{
                    None
                }
            }

            fn from_bits_truncate(bits: #ty) -> Self {
                #inner_name(bits) & Self::all()
            }

            fn insert(&mut self, other: Self){
                let new_val = *self | other;
                *self = new_val;
            }

            fn remove(&mut self, other: Self){
                let new_val = *self | other.not();
                *self = new_val;
            }

            fn toggle(&mut self, other: Self){
                let new_val = *self ^ other;
                *self = new_val;
            }
        }

        impl Into<#ty> for #inner_name{
            fn into(self) -> #ty{
                self.0 as #ty
            }
        }

        impl Into<#inner_name> for #ident{
            fn into(self) -> #inner_name{
                #inner_name(self.into())
            }
        }

        impl Into<#ty> for #ident{
            fn into(self) -> #ty{
                self as #ty
            }
        }

        impl Into<::enumflags::BitFlags<#ident>> for #inner_name{
            fn into(self) -> ::enumflags::BitFlags<#ident> {
                unsafe{ ::enumflags::BitFlags::new(self)}
            }
        }

        impl ::std::fmt::Debug for #inner_name{
            fn fmt(&self, fmt: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
                let v: Vec<_> = #flag_values_ref1.iter().filter_map(|val|{
                    let val: #ty = *val as #ty & self.0;
                    match val {
                        #(#flag_value_names => Some(#names_ref :: #variants_ref),)*
                        _ => None
                    }
                }).collect();
                fmt.write_str(&format!("0b{:b}, Flags::", self.0))?;
                fmt.debug_list().entries(v.iter()).finish()
            }
        }

        impl #ident{
           pub fn from_bitflag(bitflag: ::enumflags::BitFlags<#ident>) -> Vec<#ident> {
               #flag_values_ref1.iter().filter_map(|val|{
                   let val = *val as #ty & bitflag.bits();
                   match val {
                       #(#flag_value_names => Some(#names_ref :: #variants_ref),)*
                       _ => None
                   }
               }).collect()
           }

           pub fn max_bitflag() -> ::enumflags::BitFlags<#ident> {
               let val = (#(#flag_values_ref1)|*) as #ty;
               unsafe{ ::enumflags::BitFlags::new(#inner_name(val)) }
           }

           pub fn empty_bitflag() -> ::enumflags::BitFlags<#ident>{
               unsafe{ ::enumflags::BitFlags::new(#inner_name(0)) }
           }
        }

        impl From<#ident> for ::enumflags::BitFlags<#ident> {
            fn from(t: #ident) -> Self {
                unsafe { ::enumflags::BitFlags::new(t.into()) }
            }
        }

        impl ::std::ops::BitOr for #ident {
            type Output = ::enumflags::BitFlags<#ident>;
            fn bitor(self, other: Self) -> Self::Output {
                let l: #inner_name = self.into();
                let r: #inner_name = other.into();
                (l | r).into()
            }
        }

        impl ::std::ops::BitAnd for #ident {
            type Output = ::enumflags::BitFlags<#ident>;
            fn bitand(self, other: Self) -> Self::Output {
                let l: #inner_name = self.into();
                let r: #inner_name = other.into();
                (l & r).into()
            }
        }

        impl ::std::ops::BitXor for #ident {
            type Output = ::enumflags::BitFlags<#ident>;
            fn bitxor(self, other: Self) -> Self::Output {
                let l: #inner_name = self.into();
                let r: #inner_name = other.into();
                (l ^ r).into()
            }
        }

        impl ::std::ops::Not for #ident {
            type Output = ::enumflags::BitFlags<#ident>;
            fn not(self) -> Self::Output {
                let r: #inner_name = self.into();
                (!r).into()
            }
        }

        impl ::enumflags::EnumFlagSize for #ident {
            type Size = #inner_name;
        }
    }
}