verty 0.1.0

procedural macro to generate different versions of a type
Documentation
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
use std::ops::Bound;

use proc_macro2::{Ident, Span, TokenStream};
use quote::ToTokens as _;
use syn::parse::{Parse, ParseStream};
use syn::punctuated::Punctuated;
use syn::{Attribute, Error, Expr, Result, Token};

pub use self::input::*;
use crate::util::error_sink::ErrorSink;
use crate::util::interval::Interval;

mod input;
pub mod helper_attrs;

pub mod args {
	use quote::ToTokens;
	use syn::LitInt;
	use syn::spanned::Spanned;

	use super::*;

	#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
	pub enum RenameSource {
		Version(usize),
		Enum,
		Base,
	}

	#[derive(Debug, Clone)]
	pub enum MacroArg {
		Start(usize),
		End(usize),
		Enum,
		Base,
		Rename(RenameSource, Ident),
	}

	enum StartEnd {
		Start(kw::start),
		End(kw::end),
	}

	impl StartEnd {
		fn variant(self) -> fn(usize) -> MacroArg {
			match self {
				Self::Start(_) => MacroArg::Start,
				Self::End(_) => MacroArg::End,
			}
		}
	}

	enum ParsedRenameSource {
		Version(LitInt),
		Enum(Token![enum]),
		Base(kw::base),
	}

	enum ParsedMacroArg {
		StartEnd(StartEnd, Token![=], LitInt),
		Enum(Token![enum]),
		Base(kw::base),
		Rename(kw::rename, ParsedRenameSource, Token![=>], Ident),
		Invalid(TokenStream, Error),
	}

	impl ParsedMacroArg {
		fn try_into_arg(self) -> Result<MacroArg> {
			Ok(match self {
				ParsedMacroArg::StartEnd(kind, _, lit) => kind.variant()(lit.base10_parse()?),
				ParsedMacroArg::Enum(_) => MacroArg::Enum,
				ParsedMacroArg::Base(_) => MacroArg::Base,
				ParsedMacroArg::Rename(_, src, _, ident) => MacroArg::Rename(
					match src {
						ParsedRenameSource::Version(lit) => {
							RenameSource::Version(lit.base10_parse()?)
						}
						ParsedRenameSource::Enum(_) => RenameSource::Enum,
						ParsedRenameSource::Base(_) => RenameSource::Base,
					},
					ident,
				),
				ParsedMacroArg::Invalid(t, e) => {
					return Err(Error::new_spanned(t, format!("invalid argument; {e}")));
				}
			})
		}
	}

	mod kw {
		syn::custom_keyword!(start);
		syn::custom_keyword!(end);
		syn::custom_keyword!(base);
		syn::custom_keyword!(rename);
	}

	impl Parse for StartEnd {
		fn parse(input: ParseStream) -> Result<Self> {
			// no need for lookahead here, the error is never used
			input
				.parse::<kw::start>()
				.map(Self::Start)
				.or_else(|_| input.parse::<kw::end>().map(Self::End))
		}
	}

	impl ToTokens for StartEnd {
		fn to_tokens(&self, tokens: &mut TokenStream) {
			match self {
				StartEnd::Start(t) => t.to_tokens(tokens),
				StartEnd::End(t) => t.to_tokens(tokens),
			}
		}
	}

	impl Parse for ParsedRenameSource {
		fn parse(input: ParseStream) -> Result<Self> {
			let lookahead = input.lookahead1();
			if lookahead.peek(Token![enum]) {
				input.parse().map(Self::Enum)
			} else if lookahead.peek(kw::base) {
				input.parse().map(Self::Base)
			} else if lookahead.peek(LitInt) {
				input.parse().map(Self::Version)
			} else {
				Err(lookahead.error())
			}
		}
	}

	impl ToTokens for ParsedRenameSource {
		fn to_tokens(&self, tokens: &mut TokenStream) {
			match self {
				ParsedRenameSource::Version(lit) => lit.to_tokens(tokens),
				ParsedRenameSource::Enum(kw) => kw.to_tokens(tokens),
				ParsedRenameSource::Base(kw) => kw.to_tokens(tokens),
			}
		}
	}

	impl Parse for ParsedMacroArg {
		fn parse(input: ParseStream) -> Result<Self> {
			let lookahead = input.lookahead1();
			if lookahead.peek(kw::start) || lookahead.peek(kw::end) {
				let kind = input.parse()?;
				Ok(Self::StartEnd(kind, input.parse()?, input.parse()?))
			} else if lookahead.peek(Token![enum]) {
				input.parse().map(Self::Enum)
			} else if lookahead.peek(kw::base) {
				input.parse().map(Self::Base)
			} else if lookahead.peek(kw::rename) {
				let kw = input.parse()?;

				let inner;
				syn::parenthesized!(inner in input);
				Ok(Self::Rename(
					kw,
					inner.parse()?,
					inner.parse()?,
					inner.parse()?,
				))
			} else {
				let mut ts = TokenStream::new();
				input
					.step(|cursor| {
						let mut rest = *cursor;
						ts.extend(
							std::iter::from_fn(|| {
								let (tt, next) = rest.token_tree()?;
								match &tt {
									proc_macro2::TokenTree::Punct(p) if p.as_char() == ',' => {
										return None;
									}
									_ => rest = next,
								}
								Some(tt)
							})
							.fuse(),
						);
						Ok(((), rest))
					})
					.unwrap_or_else(|_| unreachable!());
				Ok(Self::Invalid(ts, lookahead.error()))
			}
		}
	}

	impl ToTokens for ParsedMacroArg {
		fn to_tokens(&self, tokens: &mut TokenStream) {
			match self {
				ParsedMacroArg::StartEnd(t1, t2, t3) => {
					t1.to_tokens(tokens);
					t2.to_tokens(tokens);
					t3.to_tokens(tokens);
				}
				ParsedMacroArg::Enum(t) => t.to_tokens(tokens),
				ParsedMacroArg::Base(t) => t.to_tokens(tokens),
				ParsedMacroArg::Rename(t1, t2, t3, t4) => {
					t1.to_tokens(tokens);
					t2.to_tokens(tokens);
					t3.to_tokens(tokens);
					t4.to_tokens(tokens);
				}
				ParsedMacroArg::Invalid(ts, _) => ts.to_tokens(tokens),
			}
		}
	}

	pub fn parse_macro_args(ts: TokenStream, errs: &mut ErrorSink) -> Vec<(Span, MacroArg)> {
		let pt: PunctTerminated<ParsedMacroArg, Token![,]> = {
			let Some(x) = errs.eat_err(syn::parse2(ts)) else {
				return Vec::new();
			};
			x
		};

		pt.0.into_iter()
			.filter_map(|arg| {
				let span = arg.span();
				errs.eat_err(arg.try_into_arg()).map(|arg| (span, arg))
			})
			.collect()
	}
}

fn ensure_no_attrs(attrs: &[Attribute], errs: &mut ErrorSink) {
	if !attrs.is_empty() {
		errs.push(Error::new_spanned(
			attrs
				.iter()
				.flat_map(|attr| attr.to_token_stream())
				.collect::<TokenStream>(),
			"attributes are not supported here",
		));
	}
}

fn lit_usize(expr: &Expr, errs: &mut ErrorSink) -> Result<(Span, usize)> {
	match expr {
		syn::Expr::Lit(syn::ExprLit {
			attrs,
			lit: syn::Lit::Int(lit_int),
		}) => {
			ensure_no_attrs(attrs, errs);
			lit_int
				.base10_parse::<usize>()
				.map(|res| (lit_int.span(), res))
		}
		_ => Err(Error::new_spanned(expr, "expected integer literal")),
	}
}

impl Interval {
	/// the argument `validate_bounds` carries two pieces of info: Whether to validate and, if so, the minimum and maximum version to validate with.
	fn try_from_expr(
		expr: syn::Expr,
		validate_bounds: Option<(usize, Option<usize>)>,
	) -> Result<Self> {
		let mut errs = ErrorSink::new();

		let validate_ver = |span, ver, errs: &mut ErrorSink| {
			if let Some((min, max)) = validate_bounds {
				if ver < min {
					errs.push(syn::Error::new(
						span,
						format!("version {ver} is below minimum version ({min})"),
					));
				} else if max.is_some_and(|max| ver > max) {
					errs.push(syn::Error::new(
						span,
						// this would be a good place for let chains...
						// (`else if let Some(max) = max && ver > max`, then use `max` here without having to unwrap)
						format!(
							"version {ver} is above maximum version ({})",
							max.unwrap_or_else(|| unreachable!())
						),
					));
				}
			}
		};

		match expr {
			syn::Expr::Range(er) => {
				let syn::ExprRange {
					ref attrs,
					start,
					limits,
					end,
				} = er;

				ensure_no_attrs(attrs, &mut errs);

				let start = match start
					.as_deref()
					.and_then(errs.wrap_err_once_1ary(lit_usize))
				{
					Some((span, start)) => {
						validate_ver(span, start, &mut errs);
						start
					}
					None => validate_bounds.map(|(min, _)| min).unwrap_or_default(),
				};
				let end = match end.as_deref().and_then(errs.wrap_err_once_1ary(lit_usize)) {
					None => Bound::Unbounded,
					Some((end_span, end)) => {
						validate_ver(end_span, end, &mut errs);
						match limits {
							syn::RangeLimits::Closed(_) => {
								if end < start {
									errs.push(Error::new(
										end_span,
										format!("expected at least {start}"),
									));
								}
								Bound::Included(end)
							}
							syn::RangeLimits::HalfOpen(_) => {
								if end <= start {
									errs.push(Error::new(
										end_span,
										format!("expected a number greater than {start}"),
									));
								}
								Bound::Excluded(end)
							}
						}
					}
				};

				errs.finish_with(|| Self { start, end })
			}
			expr => {
				let res = lit_usize(&expr, &mut errs)
					.map_err(|_| Error::new_spanned(expr, "expected usize literal or range"))
					.map(|(span, ver)| {
						validate_ver(span, ver, &mut errs);
						ver
					});

				errs.combine_into(res).map(|ver| Self {
					start: ver,
					end: Bound::Included(ver),
				})
			}
		}
	}
}

pub trait StagedParse: Sized {
	type Stage1: Parse;
	type Cx;

	fn stage2(from: Self::Stage1, cx: Self::Cx) -> Result<Self>;
}

pub fn staged_parse2<T: StagedParse>(tokens: TokenStream, cx: T::Cx) -> Result<T> {
	let stage1 = syn::parse2::<T::Stage1>(tokens)?;
	T::stage2(stage1, cx)
}

impl StagedParse for Interval {
	type Stage1 = Expr;
	type Cx = Option<(usize, Option<usize>)>;

	#[inline]
	fn stage2(from: Self::Stage1, cx: Self::Cx) -> Result<Self> {
		Self::try_from_expr(from, cx)
	}
}

#[cfg_attr(test, derive(Debug))]
pub struct SpannedInterval(pub Span, pub Interval);

impl StagedParse for SpannedInterval {
	type Stage1 = <Interval as StagedParse>::Stage1;
	type Cx = <Interval as StagedParse>::Cx;

	#[inline]
	fn stage2(from: Self::Stage1, cx: Self::Cx) -> Result<Self> {
		use syn::spanned::Spanned;

		Ok(Self(from.span(), Interval::stage2(from, cx)?))
	}
}

#[derive(Clone)]
#[cfg_attr(test, derive(Debug))]
pub struct PunctTerminated<T, P>(pub Punctuated<T, P>);

impl<T: Parse, P: Parse> Parse for PunctTerminated<T, P> {
	fn parse(input: ParseStream) -> syn::Result<Self> {
		Punctuated::parse_terminated(input).map(Self)
	}
}
impl<T: StagedParse<Cx: Clone>, P: Parse> StagedParse for PunctTerminated<T, P> {
	type Stage1 = PunctTerminated<T::Stage1, P>;
	type Cx = T::Cx;

	fn stage2(from: Self::Stage1, cx: Self::Cx) -> Result<Self> {
		use syn::punctuated::Pair;
		Ok(Self(
			from.0
				.into_pairs()
				.map(|p| {
					let (t, p) = p.into_tuple();
					Ok(Pair::new(T::stage2(t, cx.clone())?, p))
				})
				.collect::<Result<_>>()?,
		))
	}
}

#[cfg(test)]
mod tests {
	use super::*;

	#[test]
	fn lit_usize() {
		let lit_usize = ErrorSink::wrap_fn_1ary(super::lit_usize);

		let basic = syn::parse_quote!(10);
		assert!(lit_usize(&basic).is_ok_and(|(_, u)| u == 10));

		let binary = syn::parse_quote!(0b101);
		assert!(lit_usize(&binary).is_ok_and(|(_, u)| u == 0b101));

		let hex = syn::parse_quote!(0xbeef);
		assert!(lit_usize(&hex).is_ok_and(|(_, u)| u == 0xbeef));

		let err = syn::parse_quote!(nope);
		assert!(lit_usize(&err).is_err());
	}
}