blob: 6a04d8811d4a711be759e6058f47a4a83a31ec69 [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 Tolnay17451de2020-05-10 23:49:12 -07008use std::u64;
David Tolnay69c79602020-05-10 18:53:31 -07009use syn::{Error, Expr, Lit, Result, Token, UnOp};
David Tolnay17e137f2020-05-08 15:55:28 -070010
11pub struct DiscriminantSet {
David Tolnay9bcb4c62020-05-10 17:42:06 -070012 repr: Option<Atom>,
David Tolnaye2e303f2020-05-10 20:52:00 -070013 values: BTreeSet<Discriminant>,
David Tolnay17e137f2020-05-08 15:55:28 -070014 previous: Option<Discriminant>,
15}
16
David Tolnaye2e303f2020-05-10 20:52:00 -070017#[derive(Copy, Clone, Eq, PartialEq)]
David Tolnay17e137f2020-05-08 15:55:28 -070018pub struct Discriminant {
David Tolnay69c79602020-05-10 18:53:31 -070019 negative: bool,
David Tolnayf2d58412020-05-10 23:22:23 -070020 magnitude: u64,
David Tolnay17e137f2020-05-08 15:55:28 -070021}
22
23impl DiscriminantSet {
David Tolnayddf69e22020-05-10 22:08:20 -070024 pub fn new(repr: Option<Atom>) -> Self {
David Tolnay17e137f2020-05-08 15:55:28 -070025 DiscriminantSet {
David Tolnayddf69e22020-05-10 22:08:20 -070026 repr,
David Tolnaye2e303f2020-05-10 20:52:00 -070027 values: BTreeSet::new(),
David Tolnay17e137f2020-05-08 15:55:28 -070028 previous: None,
29 }
30 }
31
32 pub fn insert(&mut self, expr: &Expr) -> Result<Discriminant> {
David Tolnay9bcb4c62020-05-10 17:42:06 -070033 let (discriminant, repr) = expr_to_discriminant(expr)?;
David Tolnay94cce002020-05-10 23:19:39 -070034 match (self.repr, repr) {
David Tolnay65bc8e62020-05-11 00:24:31 -070035 (None, Some(new_repr)) => {
36 if let Some(limits) = Limits::of(new_repr) {
37 for &past in &self.values {
38 if limits.min <= past && past <= limits.max {
39 continue;
40 }
41 let msg = format!(
42 "discriminant value `{}` is outside the limits of {}",
43 past, new_repr,
44 );
45 return Err(Error::new(Span::call_site(), msg));
46 }
47 }
48 self.repr = Some(new_repr);
49 }
David Tolnay94cce002020-05-10 23:19:39 -070050 (Some(prev), Some(repr)) if prev != repr => {
51 let msg = format!("expected {}, found {}", prev, repr);
52 return Err(Error::new(Span::call_site(), msg));
53 }
54 _ => {}
55 }
David Tolnay17e137f2020-05-08 15:55:28 -070056 insert(self, discriminant)
57 }
58
59 pub fn insert_next(&mut self) -> Result<Discriminant> {
60 let discriminant = match self.previous {
61 None => Discriminant::zero(),
David Tolnay69c79602020-05-10 18:53:31 -070062 Some(mut discriminant) if discriminant.negative => {
63 discriminant.magnitude -= 1;
64 if discriminant.magnitude == 0 {
65 discriminant.negative = false;
66 }
67 discriminant
68 }
David Tolnay17e137f2020-05-08 15:55:28 -070069 Some(mut discriminant) => {
David Tolnayf2d58412020-05-10 23:22:23 -070070 if discriminant.magnitude == u64::MAX {
71 let msg = format!("discriminant overflow on value after {}", u64::MAX);
David Tolnay17e137f2020-05-08 15:55:28 -070072 return Err(Error::new(Span::call_site(), msg));
73 }
74 discriminant.magnitude += 1;
75 discriminant
76 }
77 };
78 insert(self, discriminant)
79 }
David Tolnaye2e303f2020-05-10 20:52:00 -070080
81 pub fn inferred_repr(&self) -> Result<Atom> {
82 if let Some(repr) = self.repr {
83 return Ok(repr);
84 }
85 if self.values.is_empty() {
86 return Ok(U8);
87 }
88 let min = *self.values.iter().next().unwrap();
89 let max = *self.values.iter().next_back().unwrap();
David Tolnay9f7c55a2020-05-11 00:19:01 -070090 for limits in &LIMITS {
91 if limits.min <= min && max <= limits.max {
92 return Ok(limits.repr);
David Tolnaye2e303f2020-05-10 20:52:00 -070093 }
94 }
95 let msg = "these discriminant values do not fit in any supported enum repr type";
96 Err(Error::new(Span::call_site(), msg))
97 }
David Tolnay17e137f2020-05-08 15:55:28 -070098}
99
David Tolnay9bcb4c62020-05-10 17:42:06 -0700100fn expr_to_discriminant(expr: &Expr) -> Result<(Discriminant, Option<Atom>)> {
David Tolnay69c79602020-05-10 18:53:31 -0700101 match expr {
102 Expr::Lit(expr) => {
103 if let Lit::Int(lit) = &expr.lit {
David Tolnay9bcb4c62020-05-10 17:42:06 -0700104 let discriminant = lit.base10_parse::<Discriminant>()?;
105 let repr = parse_int_suffix(lit.suffix())?;
106 return Ok((discriminant, repr));
David Tolnay69c79602020-05-10 18:53:31 -0700107 }
David Tolnay17e137f2020-05-08 15:55:28 -0700108 }
David Tolnay69c79602020-05-10 18:53:31 -0700109 Expr::Unary(unary) => {
110 if let UnOp::Neg(_) = unary.op {
David Tolnay9bcb4c62020-05-10 17:42:06 -0700111 let (mut discriminant, repr) = expr_to_discriminant(&unary.expr)?;
David Tolnay69c79602020-05-10 18:53:31 -0700112 discriminant.negative ^= true;
David Tolnay9bcb4c62020-05-10 17:42:06 -0700113 return Ok((discriminant, repr));
David Tolnay69c79602020-05-10 18:53:31 -0700114 }
115 }
116 _ => {}
David Tolnay17e137f2020-05-08 15:55:28 -0700117 }
118 Err(Error::new_spanned(
119 expr,
120 "enums with non-integer literal discriminants are not supported yet",
121 ))
122}
123
124fn insert(set: &mut DiscriminantSet, discriminant: Discriminant) -> Result<Discriminant> {
David Tolnay5966f7b2020-05-10 22:53:24 -0700125 if let Some(expected_repr) = set.repr {
David Tolnay65bc8e62020-05-11 00:24:31 -0700126 if let Some(limits) = Limits::of(expected_repr) {
127 if discriminant < limits.min || limits.max < discriminant {
128 let msg = format!(
129 "discriminant value `{}` is outside the limits of {}",
130 discriminant, expected_repr,
131 );
132 return Err(Error::new(Span::call_site(), msg));
David Tolnay5966f7b2020-05-10 22:53:24 -0700133 }
David Tolnay5966f7b2020-05-10 22:53:24 -0700134 }
135 }
David Tolnay17e137f2020-05-08 15:55:28 -0700136 if set.values.insert(discriminant) {
137 set.previous = Some(discriminant);
138 Ok(discriminant)
139 } else {
140 let msg = format!("discriminant value `{}` already exists", discriminant);
141 Err(Error::new(Span::call_site(), msg))
142 }
143}
144
145impl Discriminant {
David Tolnayf1715fa2020-05-10 18:58:49 -0700146 const fn zero() -> Self {
David Tolnay69c79602020-05-10 18:53:31 -0700147 Discriminant {
148 negative: false,
149 magnitude: 0,
150 }
David Tolnay17e137f2020-05-08 15:55:28 -0700151 }
David Tolnayf1715fa2020-05-10 18:58:49 -0700152
David Tolnayf2d58412020-05-10 23:22:23 -0700153 const fn pos(u: u64) -> Self {
David Tolnayf1715fa2020-05-10 18:58:49 -0700154 Discriminant {
155 negative: false,
156 magnitude: u,
157 }
158 }
159
David Tolnayf2d58412020-05-10 23:22:23 -0700160 const fn neg(i: i64) -> Self {
David Tolnayf1715fa2020-05-10 18:58:49 -0700161 Discriminant {
162 negative: i < 0,
David Tolnayf2d58412020-05-10 23:22:23 -0700163 // This is `i.abs() as u64` but without overflow on MIN. Uses the
David Tolnayf1715fa2020-05-10 18:58:49 -0700164 // fact that MIN.wrapping_abs() wraps back to MIN whose binary
David Tolnayf2d58412020-05-10 23:22:23 -0700165 // representation is 1<<63, and thus the `as u64` conversion
166 // produces 1<<63 too which happens to be the correct unsigned
David Tolnayf1715fa2020-05-10 18:58:49 -0700167 // magnitude.
David Tolnayf2d58412020-05-10 23:22:23 -0700168 magnitude: i.wrapping_abs() as u64,
David Tolnayf1715fa2020-05-10 18:58:49 -0700169 }
170 }
David Tolnay17e137f2020-05-08 15:55:28 -0700171}
172
173impl Display for Discriminant {
174 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
David Tolnay69c79602020-05-10 18:53:31 -0700175 if self.negative {
176 f.write_str("-")?;
177 }
David Tolnay17e137f2020-05-08 15:55:28 -0700178 Display::fmt(&self.magnitude, f)
179 }
180}
181
182impl ToTokens for Discriminant {
183 fn to_tokens(&self, tokens: &mut TokenStream) {
David Tolnay69c79602020-05-10 18:53:31 -0700184 if self.negative {
185 Token![-](Span::call_site()).to_tokens(tokens);
186 }
David Tolnayf2d58412020-05-10 23:22:23 -0700187 Literal::u64_unsuffixed(self.magnitude).to_tokens(tokens);
David Tolnay17e137f2020-05-08 15:55:28 -0700188 }
189}
190
191impl FromStr for Discriminant {
192 type Err = Error;
193
David Tolnay69c79602020-05-10 18:53:31 -0700194 fn from_str(mut s: &str) -> Result<Self> {
195 let negative = s.starts_with('-');
196 if negative {
197 s = &s[1..];
198 }
David Tolnayf2d58412020-05-10 23:22:23 -0700199 match s.parse::<u64>() {
David Tolnay69c79602020-05-10 18:53:31 -0700200 Ok(magnitude) => Ok(Discriminant {
201 negative,
202 magnitude,
203 }),
David Tolnay17e137f2020-05-08 15:55:28 -0700204 Err(_) => Err(Error::new(
205 Span::call_site(),
206 "discriminant value outside of supported range",
207 )),
208 }
209 }
210}
David Tolnay9bcb4c62020-05-10 17:42:06 -0700211
David Tolnaye2e303f2020-05-10 20:52:00 -0700212impl Ord for Discriminant {
213 fn cmp(&self, other: &Self) -> Ordering {
214 match (self.negative, other.negative) {
215 (true, true) => self.magnitude.cmp(&other.magnitude).reverse(),
216 (true, false) => Ordering::Less, // negative < positive
217 (false, true) => Ordering::Greater, // positive > negative
218 (false, false) => self.magnitude.cmp(&other.magnitude),
219 }
220 }
221}
222
223impl PartialOrd for Discriminant {
224 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
225 Some(self.cmp(other))
226 }
227}
228
David Tolnay9bcb4c62020-05-10 17:42:06 -0700229fn parse_int_suffix(suffix: &str) -> Result<Option<Atom>> {
230 if suffix.is_empty() {
231 return Ok(None);
232 }
233 if let Some(atom) = Atom::from_str(suffix) {
234 match atom {
235 U8 | U16 | U32 | U64 | Usize | I8 | I16 | I32 | I64 | Isize => return Ok(Some(atom)),
236 _ => {}
237 }
238 }
239 let msg = format!("unrecognized integer suffix: `{}`", suffix);
240 Err(Error::new(Span::call_site(), msg))
241}
David Tolnayf1715fa2020-05-10 18:58:49 -0700242
David Tolnay65bc8e62020-05-11 00:24:31 -0700243#[derive(Copy, Clone)]
David Tolnay9f7c55a2020-05-11 00:19:01 -0700244struct Limits {
David Tolnayf1715fa2020-05-10 18:58:49 -0700245 repr: Atom,
246 min: Discriminant,
247 max: Discriminant,
248}
249
David Tolnay65bc8e62020-05-11 00:24:31 -0700250impl Limits {
251 fn of(repr: Atom) -> Option<Limits> {
252 for limits in &LIMITS {
253 if limits.repr == repr {
254 return Some(*limits);
255 }
256 }
257 None
258 }
259}
260
David Tolnay9f7c55a2020-05-11 00:19:01 -0700261const LIMITS: [Limits; 8] = [
262 Limits {
David Tolnayf1715fa2020-05-10 18:58:49 -0700263 repr: U8,
264 min: Discriminant::zero(),
David Tolnay17451de2020-05-10 23:49:12 -0700265 max: Discriminant::pos(std::u8::MAX as u64),
David Tolnayf1715fa2020-05-10 18:58:49 -0700266 },
David Tolnay9f7c55a2020-05-11 00:19:01 -0700267 Limits {
David Tolnayf1715fa2020-05-10 18:58:49 -0700268 repr: I8,
David Tolnay17451de2020-05-10 23:49:12 -0700269 min: Discriminant::neg(std::i8::MIN as i64),
270 max: Discriminant::pos(std::i8::MAX as u64),
David Tolnayf1715fa2020-05-10 18:58:49 -0700271 },
David Tolnay9f7c55a2020-05-11 00:19:01 -0700272 Limits {
David Tolnayf1715fa2020-05-10 18:58:49 -0700273 repr: U16,
274 min: Discriminant::zero(),
David Tolnay17451de2020-05-10 23:49:12 -0700275 max: Discriminant::pos(std::u16::MAX as u64),
David Tolnayf1715fa2020-05-10 18:58:49 -0700276 },
David Tolnay9f7c55a2020-05-11 00:19:01 -0700277 Limits {
David Tolnayf1715fa2020-05-10 18:58:49 -0700278 repr: I16,
David Tolnay17451de2020-05-10 23:49:12 -0700279 min: Discriminant::neg(std::i16::MIN as i64),
280 max: Discriminant::pos(std::i16::MAX as u64),
David Tolnayf1715fa2020-05-10 18:58:49 -0700281 },
David Tolnay9f7c55a2020-05-11 00:19:01 -0700282 Limits {
David Tolnayf1715fa2020-05-10 18:58:49 -0700283 repr: U32,
284 min: Discriminant::zero(),
David Tolnay17451de2020-05-10 23:49:12 -0700285 max: Discriminant::pos(std::u32::MAX as u64),
David Tolnayf1715fa2020-05-10 18:58:49 -0700286 },
David Tolnay9f7c55a2020-05-11 00:19:01 -0700287 Limits {
David Tolnayf1715fa2020-05-10 18:58:49 -0700288 repr: I32,
David Tolnay17451de2020-05-10 23:49:12 -0700289 min: Discriminant::neg(std::i32::MIN as i64),
290 max: Discriminant::pos(std::i32::MAX as u64),
David Tolnayf2d58412020-05-10 23:22:23 -0700291 },
David Tolnay9f7c55a2020-05-11 00:19:01 -0700292 Limits {
David Tolnayf2d58412020-05-10 23:22:23 -0700293 repr: U64,
294 min: Discriminant::zero(),
David Tolnay17451de2020-05-10 23:49:12 -0700295 max: Discriminant::pos(std::u64::MAX),
David Tolnayf2d58412020-05-10 23:22:23 -0700296 },
David Tolnay9f7c55a2020-05-11 00:19:01 -0700297 Limits {
David Tolnayf2d58412020-05-10 23:22:23 -0700298 repr: I64,
David Tolnay17451de2020-05-10 23:49:12 -0700299 min: Discriminant::neg(std::i64::MIN),
300 max: Discriminant::pos(std::i64::MAX as u64),
David Tolnayf1715fa2020-05-10 18:58:49 -0700301 },
302];