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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
#![recursion_limit="512"]

#[macro_use]
extern crate quote;
extern crate proc_macro;
extern crate syn;

use proc_macro::TokenStream;
use syn::{Body, Lit, MetaItem, NestedMetaItem, Ty};
use quote::Ident as Ident;

#[proc_macro_derive(BitCollection, attributes(bit))]
pub fn bit_collection(input: TokenStream) -> TokenStream {
    let ast = syn::parse_derive_input(&input.to_string()).unwrap();
    impl_bit_collection(&ast).parse().unwrap()
}

fn impl_bit_collection(ast: &syn::DeriveInput) -> quote::Tokens {
    let std: Ident = if cfg!(feature = "std") {
        "std".into()
    } else {
        "core".into()
    };

    let bit_list = ast.attrs.iter().filter_map(|a| {
        if let MetaItem::List(ref ident, ref vec) = a.value {
            if ident.as_ref() == "bit" {
                return Some(vec);
            }
        }
        None
    }).next().expect("No `bit` attribute found.");

    let item = bit_list.iter().filter_map(|x| {
        if let NestedMetaItem::MetaItem(MetaItem::Word(ref ident)) = *x {
            Some(Ident::from(ident.as_ref()))
        } else {
            None
        }
    }).next().expect("No bit item found.");

    let get_attr = |x: &str| {
        bit_list.iter().filter_map(|a| {
            if let NestedMetaItem::MetaItem(MetaItem::NameValue(ref ident, ref val)) = *a {
                if ident == x {
                    if let Lit::Str(ref s, _) = *val {
                        return Some(Ident::from(s.as_ref()))
                    }
                }
            }
            None
        }).next()
    };

    let zero = ::syn::Ident::new("0");
    let name = Ident::from(ast.ident.as_ref());
    let mask = get_attr("mask").unwrap_or_else(|| "!0".into());
    let iter = get_attr("iter").unwrap_or_else(|| "BitIter".into());
    let backing: Ident;

    let (bits, from_x, from_x_masked, full, empty) = if let Body::Struct(ref data) = ast.body {
        let field = data.fields().get(0).expect("No fields found.");

        // Extract inner type that may be surrounded by parentheses
        let extract_ty = || {
            let mut ty = &field.ty;
            loop {
                match *ty {
                    Ty::Paren(ref b) => ty = &b,
                    Ty::Path(_, ref p) => return p,
                    _ => panic!("Incompatible type: {:?}", ty),
                }
            }
        };
        backing = extract_ty()
            .segments.get(0).expect("No backing type found.")
            .ident.as_ref().into();

        let masked_x = quote!(x & #mask);

        if let Some(ref bits) = field.ident {
            let from        = quote!(#name{#bits: x});
            let from_masked = quote!(#name{#bits: #masked_x});
            let full        = quote!(#name{#bits: #mask});
            let empty       = quote!(#name{#bits: 0});
            (bits, from, from_masked, full, empty)
        } else {
            (
                &zero,
                quote!(#name(x)),
                quote!(#name(#masked_x)),
                quote!(#name(#mask)),
                quote!(#name(0))
            )
        }
    } else {
        panic!("Expected struct type.");
    };

    let item_from_raw = quote! {
        // Endian agnostic code integer to item conversion
        use #std::mem::transmute_copy;
        match ::#std::mem::size_of::<#item>() {
            1 => transmute_copy(&(raw as u8)),
            2 => transmute_copy(&(raw as u16)),
            4 => transmute_copy(&(raw as u32)),
            8 => transmute_copy(&(raw as u64)),
            _ => unreachable!(),
        }
    };

    let convert_x = if let Some(retr) = get_attr("retr") {
        quote!(x.#retr)
    } else {
        quote!(x as #backing)
    };

    quote! {
        impl From<#item> for #name {
            #[inline(always)]
            fn from(x: #item) -> #name {
                const ONE: #backing = 1;
                let x = ONE << #convert_x;
                #from_x
            }
        }

        impl From<#iter<#name>> for #name {
            #[inline(always)]
            fn from(iter: #iter<#name>) -> #name {
                iter.0
            }
        }

        impl From<#backing> for #name {
            #[inline(always)]
            fn from(x: #backing) -> #name {
                #from_x_masked
            }
        }

        impl<'a, T: Clone + Into<#name>> From<&'a T> for #name {
            #[inline]
            fn from(r: &'a T) -> #name {
                r.clone().into()
            }
        }

        impl<'a, T: Clone + Into<#name>> From<&'a mut T> for #name {
            #[inline]
            fn from(r: &'a mut T) -> #name {
                r.clone().into()
            }
        }

        impl<T: Into<#name>> ::#std::ops::BitAnd<T> for #name {
            type Output = Self;

            #[inline]
            fn bitand(self, rhs: T) -> Self {
                let x = self.#bits.bitand(rhs.into().#bits);
                #from_x
            }
        }

        impl<T: Into<#name>> ::#std::ops::BitAndAssign<T> for #name {
            #[inline]
            fn bitand_assign(&mut self, rhs: T) {
                self.#bits.bitand_assign(rhs.into().#bits);
            }
        }

        impl<T: Into<#name>> ::#std::ops::BitOr<T> for #name {
            type Output = Self;

            #[inline]
            fn bitor(self, rhs: T) -> Self {
                let x = self.#bits.bitor(rhs.into().#bits);
                #from_x
            }
        }

        impl<T: Into<#name>> ::#std::ops::BitOrAssign<T> for #name {
            #[inline]
            fn bitor_assign(&mut self, rhs: T) {
                self.#bits.bitor_assign(rhs.into().#bits);
            }
        }

        impl<T: Into<#name>> ::#std::ops::BitXor<T> for #name {
            type Output = Self;

            #[inline]
            fn bitxor(self, rhs: T) -> Self {
                let x = self.#bits.bitxor(rhs.into().#bits);
                #from_x
            }
        }

        impl<T: Into<#name>> ::#std::ops::BitXorAssign<T> for #name {
            #[inline]
            fn bitxor_assign(&mut self, rhs: T) {
                self.#bits.bitxor_assign(rhs.into().#bits);
            }
        }

        impl<T: Into<#name>> ::#std::ops::Sub<T> for #name {
            type Output = Self;

            #[inline]
            fn sub(self, rhs: T) -> Self {
                let x = self.#bits & !rhs.into().#bits;
                #from_x
            }
        }

        impl<T: Into<#name>> ::#std::ops::SubAssign<T> for #name {
            #[inline]
            fn sub_assign(&mut self, rhs: T) {
                self.#bits &= !rhs.into().#bits;
            }
        }

        impl ::#std::ops::Not for #name {
            type Output = Self;

            #[inline]
            fn not(self) -> Self {
                (!self.#bits).into()
            }
        }

        impl<T: Into<#name>> ::#std::iter::FromIterator<T> for #name {
            #[inline]
            fn from_iter<I: IntoIterator<Item=T>>(iter: I) -> Self {
                iter.into_iter().fold(Self::EMPTY, BitCollection::inserting)
            }
        }

        impl<T: Into<#name>> Extend<T> for #name {
            #[inline]
            fn extend<I: IntoIterator<Item=T>>(&mut self, iter: I) {
                use #std::iter::FromIterator;
                self.insert(Self::from_iter(iter));
            }
        }

        impl IntoIterator for #name {
            type IntoIter = #iter<Self>;
            type Item = #item;

            #[inline]
            fn into_iter(self) -> Self::IntoIter {
                self.into()
            }
        }

        impl BitCollection for #name {
            const FULL: Self = #full;

            const EMPTY: Self = #empty;

            #[inline]
            fn len(&self) -> usize {
                self.#bits.count_ones() as _
            }

            #[inline]
            fn is_empty(&self) -> bool {
                self.#bits == 0
            }

            #[inline]
            fn has_multiple(&self) -> bool {
                self.#bits & self.#bits.wrapping_sub(1) != 0
            }

            #[inline]
            unsafe fn lsb_unchecked(&self) -> #item {
                let raw = self.#bits.trailing_zeros();
                #item_from_raw
            }

            #[inline]
            unsafe fn msb_unchecked(&self) -> #item {
                use #std::mem::size_of;
                let val = size_of::<#name>() * 8 - 1;
                let raw = val ^ self.#bits.leading_zeros() as usize;
                #item_from_raw
            }

            #[inline]
            fn remove_lsb(&mut self) {
                self.#bits &= self.#bits.wrapping_sub(1);
            }

            #[inline]
            fn remove_msb(&mut self) {
                self.pop_msb();
            }

            #[inline]
            fn pop_lsb(&mut self) -> Option<Self::Item> {
                self.lsb().map(|x| {
                    self.remove_lsb();
                    x
                })
            }

            #[inline]
            fn pop_msb(&mut self) -> Option<#item> {
                self.msb().map(|x| {
                    self.#bits ^= #name::from(x).#bits;
                    x
                })
            }

            #[inline]
            fn contains<T: Into<Self>>(&self, x: T) -> bool {
                let other = x.into().#bits;
                self.#bits & other == other
            }
        }
    }
}