blob: 4caa42b56cc12b1db081d16b883e30e00488cff6 [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 {
David Tolnayddf69e22020-05-10 22:08:20 -070023 pub fn new(repr: Option<Atom>) -> Self {
David Tolnay17e137f2020-05-08 15:55:28 -070024 DiscriminantSet {
David Tolnayddf69e22020-05-10 22:08:20 -070025 repr,
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> {
David Tolnay5966f7b2020-05-10 22:53:24 -0700103 if let Some(expected_repr) = set.repr {
104 for bounds in &BOUNDS {
105 if bounds.repr != expected_repr {
106 continue;
107 }
108 if bounds.min <= discriminant && discriminant <= bounds.max {
109 break;
110 }
111 let msg = format!(
112 "discriminant value `{}` is outside the limits of {}",
113 discriminant, expected_repr,
114 );
115 return Err(Error::new(Span::call_site(), msg));
116 }
117 }
David Tolnay17e137f2020-05-08 15:55:28 -0700118 if set.values.insert(discriminant) {
119 set.previous = Some(discriminant);
120 Ok(discriminant)
121 } else {
122 let msg = format!("discriminant value `{}` already exists", discriminant);
123 Err(Error::new(Span::call_site(), msg))
124 }
125}
126
127impl Discriminant {
David Tolnayf1715fa2020-05-10 18:58:49 -0700128 const fn zero() -> Self {
David Tolnay69c79602020-05-10 18:53:31 -0700129 Discriminant {
130 negative: false,
131 magnitude: 0,
132 }
David Tolnay17e137f2020-05-08 15:55:28 -0700133 }
David Tolnayf1715fa2020-05-10 18:58:49 -0700134
135 const fn pos(u: u32) -> Self {
136 Discriminant {
137 negative: false,
138 magnitude: u,
139 }
140 }
141
142 const fn neg(i: i32) -> Self {
143 Discriminant {
144 negative: i < 0,
145 // This is `i.abs() as u32` but without overflow on MIN. Uses the
146 // fact that MIN.wrapping_abs() wraps back to MIN whose binary
147 // representation is 1<<31, and thus the `as u32` conversion
148 // produces 1<<31 too which happens to be the correct unsigned
149 // magnitude.
150 magnitude: i.wrapping_abs() as u32,
151 }
152 }
David Tolnay17e137f2020-05-08 15:55:28 -0700153}
154
155impl Display for Discriminant {
156 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
David Tolnay69c79602020-05-10 18:53:31 -0700157 if self.negative {
158 f.write_str("-")?;
159 }
David Tolnay17e137f2020-05-08 15:55:28 -0700160 Display::fmt(&self.magnitude, f)
161 }
162}
163
164impl ToTokens for Discriminant {
165 fn to_tokens(&self, tokens: &mut TokenStream) {
David Tolnay69c79602020-05-10 18:53:31 -0700166 if self.negative {
167 Token![-](Span::call_site()).to_tokens(tokens);
168 }
David Tolnay17e137f2020-05-08 15:55:28 -0700169 Literal::u32_unsuffixed(self.magnitude).to_tokens(tokens);
170 }
171}
172
173impl FromStr for Discriminant {
174 type Err = Error;
175
David Tolnay69c79602020-05-10 18:53:31 -0700176 fn from_str(mut s: &str) -> Result<Self> {
177 let negative = s.starts_with('-');
178 if negative {
179 s = &s[1..];
180 }
David Tolnay17e137f2020-05-08 15:55:28 -0700181 match s.parse::<u32>() {
David Tolnay69c79602020-05-10 18:53:31 -0700182 Ok(magnitude) => Ok(Discriminant {
183 negative,
184 magnitude,
185 }),
David Tolnay17e137f2020-05-08 15:55:28 -0700186 Err(_) => Err(Error::new(
187 Span::call_site(),
188 "discriminant value outside of supported range",
189 )),
190 }
191 }
192}
David Tolnay9bcb4c62020-05-10 17:42:06 -0700193
David Tolnaye2e303f2020-05-10 20:52:00 -0700194impl Ord for Discriminant {
195 fn cmp(&self, other: &Self) -> Ordering {
196 match (self.negative, other.negative) {
197 (true, true) => self.magnitude.cmp(&other.magnitude).reverse(),
198 (true, false) => Ordering::Less, // negative < positive
199 (false, true) => Ordering::Greater, // positive > negative
200 (false, false) => self.magnitude.cmp(&other.magnitude),
201 }
202 }
203}
204
205impl PartialOrd for Discriminant {
206 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
207 Some(self.cmp(other))
208 }
209}
210
David Tolnay9bcb4c62020-05-10 17:42:06 -0700211fn parse_int_suffix(suffix: &str) -> Result<Option<Atom>> {
212 if suffix.is_empty() {
213 return Ok(None);
214 }
215 if let Some(atom) = Atom::from_str(suffix) {
216 match atom {
217 U8 | U16 | U32 | U64 | Usize | I8 | I16 | I32 | I64 | Isize => return Ok(Some(atom)),
218 _ => {}
219 }
220 }
221 let msg = format!("unrecognized integer suffix: `{}`", suffix);
222 Err(Error::new(Span::call_site(), msg))
223}
David Tolnayf1715fa2020-05-10 18:58:49 -0700224
225struct Bounds {
226 repr: Atom,
227 min: Discriminant,
228 max: Discriminant,
229}
230
231const BOUNDS: [Bounds; 6] = [
232 Bounds {
233 repr: U8,
234 min: Discriminant::zero(),
235 max: Discriminant::pos(u8::MAX as u32),
236 },
237 Bounds {
238 repr: I8,
239 min: Discriminant::neg(i8::MIN as i32),
240 max: Discriminant::pos(i8::MAX as u32),
241 },
242 Bounds {
243 repr: U16,
244 min: Discriminant::zero(),
245 max: Discriminant::pos(u16::MAX as u32),
246 },
247 Bounds {
248 repr: I16,
249 min: Discriminant::neg(i16::MIN as i32),
250 max: Discriminant::pos(i16::MAX as u32),
251 },
252 Bounds {
253 repr: U32,
254 min: Discriminant::zero(),
255 max: Discriminant::pos(u32::MAX),
256 },
257 Bounds {
258 repr: I32,
259 min: Discriminant::neg(i32::MIN),
260 max: Discriminant::pos(i32::MAX as u32),
261 },
262];