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
// Note(Lokathor): this extern crate is necessary even in 2018 for whatever
// reason that I'm sure is stupid.
extern crate proc_macro;

use core::str::FromStr;
use proc_macro::TokenStream;
use proc_macro2::Span;
use quote::quote;
use syn::{
  parse::{Parse, ParseStream, Result},
  parse_macro_input,
  spanned::Spanned,
  Attribute, Error, Ident, LitInt, Token, Type, TypePath,
};

// Phantom Fields

enum PhantomEntry {
  Enum {
    attributes: Vec<Attribute>,
    name: String,
    start: u64,
    end: u64,
    enum_type: Ident,
    variant_list: Vec<String>,
  },
  Integer {
    attributes: Vec<Attribute>,
    name: String,
    start: u64,
    end: u64,
  },
  Bool {
    attributes: Vec<Attribute>,
    name: String,
    bit: u64,
  },
}

struct PhantomFields {
  self_member_type: Type,
  entries: Vec<PhantomEntry>,
}

impl Parse for PhantomFields {
  fn parse(input: ParseStream) -> Result<Self> {
    let _ = input.parse::<Token![self]>()?;
    let _ = input.parse::<Token![.]>()?;
    let lit = input.parse::<LitInt>()?;
    if lit.value() != 0 {
      return Err(Error::new(lit.span(), "Currently only self.0 is supported"));
    }
    let _ = input.parse::<Token![:]>()?;
    let self_member_type: Type = {
      let tp = input.parse::<TypePath>()?;
      let tp_end_string = match tp.path.segments.last().expect("no type given") {
        syn::punctuated::Pair::Punctuated(path_segment, _colon2) => path_segment.ident.to_string(),
        syn::punctuated::Pair::End(path_segment) => path_segment.ident.to_string(),
      };
      match tp_end_string.as_ref() {
        "u8" | "i8" | "u16" | "i16" | "u32" | "i32" | "usize" | "isize" | "u64" | "i64" => Type::Path(tp),
        _ => {
          return Err(Error::new(tp.span(), format!("Unsupported target type: {:?}", tp_end_string)));
        }
      }
    };
    let _ = input.parse::<Token![,]>()?;
    //
    let mut entries: Vec<PhantomEntry> = vec![];
    'entry_loop: loop {
      if input.is_empty() {
        break;
      }
      let attributes = input.call(Attribute::parse_outer)?;
      let name = input.parse::<Ident>()?.to_string();
      let _ = input.parse::<Token![:]>()?;
      let start = input.parse::<LitInt>()?.value();
      let lookahead = input.lookahead1();
      if lookahead.peek(Token![,]) {
        // bool entry
        entries.push(PhantomEntry::Bool {
          attributes,
          name,
          bit: start,
        });
        let _ = input.parse::<Token![,]>()?;
        continue 'entry_loop;
      } else if lookahead.peek(Token![-]) {
        // spanning entry
        let _ = input.parse::<Token![-]>()?;
        let end = input.parse::<LitInt>()?.value();
        let lookahead = input.lookahead1();
        if lookahead.peek(Token![=]) {
          // enum span
          let _ = input.parse::<Token![=]>()?;
          let enum_type = input.parse::<Ident>()?;
          let mut variant_list = vec![];
          let _ = input.parse::<Token![<]>()?;
          'variant_gather_loop: loop {
            variant_list.push(input.parse::<Ident>()?.to_string());
            let lookahead = input.lookahead1();
            if lookahead.peek(Token![>]) {
              // end of list
              let _ = input.parse::<Token![>]>()?;
              break 'variant_gather_loop;
            } else if lookahead.peek(Token![,]) {
              // more to gather
              let _ = input.parse::<Token![,]>()?;
              continue 'variant_gather_loop;
            } else {
              return Err(lookahead.error());
            }
          }
          entries.push(PhantomEntry::Enum {
            attributes,
            name,
            start,
            end,
            enum_type,
            variant_list,
          });
          let _ = input.parse::<Token![,]>()?;
          continue 'entry_loop;
        } else if lookahead.peek(Token![,]) {
          // int span
          entries.push(PhantomEntry::Integer {
            attributes,
            name,
            start,
            end,
          });
          let _ = input.parse::<Token![,]>()?;
          continue 'entry_loop;
        } else {
          return Err(lookahead.error());
        }
      } else {
        return Err(lookahead.error());
      }
    }
    Ok(PhantomFields { self_member_type, entries })
  }
}

#[proc_macro]
pub fn phantom_fields(input: TokenStream) -> TokenStream {
  let PhantomFields { self_member_type, entries } = parse_macro_input!(input as PhantomFields);

  let mut out_text = String::new();

  for entry in entries.into_iter() {
    match entry {
      PhantomEntry::Enum {
        attributes,
        name,
        start,
        end,
        enum_type,
        variant_list,
      } => {
        for attribute in attributes.into_iter() {
          out_text.push_str(&format!("{}\n", TokenStream::from(quote! { #attribute })));
        }
        let mask_name = Ident::new(&format!("{}_MASK", name.to_uppercase()), Span::call_site());
        let read_name = Ident::new(&name.clone(), Span::call_site());
        let with_name = Ident::new(&format!("with_{}", name), Span::call_site());
        let width = (end - start) + 1;
        out_text.push_str(&format!(
          "{}\n",
          TokenStream::from(quote! {
            #[allow(clippy::identity_op)]
            pub const #mask_name: #self_member_type = ((1<<(#width))-1) << #start;

            #[allow(missing_docs)]
            pub fn #read_name(self) -> #enum_type
          })
        ));
        out_text.push('{');
        out_text.push_str(&format!(
          "{}\n",
          TokenStream::from(quote! {
            match (self.0 & Self::#mask_name) >> #start
          })
        ));
        out_text.push('{');
        let enum_type_string = enum_type.to_string();
        for (i, variant) in variant_list.iter().enumerate() {
          out_text.push_str(&format!("{} => {}::{},\n", i, enum_type_string, variant));
        }
        if variant_list.len() == (1 << (width - 1)) {
          out_text.push_str("_ => core::hint::unreachable_unchecked(),");
        } else {
          out_text.push_str("_ => unreachable!(),");
        }
        out_text.push_str("} }\n");
        out_text.push_str(&format!(
          "{}\n",
          TokenStream::from(quote! {
            #[allow(missing_docs)]
            pub const fn #with_name(self, #read_name: #enum_type) -> Self {
              Self((self.0 & !Self::#mask_name) | (((#read_name as #self_member_type) << #start) & Self::#mask_name))
            }
          })
        ));
      }
      PhantomEntry::Integer {
        attributes,
        name,
        start,
        end,
      } => {
        for attribute in attributes.into_iter() {
          out_text.push_str(&format!("{}\n", TokenStream::from(quote! { #attribute })));
        }
        let mask_name = Ident::new(&format!("{}_MASK", name.to_uppercase()), Span::call_site());
        let read_name = Ident::new(&name.clone(), Span::call_site());
        let with_name = Ident::new(&format!("with_{}", name), Span::call_site());
        let width = (end - start) + 1;
        out_text.push_str(&format!(
          "{}\n",
          TokenStream::from(quote! {
            #[allow(clippy::identity_op)]
            pub const #mask_name: #self_member_type = ((1<<(#width))-1) << #start;

            #[allow(missing_docs)]
            pub const fn #read_name(self) -> #self_member_type {
              (self.0 & Self::#mask_name) >> #start
            }

            #[allow(missing_docs)]
            pub const fn #with_name(self, #read_name: #self_member_type) -> Self {
              Self((self.0 & !Self::#mask_name) | ((#read_name << #start) & Self::#mask_name))
            }
          })
        ));
      }
      PhantomEntry::Bool { attributes, name, bit } => {
        for attribute in attributes.into_iter() {
          out_text.push_str(&format!("{}\n", TokenStream::from(quote! { #attribute })));
        }
        let const_name = Ident::new(&format!("{}_BIT", name.to_uppercase()), Span::call_site());
        let read_name = Ident::new(&name.clone(), Span::call_site());
        let with_name = Ident::new(&format!("with_{}", name), Span::call_site());
        out_text.push_str(&format!(
          "{}\n",
          TokenStream::from(quote! {
            #[allow(clippy::identity_op)]
            pub const #const_name: #self_member_type = 1 << #bit;

            #[allow(missing_docs)]
            pub const fn #read_name(self) -> bool {
              (self.0 & Self::#const_name) != 0
            }

            // https://graphics.stanford.edu/~seander/bithacks.html#ConditionalSetOrClearBitsWithoutBranching
            #[allow(missing_docs)]
            pub const fn #with_name(self, bit: bool) -> Self {
              Self(self.0 ^ (((#self_member_type::wrapping_sub(0, bit as #self_member_type) ^ self.0) & Self::#const_name)))
            }
          })
        ));
      }
    };
  }

  TokenStream::from_str(&out_text).map_err(|e| panic!("{:?}", e)).unwrap()
}