]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_utils/src/numeric_literal.rs
Rollup merge of #104309 - chenyukang:yukang/fix-104088-identifier-error, r=davidtwco
[rust.git] / src / tools / clippy / clippy_utils / src / numeric_literal.rs
1 use rustc_ast::ast::{Lit, LitFloatType, LitIntType, LitKind};
2 use std::iter;
3
4 #[derive(Debug, PartialEq, Eq, Copy, Clone)]
5 pub enum Radix {
6     Binary,
7     Octal,
8     Decimal,
9     Hexadecimal,
10 }
11
12 impl Radix {
13     /// Returns a reasonable digit group size for this radix.
14     #[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
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()
27 }
28
29 #[derive(Debug)]
30 pub struct NumericLiteral<'a> {
31     /// Which radix the literal was represented in.
32     pub radix: Radix,
33     /// The radix prefix, if present.
34     pub prefix: Option<&'a str>,
35
36     /// The integer part of the number.
37     pub integer: &'a str,
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)>,
43
44     /// The type suffix, including preceding underscore if present.
45     pub suffix: Option<&'a str>,
46 }
47
48 impl<'a> NumericLiteral<'a> {
49     pub fn from_lit(src: &'a str, lit: &Lit) -> Option<NumericLiteral<'a>> {
50         NumericLiteral::from_lit_kind(src, &lit.kind)
51     }
52
53     pub fn from_lit_kind(src: &'a str, lit_kind: &LitKind) -> Option<NumericLiteral<'a>> {
54         let unsigned_src = src.strip_prefix('-').map_or(src, |s| s);
55         if lit_kind.is_numeric()
56             && unsigned_src
57                 .trim_start()
58                 .chars()
59                 .next()
60                 .map_or(false, |c| c.is_ascii_digit())
61         {
62             let (unsuffixed, suffix) = split_suffix(src, lit_kind);
63             let float = matches!(lit_kind, LitKind::Float(..));
64             Some(NumericLiteral::new(unsuffixed, suffix, float))
65         } else {
66             None
67         }
68     }
69
70     #[must_use]
71     pub fn new(lit: &'a str, suffix: Option<&'a str>, float: bool) -> Self {
72         let unsigned_lit = lit.trim_start_matches('-');
73         // Determine delimiter for radix prefix, if present, and radix.
74         let radix = if unsigned_lit.starts_with("0x") {
75             Radix::Hexadecimal
76         } else if unsigned_lit.starts_with("0b") {
77             Radix::Binary
78         } else if unsigned_lit.starts_with("0o") {
79             Radix::Octal
80         } else {
81             Radix::Decimal
82         };
83
84         // Grab part of the literal after prefix, if present.
85         let (prefix, mut sans_prefix) = if radix == Radix::Decimal {
86             (None, lit)
87         } else {
88             let (p, s) = lit.split_at(2);
89             (Some(p), s)
90         };
91
92         if suffix.is_some() && sans_prefix.ends_with('_') {
93             // The '_' before the suffix isn't part of the digits
94             sans_prefix = &sans_prefix[..sans_prefix.len() - 1];
95         }
96
97         let (integer, fraction, exponent) = Self::split_digit_parts(sans_prefix, float);
98
99         Self {
100             radix,
101             prefix,
102             integer,
103             fraction,
104             exponent,
105             suffix,
106         }
107     }
108
109     pub fn is_decimal(&self) -> bool {
110         self.radix == Radix::Decimal
111     }
112
113     pub fn split_digit_parts(digits: &str, float: bool) -> (&str, Option<&str>, Option<(&str, &str)>) {
114         let mut integer = digits;
115         let mut fraction = None;
116         let mut exponent = None;
117
118         if float {
119             for (i, c) in digits.char_indices() {
120                 match c {
121                     '.' => {
122                         integer = &digits[..i];
123                         fraction = Some(&digits[i + 1..]);
124                     },
125                     'e' | 'E' => {
126                         let exp_start = if digits[..i].ends_with('_') { i - 1 } else { i };
127
128                         if integer.len() > exp_start {
129                             integer = &digits[..exp_start];
130                         } else {
131                             fraction = Some(&digits[integer.len() + 1..exp_start]);
132                         };
133                         exponent = Some((&digits[exp_start..=i], &digits[i + 1..]));
134                         break;
135                     },
136                     _ => {},
137                 }
138             }
139         }
140
141         (integer, fraction, exponent)
142     }
143
144     /// Returns literal formatted in a sensible way.
145     pub fn format(&self) -> String {
146         let mut output = String::new();
147
148         if let Some(prefix) = self.prefix {
149             output.push_str(prefix);
150         }
151
152         let group_size = self.radix.suggest_grouping();
153
154         Self::group_digits(
155             &mut output,
156             self.integer,
157             group_size,
158             true,
159             self.radix == Radix::Hexadecimal,
160         );
161
162         if let Some(fraction) = self.fraction {
163             output.push('.');
164             Self::group_digits(&mut output, fraction, group_size, false, false);
165         }
166
167         if let Some((separator, exponent)) = self.exponent {
168             if exponent != "0" {
169                 output.push_str(separator);
170                 Self::group_digits(&mut output, exponent, group_size, true, false);
171             }
172         }
173
174         if let Some(suffix) = self.suffix {
175             if output.ends_with('.') {
176                 output.push('0');
177             }
178             output.push('_');
179             output.push_str(suffix);
180         }
181
182         output
183     }
184
185     pub fn group_digits(output: &mut String, input: &str, group_size: usize, partial_group_first: bool, pad: bool) {
186         debug_assert!(group_size > 0);
187
188         let mut digits = input.chars().filter(|&c| c != '_');
189
190         // The exponent may have a sign, output it early, otherwise it will be
191         // treated as a digit
192         if digits.clone().next() == Some('-') {
193             let _ = digits.next();
194             output.push('-');
195         }
196
197         let first_group_size;
198
199         if partial_group_first {
200             first_group_size = (digits.clone().count() - 1) % group_size + 1;
201             if pad {
202                 for _ in 0..group_size - first_group_size {
203                     output.push('0');
204                 }
205             }
206         } else {
207             first_group_size = group_size;
208         }
209
210         for _ in 0..first_group_size {
211             if let Some(digit) = digits.next() {
212                 output.push(digit);
213             }
214         }
215
216         for (c, i) in iter::zip(digits, (0..group_size).cycle()) {
217             if i == 0 {
218                 output.push('_');
219             }
220             output.push(c);
221         }
222     }
223 }
224
225 fn split_suffix<'a>(src: &'a str, lit_kind: &LitKind) -> (&'a str, Option<&'a str>) {
226     debug_assert!(lit_kind.is_numeric());
227     lit_suffix_length(lit_kind)
228         .and_then(|suffix_length| src.len().checked_sub(suffix_length))
229         .map_or((src, None), |split_pos| {
230             let (unsuffixed, suffix) = src.split_at(split_pos);
231             (unsuffixed, Some(suffix))
232         })
233 }
234
235 fn lit_suffix_length(lit_kind: &LitKind) -> Option<usize> {
236     debug_assert!(lit_kind.is_numeric());
237     let suffix = match lit_kind {
238         LitKind::Int(_, int_lit_kind) => match int_lit_kind {
239             LitIntType::Signed(int_ty) => Some(int_ty.name_str()),
240             LitIntType::Unsigned(uint_ty) => Some(uint_ty.name_str()),
241             LitIntType::Unsuffixed => None,
242         },
243         LitKind::Float(_, float_lit_kind) => match float_lit_kind {
244             LitFloatType::Suffixed(float_ty) => Some(float_ty.name_str()),
245             LitFloatType::Unsuffixed => None,
246         },
247         _ => None,
248     };
249
250     suffix.map(str::len)
251 }