1use crate::{PResult, Parser, unescape};
2use alloy_primitives::U256;
3use num_bigint::{BigInt, BigUint};
4use num_rational::Ratio;
5use num_traits::{Num, Signed, Zero};
6use solar_ast::{token::*, *};
7use solar_interface::{ByteSymbol, Session, Symbol, diagnostics::ErrorGuaranteed, kw};
8use std::{borrow::Cow, fmt};
9
10impl<'sess, 'ast, 'cb> Parser<'sess, 'ast, 'cb> {
11 pub fn parse_lit(
18 &mut self,
19 with_subdenomination: bool,
20 ) -> PResult<'sess, (Lit<'ast>, Option<SubDenomination>)> {
21 self.parse_spanned(|this| this.parse_lit_inner(with_subdenomination)).map(
22 |(span, (symbol, kind, subdenomination))| (Lit { span, symbol, kind }, subdenomination),
23 )
24 }
25
26 pub fn parse_subdenomination(&mut self) -> Option<SubDenomination> {
28 let sub = self.subdenomination();
29 if sub.is_some() {
30 self.bump();
31 }
32 sub
33 }
34
35 fn subdenomination(&self) -> Option<SubDenomination> {
36 match self.token.ident()?.name {
37 kw::Wei => Some(SubDenomination::Ether(EtherSubDenomination::Wei)),
38 kw::Gwei => Some(SubDenomination::Ether(EtherSubDenomination::Gwei)),
39 kw::Ether => Some(SubDenomination::Ether(EtherSubDenomination::Ether)),
40
41 kw::Seconds => Some(SubDenomination::Time(TimeSubDenomination::Seconds)),
42 kw::Minutes => Some(SubDenomination::Time(TimeSubDenomination::Minutes)),
43 kw::Hours => Some(SubDenomination::Time(TimeSubDenomination::Hours)),
44 kw::Days => Some(SubDenomination::Time(TimeSubDenomination::Days)),
45 kw::Weeks => Some(SubDenomination::Time(TimeSubDenomination::Weeks)),
46 kw::Years => Some(SubDenomination::Time(TimeSubDenomination::Years)),
47
48 _ => None,
49 }
50 }
51
52 pub(super) fn expect_no_subdenomination(&mut self) {
54 if let Some(_sub) = self.parse_subdenomination() {
55 let span = self.prev_token.span;
56 self.dcx().emit_err(span, "subdenominations aren't allowed here");
57 }
58 }
59
60 fn parse_lit_inner(
61 &mut self,
62 with_subdenomination: bool,
63 ) -> PResult<'sess, (Symbol, LitKind<'ast>, Option<SubDenomination>)> {
64 let lo = self.token.span;
65 if let TokenKind::Ident(symbol @ (kw::True | kw::False)) = self.token.kind {
66 self.bump();
67 let mut subdenomination =
68 if with_subdenomination { self.parse_subdenomination() } else { None };
69 self.subdenom_error(&mut subdenomination, lo.to(self.prev_token.span));
70 return Ok((symbol, LitKind::Bool(symbol != kw::False), subdenomination));
71 }
72
73 if !self.check_lit() {
74 return self.unexpected();
75 }
76
77 let Some(lit) = self.token.lit() else {
78 unreachable!("check_lit() returned true for non-literal token");
79 };
80 self.bump();
81 let mut subdenomination =
82 if with_subdenomination { self.parse_subdenomination() } else { None };
83 let result = match lit.kind {
84 TokenLitKind::Integer => self.parse_lit_int(lit.symbol, subdenomination),
85 TokenLitKind::Rational => self.parse_lit_rational(lit.symbol, subdenomination),
86 TokenLitKind::Str | TokenLitKind::UnicodeStr | TokenLitKind::HexStr => {
87 self.subdenom_error(&mut subdenomination, lo.to(self.prev_token.span));
88 self.parse_lit_str(lit, lo)
89 }
90 TokenLitKind::Err(guar) => Ok(LitKind::Err(guar)),
91 };
92 let kind =
93 result.unwrap_or_else(|e| LitKind::Err(e.span(lo.to(self.prev_token.span)).emit()));
94 if matches!(kind, LitKind::Err(_)) {
95 subdenomination = None;
96 }
97 Ok((lit.symbol, kind, subdenomination))
98 }
99
100 fn subdenom_error(&mut self, slot: &mut Option<SubDenomination>, span: Span) {
101 if slot.is_some() {
102 *slot = None;
103 let msg = "sub-denominations are only allowed on number and rational literals";
104 self.dcx().emit_err(span, msg);
105 }
106 }
107
108 fn parse_lit_int(
110 &mut self,
111 symbol: Symbol,
112 subdenomination: Option<SubDenomination>,
113 ) -> PResult<'sess, LitKind<'ast>> {
114 use LitError::*;
115 match parse_integer(self.sess, symbol, subdenomination) {
116 Ok(l) => Ok(l),
117 Err(e @ (IntegerLeadingZeros | IntegerTooLarge)) => Err(self.dcx().err(e.to_string())),
119 Err(EmptyInteger) => Ok(LitKind::Err(ErrorGuaranteed::new_unchecked())),
121 Err(e @ ParseInteger(_)) => panic!("failed to parse integer literal {symbol:?}: {e}"),
123 Err(
125 e @ (InvalidRational | RationalPlusExponent | EmptyRational | EmptyExponent
126 | ParseRational(_) | ParseExponent(_) | RationalTooLarge | ExponentTooLarge),
127 ) => panic!("this error shouldn't happen for normal integer literals: {e}"),
128 }
129 }
130
131 fn parse_lit_rational(
133 &mut self,
134 symbol: Symbol,
135 subdenomination: Option<SubDenomination>,
136 ) -> PResult<'sess, LitKind<'ast>> {
137 use LitError::*;
138 match parse_rational(self.sess, symbol, subdenomination) {
139 Ok(l) => Ok(l),
140 Err(
142 e @ (EmptyRational | RationalPlusExponent | IntegerTooLarge | RationalTooLarge
143 | ExponentTooLarge | IntegerLeadingZeros),
144 ) => Err(self.dcx().err(e.to_string())),
145 Err(InvalidRational | EmptyExponent) => {
147 Ok(LitKind::Err(ErrorGuaranteed::new_unchecked()))
148 }
149 Err(e @ (ParseExponent(_) | ParseInteger(_) | ParseRational(_) | EmptyInteger)) => {
151 panic!("failed to parse rational literal {symbol:?}: {e}")
152 }
153 }
154 }
155
156 fn parse_lit_str(&mut self, lit: TokenLit, span: Span) -> PResult<'sess, LitKind<'ast>> {
158 let mode = match lit.kind {
159 TokenLitKind::Str => StrKind::Str,
160 TokenLitKind::UnicodeStr => StrKind::Unicode,
161 TokenLitKind::HexStr => StrKind::Hex,
162 _ => unreachable!(),
163 };
164
165 let (mut value, _) =
166 unescape::parse_string_literal(lit.symbol.as_str(), mode, span, self.sess);
167 let mut extra = vec![];
168 while let Some(TokenLit { symbol, kind }) = self.token.lit() {
169 if kind != lit.kind {
170 break;
171 }
172 extra.push((self.token.span, symbol));
173 let (parsed, _) =
174 unescape::parse_string_literal(symbol.as_str(), mode, self.token.span, self.sess);
175 value.to_mut().extend_from_slice(&parsed);
176 self.bump();
177 }
178
179 let kind = match lit.kind {
180 TokenLitKind::Str => StrKind::Str,
181 TokenLitKind::UnicodeStr => StrKind::Unicode,
182 TokenLitKind::HexStr => StrKind::Hex,
183 _ => unreachable!(),
184 };
185 let extra = self.alloc_vec(extra);
186 Ok(LitKind::Str(kind, ByteSymbol::intern(&value), extra))
187 }
188
189 pub(super) fn validate_str_lit(&self, lit: &StrLit) -> bool {
192 let (_, has_error) =
193 unescape::parse_string_literal(lit.value.as_str(), StrKind::Str, lit.span, self.sess);
194 !has_error
195 }
196}
197
198#[derive(Debug, PartialEq, Eq)]
199enum LitError {
200 InvalidRational,
201
202 EmptyInteger,
203 EmptyRational,
204 EmptyExponent,
205 RationalPlusExponent,
206
207 ParseInteger(num_bigint::ParseBigIntError),
208 ParseRational(num_bigint::ParseBigIntError),
209 ParseExponent(std::num::ParseIntError),
210
211 IntegerTooLarge,
212 RationalTooLarge,
213 ExponentTooLarge,
214 IntegerLeadingZeros,
215}
216
217impl fmt::Display for LitError {
218 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
219 match self {
220 Self::InvalidRational => write!(f, "invalid rational literal"),
221 Self::EmptyInteger => write!(f, "empty integer"),
222 Self::EmptyRational => write!(f, "empty rational"),
223 Self::EmptyExponent => write!(f, "empty exponent"),
224 Self::RationalPlusExponent => write!(f, "`+` is not allowed in the exponent"),
225 Self::ParseInteger(e) => write!(f, "failed to parse integer: {e}"),
226 Self::ParseRational(e) => write!(f, "failed to parse rational: {e}"),
227 Self::ParseExponent(e) => write!(f, "failed to parse exponent: {e}"),
228 Self::IntegerTooLarge => write!(f, "integer part too large"),
229 Self::RationalTooLarge => write!(f, "rational part too large"),
230 Self::ExponentTooLarge => write!(f, "exponent too large"),
231 Self::IntegerLeadingZeros => write!(f, "leading zeros are not allowed in integers"),
232 }
233 }
234}
235
236fn parse_integer<'ast>(
237 sess: &Session,
238 symbol: Symbol,
239 subdenomination: Option<SubDenomination>,
240) -> Result<LitKind<'ast>, LitError> {
241 let s = &strip_underscores(symbol, sess)[..];
242 let base = match s.as_bytes() {
243 [b'0', b'x', ..] => Base::Hexadecimal,
244 [b'0', b'o', ..] => Base::Octal,
245 [b'0', b'b', ..] => Base::Binary,
246 _ => Base::Decimal,
247 };
248
249 if base == Base::Decimal && s.starts_with('0') && s.len() > 1 {
250 return Err(LitError::IntegerLeadingZeros);
251 }
252
253 if base == Base::Hexadecimal
255 && subdenomination.is_none()
256 && s.len() == 42
257 && let Ok(address) = s.parse()
258 {
259 return Ok(LitKind::Address(address));
260 }
261
262 let start = if base == Base::Decimal { 0 } else { 2 };
263 let s = &s[start..];
264 if s.is_empty() {
265 return Err(LitError::EmptyInteger);
266 }
267 let multiplier = subdenomination.map_or(1, SubDenomination::value);
268 if let Some(n) =
269 u256_from_str_radix(s, base).and_then(|n| n.checked_mul(U256::from(multiplier)))
270 {
271 return Ok(LitKind::Number(n));
272 }
273 Ok(number_lit(big_int_from_str_radix(s, base, false)? * multiplier))
274}
275
276fn parse_rational<'ast>(
277 sess: &Session,
278 symbol: Symbol,
279 subdenomination: Option<SubDenomination>,
280) -> Result<LitKind<'ast>, LitError> {
281 let s = &strip_underscores(symbol, sess)[..];
282 debug_assert!(!s.is_empty());
283
284 if matches!(s.get(..2), Some("0b" | "0o" | "0x")) {
285 return Err(LitError::InvalidRational);
286 }
287
288 let (mut int, rat, exp) = match (s.find('.'), s.find(['e', 'E'])) {
290 (None, None) => (s, None, None),
292 (Some(dot), None) => {
294 let (int, rat) = split_at_exclusive(s, dot);
295 (int, Some(rat), None)
296 }
297 (None, Some(exp)) => {
299 let (int, exp) = split_at_exclusive(s, exp);
300 (int, None, Some(exp))
301 }
302 (Some(dot), Some(exp)) => {
304 if exp < dot {
305 return Err(LitError::InvalidRational);
306 }
307 let (int, rest) = split_at_exclusive(s, dot);
308 let (rat, exp) = split_at_exclusive(rest, exp - dot - 1);
309 (int, Some(rat), Some(exp))
310 }
311 };
312
313 if cfg!(debug_assertions) {
314 let mut reconstructed = String::from(int);
315 if let Some(rat) = rat {
316 reconstructed.push('.');
317 reconstructed.push_str(rat);
318 }
319 if let Some(exp) = exp {
320 let e = if s.contains('E') { 'E' } else { 'e' };
321 reconstructed.push(e);
322 reconstructed.push_str(exp);
323 }
324 assert_eq!(reconstructed, s, "{int:?} + {rat:?} + {exp:?}");
325 }
326
327 if int.is_empty() {
329 int = "0";
330 }
331 if rat.is_some_and(str::is_empty) {
332 return Err(LitError::EmptyRational);
333 }
334 if let Some(exp) = exp {
335 if exp.starts_with('+') {
336 return Err(LitError::RationalPlusExponent);
337 }
338 if matches!(exp, "" | "-") {
339 return Err(LitError::EmptyExponent);
340 }
341 }
342
343 if int.starts_with('0') && int.len() > 1 {
344 return Err(LitError::IntegerLeadingZeros);
345 }
346 let rat = rat.map(|rat| rat.trim_end_matches('0'));
349 let (int_s, is_rat) = match rat {
350 Some(rat) => (&[int, rat].concat()[..], true),
351 None => (int, false),
352 };
353 let int = big_int_from_str_radix(int_s, Base::Decimal, is_rat)?;
354
355 let fract_len = rat.map_or(0, str::len);
356 let fract_len = u16::try_from(fract_len).map_err(|_| LitError::RationalTooLarge)?;
357 let denominator = pow10(fract_len as u32);
358 let mut number = Ratio::new(int, denominator);
359
360 if number.is_zero() {
362 return Ok(LitKind::Number(U256::ZERO));
363 }
364
365 if let Some(exp) = exp {
366 let exp = exp.parse::<i32>().map_err(|e| match *e.kind() {
367 std::num::IntErrorKind::PosOverflow | std::num::IntErrorKind::NegOverflow => {
368 LitError::ExponentTooLarge
369 }
370 _ => LitError::ParseExponent(e),
371 })?;
372 let exp_abs = exp.unsigned_abs();
373 let power = || pow10(exp_abs);
374 if exp.is_negative() {
375 if !fits_precision_base_10(&number.denom().abs().into_parts().1, exp_abs) {
376 return Err(LitError::ExponentTooLarge);
377 }
378 number /= power();
379 } else if exp > 0 {
380 if !fits_precision_base_10(&number.numer().abs().into_parts().1, exp_abs) {
381 return Err(LitError::ExponentTooLarge);
382 }
383 number *= power();
384 }
385 }
386
387 if let Some(subdenomination) = subdenomination {
388 number *= BigInt::from(subdenomination.value());
389 }
390
391 if number.is_integer() {
392 Ok(number_lit(number.to_integer()))
393 } else {
394 let (numer, denom) = number.into_raw();
395 Ok(LitKind::Rational(lit_uint(&numer), lit_uint(&denom)))
396 }
397}
398
399fn number_lit<'ast>(n: BigInt) -> LitKind<'ast> {
401 if n.bits() > 256 {
402 return LitKind::BigNumber(lit_uint(&n));
403 }
404 let mut limbs = [0; 4];
405 for (limb, digit) in limbs.iter_mut().zip(n.iter_u64_digits()) {
406 *limb = digit;
407 }
408 LitKind::Number(U256::from_limbs(limbs))
409}
410
411fn lit_uint(n: &BigInt) -> LitUint {
412 LitUint::from_be_bytes(&n.magnitude().to_bytes_be())
413}
414
415type Primitive = u128;
419
420const MAX_BITS: u32 = 4096;
422
423#[inline]
431const fn max_digits<const BITS: u32>(base: Base) -> usize {
432 if matches!(base, Base::Binary) {
433 return BITS as usize;
434 }
435 match BITS {
436 Primitive::BITS => match base {
437 Base::Binary => BITS as usize,
438 Base::Octal => 43,
439 Base::Decimal => 39,
440 Base::Hexadecimal => 32,
441 },
442 MAX_BITS => match base {
443 Base::Binary => BITS as usize,
444 Base::Octal => 1366,
445 Base::Decimal => 1234,
446 Base::Hexadecimal => 1024,
447 },
448 _ => panic!("unknown bits"),
449 }
450}
451
452fn u256_from_str_radix(s: &str, base: Base) -> Option<U256> {
453 if s.len() <= max_digits::<{ Primitive::BITS }>(base)
454 && let Ok(n) = Primitive::from_str_radix(s, base as u32)
455 {
456 return Some(U256::from(n));
457 }
458 U256::from_str_radix(s, base as u64).ok()
459}
460
461fn big_int_from_str_radix(s: &str, base: Base, rat: bool) -> Result<BigInt, LitError> {
462 let too_large = || if rat { LitError::RationalTooLarge } else { LitError::IntegerTooLarge };
463 let s = match s.trim_start_matches('0') {
466 "" => "0",
467 digits if !rat => digits,
468 _ => s,
469 };
470 if s.len() > max_digits::<MAX_BITS>(base) {
471 return Err(too_large());
472 }
473 if s.len() <= max_digits::<{ Primitive::BITS }>(base)
474 && let Ok(n) = Primitive::from_str_radix(s, base as u32)
475 {
476 return Ok(BigInt::from(n));
477 }
478 let n = BigInt::from_str_radix(s, base as u32)
479 .map_err(|e| if rat { LitError::ParseRational(e) } else { LitError::ParseInteger(e) })?;
480 if n.bits() > u64::from(MAX_BITS) {
482 return Err(too_large());
483 }
484 Ok(n)
485}
486
487fn pow10(exp: u32) -> BigInt {
488 if let Some(n) = 10usize.checked_pow(exp) {
489 BigInt::from(n)
490 } else {
491 BigInt::from(10u64).pow(exp)
492 }
493}
494
495fn fits_precision_base_10(mantissa: &BigUint, exp: u32) -> bool {
497 fits_precision_base_x(mantissa, std::f64::consts::LOG2_10, exp)
499}
500
501fn fits_precision_base_x(mantissa: &BigUint, log_2_of_base: f64, exp: u32) -> bool {
504 if mantissa.is_zero() {
506 return true;
507 }
508
509 let max = MAX_BITS as u64;
510 let bits = mantissa.bits();
511 if bits > max {
512 return false;
513 }
514 let bits_needed = bits + f64::floor(log_2_of_base * exp as f64) as u64;
515 bits_needed <= max
516}
517
518#[track_caller]
519fn split_at_exclusive(s: &str, idx: usize) -> (&str, &str) {
520 (&s[..idx], &s[idx + 1..])
521}
522
523#[inline]
524fn strip_underscores(symbol: Symbol, sess: &Session) -> Cow<'_, str> {
525 let s = symbol.as_str_in(sess);
527 if s.contains('_') { Cow::Owned(strip_underscores_slow(s)) } else { Cow::Borrowed(s) }
528}
529
530#[inline(never)]
531#[cold]
532fn strip_underscores_slow(s: &str) -> String {
533 let mut s = s.to_string();
534 s.retain(|c| c != '_');
535 s
536}
537
538#[cfg(test)]
539mod tests {
540 use super::*;
541 use crate::Lexer;
542 use alloy_primitives::{Address, address};
543 use solar_interface::Session;
544
545 #[track_caller]
549 fn lex_literal(src: &str, should_fail: bool, f: impl FnOnce(&Session, Symbol)) {
550 let sess =
551 Session::builder().with_buffer_emitter(Default::default()).single_threaded().build();
552 sess.enter_sequential(|| {
553 let file = sess.source_map().new_source_file("test".to_string(), src).unwrap();
554 let tokens = Lexer::from_source_file(&sess, &file).into_tokens();
555 let diags = sess.dcx.emitted_diagnostics().unwrap();
556 assert_eq!(tokens.len(), 1, "expected exactly 1 token: {tokens:?}\n{diags}");
557 assert_eq!(
558 sess.dcx.has_errors().is_err(),
559 should_fail,
560 "{src:?} -> {tokens:?};\n{diags}",
561 );
562 f(&sess, tokens[0].lit().expect("not a literal").symbol)
563 });
564 }
565
566 #[test]
567 fn integer() {
568 use LitError::*;
569
570 #[track_caller]
571 fn check_int(src: &str, expected: Result<&str, LitError>) {
572 lex_literal(src, false, |sess, symbol| {
573 let res = match parse_integer(sess, symbol, None) {
574 Ok(LitKind::Number(n)) => Ok(n),
575 Ok(x) => panic!("not a number: {x:?} ({src:?})"),
576 Err(e) => Err(e),
577 };
578 let expected = match expected {
579 Ok(s) => Ok(U256::from_str_radix(s, 10).unwrap()),
580 Err(e) => Err(e),
581 };
582 assert_eq!(res, expected, "{src:?}");
583 });
584 }
585
586 #[track_caller]
587 fn check_address(src: &str, expected: Result<Address, &str>) {
588 lex_literal(src, false, |sess, symbol| match expected {
589 Ok(address) => match parse_integer(sess, symbol, None) {
590 Ok(LitKind::Address(a)) => assert_eq!(a, address, "{src:?}"),
591 e => panic!("not an address: {e:?} ({src:?})"),
592 },
593 Err(int) => match parse_integer(sess, symbol, None) {
594 Ok(LitKind::Number(n)) => {
595 assert_eq!(n, U256::from_str_radix(int, 10).unwrap(), "{src:?}")
596 }
597 e => panic!("not an integer: {e:?} ({src:?})"),
598 },
599 });
600 }
601
602 check_int("00", Err(IntegerLeadingZeros));
603 check_int("01", Err(IntegerLeadingZeros));
604 check_int("00", Err(IntegerLeadingZeros));
605 check_int("001", Err(IntegerLeadingZeros));
606 check_int("000", Err(IntegerLeadingZeros));
607 check_int("0001", Err(IntegerLeadingZeros));
608
609 check_int("0", Ok("0"));
610 check_int("1", Ok("1"));
611
612 check_int("10", Ok("10"));
615 check_int("0x10", Ok("16"));
616
617 check_address("0x00000000000000000000000000000000000000", Err("0"));
618 check_address("0x000000000000000000000000000000000000000", Err("0"));
619 check_address("0x0000000000000000000000000000000000000000", Ok(Address::ZERO));
620 check_address("0x00000000000000000000000000000000000000000", Err("0"));
621 check_address("0x000000000000000000000000000000000000000000", Err("0"));
622 check_address("0x0000000000000000000000000000000000000001", Ok(Address::with_last_byte(1)));
623
624 lex_literal(&format!("0x1{}", "0".repeat(64)), false, |sess, symbol| {
625 let Ok(LitKind::BigNumber(n)) = parse_integer(sess, symbol, None) else {
626 panic!("not a big number")
627 };
628 assert_eq!(n.to_be_bytes(), [&[1][..], &[0; 32]].concat());
629 });
630
631 check_address(
632 "0x52908400098527886E0F7030069857D2E4169EE7",
633 Ok(address!("0x52908400098527886E0F7030069857D2E4169EE7")),
634 );
635 check_address(
636 "0x52908400098527886E0F7030069857D2E4169Ee7",
637 Ok(address!("0x52908400098527886E0F7030069857D2E4169EE7")),
638 );
639
640 check_address(
641 "0x8617E340B3D01FA5F11F306F4090FD50E238070D",
642 Ok(address!("0x8617E340B3D01FA5F11F306F4090FD50E238070D")),
643 );
644 check_address(
645 "0xde709f2102306220921060314715629080e2fb77",
646 Ok(address!("0xde709f2102306220921060314715629080e2fb77")),
647 );
648 check_address(
649 "0x27b1fdb04752bbc536007a920d24acb045561c26",
650 Ok(address!("0x27b1fdb04752bbc536007a920d24acb045561c26")),
651 );
652 check_address(
653 "0x5aAeb6053F3E94C9b9A09f33669435E7Ef1BeAed",
654 Ok(address!("0x5aAeb6053F3E94C9b9A09f33669435E7Ef1BeAed")),
655 );
656 check_address(
657 "0xfB6916095ca1df60bB79Ce92cE3Ea74c37c5d359",
658 Ok(address!("0xfB6916095ca1df60bB79Ce92cE3Ea74c37c5d359")),
659 );
660 check_address(
661 "0xdbF03B407c01E7cD3CBea99509d93f8DDDC8C6FB",
662 Ok(address!("0xdbF03B407c01E7cD3CBea99509d93f8DDDC8C6FB")),
663 );
664 check_address(
665 "0xD1220A0cf47c7B9Be7A2E6BA89F429762e7b9aDb",
666 Ok(address!("0xD1220A0cf47c7B9Be7A2E6BA89F429762e7b9aDb")),
667 );
668 }
669
670 #[test]
671 fn rational() {
672 use LitError::*;
673
674 #[track_caller]
675 fn check_int_full(src: &str, should_fail_lexing: bool, expected: Result<&str, LitError>) {
676 lex_literal(src, should_fail_lexing, |sess, symbol| {
677 let res = match parse_rational(sess, symbol, None) {
678 Ok(LitKind::Number(r)) => Ok(r),
679 Ok(x) => panic!("not a number: {x:?} ({src:?})"),
680 Err(e) => Err(e),
681 };
682 let expected = match expected {
683 Ok(s) => Ok(U256::from_str_radix(s, 10).unwrap()),
684 Err(e) => Err(e),
685 };
686 assert_eq!(res, expected, "{src:?}");
687 });
688 }
689
690 #[track_caller]
691 fn check_int(src: &str, expected: Result<&str, LitError>) {
692 check_int_full(src, false, expected);
693 }
694
695 #[track_caller]
696 fn check_rat(src: &str, expected: Result<&str, LitError>) {
697 lex_literal(src, false, |sess, symbol| {
698 let res = match parse_rational(sess, symbol, None) {
699 Ok(LitKind::Rational(numer, denom)) => Ok(Ratio::new_raw(
700 BigUint::from_bytes_be(numer.to_be_bytes()),
701 BigUint::from_bytes_be(denom.to_be_bytes()),
702 )),
703 Ok(x) => panic!("not a number: {x:?} ({src:?})"),
704 Err(e) => Err(e),
705 };
706 let expected = match expected {
707 Ok(s) => Ok(Ratio::from_str_radix(s, 10).unwrap()),
708 Err(e) => Err(e),
709 };
710 assert_eq!(res, expected, "{src:?}");
711 });
712 }
713
714 #[track_caller]
715 fn check_big(src: &str, expected: &str) {
716 lex_literal(src, false, |sess, symbol| {
717 let Ok(LitKind::BigNumber(n)) = parse_rational(sess, symbol, None) else {
718 panic!("not a big number ({src:?})")
719 };
720 assert_eq!(BigUint::from_bytes_be(n.to_be_bytes()).to_string(), expected);
721 });
722 }
723
724 #[track_caller]
725 fn zeros(before: &str, zeros: usize) -> String {
726 before.to_string() + &"0".repeat(zeros)
727 }
728
729 check_int("00", Err(IntegerLeadingZeros));
730 check_int("0_0", Err(IntegerLeadingZeros));
731 check_int("01", Err(IntegerLeadingZeros));
732 check_int("0_1", Err(IntegerLeadingZeros));
733 check_int("00", Err(IntegerLeadingZeros));
734 check_int("001", Err(IntegerLeadingZeros));
735 check_int("000", Err(IntegerLeadingZeros));
736 check_int("0001", Err(IntegerLeadingZeros));
737
738 check_int("0.", Err(EmptyRational));
739 check_int_full("0e-", true, Err(EmptyExponent));
740 check_int_full("0e", true, Err(EmptyExponent));
741
742 check_int_full("0e+", true, Err(RationalPlusExponent));
743 check_int("0e+0", Err(RationalPlusExponent));
744 check_int("0e+1", Err(RationalPlusExponent));
745
746 check_int("0", Ok("0"));
747 check_int("0e0", Ok("0"));
748 check_int("0.0", Ok("0"));
749 check_int("0.00", Ok("0"));
750 check_int("0.0e0", Ok("0"));
751 check_int("0.00e0", Ok("0"));
752 check_int("0.0e00", Ok("0"));
753 check_int("0.00e00", Ok("0"));
754 check_int("0.0e-0", Ok("0"));
755 check_int("0.00e-0", Ok("0"));
756 check_int("0.0e-00", Ok("0"));
757 check_int("0.00e-00", Ok("0"));
758 check_int("0.0e1", Ok("0"));
759 check_int("0.00e1", Ok("0"));
760 check_int("0.00e01", Ok("0"));
761 check_int("0e999999", Ok("0"));
762 check_int("0E123456789", Ok("0"));
763
764 check_int(".0", Ok("0"));
765 check_int(".00", Ok("0"));
766 check_int(".0e0", Ok("0"));
767 check_int(".00e0", Ok("0"));
768 check_int(".0e00", Ok("0"));
769 check_int(".00e00", Ok("0"));
770 check_int(".0e-0", Ok("0"));
771 check_int(".00e-0", Ok("0"));
772 check_int(".0e-00", Ok("0"));
773 check_int(".00e-00", Ok("0"));
774 check_int(".0e1", Ok("0"));
775 check_int(".00e1", Ok("0"));
776 check_int(".00e01", Ok("0"));
777
778 check_int("1", Ok("1"));
779 check_int("1e0", Ok("1"));
780 check_int("1.0", Ok("1"));
781 check_int("1.00", Ok("1"));
782 check_int("1.0e0", Ok("1"));
783 check_int("1.00e0", Ok("1"));
784 check_int("1.0e00", Ok("1"));
785 check_int("1.00e00", Ok("1"));
786 check_int("1.0e-0", Ok("1"));
787 check_int("1.00e-0", Ok("1"));
788 check_int("1.0e-00", Ok("1"));
789 check_int("1.00e-00", Ok("1"));
790
791 check_int_full("0b", true, Err(InvalidRational));
792 check_int_full("0b0", true, Err(InvalidRational));
793 check_int_full("0b01", true, Err(InvalidRational));
794 check_int_full("0b01.0", true, Err(InvalidRational));
795 check_int_full("0b01.0e1", true, Err(InvalidRational));
796 check_int_full("0b0e", true, Err(InvalidRational));
797 check_int_full("0o", true, Err(InvalidRational));
801 check_int_full("0o0", true, Err(InvalidRational));
802 check_int_full("0o01", true, Err(InvalidRational));
803 check_int_full("0o01.0", true, Err(InvalidRational));
804 check_int_full("0o01.0e1", true, Err(InvalidRational));
805 check_int_full("0o0e", true, Err(InvalidRational));
806 check_int_full("0x", true, Err(InvalidRational));
810 check_int_full("0x0", false, Err(InvalidRational));
811 check_int_full("0x01", false, Err(InvalidRational));
812 check_int_full("0x01.0", true, Err(InvalidRational));
813 check_int_full("0x01.0e1", true, Err(InvalidRational));
814 check_int_full("0x0e", false, Err(InvalidRational));
815 check_int_full("0x0e.0", true, Err(InvalidRational));
816 check_int_full("0x0e.0e1", true, Err(InvalidRational));
817
818 check_int("1e1", Ok("10"));
819 check_int("1.0e1", Ok("10"));
820 check_int("1.00e1", Ok("10"));
821 check_int("1.00e01", Ok("10"));
822
823 check_int("1.1e1", Ok("11"));
824 check_int("1.10e1", Ok("11"));
825 check_int("1.100e1", Ok("11"));
826 check_int("1.2e1", Ok("12"));
827 check_int("1.200e1", Ok("12"));
828
829 check_int("1e10", Ok(&zeros("1", 10)));
830 check_int("1.0e10", Ok(&zeros("1", 10)));
831 check_int("1.1e10", Ok(&zeros("11", 9)));
832 check_int("10e-1", Ok("1"));
833 check_rat("1e-1", Ok("1/10"));
837 check_rat("1e-2", Ok("1/100"));
838 check_rat("1e-3", Ok("1/1000"));
839 check_rat("1.0e-1", Ok("1/10"));
840 check_rat("1.0e-2", Ok("1/100"));
841 check_rat("1.0e-3", Ok("1/1000"));
842 check_rat("1.1e-1", Ok("11/100"));
843 check_rat("1.1e-2", Ok("11/1000"));
844 check_rat("1.1e-3", Ok("11/10000"));
845
846 check_rat("1.1", Ok("11/10"));
847 check_rat("1.10", Ok("11/10"));
848 check_rat("1.100", Ok("11/10"));
849 check_rat("1.2", Ok("12/10"));
850 check_rat("1.20", Ok("12/10"));
851
852 check_rat("1e-78", Ok(&zeros("1/1", 78)));
854 check_rat("1.5e-100", Ok(&zeros("15/1", 101)));
855 check_big("1e78", &zeros("1", 78));
856 }
857}