Skip to main content

cxx_gen/syntax/
discriminant.rs

1use crate::syntax::Atom::{self, *};
2use proc_macro2::{Literal, Span, TokenStream};
3use quote::ToTokens;
4use std::cmp::Ordering;
5use std::collections::BTreeSet;
6use std::fmt::{self, Display};
7use std::str::FromStr;
8use syn::{Error, Expr, Lit, Result, Token, UnOp};
9
10pub(crate) struct DiscriminantSet {
11    repr: Option<Atom>,
12    values: BTreeSet<Discriminant>,
13    previous: Option<Discriminant>,
14}
15
16#[derive(#[automatically_derived]
impl ::core::marker::Copy for Discriminant { }Copy, #[automatically_derived]
impl ::core::clone::Clone for Discriminant {
    #[inline]
    fn clone(&self) -> Discriminant {
        let _: ::core::clone::AssertParamIsClone<Sign>;
        let _: ::core::clone::AssertParamIsClone<u64>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::cmp::Eq for Discriminant {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<Sign>;
        let _: ::core::cmp::AssertParamIsEq<u64>;
    }
}Eq, #[automatically_derived]
impl ::core::cmp::PartialEq for Discriminant {
    #[inline]
    fn eq(&self, other: &Discriminant) -> bool {
        self.magnitude == other.magnitude && self.sign == other.sign
    }
}PartialEq)]
17pub(crate) struct Discriminant {
18    sign: Sign,
19    magnitude: u64,
20}
21
22#[derive(#[automatically_derived]
impl ::core::marker::Copy for Sign { }Copy, #[automatically_derived]
impl ::core::clone::Clone for Sign {
    #[inline]
    fn clone(&self) -> Sign { *self }
}Clone, #[automatically_derived]
impl ::core::cmp::Eq for Sign {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {}
}Eq, #[automatically_derived]
impl ::core::cmp::PartialEq for Sign {
    #[inline]
    fn eq(&self, other: &Sign) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq)]
23enum Sign {
24    Negative,
25    Positive,
26}
27
28impl DiscriminantSet {
29    pub(crate) fn new(repr: Option<Atom>) -> Self {
30        DiscriminantSet {
31            repr,
32            values: BTreeSet::new(),
33            previous: None,
34        }
35    }
36
37    pub(crate) fn insert(&mut self, expr: &Expr) -> Result<Discriminant> {
38        let (discriminant, repr) = expr_to_discriminant(expr)?;
39        match (self.repr, repr) {
40            (None, Some(new_repr)) => {
41                if let Some(limits) = Limits::of(new_repr) {
42                    for &past in &self.values {
43                        if limits.min <= past && past <= limits.max {
44                            continue;
45                        }
46                        let msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("discriminant value `{0}` is outside the limits of {1}",
                past, new_repr))
    })format!(
47                            "discriminant value `{}` is outside the limits of {}",
48                            past, new_repr,
49                        );
50                        return Err(Error::new(Span::call_site(), msg));
51                    }
52                }
53                self.repr = Some(new_repr);
54            }
55            (Some(prev), Some(repr)) if prev != repr => {
56                let msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("expected {0}, found {1}", prev,
                repr))
    })format!("expected {}, found {}", prev, repr);
57                return Err(Error::new(Span::call_site(), msg));
58            }
59            _ => {}
60        }
61        insert(self, discriminant)
62    }
63
64    pub(crate) fn insert_next(&mut self) -> Result<Discriminant> {
65        let discriminant = match self.previous {
66            None => Discriminant::zero(),
67            Some(mut discriminant) => match discriminant.sign {
68                Sign::Negative => {
69                    discriminant.magnitude -= 1;
70                    if discriminant.magnitude == 0 {
71                        discriminant.sign = Sign::Positive;
72                    }
73                    discriminant
74                }
75                Sign::Positive => {
76                    if discriminant.magnitude == u64::MAX {
77                        let msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("discriminant overflow on value after {0}",
                u64::MAX))
    })format!("discriminant overflow on value after {}", u64::MAX);
78                        return Err(Error::new(Span::call_site(), msg));
79                    }
80                    discriminant.magnitude += 1;
81                    discriminant
82                }
83            },
84        };
85        insert(self, discriminant)
86    }
87
88    pub(crate) fn inferred_repr(&self) -> Result<Atom> {
89        if let Some(repr) = self.repr {
90            return Ok(repr);
91        }
92        if self.values.is_empty() {
93            return Ok(U8);
94        }
95        let min = *self.values.iter().next().unwrap();
96        let max = *self.values.iter().next_back().unwrap();
97        for limits in &LIMITS {
98            if limits.min <= min && max <= limits.max {
99                return Ok(limits.repr);
100            }
101        }
102        let msg = "these discriminant values do not fit in any supported enum repr type";
103        Err(Error::new(Span::call_site(), msg))
104    }
105}
106
107fn expr_to_discriminant(expr: &Expr) -> Result<(Discriminant, Option<Atom>)> {
108    match expr {
109        Expr::Lit(expr) => {
110            if let Lit::Int(lit) = &expr.lit {
111                let discriminant = lit.base10_parse::<Discriminant>()?;
112                let repr = parse_int_suffix(lit.suffix())?;
113                return Ok((discriminant, repr));
114            }
115        }
116        Expr::Unary(unary) => {
117            if let UnOp::Neg(_) = unary.op {
118                let (mut discriminant, repr) = expr_to_discriminant(&unary.expr)?;
119                discriminant.sign = match discriminant.sign {
120                    Sign::Positive => Sign::Negative,
121                    Sign::Negative => Sign::Positive,
122                };
123                return Ok((discriminant, repr));
124            }
125        }
126        _ => {}
127    }
128    Err(Error::new_spanned(
129        expr,
130        "enums with non-integer literal discriminants are not supported yet",
131    ))
132}
133
134fn insert(set: &mut DiscriminantSet, discriminant: Discriminant) -> Result<Discriminant> {
135    if let Some(expected_repr) = set.repr
136        && let Some(limits) = Limits::of(expected_repr)
137        && (discriminant < limits.min || limits.max < discriminant)
138    {
139        let msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("discriminant value `{0}` is outside the limits of {1}",
                discriminant, expected_repr))
    })format!(
140            "discriminant value `{}` is outside the limits of {}",
141            discriminant, expected_repr,
142        );
143        return Err(Error::new(Span::call_site(), msg));
144    }
145    set.values.insert(discriminant);
146    set.previous = Some(discriminant);
147    Ok(discriminant)
148}
149
150impl Discriminant {
151    pub(crate) const fn zero() -> Self {
152        Discriminant {
153            sign: Sign::Positive,
154            magnitude: 0,
155        }
156    }
157
158    const fn pos(u: u64) -> Self {
159        Discriminant {
160            sign: Sign::Positive,
161            magnitude: u,
162        }
163    }
164
165    const fn neg(i: i64) -> Self {
166        Discriminant {
167            sign: if i < 0 {
168                Sign::Negative
169            } else {
170                Sign::Positive
171            },
172            // This is `i.abs() as u64` but without overflow on MIN. Uses the
173            // fact that MIN.wrapping_abs() wraps back to MIN whose binary
174            // representation is 1<<63, and thus the `as u64` conversion
175            // produces 1<<63 too which happens to be the correct unsigned
176            // magnitude.
177            magnitude: i.wrapping_abs() as u64,
178        }
179    }
180}
181
182impl Display for Discriminant {
183    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
184        if self.sign == Sign::Negative {
185            f.write_str("-")?;
186        }
187        f.write_fmt(format_args!("{0}", self.magnitude))write!(f, "{}", self.magnitude)
188    }
189}
190
191impl ToTokens for Discriminant {
192    fn to_tokens(&self, tokens: &mut TokenStream) {
193        if self.sign == Sign::Negative {
194            ::syn::token::MinusToken![-](Span::call_site()).to_tokens(tokens);
195        }
196        Literal::u64_unsuffixed(self.magnitude).to_tokens(tokens);
197    }
198}
199
200impl FromStr for Discriminant {
201    type Err = Error;
202
203    fn from_str(mut s: &str) -> Result<Self> {
204        let sign = if s.starts_with('-') {
205            s = &s[1..];
206            Sign::Negative
207        } else {
208            Sign::Positive
209        };
210        match s.parse::<u64>() {
211            Ok(magnitude) => Ok(Discriminant { sign, magnitude }),
212            Err(_) => Err(Error::new(
213                Span::call_site(),
214                "discriminant value outside of supported range",
215            )),
216        }
217    }
218}
219
220impl Ord for Discriminant {
221    fn cmp(&self, other: &Self) -> Ordering {
222        use self::Sign::{Negative, Positive};
223        match (self.sign, other.sign) {
224            (Negative, Negative) => self.magnitude.cmp(&other.magnitude).reverse(),
225            (Negative, Positive) => Ordering::Less, // negative < positive
226            (Positive, Negative) => Ordering::Greater, // positive > negative
227            (Positive, Positive) => self.magnitude.cmp(&other.magnitude),
228        }
229    }
230}
231
232impl PartialOrd for Discriminant {
233    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
234        Some(self.cmp(other))
235    }
236}
237
238fn parse_int_suffix(suffix: &str) -> Result<Option<Atom>> {
239    if suffix.is_empty() {
240        return Ok(None);
241    }
242    if let Some(atom) = Atom::from_str(suffix) {
243        match atom {
244            U8 | U16 | U32 | U64 | Usize | I8 | I16 | I32 | I64 | Isize => return Ok(Some(atom)),
245            _ => {}
246        }
247    }
248    let msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("unrecognized integer suffix: `{0}`",
                suffix))
    })format!("unrecognized integer suffix: `{}`", suffix);
249    Err(Error::new(Span::call_site(), msg))
250}
251
252#[derive(#[automatically_derived]
impl ::core::marker::Copy for Limits { }Copy, #[automatically_derived]
impl ::core::clone::Clone for Limits {
    #[inline]
    fn clone(&self) -> Limits {
        let _: ::core::clone::AssertParamIsClone<Atom>;
        let _: ::core::clone::AssertParamIsClone<Discriminant>;
        *self
    }
}Clone)]
253pub(crate) struct Limits {
254    pub repr: Atom,
255    pub min: Discriminant,
256    pub max: Discriminant,
257}
258
259impl Limits {
260    pub(crate) fn of(repr: Atom) -> Option<Limits> {
261        for limits in &LIMITS {
262            if limits.repr == repr {
263                return Some(*limits);
264            }
265        }
266        None
267    }
268}
269
270const LIMITS: [Limits; 8] = [
271    Limits {
272        repr: U8,
273        min: Discriminant::zero(),
274        max: Discriminant::pos(u8::MAX as u64),
275    },
276    Limits {
277        repr: I8,
278        min: Discriminant::neg(i8::MIN as i64),
279        max: Discriminant::pos(i8::MAX as u64),
280    },
281    Limits {
282        repr: U16,
283        min: Discriminant::zero(),
284        max: Discriminant::pos(u16::MAX as u64),
285    },
286    Limits {
287        repr: I16,
288        min: Discriminant::neg(i16::MIN as i64),
289        max: Discriminant::pos(i16::MAX as u64),
290    },
291    Limits {
292        repr: U32,
293        min: Discriminant::zero(),
294        max: Discriminant::pos(u32::MAX as u64),
295    },
296    Limits {
297        repr: I32,
298        min: Discriminant::neg(i32::MIN as i64),
299        max: Discriminant::pos(i32::MAX as u64),
300    },
301    Limits {
302        repr: U64,
303        min: Discriminant::zero(),
304        max: Discriminant::pos(u64::MAX),
305    },
306    Limits {
307        repr: I64,
308        min: Discriminant::neg(i64::MIN),
309        max: Discriminant::pos(i64::MAX as u64),
310    },
311];