blob: 388a117a7a569672b49aaaf97b0e683e89d75ee0 [file] [log] [blame]
David Tolnay9bcb4c62020-05-10 17:42:06 -07001use crate::syntax::Atom::{self, *};
David Tolnay17e137f2020-05-08 15:55:28 -07002use proc_macro2::{Literal, Span, TokenStream};
3use quote::ToTokens;
David Tolnaye2e303f2020-05-10 20:52:00 -07004use std::cmp::Ordering;
5use std::collections::BTreeSet;
David Tolnay17e137f2020-05-08 15:55:28 -07006use std::fmt::{self, Display};
7use std::str::FromStr;
David Tolnay69c79602020-05-10 18:53:31 -07008use syn::{Error, Expr, Lit, Result, Token, UnOp};
David Tolnay17e137f2020-05-08 15:55:28 -07009
10pub struct DiscriminantSet {
David Tolnay9bcb4c62020-05-10 17:42:06 -070011 repr: Option<Atom>,
David Tolnaye2e303f2020-05-10 20:52:00 -070012 values: BTreeSet<Discriminant>,
David Tolnay17e137f2020-05-08 15:55:28 -070013 previous: Option<Discriminant>,
14}
15
David Tolnaye2e303f2020-05-10 20:52:00 -070016#[derive(Copy, Clone, Eq, PartialEq)]
David Tolnay17e137f2020-05-08 15:55:28 -070017pub struct Discriminant {
David Tolnay69c79602020-05-10 18:53:31 -070018 negative: bool,
David Tolnay17e137f2020-05-08 15:55:28 -070019 magnitude: u32,
20}
21
22impl DiscriminantSet {
23 pub fn new() -> Self {
24 DiscriminantSet {
David Tolnay9bcb4c62020-05-10 17:42:06 -070025 repr: None,
David Tolnaye2e303f2020-05-10 20:52:00 -070026 values: BTreeSet::new(),
David Tolnay17e137f2020-05-08 15:55:28 -070027 previous: None,
28 }
29 }
30
31 pub fn insert(&mut self, expr: &Expr) -> Result<Discriminant> {
David Tolnay9bcb4c62020-05-10 17:42:06 -070032 let (discriminant, repr) = expr_to_discriminant(expr)?;
33 self.repr = self.repr.or(repr);
David Tolnay17e137f2020-05-08 15:55:28 -070034 insert(self, discriminant)
35 }
36
37 pub fn insert_next(&mut self) -> Result<Discriminant> {
38 let discriminant = match self.previous {
39 None => Discriminant::zero(),
David Tolnay69c79602020-05-10 18:53:31 -070040 Some(mut discriminant) if discriminant.negative => {
41 discriminant.magnitude -= 1;
42 if discriminant.magnitude == 0 {
43 discriminant.negative = false;
44 }
45 discriminant
46 }
David Tolnay17e137f2020-05-08 15:55:28 -070047 Some(mut discriminant) => {
48 if discriminant.magnitude == u32::MAX {
49 let msg = format!("discriminant overflow on value after {}", u32::MAX);
50 return Err(Error::new(Span::call_site(), msg));
51 }
52 discriminant.magnitude += 1;
53 discriminant
54 }
55 };
56 insert(self, discriminant)
57 }
David Tolnaye2e303f2020-05-10 20:52:00 -070058
59 pub fn inferred_repr(&self) -> Result<Atom> {
60 if let Some(repr) = self.repr {
61 return Ok(repr);
62 }
63 if self.values.is_empty() {
64 return Ok(U8);
65 }
66 let min = *self.values.iter().next().unwrap();
67 let max = *self.values.iter().next_back().unwrap();
68 for bounds in &BOUNDS {
69 if bounds.min <= min && max <= bounds.max {
70 return Ok(bounds.repr);
71 }
72 }
73 let msg = "these discriminant values do not fit in any supported enum repr type";
74 Err(Error::new(Span::call_site(), msg))
75 }
David Tolnay17e137f2020-05-08 15:55:28 -070076}
77
David Tolnay9bcb4c62020-05-10 17:42:06 -070078fn expr_to_discriminant(expr: &Expr) -> Result<(Discriminant, Option<Atom>)> {
David Tolnay69c79602020-05-10 18:53:31 -070079 match expr {
80 Expr::Lit(expr) => {
81 if let Lit::Int(lit) = &expr.lit {
David Tolnay9bcb4c62020-05-10 17:42:06 -070082 let discriminant = lit.base10_parse::<Discriminant>()?;
83 let repr = parse_int_suffix(lit.suffix())?;
84 return Ok((discriminant, repr));
David Tolnay69c79602020-05-10 18:53:31 -070085 }
David Tolnay17e137f2020-05-08 15:55:28 -070086 }
David Tolnay69c79602020-05-10 18:53:31 -070087 Expr::Unary(unary) => {
88 if let UnOp::Neg(_) = unary.op {
David Tolnay9bcb4c62020-05-10 17:42:06 -070089 let (mut discriminant, repr) = expr_to_discriminant(&unary.expr)?;
David Tolnay69c79602020-05-10 18:53:31 -070090 discriminant.negative ^= true;
David Tolnay9bcb4c62020-05-10 17:42:06 -070091 return Ok((discriminant, repr));
David Tolnay69c79602020-05-10 18:53:31 -070092 }
93 }
94 _ => {}
David Tolnay17e137f2020-05-08 15:55:28 -070095 }
96 Err(Error::new_spanned(
97 expr,
98 "enums with non-integer literal discriminants are not supported yet",
99 ))
100}
101
102fn insert(set: &mut DiscriminantSet, discriminant: Discriminant) -> Result<Discriminant> {
103 if set.values.insert(discriminant) {
104 set.previous = Some(discriminant);
105 Ok(discriminant)
106 } else {
107 let msg = format!("discriminant value `{}` already exists", discriminant);
108 Err(Error::new(Span::call_site(), msg))
109 }
110}
111
112impl Discriminant {
David Tolnayf1715fa2020-05-10 18:58:49 -0700113 const fn zero() -> Self {
David Tolnay69c79602020-05-10 18:53:31 -0700114 Discriminant {
115 negative: false,
116 magnitude: 0,
117 }
David Tolnay17e137f2020-05-08 15:55:28 -0700118 }
David Tolnayf1715fa2020-05-10 18:58:49 -0700119
120 const fn pos(u: u32) -> Self {
121 Discriminant {
122 negative: false,
123 magnitude: u,
124 }
125 }
126
127 const fn neg(i: i32) -> Self {
128 Discriminant {
129 negative: i < 0,
130 // This is `i.abs() as u32` but without overflow on MIN. Uses the
131 // fact that MIN.wrapping_abs() wraps back to MIN whose binary
132 // representation is 1<<31, and thus the `as u32` conversion
133 // produces 1<<31 too which happens to be the correct unsigned
134 // magnitude.
135 magnitude: i.wrapping_abs() as u32,
136 }
137 }
David Tolnay17e137f2020-05-08 15:55:28 -0700138}
139
140impl Display for Discriminant {
141 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
David Tolnay69c79602020-05-10 18:53:31 -0700142 if self.negative {
143 f.write_str("-")?;
144 }
David Tolnay17e137f2020-05-08 15:55:28 -0700145 Display::fmt(&self.magnitude, f)
146 }
147}
148
149impl ToTokens for Discriminant {
150 fn to_tokens(&self, tokens: &mut TokenStream) {
David Tolnay69c79602020-05-10 18:53:31 -0700151 if self.negative {
152 Token![-](Span::call_site()).to_tokens(tokens);
153 }
David Tolnay17e137f2020-05-08 15:55:28 -0700154 Literal::u32_unsuffixed(self.magnitude).to_tokens(tokens);
155 }
156}
157
158impl FromStr for Discriminant {
159 type Err = Error;
160
David Tolnay69c79602020-05-10 18:53:31 -0700161 fn from_str(mut s: &str) -> Result<Self> {
162 let negative = s.starts_with('-');
163 if negative {
164 s = &s[1..];
165 }
David Tolnay17e137f2020-05-08 15:55:28 -0700166 match s.parse::<u32>() {
David Tolnay69c79602020-05-10 18:53:31 -0700167 Ok(magnitude) => Ok(Discriminant {
168 negative,
169 magnitude,
170 }),
David Tolnay17e137f2020-05-08 15:55:28 -0700171 Err(_) => Err(Error::new(
172 Span::call_site(),
173 "discriminant value outside of supported range",
174 )),
175 }
176 }
177}
David Tolnay9bcb4c62020-05-10 17:42:06 -0700178
David Tolnaye2e303f2020-05-10 20:52:00 -0700179impl Ord for Discriminant {
180 fn cmp(&self, other: &Self) -> Ordering {
181 match (self.negative, other.negative) {
182 (true, true) => self.magnitude.cmp(&other.magnitude).reverse(),
183 (true, false) => Ordering::Less, // negative < positive
184 (false, true) => Ordering::Greater, // positive > negative
185 (false, false) => self.magnitude.cmp(&other.magnitude),
186 }
187 }
188}
189
190impl PartialOrd for Discriminant {
191 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
192 Some(self.cmp(other))
193 }
194}
195
David Tolnay9bcb4c62020-05-10 17:42:06 -0700196fn parse_int_suffix(suffix: &str) -> Result<Option<Atom>> {
197 if suffix.is_empty() {
198 return Ok(None);
199 }
200 if let Some(atom) = Atom::from_str(suffix) {
201 match atom {
202 U8 | U16 | U32 | U64 | Usize | I8 | I16 | I32 | I64 | Isize => return Ok(Some(atom)),
203 _ => {}
204 }
205 }
206 let msg = format!("unrecognized integer suffix: `{}`", suffix);
207 Err(Error::new(Span::call_site(), msg))
208}
David Tolnayf1715fa2020-05-10 18:58:49 -0700209
210struct Bounds {
211 repr: Atom,
212 min: Discriminant,
213 max: Discriminant,
214}
215
216const BOUNDS: [Bounds; 6] = [
217 Bounds {
218 repr: U8,
219 min: Discriminant::zero(),
220 max: Discriminant::pos(u8::MAX as u32),
221 },
222 Bounds {
223 repr: I8,
224 min: Discriminant::neg(i8::MIN as i32),
225 max: Discriminant::pos(i8::MAX as u32),
226 },
227 Bounds {
228 repr: U16,
229 min: Discriminant::zero(),
230 max: Discriminant::pos(u16::MAX as u32),
231 },
232 Bounds {
233 repr: I16,
234 min: Discriminant::neg(i16::MIN as i32),
235 max: Discriminant::pos(i16::MAX as u32),
236 },
237 Bounds {
238 repr: U32,
239 min: Discriminant::zero(),
240 max: Discriminant::pos(u32::MAX),
241 },
242 Bounds {
243 repr: I32,
244 min: Discriminant::neg(i32::MIN),
245 max: Discriminant::pos(i32::MAX as u32),
246 },
247];