cxx_build/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_receiver_is_total_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_receiver_is_total_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        if let Some(limits) = Limits::of(expected_repr) {
137            if discriminant < limits.min || limits.max < discriminant {
138                let msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("discriminant value `{0}` is outside the limits of {1}",
                discriminant, expected_repr))
    })format!(
139                    "discriminant value `{}` is outside the limits of {}",
140                    discriminant, expected_repr,
141                );
142                return Err(Error::new(Span::call_site(), msg));
143            }
144        }
145    }
146    set.values.insert(discriminant);
147    set.previous = Some(discriminant);
148    Ok(discriminant)
149}
150
151impl Discriminant {
152    pub(crate) const fn zero() -> Self {
153        Discriminant {
154            sign: Sign::Positive,
155            magnitude: 0,
156        }
157    }
158
159    const fn pos(u: u64) -> Self {
160        Discriminant {
161            sign: Sign::Positive,
162            magnitude: u,
163        }
164    }
165
166    const fn neg(i: i64) -> Self {
167        Discriminant {
168            sign: if i < 0 {
169                Sign::Negative
170            } else {
171                Sign::Positive
172            },
173            // This is `i.abs() as u64` but without overflow on MIN. Uses the
174            // fact that MIN.wrapping_abs() wraps back to MIN whose binary
175            // representation is 1<<63, and thus the `as u64` conversion
176            // produces 1<<63 too which happens to be the correct unsigned
177            // magnitude.
178            magnitude: i.wrapping_abs() as u64,
179        }
180    }
181}
182
183impl Display for Discriminant {
184    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
185        if self.sign == Sign::Negative {
186            f.write_str("-")?;
187        }
188        f.write_fmt(format_args!("{0}", self.magnitude))write!(f, "{}", self.magnitude)
189    }
190}
191
192impl ToTokens for Discriminant {
193    fn to_tokens(&self, tokens: &mut TokenStream) {
194        if self.sign == Sign::Negative {
195            ::syn::token::MinusToken![-](Span::call_site()).to_tokens(tokens);
196        }
197        Literal::u64_unsuffixed(self.magnitude).to_tokens(tokens);
198    }
199}
200
201impl FromStr for Discriminant {
202    type Err = Error;
203
204    fn from_str(mut s: &str) -> Result<Self> {
205        let sign = if s.starts_with('-') {
206            s = &s[1..];
207            Sign::Negative
208        } else {
209            Sign::Positive
210        };
211        match s.parse::<u64>() {
212            Ok(magnitude) => Ok(Discriminant { sign, magnitude }),
213            Err(_) => Err(Error::new(
214                Span::call_site(),
215                "discriminant value outside of supported range",
216            )),
217        }
218    }
219}
220
221impl Ord for Discriminant {
222    fn cmp(&self, other: &Self) -> Ordering {
223        use self::Sign::{Negative, Positive};
224        match (self.sign, other.sign) {
225            (Negative, Negative) => self.magnitude.cmp(&other.magnitude).reverse(),
226            (Negative, Positive) => Ordering::Less, // negative < positive
227            (Positive, Negative) => Ordering::Greater, // positive > negative
228            (Positive, Positive) => self.magnitude.cmp(&other.magnitude),
229        }
230    }
231}
232
233impl PartialOrd for Discriminant {
234    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
235        Some(self.cmp(other))
236    }
237}
238
239fn parse_int_suffix(suffix: &str) -> Result<Option<Atom>> {
240    if suffix.is_empty() {
241        return Ok(None);
242    }
243    if let Some(atom) = Atom::from_str(suffix) {
244        match atom {
245            U8 | U16 | U32 | U64 | Usize | I8 | I16 | I32 | I64 | Isize => return Ok(Some(atom)),
246            _ => {}
247        }
248    }
249    let msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("unrecognized integer suffix: `{0}`",
                suffix))
    })format!("unrecognized integer suffix: `{}`", suffix);
250    Err(Error::new(Span::call_site(), msg))
251}
252
253#[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)]
254pub(crate) struct Limits {
255    pub repr: Atom,
256    pub min: Discriminant,
257    pub max: Discriminant,
258}
259
260impl Limits {
261    pub(crate) fn of(repr: Atom) -> Option<Limits> {
262        for limits in &LIMITS {
263            if limits.repr == repr {
264                return Some(*limits);
265            }
266        }
267        None
268    }
269}
270
271const LIMITS: [Limits; 8] = [
272    Limits {
273        repr: U8,
274        min: Discriminant::zero(),
275        max: Discriminant::pos(u8::MAX as u64),
276    },
277    Limits {
278        repr: I8,
279        min: Discriminant::neg(i8::MIN as i64),
280        max: Discriminant::pos(i8::MAX as u64),
281    },
282    Limits {
283        repr: U16,
284        min: Discriminant::zero(),
285        max: Discriminant::pos(u16::MAX as u64),
286    },
287    Limits {
288        repr: I16,
289        min: Discriminant::neg(i16::MIN as i64),
290        max: Discriminant::pos(i16::MAX as u64),
291    },
292    Limits {
293        repr: U32,
294        min: Discriminant::zero(),
295        max: Discriminant::pos(u32::MAX as u64),
296    },
297    Limits {
298        repr: I32,
299        min: Discriminant::neg(i32::MIN as i64),
300        max: Discriminant::pos(i32::MAX as u64),
301    },
302    Limits {
303        repr: U64,
304        min: Discriminant::zero(),
305        max: Discriminant::pos(u64::MAX),
306    },
307    Limits {
308        repr: I64,
309        min: Discriminant::neg(i64::MIN),
310        max: Discriminant::pos(i64::MAX as u64),
311    },
312];