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
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
//! A macro for generating bounded integer structs and enums.

use std::cmp::Ordering;
use std::ops::RangeInclusive;

use proc_macro2::{Ident, Literal, Span, TokenStream};
use quote::{quote, quote_spanned, ToTokens, TokenStreamExt};
use syn::parse::{self, Parse, ParseStream};
use syn::{braced, parse_macro_input, token::Brace, Token};
use syn::{Attribute, Error, Expr, Visibility};
use syn::{BinOp, ExprBinary, ExprRange, ExprUnary, RangeLimits, UnOp};
use syn::{ExprGroup, ExprParen};
use syn::{ExprLit, Lit};

/// Generate a bounded integer type.
///
/// It takes in single struct or enum, with the content being any range expression, which can be
/// inclusive or not. The attributes and visibility (e.g. `pub`) of the type are forwarded directly
/// to the output type. It also derives `Debug`, `Hash`, `Clone`, `Copy`, `PartialEq`, `Eq`,
/// `PartialOrd` and `Ord`.
///
/// The item must have a `repr` attribute to specify how it will be represented in memory, and it
/// must be a `u*` or `i*` type.
///
/// # Examples
/// With a struct:
/// ```rust
/// # mod force_item_scope {
/// # use bounded_integer_macro::bounded_integer;
/// bounded_integer! {
///     #[repr(i8)]
///     pub struct S { -3..2 }
/// }
/// # }
/// ```
/// The generated item should look like this:
/// ```rust
/// #[derive(Debug, Hash, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
/// pub struct S(i8);
/// ```
/// And the methods will ensure that `-3 <= S.0 < 2`.
///
/// With an enum:
/// ```rust
/// # mod force_item_scope {
/// # use bounded_integer_macro::bounded_integer;
/// bounded_integer! {
///     #[repr(i8)]
///     pub enum S { 5..=7 }
/// }
/// # }
/// ```
/// The generated item should look like this:
/// ```rust
/// #[derive(Debug, Hash, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
/// #[repr(i8)]
/// pub enum S {
///     P5 = 5, P6, P7
/// }
/// ```
///
///
/// # Limitations
///
/// - Both bounds of enum ranges must be closed and be a simple const expression involving only
/// literals and the following operators:
///     - Negation (`-x`)
///     - Addition (`x+y`), subtraction (`x-y`), multiplication (`x*y`), division (`x/y`) and
///     remainder (`x%y`).
///     - Bitwise not (`!x`), XOR (`x^y`), AND (`x&y`) and OR (`x|y`).
#[proc_macro]
pub fn bounded_integer(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
    let mut result = TokenStream::new();
    let bounded_integer = parse_macro_input!(input as BoundedInteger);
    bounded_integer.generate_item(&mut result);
    bounded_integer.generate_impl(&mut result);
    result.into()
}

#[allow(dead_code)]
enum BoundedInteger {
    Struct {
        attrs: Vec<Attribute>,
        repr: Ident,
        vis: Visibility,
        struct_token: Token![struct],
        ident: Ident,
        brace_token: Brace,
        range: Box<(Option<Expr>, Option<Expr>)>,
    },
    Enum {
        attrs: Vec<Attribute>,
        repr: Ident,
        vis: Visibility,
        enum_token: Token![enum],
        ident: Ident,
        brace_token: Brace,
        range: RangeInclusive<isize>,
        semi_token: Option<Token![;]>,
    },
}

impl BoundedInteger {
    fn generate_item(&self, tokens: &mut TokenStream) {
        for attr in self.attrs() {
            attr.to_tokens(tokens);
        }
        tokens.extend(quote! {
            #[derive(Debug, Hash, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
        });

        match self {
            Self::Struct {
                repr,
                vis,
                struct_token,
                ident,
                brace_token,
                ..
            } => {
                vis.to_tokens(tokens);
                struct_token.to_tokens(tokens);
                ident.to_tokens(tokens);
                tokens.extend(quote_spanned!(brace_token.span=> (#repr)));
                Token![;](Span::call_site()).to_tokens(tokens);
            }
            Self::Enum {
                repr,
                vis,
                enum_token,
                ident,
                brace_token,
                range,
                semi_token,
                ..
            } => {
                tokens.extend(quote!(#[repr(#repr)]));
                vis.to_tokens(tokens);
                enum_token.to_tokens(tokens);
                ident.to_tokens(tokens);

                let mut inner_tokens = TokenStream::new();

                let mut variants = range.clone().map(enum_variant);

                if let Some(first_variant) = variants.next() {
                    first_variant.to_tokens(&mut inner_tokens);
                    Token![=](Span::call_site()).to_tokens(&mut inner_tokens);
                    inner_tokens.append(Literal::isize_unsuffixed(*range.start()));
                }
                for variant in variants {
                    Token![,](Span::call_site()).to_tokens(&mut inner_tokens);
                    variant.to_tokens(&mut inner_tokens);
                }

                tokens.extend(quote_spanned!(brace_token.span=> { #inner_tokens }));
                semi_token.to_tokens(tokens);
            }
        }
    }

    fn generate_consts(&self, tokens: &mut TokenStream) {
        let vis = self.vis();
        let repr = self.repr();

        let (min_value, min, max_value, max);
        match self {
            Self::Struct { range, .. } => {
                min_value = match &range.0 {
                    Some(from) => from.into_token_stream(),
                    None => quote!(::core::primitive::#repr::MIN),
                };
                min = quote!(Self(Self::MIN_VALUE));
                max_value = match &range.1 {
                    Some(to) => to.into_token_stream(),
                    None => quote!(::core::primitive::#repr::MAX),
                };
                max = quote!(Self(Self::MAX_VALUE));
            }
            Self::Enum { range, .. } => {
                min_value = Literal::isize_unsuffixed(*range.start()).into_token_stream();
                max_value = Literal::isize_unsuffixed(*range.end()).into_token_stream();
                let min_variant = enum_variant(*range.start());
                let max_variant = enum_variant(*range.end());
                min = quote!(Self::#min_variant);
                max = quote!(Self::#max_variant);
            }
        }

        tokens.extend(quote! {
            /// The smallest value that this bounded integer can contain.
            #vis const MIN_VALUE: #repr = #min_value;
            /// The largest value that this bounded integer can contain.
            #vis const MAX_VALUE: #repr = #max_value;

            /// The smallest value of the bounded integer.
            #vis const MIN: Self = #min;
            /// The largest value of the bounded integer.
            #vis const MAX: Self = #max;

            /// The number of values the bounded integer can contain.
            #vis const RANGE: #repr = Self::MAX_VALUE - Self::MIN_VALUE + 1;
        });
    }

    fn generate_base(&self, tokens: &mut TokenStream) {
        let vis = self.vis();
        let repr = self.repr();

        let (get_body, new_body, low_bounded, high_bounded) = match self {
            Self::Struct { range, .. } => (
                quote!(self.0),
                quote!(Self(n)),
                range.0.is_some(),
                range.1.is_some(),
            ),
            Self::Enum { .. } => (
                quote!(self as #repr),
                quote!(::core::mem::transmute::<#repr, Self>(n)),
                true,
                true,
            ),
        };

        let low_check = if low_bounded {
            quote!(n >= Self::MIN_VALUE)
        } else {
            quote!(true)
        };
        let high_check = if high_bounded {
            quote!(n <= Self::MAX_VALUE)
        } else {
            quote!(true)
        };

        tokens.extend(quote! {
            /// Creates a bounded integer without checking the value.
            ///
            /// # Safety
            ///
            /// The value must not be outside the valid range of values; it must not be less than
            /// `MIN` or greater than `MAX`.
            #[must_use]
            #vis unsafe fn new_unchecked(n: #repr) -> Self {
                #new_body
            }

            /// Checks whether the given value is in the range of the bounded integer.
            #[must_use]
            #vis fn in_range(n: #repr) -> bool {
                #low_check && #high_check
            }

            /// Creates a bounded integer if the given value is within the range [`MIN`, `MAX`].
            #[must_use]
            #vis fn new(n: #repr) -> Option<Self> {
                if Self::in_range(n) {
                    // SAFETY: We just asserted that the value is in range.
                    Some(unsafe { Self::new_unchecked(n) })
                } else {
                    None
                }
            }

            /// Creates a bounded integer by setting the value to `MIN` or `MAX` if it is too low
            /// or too high respectively.
            #[must_use]
            #vis fn new_saturating(n: #repr) -> Self {
                if !(#low_check) {
                    Self::MIN
                } else if !(#high_check) {
                    Self::MAX
                } else {
                    // SAFETY: This branch can only happen if n is in range.
                    unsafe { Self::new_unchecked(n) }
                }
            }

            /// Creates a bounded integer by using modulo arithmetic. Values in the range won't be
            /// changed but values outside will be wrapped around.
            #[must_use]
            #vis fn new_wrapping(n: #repr) -> Self {
                unsafe {
                    Self::new_unchecked(
                        (n + (Self::RANGE - (Self::MIN_VALUE.rem_euclid(Self::RANGE)))).rem_euclid(Self::RANGE)
                            + Self::MIN_VALUE
                    )
                }
            }

            /// Gets the value of the bounded integer as a primitive type.
            #[must_use]
            #vis fn get(self) -> #repr {
                #get_body
            }
        });
    }

    fn generate_operators(&self, tokens: &mut TokenStream) {
        let vis = self.vis();
        let repr = self.repr();

        tokens.extend(quote! {
            /// Computes the absolute value of `self`, panicking if it is out of range.
            #[must_use]
            #vis fn abs(self) -> Self {
                Self::new(self.get().abs()).expect("Absolute value out of range")
            }
            /// Raises self to the power of `exp`, using exponentiation by squaring. Panics if it
            /// is out of range.
            #[must_use]
            #vis fn pow(self, exp: u32) -> Self {
                Self::new(self.get().pow(exp)).expect("Value raised to power out of range")
            }
            /// Calculates the quotient of Euclidean division of `self` by `rhs`. Panics if `rhs`
            /// is 0 or the result is out of range.
            #[must_use]
            #vis fn div_euclid(self, rhs: #repr) -> Self {
                Self::new(self.get().div_euclid(rhs)).expect("Attempted to divide out of range")
            }
            /// Calculates the least nonnegative remainder of `self (mod rhs)`. Panics if `rhs` is 0
            /// or the result is out of range.
            #[must_use]
            #vis fn rem_euclid(self, rhs: #repr) -> Self {
                Self::new(self.get().rem_euclid(rhs))
                    .expect("Attempted to divide with remainder out of range")
            }
        });
    }

    fn generate_ops_traits(&self, tokens: &mut TokenStream) {
        let ident = self.ident();
        let repr = self.repr();

        for op in OPERATORS {
            let description = op.description;

            if op.bin {
                binop_trait_variations(
                    op.trait_name,
                    op.method,
                    ident,
                    repr,
                    |trait_name, method| {
                        quote! {
                            Self::new(<#repr as ::core::ops::#trait_name>::#method(self.get(), rhs))
                                .expect(concat!("Attempted to ", #description, " out of range"))
                        }
                    },
                    tokens,
                );

                binop_trait_variations(
                    op.trait_name,
                    op.method,
                    ident,
                    ident,
                    |trait_name, method| {
                        quote! {
                            <Self as ::core::ops::#trait_name<#repr>>::#method(self, rhs.get())
                        }
                    },
                    tokens,
                );
            } else {
                let trait_name = Ident::new(op.trait_name, Span::call_site());
                let method = Ident::new(op.method, Span::call_site());

                unop_trait_variations(
                    &trait_name,
                    &method,
                    ident,
                    &quote! {
                        Self::new(<#repr as ::core::ops::#trait_name>::#method(self.get()))
                            .expect(concat!("Attempted to ", #description, " out of range"))
                    },
                    tokens,
                );
            }
        }
    }

    fn generate_checked_operators(&self, tokens: &mut TokenStream) {
        let vis = self.vis();

        for op in CHECKED_OPERATORS {
            // Dummy storage to extend the lifetime of rhs.
            let mut rhs_ident_storage = None;
            let rhs = op.rhs.map(|name| {
                if name == "Self" {
                    self.repr()
                } else {
                    rhs_ident_storage.get_or_insert_with(|| Ident::new(name, Span::call_site()))
                }
            });
            let rhs_type = rhs.map(|ty| quote!(rhs: #ty,));
            let rhs_value = rhs.map(|_| quote!(rhs,));

            let checked_name = Ident::new(&format!("checked_{}", op.name), Span::call_site());
            let checked_comment = format!("Checked {}.", op.description);

            tokens.extend(quote! {
                #[doc = #checked_comment]
                #[must_use]
                #vis fn #checked_name(self, #rhs_type) -> Option<Self> {
                    self.get().#checked_name(#rhs_value).and_then(Self::new)
                }
            });

            if op.saturating {
                let saturating_name =
                    Ident::new(&format!("saturating_{}", op.name), Span::call_site());
                let saturating_comment = format!("Saturing {}.", op.description);

                tokens.extend(quote! {
                    #[doc = #saturating_comment]
                    #[must_use]
                    #vis fn #saturating_name(self, #rhs_type) -> Self {
                        Self::new_saturating(self.get().#saturating_name(#rhs_value))
                    }
                });
            }
        }
    }

    fn generate_fmt_traits(&self, tokens: &mut TokenStream) {
        let ident = self.ident();
        let repr = self.repr();

        for &fmt_trait in &[
            "Binary", "Display", "LowerExp", "LowerHex", "Octal", "UpperExp", "UpperHex",
        ] {
            let fmt_trait = Ident::new(fmt_trait, Span::call_site());

            tokens.extend(quote! {
                impl ::core::fmt::#fmt_trait for #ident {
                    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
                        <#repr as ::core::fmt::#fmt_trait>::fmt(&self.get(), f)
                    }
                }
            });
        }
    }

    fn generate_impl(&self, tokens: &mut TokenStream) {
        let mut inner_tokens = TokenStream::new();

        self.generate_consts(&mut inner_tokens);
        self.generate_base(&mut inner_tokens);
        self.generate_operators(&mut inner_tokens);
        self.generate_checked_operators(&mut inner_tokens);

        let ident = self.ident();
        tokens.extend(quote!(impl #ident { #inner_tokens }));

        self.generate_ops_traits(tokens);
        self.generate_fmt_traits(tokens);
    }

    fn attrs(&self) -> &Vec<Attribute> {
        match self {
            Self::Struct { attrs, .. } => attrs,
            Self::Enum { attrs, .. } => attrs,
        }
    }
    fn repr(&self) -> &Ident {
        match self {
            Self::Struct { repr, .. } => repr,
            Self::Enum { repr, .. } => repr,
        }
    }
    fn vis(&self) -> &Visibility {
        match self {
            Self::Struct { vis, .. } => vis,
            Self::Enum { vis, .. } => vis,
        }
    }
    fn ident(&self) -> &Ident {
        match self {
            Self::Struct { ident, .. } => ident,
            Self::Enum { ident, .. } => ident,
        }
    }
}

impl Parse for BoundedInteger {
    fn parse(input: ParseStream) -> parse::Result<Self> {
        let mut attrs = input.call(Attribute::parse_outer)?;
        let repr_pos = attrs
            .iter()
            .position(|attr| attr.path.is_ident("repr"))
            .ok_or_else(|| input.error("no repr attribute on bounded integer"))?;
        let repr = attrs.remove(repr_pos).parse_args()?;
        let vis: Visibility = input.parse()?;

        Ok(if input.peek(Token![struct]) {
            let struct_token: Token![struct] = input.parse()?;
            let repr: Ident = repr;

            let range;
            #[allow(clippy::eval_order_dependence)]
            let this = Self::Struct {
                attrs,
                repr,
                vis,
                struct_token,
                ident: input.parse()?,
                brace_token: braced!(range in input),
                range: {
                    let range: ExprRange = range.parse()?;
                    let limits = range.limits;
                    Box::new((
                        range.from.map(|from| *from),
                        range.to.map(|to| match limits {
                            RangeLimits::HalfOpen(_) => Expr::Verbatim(quote!(#to - 1)),
                            RangeLimits::Closed(_) => *to,
                        }),
                    ))
                },
            };
            input.parse::<Option<Token![;]>>()?;
            this
        } else {
            let range_tokens;
            #[allow(clippy::eval_order_dependence)]
            Self::Enum {
                attrs,
                repr,
                vis,
                enum_token: input.parse()?,
                ident: input.parse()?,
                brace_token: braced!(range_tokens in input),
                range: {
                    let range: ExprRange = range_tokens.parse()?;
                    let range_spans = range_spans(&range.limits);
                    let from = eval_expr(&*range.from.ok_or_else(|| {
                        Error::new(range_spans.0, "the bounds of an enum range must be closed")
                    })?)?;
                    let to = eval_expr(&*range.to.ok_or_else(|| {
                        Error::new(range_spans.1, "the bounds of an enum range must be closed")
                    })?)?;
                    from..=if let RangeLimits::HalfOpen(_) = range.limits {
                        to - 1
                    } else {
                        to
                    }
                },
                semi_token: input.parse()?,
            }
        })
    }
}

fn range_spans(range: &RangeLimits) -> (Span, Span) {
    match range {
        RangeLimits::HalfOpen(dots) => (dots.spans[0], dots.spans[1]),
        RangeLimits::Closed(dots_eq) => (dots_eq.spans[0], dots_eq.spans[2]),
    }
}

fn eval_expr(expr: &Expr) -> syn::Result<isize> {
    Ok(match expr {
        Expr::Lit(ExprLit { lit, .. }) => match lit {
            Lit::Int(int) => int.base10_parse()?,
            _ => {
                return Err(Error::new(
                    span_of(lit),
                    "literal not supported in this context",
                ))
            }
        },
        Expr::Unary(ExprUnary { op, expr, .. }) => {
            let expr = eval_expr(&expr)?;
            match op {
                UnOp::Not(_) => !expr,
                UnOp::Neg(_) => -expr,
                _ => {
                    return Err(Error::new(
                        span_of(op),
                        "operator not supported in this context",
                    ))
                }
            }
        }
        Expr::Binary(ExprBinary {
            left, op, right, ..
        }) => {
            let left = eval_expr(&left)?;
            let right = eval_expr(&right)?;
            match op {
                BinOp::Add(_) => left + right,
                BinOp::Sub(_) => left - right,
                BinOp::Mul(_) => left * right,
                BinOp::Div(_) => left / right,
                BinOp::Rem(_) => left % right,
                BinOp::BitXor(_) => left ^ right,
                BinOp::BitAnd(_) => left & right,
                BinOp::BitOr(_) => left | right,
                _ => {
                    return Err(Error::new(
                        span_of(op),
                        "operator not supported in this context",
                    ))
                }
            }
        }
        Expr::Group(ExprGroup { expr, .. }) | Expr::Paren(ExprParen { expr, .. }) => {
            eval_expr(expr)?
        }
        _ => return Err(Error::new(span_of(&expr), "expected integer literal")),
    })
}

fn span_of<T: ToTokens>(item: &T) -> Span {
    item.into_token_stream()
        .into_iter()
        .next()
        .map(|tree| tree.span())
        .unwrap_or_else(Span::call_site)
}

fn enum_variant(i: isize) -> Ident {
    Ident::new(
        &*match i.cmp(&0) {
            Ordering::Less => format!("N{}", i.abs()),
            Ordering::Equal => "Z0".to_string(),
            Ordering::Greater => format!("P{}", i),
        },
        Span::call_site(),
    )
}

#[rustfmt::skip]
const CHECKED_OPERATORS: &[CheckedOperator] = &[
    CheckedOperator::new("add"       , "integer addition"      , Some("Self"), true ),
    CheckedOperator::new("sub"       , "integer subtraction"   , Some("Self"), true ),
    CheckedOperator::new("mul"       , "integer multiplication", Some("Self"), true ),
    CheckedOperator::new("div"       , "integer division"      , Some("Self"), false),
    CheckedOperator::new("div_euclid", "Euclidean division"    , Some("Self"), false),
    CheckedOperator::new("rem"       , "integer remainder"     , Some("Self"), false),
    CheckedOperator::new("rem_euclid", "Euclidean remainder"   , Some("Self"), false),
    // Waiting on Rust 1.45 (2020-07-16) when `saturating_{neg, abs}` stabilizes on stable
    CheckedOperator::new("neg"       , "negation"              , None        , false),
    CheckedOperator::new("abs"       , "absolute value"        , None        , false),
    CheckedOperator::new("pow"       , "exponentiation"        , Some("u32") , true ),
];

struct CheckedOperator {
    name: &'static str,
    description: &'static str,
    rhs: Option<&'static str>,
    saturating: bool,
}

impl CheckedOperator {
    const fn new(
        name: &'static str,
        description: &'static str,
        rhs: Option<&'static str>,
        saturating: bool,
    ) -> Self {
        Self {
            name,
            description,
            rhs,
            saturating,
        }
    }
}

#[rustfmt::skip]
const OPERATORS: &[Operator] = &[
    Operator { trait_name: "Add", method: "add", description: "add", bin: true },
    Operator { trait_name: "Sub", method: "sub", description: "subtract", bin: true },
    Operator { trait_name: "Mul", method: "mul", description: "multiply", bin: true },
    Operator { trait_name: "Div", method: "div", description: "divide", bin: true },
    Operator { trait_name: "Rem", method: "rem", description: "take remainder", bin: true },
    Operator { trait_name: "Neg", method: "neg", description: "negate", bin: false },
];

struct Operator {
    trait_name: &'static str,
    method: &'static str,
    description: &'static str,
    bin: bool,
}

fn binop_trait_variations<B: ToTokens>(
    trait_name_root: &str,
    method_root: &str,
    lhs: &impl ToTokens,
    rhs: &impl ToTokens,
    body: impl FnOnce(&Ident, &Ident) -> B,
    tokens: &mut TokenStream,
) {
    let trait_name = Ident::new(trait_name_root, Span::call_site());
    let trait_name_assign = Ident::new(&format!("{}Assign", trait_name_root), Span::call_site());
    let method = Ident::new(method_root, Span::call_site());
    let method_assign = Ident::new(&format!("{}_assign", method_root), Span::call_site());
    let body = body(&trait_name, &method);

    tokens.extend(quote! {
        impl ::core::ops::#trait_name<#rhs> for #lhs {
            type Output = #lhs;
            fn #method(self, rhs: #rhs) -> Self::Output {
                #body
            }
        }
        impl<'a> ::core::ops::#trait_name<#rhs> for &'a #lhs {
            type Output = #lhs;
            fn #method(self, rhs: #rhs) -> Self::Output {
                <#lhs as ::core::ops::#trait_name<#rhs>>::#method(*self, rhs)
            }
        }
        impl<'b> ::core::ops::#trait_name<&'b #rhs> for #lhs {
            type Output = #lhs;
            fn #method(self, rhs: &'b #rhs) -> Self::Output {
                <#lhs as ::core::ops::#trait_name<#rhs>>::#method(self, *rhs)
            }
        }
        impl<'b, 'a> ::core::ops::#trait_name<&'b #rhs> for &'a #lhs {
            type Output = #lhs;
            fn #method(self, rhs: &'b #rhs) -> Self::Output {
                <#lhs as ::core::ops::#trait_name<#rhs>>::#method(*self, *rhs)
            }
        }

        impl ::core::ops::#trait_name_assign<#rhs> for #lhs {
            fn #method_assign(&mut self, rhs: #rhs) {
                *self = <Self as ::core::ops::#trait_name<#rhs>>::#method(*self, rhs);
            }
        }
        impl<'a> ::core::ops::#trait_name_assign<&'a #rhs> for #lhs {
            fn #method_assign(&mut self, rhs: &'a #rhs) {
                *self = <Self as ::core::ops::#trait_name<#rhs>>::#method(*self, *rhs);
            }
        }
    });
}

fn unop_trait_variations(
    trait_name: &impl ToTokens,
    method: &impl ToTokens,
    lhs: &impl ToTokens,
    body: &impl ToTokens,
    tokens: &mut TokenStream,
) {
    tokens.extend(quote! {
        impl ::core::ops::#trait_name for #lhs {
            type Output = #lhs;
            fn #method(self) -> Self::Output {
                #body
            }
        }
        impl<'a> ::core::ops::#trait_name for &'a #lhs {
            type Output = #lhs;
            fn #method(self) -> Self::Output {
                <#lhs as ::core::ops::#trait_name>::#method(*self)
            }
        }
    });
}

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

    fn assert_result(
        f: impl FnOnce(&BoundedInteger, &mut TokenStream),
        input: TokenStream,
        expected: TokenStream,
    ) {
        let mut result = TokenStream::new();
        f(&parse2::<BoundedInteger>(input).unwrap(), &mut result);
        assert_eq!(result.to_string(), expected.to_string());
    }

    #[cfg(test)]
    #[test]
    fn test_tokens() {
        assert_result(
            BoundedInteger::generate_item,
            quote! {
                #[repr(isize)]
                pub(crate) enum Nibble { -8..6+2 }
            },
            quote! {
                #[derive(Debug, Hash, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
                #[repr(isize)]
                pub(crate) enum Nibble {
                    N8 = -8, N7, N6, N5, N4, N3, N2, N1, Z0, P1, P2, P3, P4, P5, P6, P7
                }
            },
        );

        assert_result(
            BoundedInteger::generate_item,
            quote! {
                #[repr(u16)]
                enum Nibble { 3..=7 };
            },
            quote! {
                #[derive(Debug, Hash, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
                #[repr(u16)]
                enum Nibble {
                    P3 = 3, P4, P5, P6, P7
                };
            },
        );

        assert_result(
            BoundedInteger::generate_item,
            quote! {
                #[repr(i8)]
                pub struct S { -3..2 }
            },
            quote! {
                #[derive(Debug, Hash, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
                pub struct S(i8);
            },
        );
    }
}