blob: 35ef4cbdba4bdbe45c35db72249cb1968f6e8559 [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) {
35 (None, _) => self.repr = repr,
36 (Some(prev), Some(repr)) if prev != repr => {
37 let msg = format!("expected {}, found {}", prev, repr);
38 return Err(Error::new(Span::call_site(), msg));
39 }
40 _ => {}
41 }
David Tolnay17e137f2020-05-08 15:55:28 -070042 insert(self, discriminant)
43 }
44
45 pub fn insert_next(&mut self) -> Result<Discriminant> {
46 let discriminant = match self.previous {
47 None => Discriminant::zero(),
David Tolnay69c79602020-05-10 18:53:31 -070048 Some(mut discriminant) if discriminant.negative => {
49 discriminant.magnitude -= 1;
50 if discriminant.magnitude == 0 {
51 discriminant.negative = false;
52 }
53 discriminant
54 }
David Tolnay17e137f2020-05-08 15:55:28 -070055 Some(mut discriminant) => {
David Tolnayf2d58412020-05-10 23:22:23 -070056 if discriminant.magnitude == u64::MAX {
57 let msg = format!("discriminant overflow on value after {}", u64::MAX);
David Tolnay17e137f2020-05-08 15:55:28 -070058 return Err(Error::new(Span::call_site(), msg));
59 }
60 discriminant.magnitude += 1;
61 discriminant
62 }
63 };
64 insert(self, discriminant)
65 }
David Tolnaye2e303f2020-05-10 20:52:00 -070066
67 pub fn inferred_repr(&self) -> Result<Atom> {
68 if let Some(repr) = self.repr {
69 return Ok(repr);
70 }
71 if self.values.is_empty() {
72 return Ok(U8);
73 }
74 let min = *self.values.iter().next().unwrap();
75 let max = *self.values.iter().next_back().unwrap();
David Tolnay9f7c55a2020-05-11 00:19:01 -070076 for limits in &LIMITS {
77 if limits.min <= min && max <= limits.max {
78 return Ok(limits.repr);
David Tolnaye2e303f2020-05-10 20:52:00 -070079 }
80 }
81 let msg = "these discriminant values do not fit in any supported enum repr type";
82 Err(Error::new(Span::call_site(), msg))
83 }
David Tolnay17e137f2020-05-08 15:55:28 -070084}
85
David Tolnay9bcb4c62020-05-10 17:42:06 -070086fn expr_to_discriminant(expr: &Expr) -> Result<(Discriminant, Option<Atom>)> {
David Tolnay69c79602020-05-10 18:53:31 -070087 match expr {
88 Expr::Lit(expr) => {
89 if let Lit::Int(lit) = &expr.lit {
David Tolnay9bcb4c62020-05-10 17:42:06 -070090 let discriminant = lit.base10_parse::<Discriminant>()?;
91 let repr = parse_int_suffix(lit.suffix())?;
92 return Ok((discriminant, repr));
David Tolnay69c79602020-05-10 18:53:31 -070093 }
David Tolnay17e137f2020-05-08 15:55:28 -070094 }
David Tolnay69c79602020-05-10 18:53:31 -070095 Expr::Unary(unary) => {
96 if let UnOp::Neg(_) = unary.op {
David Tolnay9bcb4c62020-05-10 17:42:06 -070097 let (mut discriminant, repr) = expr_to_discriminant(&unary.expr)?;
David Tolnay69c79602020-05-10 18:53:31 -070098 discriminant.negative ^= true;
David Tolnay9bcb4c62020-05-10 17:42:06 -070099 return Ok((discriminant, repr));
David Tolnay69c79602020-05-10 18:53:31 -0700100 }
101 }
102 _ => {}
David Tolnay17e137f2020-05-08 15:55:28 -0700103 }
104 Err(Error::new_spanned(
105 expr,
106 "enums with non-integer literal discriminants are not supported yet",
107 ))
108}
109
110fn insert(set: &mut DiscriminantSet, discriminant: Discriminant) -> Result<Discriminant> {
David Tolnay5966f7b2020-05-10 22:53:24 -0700111 if let Some(expected_repr) = set.repr {
David Tolnay9f7c55a2020-05-11 00:19:01 -0700112 for limits in &LIMITS {
113 if limits.repr != expected_repr {
David Tolnay5966f7b2020-05-10 22:53:24 -0700114 continue;
115 }
David Tolnay9f7c55a2020-05-11 00:19:01 -0700116 if limits.min <= discriminant && discriminant <= limits.max {
David Tolnay5966f7b2020-05-10 22:53:24 -0700117 break;
118 }
119 let msg = format!(
120 "discriminant value `{}` is outside the limits of {}",
121 discriminant, expected_repr,
122 );
123 return Err(Error::new(Span::call_site(), msg));
124 }
125 }
David Tolnay17e137f2020-05-08 15:55:28 -0700126 if set.values.insert(discriminant) {
127 set.previous = Some(discriminant);
128 Ok(discriminant)
129 } else {
130 let msg = format!("discriminant value `{}` already exists", discriminant);
131 Err(Error::new(Span::call_site(), msg))
132 }
133}
134
135impl Discriminant {
David Tolnayf1715fa2020-05-10 18:58:49 -0700136 const fn zero() -> Self {
David Tolnay69c79602020-05-10 18:53:31 -0700137 Discriminant {
138 negative: false,
139 magnitude: 0,
140 }
David Tolnay17e137f2020-05-08 15:55:28 -0700141 }
David Tolnayf1715fa2020-05-10 18:58:49 -0700142
David Tolnayf2d58412020-05-10 23:22:23 -0700143 const fn pos(u: u64) -> Self {
David Tolnayf1715fa2020-05-10 18:58:49 -0700144 Discriminant {
145 negative: false,
146 magnitude: u,
147 }
148 }
149
David Tolnayf2d58412020-05-10 23:22:23 -0700150 const fn neg(i: i64) -> Self {
David Tolnayf1715fa2020-05-10 18:58:49 -0700151 Discriminant {
152 negative: i < 0,
David Tolnayf2d58412020-05-10 23:22:23 -0700153 // This is `i.abs() as u64` but without overflow on MIN. Uses the
David Tolnayf1715fa2020-05-10 18:58:49 -0700154 // fact that MIN.wrapping_abs() wraps back to MIN whose binary
David Tolnayf2d58412020-05-10 23:22:23 -0700155 // representation is 1<<63, and thus the `as u64` conversion
156 // produces 1<<63 too which happens to be the correct unsigned
David Tolnayf1715fa2020-05-10 18:58:49 -0700157 // magnitude.
David Tolnayf2d58412020-05-10 23:22:23 -0700158 magnitude: i.wrapping_abs() as u64,
David Tolnayf1715fa2020-05-10 18:58:49 -0700159 }
160 }
David Tolnay17e137f2020-05-08 15:55:28 -0700161}
162
163impl Display for Discriminant {
164 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
David Tolnay69c79602020-05-10 18:53:31 -0700165 if self.negative {
166 f.write_str("-")?;
167 }
David Tolnay17e137f2020-05-08 15:55:28 -0700168 Display::fmt(&self.magnitude, f)
169 }
170}
171
172impl ToTokens for Discriminant {
173 fn to_tokens(&self, tokens: &mut TokenStream) {
David Tolnay69c79602020-05-10 18:53:31 -0700174 if self.negative {
175 Token![-](Span::call_site()).to_tokens(tokens);
176 }
David Tolnayf2d58412020-05-10 23:22:23 -0700177 Literal::u64_unsuffixed(self.magnitude).to_tokens(tokens);
David Tolnay17e137f2020-05-08 15:55:28 -0700178 }
179}
180
181impl FromStr for Discriminant {
182 type Err = Error;
183
David Tolnay69c79602020-05-10 18:53:31 -0700184 fn from_str(mut s: &str) -> Result<Self> {
185 let negative = s.starts_with('-');
186 if negative {
187 s = &s[1..];
188 }
David Tolnayf2d58412020-05-10 23:22:23 -0700189 match s.parse::<u64>() {
David Tolnay69c79602020-05-10 18:53:31 -0700190 Ok(magnitude) => Ok(Discriminant {
191 negative,
192 magnitude,
193 }),
David Tolnay17e137f2020-05-08 15:55:28 -0700194 Err(_) => Err(Error::new(
195 Span::call_site(),
196 "discriminant value outside of supported range",
197 )),
198 }
199 }
200}
David Tolnay9bcb4c62020-05-10 17:42:06 -0700201
David Tolnaye2e303f2020-05-10 20:52:00 -0700202impl Ord for Discriminant {
203 fn cmp(&self, other: &Self) -> Ordering {
204 match (self.negative, other.negative) {
205 (true, true) => self.magnitude.cmp(&other.magnitude).reverse(),
206 (true, false) => Ordering::Less, // negative < positive
207 (false, true) => Ordering::Greater, // positive > negative
208 (false, false) => self.magnitude.cmp(&other.magnitude),
209 }
210 }
211}
212
213impl PartialOrd for Discriminant {
214 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
215 Some(self.cmp(other))
216 }
217}
218
David Tolnay9bcb4c62020-05-10 17:42:06 -0700219fn parse_int_suffix(suffix: &str) -> Result<Option<Atom>> {
220 if suffix.is_empty() {
221 return Ok(None);
222 }
223 if let Some(atom) = Atom::from_str(suffix) {
224 match atom {
225 U8 | U16 | U32 | U64 | Usize | I8 | I16 | I32 | I64 | Isize => return Ok(Some(atom)),
226 _ => {}
227 }
228 }
229 let msg = format!("unrecognized integer suffix: `{}`", suffix);
230 Err(Error::new(Span::call_site(), msg))
231}
David Tolnayf1715fa2020-05-10 18:58:49 -0700232
David Tolnay9f7c55a2020-05-11 00:19:01 -0700233struct Limits {
David Tolnayf1715fa2020-05-10 18:58:49 -0700234 repr: Atom,
235 min: Discriminant,
236 max: Discriminant,
237}
238
David Tolnay9f7c55a2020-05-11 00:19:01 -0700239const LIMITS: [Limits; 8] = [
240 Limits {
David Tolnayf1715fa2020-05-10 18:58:49 -0700241 repr: U8,
242 min: Discriminant::zero(),
David Tolnay17451de2020-05-10 23:49:12 -0700243 max: Discriminant::pos(std::u8::MAX as u64),
David Tolnayf1715fa2020-05-10 18:58:49 -0700244 },
David Tolnay9f7c55a2020-05-11 00:19:01 -0700245 Limits {
David Tolnayf1715fa2020-05-10 18:58:49 -0700246 repr: I8,
David Tolnay17451de2020-05-10 23:49:12 -0700247 min: Discriminant::neg(std::i8::MIN as i64),
248 max: Discriminant::pos(std::i8::MAX as u64),
David Tolnayf1715fa2020-05-10 18:58:49 -0700249 },
David Tolnay9f7c55a2020-05-11 00:19:01 -0700250 Limits {
David Tolnayf1715fa2020-05-10 18:58:49 -0700251 repr: U16,
252 min: Discriminant::zero(),
David Tolnay17451de2020-05-10 23:49:12 -0700253 max: Discriminant::pos(std::u16::MAX as u64),
David Tolnayf1715fa2020-05-10 18:58:49 -0700254 },
David Tolnay9f7c55a2020-05-11 00:19:01 -0700255 Limits {
David Tolnayf1715fa2020-05-10 18:58:49 -0700256 repr: I16,
David Tolnay17451de2020-05-10 23:49:12 -0700257 min: Discriminant::neg(std::i16::MIN as i64),
258 max: Discriminant::pos(std::i16::MAX as u64),
David Tolnayf1715fa2020-05-10 18:58:49 -0700259 },
David Tolnay9f7c55a2020-05-11 00:19:01 -0700260 Limits {
David Tolnayf1715fa2020-05-10 18:58:49 -0700261 repr: U32,
262 min: Discriminant::zero(),
David Tolnay17451de2020-05-10 23:49:12 -0700263 max: Discriminant::pos(std::u32::MAX as u64),
David Tolnayf1715fa2020-05-10 18:58:49 -0700264 },
David Tolnay9f7c55a2020-05-11 00:19:01 -0700265 Limits {
David Tolnayf1715fa2020-05-10 18:58:49 -0700266 repr: I32,
David Tolnay17451de2020-05-10 23:49:12 -0700267 min: Discriminant::neg(std::i32::MIN as i64),
268 max: Discriminant::pos(std::i32::MAX as u64),
David Tolnayf2d58412020-05-10 23:22:23 -0700269 },
David Tolnay9f7c55a2020-05-11 00:19:01 -0700270 Limits {
David Tolnayf2d58412020-05-10 23:22:23 -0700271 repr: U64,
272 min: Discriminant::zero(),
David Tolnay17451de2020-05-10 23:49:12 -0700273 max: Discriminant::pos(std::u64::MAX),
David Tolnayf2d58412020-05-10 23:22:23 -0700274 },
David Tolnay9f7c55a2020-05-11 00:19:01 -0700275 Limits {
David Tolnayf2d58412020-05-10 23:22:23 -0700276 repr: I64,
David Tolnay17451de2020-05-10 23:49:12 -0700277 min: Discriminant::neg(std::i64::MIN),
278 max: Discriminant::pos(std::i64::MAX as u64),
David Tolnayf1715fa2020-05-10 18:58:49 -0700279 },
280];