1use rustc_ast::ast::{LitFloatType, LitIntType, LitKind};
2use std::iter;
3
4#[derive(Debug, PartialEq, Eq, Copy, Clone)]
6pub enum Radix {
7 Binary,
9 Octal,
11 Decimal,
13 Hexadecimal,
15}
16
17impl Radix {
18 #[must_use]
20 fn suggest_grouping(self) -> usize {
21 match self {
22 Self::Binary | Self::Hexadecimal => 4,
23 Self::Octal | Self::Decimal => 3,
24 }
25 }
26}
27
28pub fn format(lit: &str, type_suffix: Option<&str>, float: bool) -> String {
31 NumericLiteral::new(lit, type_suffix, float).format()
32}
33
34#[derive(Debug)]
35pub struct NumericLiteral<'a> {
36 pub radix: Radix,
38 pub prefix: Option<&'a str>,
40
41 pub integer: &'a str,
43 pub fraction: Option<&'a str>,
45 pub exponent: Option<(&'a str, &'a str)>,
48
49 pub suffix: Option<&'a str>,
51}
52
53impl<'a> NumericLiteral<'a> {
54 pub fn from_lit_kind(src: &'a str, lit_kind: &LitKind) -> Option<NumericLiteral<'a>> {
56 let unsigned_src = src.strip_prefix('-').map_or(src, |s| s);
57 if lit_kind.is_numeric()
58 && unsigned_src
59 .trim_start()
60 .chars()
61 .next()
62 .is_some_and(|c| c.is_ascii_digit())
63 {
64 let (unsuffixed, suffix) = split_suffix(src, lit_kind);
65 let float = matches!(lit_kind, LitKind::Float(..));
66 Some(NumericLiteral::new(unsuffixed, suffix, float))
67 } else {
68 None
69 }
70 }
71
72 #[must_use]
74 pub fn new(lit: &'a str, suffix: Option<&'a str>, float: bool) -> Self {
75 let unsigned_lit = lit.trim_start_matches('-');
76 let radix = if unsigned_lit.starts_with("0x") {
78 Radix::Hexadecimal
79 } else if unsigned_lit.starts_with("0b") {
80 Radix::Binary
81 } else if unsigned_lit.starts_with("0o") {
82 Radix::Octal
83 } else {
84 Radix::Decimal
85 };
86
87 let (prefix, mut sans_prefix) = if radix == Radix::Decimal {
89 (None, lit)
90 } else {
91 let (p, s) = lit.split_at(2);
92 (Some(p), s)
93 };
94
95 if suffix.is_some() && sans_prefix.ends_with('_') {
96 sans_prefix = &sans_prefix[..sans_prefix.len() - 1];
98 }
99
100 let (integer, fraction, exponent) = Self::split_digit_parts(sans_prefix, float);
101
102 Self {
103 radix,
104 prefix,
105 integer,
106 fraction,
107 exponent,
108 suffix,
109 }
110 }
111
112 pub fn is_decimal(&self) -> bool {
114 self.radix == Radix::Decimal
115 }
116
117 fn split_digit_parts(digits: &str, float: bool) -> (&str, Option<&str>, Option<(&str, &str)>) {
118 let mut integer = digits;
119 let mut fraction = None;
120 let mut exponent = None;
121
122 if float {
123 for (i, c) in digits.char_indices() {
124 match c {
125 '.' => {
126 integer = &digits[..i];
127 fraction = Some(&digits[i + 1..]);
128 },
129 'e' | 'E' => {
130 let exp_start = if digits[..i].ends_with('_') { i - 1 } else { i };
131
132 if integer.len() > exp_start {
133 integer = &digits[..exp_start];
134 } else {
135 fraction = Some(&digits[integer.len() + 1..exp_start]);
136 }
137 exponent = Some((&digits[exp_start..=i], &digits[i + 1..]));
138 break;
139 },
140 _ => {},
141 }
142 }
143 }
144
145 (integer, fraction, exponent)
146 }
147
148 pub fn format(&self) -> String {
150 let mut output = String::new();
151
152 if let Some(prefix) = self.prefix {
153 output.push_str(prefix);
154 }
155
156 let group_size = self.radix.suggest_grouping();
157
158 Self::group_digits(
159 &mut output,
160 self.integer,
161 group_size,
162 true,
163 self.radix == Radix::Hexadecimal,
164 );
165
166 if let Some(fraction) = self.fraction {
167 output.push('.');
168 Self::group_digits(&mut output, fraction, group_size, false, false);
169 }
170
171 if let Some((separator, exponent)) = self.exponent {
172 if !exponent.is_empty() && exponent != "0" {
173 output.push_str(separator);
174 Self::group_digits(&mut output, exponent, group_size, true, false);
175 } else if exponent == "0" && self.fraction.is_none() && self.suffix.is_none() {
176 output.push_str(".0");
177 }
178 }
179
180 if let Some(suffix) = self.suffix {
181 if output.ends_with('.') {
182 output.push('0');
183 }
184 output.push('_');
185 output.push_str(suffix);
186 }
187
188 output
189 }
190
191 fn group_digits(output: &mut String, input: &str, group_size: usize, partial_group_first: bool, zero_pad: bool) {
192 debug_assert!(group_size > 0);
193
194 let mut digits = input.chars().filter(|&c| c != '_');
195
196 if digits.clone().next() == Some('-') {
199 let _: Option<char> = digits.next();
200 output.push('-');
201 }
202
203 let first_group_size;
204
205 if partial_group_first {
206 first_group_size = (digits.clone().count() - 1) % group_size + 1;
207 if zero_pad {
208 for _ in 0..group_size - first_group_size {
209 output.push('0');
210 }
211 }
212 } else {
213 first_group_size = group_size;
214 }
215
216 for _ in 0..first_group_size {
217 if let Some(digit) = digits.next() {
218 output.push(digit);
219 }
220 }
221
222 for (c, i) in iter::zip(digits, (0..group_size).cycle()) {
223 if i == 0 {
224 output.push('_');
225 }
226 output.push(c);
227 }
228 }
229}
230
231fn split_suffix<'a>(src: &'a str, lit_kind: &LitKind) -> (&'a str, Option<&'a str>) {
232 debug_assert!(lit_kind.is_numeric());
233 lit_suffix_length(lit_kind)
234 .and_then(|suffix_length| src.len().checked_sub(suffix_length))
235 .map_or((src, None), |split_pos| {
236 let (unsuffixed, suffix) = src.split_at(split_pos);
237 (unsuffixed, Some(suffix))
238 })
239}
240
241fn lit_suffix_length(lit_kind: &LitKind) -> Option<usize> {
242 debug_assert!(lit_kind.is_numeric());
243 let suffix = match lit_kind {
244 LitKind::Int(_, int_lit_kind) => match int_lit_kind {
245 LitIntType::Signed(int_ty) => Some(int_ty.name_str()),
246 LitIntType::Unsigned(uint_ty) => Some(uint_ty.name_str()),
247 LitIntType::Unsuffixed => None,
248 },
249 LitKind::Float(_, float_lit_kind) => match float_lit_kind {
250 LitFloatType::Suffixed(float_ty) => Some(float_ty.name_str()),
251 LitFloatType::Unsuffixed => None,
252 },
253 _ => None,
254 };
255
256 suffix.map(str::len)
257}