1 use rustc_ast::ast::{Lit, LitFloatType, LitIntType, LitKind};
3 #[derive(Debug, PartialEq, Copy, Clone)]
12 /// Returns a reasonable digit group size for this radix.
14 fn suggest_grouping(self) -> usize {
16 Self::Binary | Self::Hexadecimal => 4,
17 Self::Octal | Self::Decimal => 3,
22 /// A helper method to format numeric literals with digit grouping.
23 /// `lit` must be a valid numeric literal without suffix.
24 pub fn format(lit: &str, type_suffix: Option<&str>, float: bool) -> String {
25 NumericLiteral::new(lit, type_suffix, float).format()
29 pub struct NumericLiteral<'a> {
30 /// Which radix the literal was represented in.
32 /// The radix prefix, if present.
33 pub prefix: Option<&'a str>,
35 /// The integer part of the number.
37 /// The fraction part of the number.
38 pub fraction: Option<&'a str>,
39 /// The exponent separator (b'e' or b'E') including preceding underscore if present
40 /// and the exponent part.
41 pub exponent: Option<(&'a str, &'a str)>,
43 /// The type suffix, including preceding underscore if present.
44 pub suffix: Option<&'a str>,
47 impl<'a> NumericLiteral<'a> {
48 pub fn from_lit(src: &'a str, lit: &Lit) -> Option<NumericLiteral<'a>> {
49 NumericLiteral::from_lit_kind(src, &lit.kind)
52 pub fn from_lit_kind(src: &'a str, lit_kind: &LitKind) -> Option<NumericLiteral<'a>> {
53 if lit_kind.is_numeric() && src.chars().next().map_or(false, |c| c.is_digit(10)) {
54 let (unsuffixed, suffix) = split_suffix(&src, lit_kind);
55 let float = matches!(lit_kind, LitKind::Float(..));
56 Some(NumericLiteral::new(unsuffixed, suffix, float))
63 pub fn new(lit: &'a str, suffix: Option<&'a str>, float: bool) -> Self {
64 // Determine delimiter for radix prefix, if present, and radix.
65 let radix = if lit.starts_with("0x") {
67 } else if lit.starts_with("0b") {
69 } else if lit.starts_with("0o") {
75 // Grab part of the literal after prefix, if present.
76 let (prefix, mut sans_prefix) = if let Radix::Decimal = radix {
79 let (p, s) = lit.split_at(2);
83 if suffix.is_some() && sans_prefix.ends_with('_') {
84 // The '_' before the suffix isn't part of the digits
85 sans_prefix = &sans_prefix[..sans_prefix.len() - 1];
88 let (integer, fraction, exponent) = Self::split_digit_parts(sans_prefix, float);
100 pub fn is_decimal(&self) -> bool {
101 self.radix == Radix::Decimal
104 pub fn split_digit_parts(digits: &str, float: bool) -> (&str, Option<&str>, Option<(&str, &str)>) {
105 let mut integer = digits;
106 let mut fraction = None;
107 let mut exponent = None;
110 for (i, c) in digits.char_indices() {
113 integer = &digits[..i];
114 fraction = Some(&digits[i + 1..]);
117 let exp_start = if digits[..i].ends_with('_') { i - 1 } else { i };
119 if integer.len() > exp_start {
120 integer = &digits[..exp_start];
122 fraction = Some(&digits[integer.len() + 1..exp_start]);
124 exponent = Some((&digits[exp_start..=i], &digits[i + 1..]));
132 (integer, fraction, exponent)
135 /// Returns literal formatted in a sensible way.
136 pub fn format(&self) -> String {
137 let mut output = String::new();
139 if let Some(prefix) = self.prefix {
140 output.push_str(prefix);
143 let group_size = self.radix.suggest_grouping();
150 self.radix == Radix::Hexadecimal,
153 if let Some(fraction) = self.fraction {
155 Self::group_digits(&mut output, fraction, group_size, false, false);
158 if let Some((separator, exponent)) = self.exponent {
159 output.push_str(separator);
160 Self::group_digits(&mut output, exponent, group_size, true, false);
163 if let Some(suffix) = self.suffix {
165 output.push_str(suffix);
171 pub fn group_digits(output: &mut String, input: &str, group_size: usize, partial_group_first: bool, pad: bool) {
172 debug_assert!(group_size > 0);
174 let mut digits = input.chars().filter(|&c| c != '_');
176 let first_group_size;
178 if partial_group_first {
179 first_group_size = (digits.clone().count() - 1) % group_size + 1;
181 for _ in 0..group_size - first_group_size {
186 first_group_size = group_size;
189 for _ in 0..first_group_size {
190 if let Some(digit) = digits.next() {
195 for (c, i) in digits.zip((0..group_size).cycle()) {
204 fn split_suffix<'a>(src: &'a str, lit_kind: &LitKind) -> (&'a str, Option<&'a str>) {
205 debug_assert!(lit_kind.is_numeric());
206 lit_suffix_length(lit_kind).map_or((src, None), |suffix_length| {
207 let (unsuffixed, suffix) = src.split_at(src.len() - suffix_length);
208 (unsuffixed, Some(suffix))
212 fn lit_suffix_length(lit_kind: &LitKind) -> Option<usize> {
213 debug_assert!(lit_kind.is_numeric());
214 let suffix = match lit_kind {
215 LitKind::Int(_, int_lit_kind) => match int_lit_kind {
216 LitIntType::Signed(int_ty) => Some(int_ty.name_str()),
217 LitIntType::Unsigned(uint_ty) => Some(uint_ty.name_str()),
218 LitIntType::Unsuffixed => None,
220 LitKind::Float(_, float_lit_kind) => match float_lit_kind {
221 LitFloatType::Suffixed(float_ty) => Some(float_ty.name_str()),
222 LitFloatType::Unsuffixed => None,