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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
use proc_macro::*;
use std::iter::FromIterator;

/// # Named constants

///

/// Makes enums behave like named constants in languages like C/C++ or C#.

///

/// Put this attribute on an enum and it will be rewritten as a newtype struct.

/// The enum variants are turned into associated constants.

///

/// # Examples

///

/// ```

/// use named_constants::named_constants;

///

/// #[named_constants]

/// // Derives are applied to the newtype wrapper

/// #[derive(Copy, Clone, Debug, Eq, PartialEq)]

/// // Required repr to specify the underlying type

/// #[repr(i32)]

/// pub enum CardSuit {

/// 	CLUBS,      // (= 0) Starts from zero

/// 	DIAMONDS,   // (= 1) Autoincrements the previous value

/// 	HEARTS = 4, // (= 4) Direct assignment

/// 	SPADES,     // (= 5) Autoincrements the previous value

/// }

///

/// let clubs = CardSuit::CLUBS;

/// let weird = CardSuit(14); // Legal!

/// ```

///

/// # Implementation notes

///

/// In the example above, `CardSuit` is transformed into:

///

/// ```

/// #[derive(Copy, Clone, Debug, Eq, PartialEq)]

/// #[repr(transparent)]

/// pub struct CardSuit(pub i32);

/// impl CardSuit {

/// 	pub const CLUBS: CardSuit = CardSuit(0);

/// 	pub const DIAMONDS: CardSuit = CardSuit(1);

/// 	pub const HEARTS: CardSuit = CardSuit(4);

/// 	pub const SPADES: CardSuit = CardSuit(4 + 1);

/// }

/// ```

#[proc_macro_attribute]
pub fn named_constants(attr: TokenStream, item: TokenStream) -> TokenStream {
	if !attr.is_empty() {
		panic!("the attribute macro does not support any arguments. {}", attr);
	}
	let named = parse_named(item);
	let mut tokens = Vec::new();
	render(&mut tokens, &named);
	tokens.into_iter().collect()
}

macro_rules! token_stream {
	($($e:expr),*$(,)?) => {
		TokenStream::from_iter(vec![$(TokenTree::from($e)),*])
	};
}

//================================================================

// Parser


fn to_vec(stream: TokenStream) -> Vec<TokenTree> {
	stream.into_iter().collect()
}
fn to_group(tt: TokenTree) -> Group {
	match tt {
		TokenTree::Group(group) => group,
		_ => panic!(),
	}
}
fn to_ident(tt: TokenTree) -> Ident {
	match tt {
		TokenTree::Ident(ident) => ident,
		_ => panic!(),
	}
}

/*
macro_rules! named_constants {
	(
		$(#[$meta:meta])*
		$vis:vis enum $name:ident {
			$(
				$(#[$cmeta:meta])*
				$key:ident $(= $value:expr)?,
			)*
		}
	) => {
		//...
	};
}
*/

struct NamedConstants {
	attributes: Vec<TokenStream>,
	repr_type: TokenStream,
	reflection: bool,
	visibility: Visibility,
	name: Ident,
	constants: Vec<Constant>,
}
struct Visibility {
	keyword: Option<Ident>,
	group: Option<Group>,
}
struct Constant {
	attributes: Vec<TokenStream>,
	key: Ident,
	value: Option<TokenStream>,
}

fn parse_commalist(stream: TokenStream) -> Vec<Vec<TokenTree>> {
	let mut tokens = to_vec(stream);
	tokens.reverse();

	let mut result = Vec::new();
	let mut temp = Vec::new();
	while let Some(token) = tokens.pop() {
		match token {
			TokenTree::Punct(punct) if punct.as_char() == ',' => {
				result.push(std::mem::replace(&mut temp, Vec::new()));
			},
			other => temp.push(other),
		}
	}
	if !temp.is_empty() {
		result.push(temp);
	}
	result
}
fn join_commalist(tokens: Vec<Vec<TokenTree>>) -> TokenStream {
	tokens.into_iter().flat_map(|mut item| {
		item.push(TokenTree::Punct(Punct::new(',', Spacing::Alone)));
		item
	}).collect()
}
fn parse_attributes(stream: TokenStream) -> (Vec<TokenStream>, TokenStream) {
	let mut tokens = to_vec(stream);
	tokens.reverse();

	// $(#[meta:meta])*

	let mut attributes = Vec::new();
	loop {
		match &tokens[..] {
			[.., TokenTree::Group(group), TokenTree::Punct(punct)] if punct.as_char() == '#' && group.delimiter() == Delimiter::Bracket => {
				let _ = tokens.pop();
				let group = to_group(tokens.pop().unwrap());
				attributes.push(group.stream());
			},
			_ => break,
		}
	}
	(attributes, tokens.into_iter().rev().collect())
}
fn parse_visibility(stream: TokenStream) -> (Visibility, TokenStream) {
	let mut tokens = to_vec(stream);
	tokens.reverse();

	let vis = match &tokens[..] {
		[.., TokenTree::Group(group), TokenTree::Ident(keyword)] if keyword.to_string() == "pub" && group.delimiter() == Delimiter::Parenthesis => {
			let keyword = Some(to_ident(tokens.pop().unwrap()));
			let group = Some(to_group(tokens.pop().unwrap()));
			Visibility { keyword, group }
		},
		[.., TokenTree::Ident(keyword)] if keyword.to_string() == "pub" => {
			let keyword = Some(to_ident(tokens.pop().unwrap()));
			let group = None;
			Visibility { keyword, group }
		},
		_ => {
			let keyword = None;
			let group = None;
			Visibility { keyword, group }
		},
	};
	(vis, tokens.into_iter().rev().collect())
}
fn parse_constants(stream: TokenStream) -> Vec<Constant> {
	let mut tokens = to_vec(stream);
	tokens.reverse();

	// $($(#[#meta:meta])* $key:ident $(= $value:expr,)?)

	let mut constants = Vec::new();
	loop {
		let mut attributes = Vec::new();
		while let [.., TokenTree::Group(_), TokenTree::Punct(_)] = &tokens[..] {
			let _ = tokens.pop();
			let group = to_group(tokens.pop().unwrap());
			attributes.push(group.stream());
		}

		let key = match tokens.pop() {
			Some(TokenTree::Ident(key)) => key,
			None => break,
			_ => panic!("expected a list of constants `KEY $(= VALUE,)?`")
		};

		let value = match tokens.pop() {
			Some(TokenTree::Punct(punct)) if punct.as_char() == ',' => None,
			Some(TokenTree::Punct(punct)) if punct.as_char() == '=' => {
				let mut value = Vec::new();
				loop {
					match tokens.pop() {
						Some(TokenTree::Punct(punct)) if punct.as_char() == ',' => break,
						Some(tt) => value.push(tt),
						None => break,
					}
				}
				Some(TokenStream::from_iter(value))
			},
			None => None,
			_ => panic!("expected a list of constants `KEY $(= VALUE,)?`")
		};

		constants.push(Constant { attributes, key, value })
	}
	constants
}
fn parse_named(stream: TokenStream) -> NamedConstants {
	let (mut attributes, stream) = parse_attributes(stream);
	let repr_type = rewrite_repr(&mut attributes).expect("must have a repr attribute");
	let reflection = rewrite_derives(&mut attributes);
	let (visibility, stream) = parse_visibility(stream);
	let tokens = to_vec(stream);
	match &tokens[..] {
		[TokenTree::Ident(keyword), TokenTree::Ident(name), TokenTree::Group(group)] => {
			match keyword.to_string().as_str() {
				"enum" => (),
				_ => panic!("named constants are only supported for enum declarations"),
			}
			match group.delimiter() {
				Delimiter::Brace => (),
				_ => panic!("named constants must use { } to declare the constants"),
			}
			let constants = parse_constants(group.stream());
			NamedConstants {
				attributes,
				repr_type,
				reflection,
				visibility,
				name: name.clone(),
				constants
			}
		},
		[TokenTree::Ident(_), TokenTree::Ident(_), TokenTree::Punct(_), ..] => panic!("named constants do not support generics"),
		_ => panic!(),
	}
}
// Rewrite #[repr(TYPE)] into #[repr(transparent)]

fn rewrite_repr(attributes: &mut Vec<TokenStream>) -> Option<TokenStream> {
	let mut repr_type = None;
	for meta in attributes {
		let tokens = to_vec(meta.clone());
		match &tokens[..] {
			[TokenTree::Ident(repr), TokenTree::Group(group)] if repr.to_string() == "repr" => {
				repr_type = Some(group.stream());
				*meta = token_stream!(repr.clone(), Group::new(Delimiter::Parenthesis, token_stream!(Ident::new("transparent", group.span()))));
			},
			_ => (),
		}
	}
	repr_type
}
// Rewrite #[derive(..)] looking for Reflection

fn rewrite_derives(attributes: &mut Vec<TokenStream>) -> bool {
	let mut reflection = false;
	for meta in attributes {
		let tokens = to_vec(meta.clone());
		match &tokens[..] {
			[TokenTree::Ident(derive), TokenTree::Group(group)] if derive.to_string() == "derive" => {
				let mut derives = parse_commalist(group.stream());
				derives.retain(|item| {
					match &item[..] {
						[TokenTree::Ident(ident)] if ident.to_string() == "Reflection" => {
							reflection = true;
							false
						},
						_ => true,
					}
				});
				*meta = token_stream!(derive.clone(), Group::new(Delimiter::Parenthesis, join_commalist(derives)));
			},
			_ => (),
		}
	}
	reflection
}

//================================================================

// Render


fn render(tokens: &mut Vec<TokenTree>, named: &NamedConstants) {
	// Render attributes

	for meta in &named.attributes {
		render_attribute(tokens, meta);
	}
	// Render visibility

	render_visibility(tokens, &named.visibility);
	// Render the newtype

	render_newtype(tokens, &named.name, &named.visibility, &named.repr_type);
	// Render the constants

	render_constants(tokens, &named.name, &named.constants);
	// Render the reflection

	if named.reflection {
		render_reflection(tokens, &named.name, &named.constants);
	}
}
fn render_attribute(tokens: &mut Vec<TokenTree>, meta: &TokenStream) {
	tokens.push(TokenTree::Punct(Punct::new('#', Spacing::Alone)));
	tokens.push(TokenTree::Group(Group::new(Delimiter::Bracket, meta.clone())));
}
fn render_doc_comment(tokens: &mut Vec<TokenTree>, comment: &str) {
	tokens.push(TokenTree::Punct(Punct::new('#', Spacing::Alone)));
	render_group(tokens, Delimiter::Bracket, |tokens| {
		tokens.push(TokenTree::Ident(Ident::new("doc", Span::call_site())));
		tokens.push(TokenTree::Punct(Punct::new('=', Spacing::Alone)));
		tokens.push(TokenTree::Literal(Literal::string(comment)));
	});
}
fn render_string(tokens: &mut Vec<TokenTree>, string: &str) {
	tokens.extend(string.parse::<TokenStream>().unwrap());
}
fn render_impl(tokens: &mut Vec<TokenTree>, name: &Ident, items: impl FnMut(&mut Vec<TokenTree>)) {
	tokens.push(TokenTree::Ident(Ident::new("impl", Span::call_site())));
	tokens.push(TokenTree::Ident(name.clone()));
	render_group(tokens, Delimiter::Brace, items);
}
fn render_group(tokens: &mut Vec<TokenTree>, delimiter: Delimiter, mut contents: impl FnMut(&mut Vec<TokenTree>)) {
	tokens.push(TokenTree::Group(Group::new(delimiter, {
		let mut tokens = Vec::new();
		contents(&mut tokens);
		tokens.into_iter().collect()
	})));
}
fn render_visibility(tokens: &mut Vec<TokenTree>, visibility: &Visibility) {
	if let Some(keyword) = &visibility.keyword {
		tokens.push(TokenTree::Ident(keyword.clone()));
	}
	if let Some(group) = &visibility.group {
		tokens.push(TokenTree::Group(group.clone()));
	}
}
fn render_newtype(tokens: &mut Vec<TokenTree>, name: &Ident, vis: &Visibility, ty: &TokenStream) {
	tokens.push(TokenTree::Ident(Ident::new("struct", Span::call_site())));
	tokens.push(TokenTree::Ident(name.clone()));
	render_group(tokens, Delimiter::Parenthesis, |tokens| {
		render_visibility(tokens, vis);
		tokens.extend(ty.clone().into_iter());
	});
	tokens.push(TokenTree::Punct(Punct::new(';', Spacing::Alone)));
}
fn render_constants(tokens: &mut Vec<TokenTree>, name: &Ident, constants: &[Constant]) {
	render_string(tokens, "#[allow(non_upper_case_globals)]");
	render_impl(tokens, name, |tokens| {
		let mut last_value = (None, 0);
		for constant in constants {
			render_constant(tokens, name, constant, &mut last_value);
		}
	});
}
fn render_constant<'a>(tokens: &mut Vec<TokenTree>, name: &Ident, constant: &'a Constant, last_value: &mut (Option<&'a TokenStream>, i32)) {
	for attr in &constant.attributes {
		render_attribute(tokens, attr);
	}
	let value = {
		match &constant.value {
			// If an explicit value is assigned to this constant

			Some(value) => {
				// Set this constant as the base for iota and reset iota to 1 for the next constant

				last_value.0 = Some(value);
				last_value.1 = 1;
				value.clone()
			},
			// If no explicit value is assigned to this constant

			None => {
				// Then take the last known constant and add

				let mut tokens = Vec::new();
				if let Some(last_value) = last_value.0 {
					// Curious: Using Delimiter::None does not ensure proper precedence

					tokens.push(TokenTree::Group(Group::new(Delimiter::Parenthesis, last_value.clone())));
					tokens.push(TokenTree::Punct(Punct::new('+', Spacing::Alone)));
				}
				// The iota as its value

				tokens.push(TokenTree::Literal(Literal::i32_unsuffixed(last_value.1)));
				// Increment the iota for next constant

				last_value.1 += 1;
				tokens.into_iter().collect()
			},
		}
	};
	render_doc_comment(tokens, "");
	render_doc_comment(tokens, &format!("const `{}::{}` = `{}`.", name, constant.key, value));
	tokens.push(TokenTree::Ident(Ident::new("pub", Span::call_site())));
	tokens.push(TokenTree::Ident(Ident::new("const", Span::call_site())));
	tokens.push(TokenTree::Ident(constant.key.clone()));
	tokens.push(TokenTree::Punct(Punct::new(':', Spacing::Alone)));
	tokens.push(TokenTree::Ident(name.clone()));
	tokens.push(TokenTree::Punct(Punct::new('=', Spacing::Alone)));
	tokens.push(TokenTree::Ident(name.clone()));
	tokens.push(TokenTree::Group(Group::new(Delimiter::Parenthesis, value)));
	tokens.push(TokenTree::Punct(Punct::new(';', Spacing::Alone)));
}
fn render_reflection(tokens: &mut Vec<TokenTree>, name: &Ident, constants: &[Constant]) {
	render_impl(tokens, name, |tokens| {
		render_string(tokens, "const fn _str(&self) -> ::core::option::Option<&'static str>");
		render_group(tokens, Delimiter::Brace, |tokens| {
			render_string(tokens, "match self");
			render_group(tokens, Delimiter::Brace, |tokens| {
				for constant in constants {
					render_string(tokens, "&Self::");
					tokens.push(TokenTree::Ident(constant.key.clone()));
					render_string(tokens, "=> ::core::option::Option::Some");
					tokens.push(TokenTree::Group(Group::new(Delimiter::Parenthesis, token_stream!(Literal::string(&constant.key.to_string())))));
					tokens.push(TokenTree::Punct(Punct::new(',', Spacing::Alone)));
				}
				render_string(tokens, "_ => ::core::option::Option::None,");
			});
		});
		render_string(tokens, "const fn _keys() -> &'static [&'static str]");
		render_group(tokens, Delimiter::Brace, |tokens| {
			tokens.push(TokenTree::Punct(Punct::new('&', Spacing::Alone)));
			render_group(tokens, Delimiter::Bracket, |tokens| {
				for constant in constants {
					tokens.push(TokenTree::Literal(Literal::string(&constant.key.to_string())));
					tokens.push(TokenTree::Punct(Punct::new(',', Spacing::Alone)));
				}
			});
		});
		render_string(tokens, "const fn _values() -> &'static [Self]");
		render_group(tokens, Delimiter::Brace, |tokens| {
			tokens.push(TokenTree::Punct(Punct::new('&', Spacing::Alone)));
			render_group(tokens, Delimiter::Bracket, |tokens| {
				for constant in constants {
					render_string(tokens, "Self::");
					tokens.push(TokenTree::Ident(constant.key.clone()));
					tokens.push(TokenTree::Punct(Punct::new(',', Spacing::Alone)));
				}
			});
		});
	});
	render_string(tokens, "impl ::core::fmt::Debug for");
	tokens.push(TokenTree::Ident(name.clone()));
	render_string(tokens, "{
		fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
			::core::write!(f, \"{} ({:?})\", self._str().unwrap_or(\"_\"), self.0)
		}
	}");
}