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