]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_utils/src/numeric_literal.rs
Auto merge of #81458 - estebank:match-stmt-remove-semi, r=oli-obk
[rust.git] / src / tools / clippy / clippy_utils / src / numeric_literal.rs
1 use rustc_ast::ast::{Lit, LitFloatType, LitIntType, LitKind};
2
3 #[derive(Debug, PartialEq, Copy, Clone)]
4 pub enum Radix {
5     Binary,
6     Octal,
7     Decimal,
8     Hexadecimal,
9 }
10
11 impl Radix {
12     /// Returns a reasonable digit group size for this radix.
13     #[must_use]
14     fn suggest_grouping(self) -> usize {
15         match self {
16             Self::Binary | Self::Hexadecimal => 4,
17             Self::Octal | Self::Decimal => 3,
18         }
19     }
20 }
21
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()
26 }
27
28 #[derive(Debug)]
29 pub struct NumericLiteral<'a> {
30     /// Which radix the literal was represented in.
31     pub radix: Radix,
32     /// The radix prefix, if present.
33     pub prefix: Option<&'a str>,
34
35     /// The integer part of the number.
36     pub integer: &'a str,
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)>,
42
43     /// The type suffix, including preceding underscore if present.
44     pub suffix: Option<&'a str>,
45 }
46
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)
50     }
51
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))
57         } else {
58             None
59         }
60     }
61
62     #[must_use]
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") {
66             Radix::Hexadecimal
67         } else if lit.starts_with("0b") {
68             Radix::Binary
69         } else if lit.starts_with("0o") {
70             Radix::Octal
71         } else {
72             Radix::Decimal
73         };
74
75         // Grab part of the literal after prefix, if present.
76         let (prefix, mut sans_prefix) = if let Radix::Decimal = radix {
77             (None, lit)
78         } else {
79             let (p, s) = lit.split_at(2);
80             (Some(p), s)
81         };
82
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];
86         }
87
88         let (integer, fraction, exponent) = Self::split_digit_parts(sans_prefix, float);
89
90         Self {
91             radix,
92             prefix,
93             integer,
94             fraction,
95             exponent,
96             suffix,
97         }
98     }
99
100     pub fn is_decimal(&self) -> bool {
101         self.radix == Radix::Decimal
102     }
103
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;
108
109         if float {
110             for (i, c) in digits.char_indices() {
111                 match c {
112                     '.' => {
113                         integer = &digits[..i];
114                         fraction = Some(&digits[i + 1..]);
115                     },
116                     'e' | 'E' => {
117                         let exp_start = if digits[..i].ends_with('_') { i - 1 } else { i };
118
119                         if integer.len() > exp_start {
120                             integer = &digits[..exp_start];
121                         } else {
122                             fraction = Some(&digits[integer.len() + 1..exp_start]);
123                         };
124                         exponent = Some((&digits[exp_start..=i], &digits[i + 1..]));
125                         break;
126                     },
127                     _ => {},
128                 }
129             }
130         }
131
132         (integer, fraction, exponent)
133     }
134
135     /// Returns literal formatted in a sensible way.
136     pub fn format(&self) -> String {
137         let mut output = String::new();
138
139         if let Some(prefix) = self.prefix {
140             output.push_str(prefix);
141         }
142
143         let group_size = self.radix.suggest_grouping();
144
145         Self::group_digits(
146             &mut output,
147             self.integer,
148             group_size,
149             true,
150             self.radix == Radix::Hexadecimal,
151         );
152
153         if let Some(fraction) = self.fraction {
154             output.push('.');
155             Self::group_digits(&mut output, fraction, group_size, false, false);
156         }
157
158         if let Some((separator, exponent)) = self.exponent {
159             output.push_str(separator);
160             Self::group_digits(&mut output, exponent, group_size, true, false);
161         }
162
163         if let Some(suffix) = self.suffix {
164             output.push('_');
165             output.push_str(suffix);
166         }
167
168         output
169     }
170
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);
173
174         let mut digits = input.chars().filter(|&c| c != '_');
175
176         let first_group_size;
177
178         if partial_group_first {
179             first_group_size = (digits.clone().count() - 1) % group_size + 1;
180             if pad {
181                 for _ in 0..group_size - first_group_size {
182                     output.push('0');
183                 }
184             }
185         } else {
186             first_group_size = group_size;
187         }
188
189         for _ in 0..first_group_size {
190             if let Some(digit) = digits.next() {
191                 output.push(digit);
192             }
193         }
194
195         for (c, i) in digits.zip((0..group_size).cycle()) {
196             if i == 0 {
197                 output.push('_');
198             }
199             output.push(c);
200         }
201     }
202 }
203
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))
209     })
210 }
211
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,
219         },
220         LitKind::Float(_, float_lit_kind) => match float_lit_kind {
221             LitFloatType::Suffixed(float_ty) => Some(float_ty.name_str()),
222             LitFloatType::Unsuffixed => None,
223         },
224         _ => None,
225     };
226
227     suffix.map(str::len)
228 }