blob: 5e39f63a201aaa44b5ce7a64e1871f710eaaa69a [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 Tolnayced2adc2020-11-19 19:52:54 -0800136 set.values.insert(discriminant);
137 set.previous = Some(discriminant);
138 Ok(discriminant)
David Tolnay17e137f2020-05-08 15:55:28 -0700139}
140
141impl Discriminant {
David Tolnayf1715fa2020-05-10 18:58:49 -0700142 const fn zero() -> Self {
David Tolnay69c79602020-05-10 18:53:31 -0700143 Discriminant {
144 negative: false,
145 magnitude: 0,
146 }
David Tolnay17e137f2020-05-08 15:55:28 -0700147 }
David Tolnayf1715fa2020-05-10 18:58:49 -0700148
David Tolnayf2d58412020-05-10 23:22:23 -0700149 const fn pos(u: u64) -> Self {
David Tolnayf1715fa2020-05-10 18:58:49 -0700150 Discriminant {
151 negative: false,
152 magnitude: u,
153 }
154 }
155
David Tolnayf2d58412020-05-10 23:22:23 -0700156 const fn neg(i: i64) -> Self {
David Tolnayf1715fa2020-05-10 18:58:49 -0700157 Discriminant {
158 negative: i < 0,
David Tolnayf2d58412020-05-10 23:22:23 -0700159 // This is `i.abs() as u64` but without overflow on MIN. Uses the
David Tolnayf1715fa2020-05-10 18:58:49 -0700160 // fact that MIN.wrapping_abs() wraps back to MIN whose binary
David Tolnayf2d58412020-05-10 23:22:23 -0700161 // representation is 1<<63, and thus the `as u64` conversion
162 // produces 1<<63 too which happens to be the correct unsigned
David Tolnayf1715fa2020-05-10 18:58:49 -0700163 // magnitude.
David Tolnayf2d58412020-05-10 23:22:23 -0700164 magnitude: i.wrapping_abs() as u64,
David Tolnayf1715fa2020-05-10 18:58:49 -0700165 }
166 }
David Tolnay17e137f2020-05-08 15:55:28 -0700167}
168
169impl Display for Discriminant {
170 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
David Tolnay69c79602020-05-10 18:53:31 -0700171 if self.negative {
172 f.write_str("-")?;
173 }
David Tolnay17e137f2020-05-08 15:55:28 -0700174 Display::fmt(&self.magnitude, f)
175 }
176}
177
178impl ToTokens for Discriminant {
179 fn to_tokens(&self, tokens: &mut TokenStream) {
David Tolnay69c79602020-05-10 18:53:31 -0700180 if self.negative {
181 Token![-](Span::call_site()).to_tokens(tokens);
182 }
David Tolnayf2d58412020-05-10 23:22:23 -0700183 Literal::u64_unsuffixed(self.magnitude).to_tokens(tokens);
David Tolnay17e137f2020-05-08 15:55:28 -0700184 }
185}
186
187impl FromStr for Discriminant {
188 type Err = Error;
189
David Tolnay69c79602020-05-10 18:53:31 -0700190 fn from_str(mut s: &str) -> Result<Self> {
191 let negative = s.starts_with('-');
192 if negative {
193 s = &s[1..];
194 }
David Tolnayf2d58412020-05-10 23:22:23 -0700195 match s.parse::<u64>() {
David Tolnay69c79602020-05-10 18:53:31 -0700196 Ok(magnitude) => Ok(Discriminant {
197 negative,
198 magnitude,
199 }),
David Tolnay17e137f2020-05-08 15:55:28 -0700200 Err(_) => Err(Error::new(
201 Span::call_site(),
202 "discriminant value outside of supported range",
203 )),
204 }
205 }
206}
David Tolnay9bcb4c62020-05-10 17:42:06 -0700207
David Tolnaye2e303f2020-05-10 20:52:00 -0700208impl Ord for Discriminant {
209 fn cmp(&self, other: &Self) -> Ordering {
210 match (self.negative, other.negative) {
211 (true, true) => self.magnitude.cmp(&other.magnitude).reverse(),
212 (true, false) => Ordering::Less, // negative < positive
213 (false, true) => Ordering::Greater, // positive > negative
214 (false, false) => self.magnitude.cmp(&other.magnitude),
215 }
216 }
217}
218
219impl PartialOrd for Discriminant {
220 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
221 Some(self.cmp(other))
222 }
223}
224
David Tolnay9bcb4c62020-05-10 17:42:06 -0700225fn parse_int_suffix(suffix: &str) -> Result<Option<Atom>> {
226 if suffix.is_empty() {
227 return Ok(None);
228 }
229 if let Some(atom) = Atom::from_str(suffix) {
230 match atom {
231 U8 | U16 | U32 | U64 | Usize | I8 | I16 | I32 | I64 | Isize => return Ok(Some(atom)),
232 _ => {}
233 }
234 }
235 let msg = format!("unrecognized integer suffix: `{}`", suffix);
236 Err(Error::new(Span::call_site(), msg))
237}
David Tolnayf1715fa2020-05-10 18:58:49 -0700238
David Tolnay65bc8e62020-05-11 00:24:31 -0700239#[derive(Copy, Clone)]
David Tolnay9f7c55a2020-05-11 00:19:01 -0700240struct Limits {
David Tolnayf1715fa2020-05-10 18:58:49 -0700241 repr: Atom,
242 min: Discriminant,
243 max: Discriminant,
244}
245
David Tolnay65bc8e62020-05-11 00:24:31 -0700246impl Limits {
247 fn of(repr: Atom) -> Option<Limits> {
248 for limits in &LIMITS {
249 if limits.repr == repr {
250 return Some(*limits);
251 }
252 }
253 None
254 }
255}
256
David Tolnay9f7c55a2020-05-11 00:19:01 -0700257const LIMITS: [Limits; 8] = [
258 Limits {
David Tolnayf1715fa2020-05-10 18:58:49 -0700259 repr: U8,
260 min: Discriminant::zero(),
David Tolnay17451de2020-05-10 23:49:12 -0700261 max: Discriminant::pos(std::u8::MAX as u64),
David Tolnayf1715fa2020-05-10 18:58:49 -0700262 },
David Tolnay9f7c55a2020-05-11 00:19:01 -0700263 Limits {
David Tolnayf1715fa2020-05-10 18:58:49 -0700264 repr: I8,
David Tolnay17451de2020-05-10 23:49:12 -0700265 min: Discriminant::neg(std::i8::MIN as i64),
266 max: Discriminant::pos(std::i8::MAX as u64),
David Tolnayf1715fa2020-05-10 18:58:49 -0700267 },
David Tolnay9f7c55a2020-05-11 00:19:01 -0700268 Limits {
David Tolnayf1715fa2020-05-10 18:58:49 -0700269 repr: U16,
270 min: Discriminant::zero(),
David Tolnay17451de2020-05-10 23:49:12 -0700271 max: Discriminant::pos(std::u16::MAX as u64),
David Tolnayf1715fa2020-05-10 18:58:49 -0700272 },
David Tolnay9f7c55a2020-05-11 00:19:01 -0700273 Limits {
David Tolnayf1715fa2020-05-10 18:58:49 -0700274 repr: I16,
David Tolnay17451de2020-05-10 23:49:12 -0700275 min: Discriminant::neg(std::i16::MIN as i64),
276 max: Discriminant::pos(std::i16::MAX as u64),
David Tolnayf1715fa2020-05-10 18:58:49 -0700277 },
David Tolnay9f7c55a2020-05-11 00:19:01 -0700278 Limits {
David Tolnayf1715fa2020-05-10 18:58:49 -0700279 repr: U32,
280 min: Discriminant::zero(),
David Tolnay17451de2020-05-10 23:49:12 -0700281 max: Discriminant::pos(std::u32::MAX as u64),
David Tolnayf1715fa2020-05-10 18:58:49 -0700282 },
David Tolnay9f7c55a2020-05-11 00:19:01 -0700283 Limits {
David Tolnayf1715fa2020-05-10 18:58:49 -0700284 repr: I32,
David Tolnay17451de2020-05-10 23:49:12 -0700285 min: Discriminant::neg(std::i32::MIN as i64),
286 max: Discriminant::pos(std::i32::MAX as u64),
David Tolnayf2d58412020-05-10 23:22:23 -0700287 },
David Tolnay9f7c55a2020-05-11 00:19:01 -0700288 Limits {
David Tolnayf2d58412020-05-10 23:22:23 -0700289 repr: U64,
290 min: Discriminant::zero(),
David Tolnay17451de2020-05-10 23:49:12 -0700291 max: Discriminant::pos(std::u64::MAX),
David Tolnayf2d58412020-05-10 23:22:23 -0700292 },
David Tolnay9f7c55a2020-05-11 00:19:01 -0700293 Limits {
David Tolnayf2d58412020-05-10 23:22:23 -0700294 repr: I64,
David Tolnay17451de2020-05-10 23:49:12 -0700295 min: Discriminant::neg(std::i64::MIN),
296 max: Discriminant::pos(std::i64::MAX as u64),
David Tolnayf1715fa2020-05-10 18:58:49 -0700297 },
298];