1 use rustc_ast::ast::{LitFloatType, LitIntType, LitKind};
4 #[derive(Debug, PartialEq, Eq, Copy, Clone)]
13 /// Returns a reasonable digit group size for this radix.
15 fn suggest_grouping(self) -> usize {
17 Self::Binary | Self::Hexadecimal => 4,
18 Self::Octal | Self::Decimal => 3,
23 /// A helper method to format numeric literals with digit grouping.
24 /// `lit` must be a valid numeric literal without suffix.
25 pub fn format(lit: &str, type_suffix: Option<&str>, float: bool) -> String {
26 NumericLiteral::new(lit, type_suffix, float).format()
30 pub struct NumericLiteral<'a> {
31 /// Which radix the literal was represented in.
33 /// The radix prefix, if present.
34 pub prefix: Option<&'a str>,
36 /// The integer part of the number.
38 /// The fraction part of the number.
39 pub fraction: Option<&'a str>,
40 /// The exponent separator (b'e' or b'E') including preceding underscore if present
41 /// and the exponent part.
42 pub exponent: Option<(&'a str, &'a str)>,
44 /// The type suffix, including preceding underscore if present.
45 pub suffix: Option<&'a str>,
48 impl<'a> NumericLiteral<'a> {
49 pub fn from_lit_kind(src: &'a str, lit_kind: &LitKind) -> Option<NumericLiteral<'a>> {
50 let unsigned_src = src.strip_prefix('-').map_or(src, |s| s);
51 if lit_kind.is_numeric()
56 .map_or(false, |c| c.is_ascii_digit())
58 let (unsuffixed, suffix) = split_suffix(src, lit_kind);
59 let float = matches!(lit_kind, LitKind::Float(..));
60 Some(NumericLiteral::new(unsuffixed, suffix, float))
67 pub fn new(lit: &'a str, suffix: Option<&'a str>, float: bool) -> Self {
68 let unsigned_lit = lit.trim_start_matches('-');
69 // Determine delimiter for radix prefix, if present, and radix.
70 let radix = if unsigned_lit.starts_with("0x") {
72 } else if unsigned_lit.starts_with("0b") {
74 } else if unsigned_lit.starts_with("0o") {
80 // Grab part of the literal after prefix, if present.
81 let (prefix, mut sans_prefix) = if radix == Radix::Decimal {
84 let (p, s) = lit.split_at(2);
88 if suffix.is_some() && sans_prefix.ends_with('_') {
89 // The '_' before the suffix isn't part of the digits
90 sans_prefix = &sans_prefix[..sans_prefix.len() - 1];
93 let (integer, fraction, exponent) = Self::split_digit_parts(sans_prefix, float);
105 pub fn is_decimal(&self) -> bool {
106 self.radix == Radix::Decimal
109 pub fn split_digit_parts(digits: &str, float: bool) -> (&str, Option<&str>, Option<(&str, &str)>) {
110 let mut integer = digits;
111 let mut fraction = None;
112 let mut exponent = None;
115 for (i, c) in digits.char_indices() {
118 integer = &digits[..i];
119 fraction = Some(&digits[i + 1..]);
122 let exp_start = if digits[..i].ends_with('_') { i - 1 } else { i };
124 if integer.len() > exp_start {
125 integer = &digits[..exp_start];
127 fraction = Some(&digits[integer.len() + 1..exp_start]);
129 exponent = Some((&digits[exp_start..=i], &digits[i + 1..]));
137 (integer, fraction, exponent)
140 /// Returns literal formatted in a sensible way.
141 pub fn format(&self) -> String {
142 let mut output = String::new();
144 if let Some(prefix) = self.prefix {
145 output.push_str(prefix);
148 let group_size = self.radix.suggest_grouping();
155 self.radix == Radix::Hexadecimal,
158 if let Some(fraction) = self.fraction {
160 Self::group_digits(&mut output, fraction, group_size, false, false);
163 if let Some((separator, exponent)) = self.exponent {
165 output.push_str(separator);
166 Self::group_digits(&mut output, exponent, group_size, true, false);
170 if let Some(suffix) = self.suffix {
171 if output.ends_with('.') {
175 output.push_str(suffix);
181 pub fn group_digits(output: &mut String, input: &str, group_size: usize, partial_group_first: bool, pad: bool) {
182 debug_assert!(group_size > 0);
184 let mut digits = input.chars().filter(|&c| c != '_');
186 // The exponent may have a sign, output it early, otherwise it will be
187 // treated as a digit
188 if digits.clone().next() == Some('-') {
189 let _ = digits.next();
193 let first_group_size;
195 if partial_group_first {
196 first_group_size = (digits.clone().count() - 1) % group_size + 1;
198 for _ in 0..group_size - first_group_size {
203 first_group_size = group_size;
206 for _ in 0..first_group_size {
207 if let Some(digit) = digits.next() {
212 for (c, i) in iter::zip(digits, (0..group_size).cycle()) {
221 fn split_suffix<'a>(src: &'a str, lit_kind: &LitKind) -> (&'a str, Option<&'a str>) {
222 debug_assert!(lit_kind.is_numeric());
223 lit_suffix_length(lit_kind)
224 .and_then(|suffix_length| src.len().checked_sub(suffix_length))
225 .map_or((src, None), |split_pos| {
226 let (unsuffixed, suffix) = src.split_at(split_pos);
227 (unsuffixed, Some(suffix))
231 fn lit_suffix_length(lit_kind: &LitKind) -> Option<usize> {
232 debug_assert!(lit_kind.is_numeric());
233 let suffix = match lit_kind {
234 LitKind::Int(_, int_lit_kind) => match int_lit_kind {
235 LitIntType::Signed(int_ty) => Some(int_ty.name_str()),
236 LitIntType::Unsigned(uint_ty) => Some(uint_ty.name_str()),
237 LitIntType::Unsuffixed => None,
239 LitKind::Float(_, float_lit_kind) => match float_lit_kind {
240 LitFloatType::Suffixed(float_ty) => Some(float_ty.name_str()),
241 LitFloatType::Unsuffixed => None,