]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/utils/numeric_literal.rs
Merge commit 'da5a6fb1b65ec6581a67e942a3850f6bc15a552c' into clippyup
[rust.git] / src / tools / clippy / clippy_lints / src / utils / numeric_literal.rs
1 use rustc_ast::ast::{Lit, LitFloatType, LitIntType, LitKind};
2
3 #[derive(Debug, PartialEq)]
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 character used as exponent separator (b'e' or b'E') and the exponent part.
40     pub exponent: Option<(char, &'a str)>,
41
42     /// The type suffix, including preceding underscore if present.
43     pub suffix: Option<&'a str>,
44 }
45
46 impl<'a> NumericLiteral<'a> {
47     pub fn from_lit(src: &'a str, lit: &Lit) -> Option<NumericLiteral<'a>> {
48         NumericLiteral::from_lit_kind(src, &lit.kind)
49     }
50
51     pub fn from_lit_kind(src: &'a str, lit_kind: &LitKind) -> Option<NumericLiteral<'a>> {
52         if lit_kind.is_numeric() && src.chars().next().map_or(false, |c| c.is_digit(10)) {
53             let (unsuffixed, suffix) = split_suffix(&src, lit_kind);
54             let float = matches!(lit_kind, LitKind::Float(..));
55             Some(NumericLiteral::new(unsuffixed, suffix, float))
56         } else {
57             None
58         }
59     }
60
61     #[must_use]
62     pub fn new(lit: &'a str, suffix: Option<&'a str>, float: bool) -> Self {
63         // Determine delimiter for radix prefix, if present, and radix.
64         let radix = if lit.starts_with("0x") {
65             Radix::Hexadecimal
66         } else if lit.starts_with("0b") {
67             Radix::Binary
68         } else if lit.starts_with("0o") {
69             Radix::Octal
70         } else {
71             Radix::Decimal
72         };
73
74         // Grab part of the literal after prefix, if present.
75         let (prefix, mut sans_prefix) = if let Radix::Decimal = radix {
76             (None, lit)
77         } else {
78             let (p, s) = lit.split_at(2);
79             (Some(p), s)
80         };
81
82         if suffix.is_some() && sans_prefix.ends_with('_') {
83             // The '_' before the suffix isn't part of the digits
84             sans_prefix = &sans_prefix[..sans_prefix.len() - 1];
85         }
86
87         let (integer, fraction, exponent) = Self::split_digit_parts(sans_prefix, float);
88
89         Self {
90             radix,
91             prefix,
92             integer,
93             fraction,
94             exponent,
95             suffix,
96         }
97     }
98
99     pub fn is_decimal(&self) -> bool {
100         self.radix == Radix::Decimal
101     }
102
103     pub fn split_digit_parts(digits: &str, float: bool) -> (&str, Option<&str>, Option<(char, &str)>) {
104         let mut integer = digits;
105         let mut fraction = None;
106         let mut exponent = None;
107
108         if float {
109             for (i, c) in digits.char_indices() {
110                 match c {
111                     '.' => {
112                         integer = &digits[..i];
113                         fraction = Some(&digits[i + 1..]);
114                     },
115                     'e' | 'E' => {
116                         if integer.len() > i {
117                             integer = &digits[..i];
118                         } else {
119                             fraction = Some(&digits[integer.len() + 1..i]);
120                         };
121                         exponent = Some((c, &digits[i + 1..]));
122                         break;
123                     },
124                     _ => {},
125                 }
126             }
127         }
128
129         (integer, fraction, exponent)
130     }
131
132     /// Returns literal formatted in a sensible way.
133     pub fn format(&self) -> String {
134         let mut output = String::new();
135
136         if let Some(prefix) = self.prefix {
137             output.push_str(prefix);
138         }
139
140         let group_size = self.radix.suggest_grouping();
141
142         Self::group_digits(
143             &mut output,
144             self.integer,
145             group_size,
146             true,
147             self.radix == Radix::Hexadecimal,
148         );
149
150         if let Some(fraction) = self.fraction {
151             output.push('.');
152             Self::group_digits(&mut output, fraction, group_size, false, false);
153         }
154
155         if let Some((separator, exponent)) = self.exponent {
156             output.push(separator);
157             Self::group_digits(&mut output, exponent, group_size, true, false);
158         }
159
160         if let Some(suffix) = self.suffix {
161             output.push('_');
162             output.push_str(suffix);
163         }
164
165         output
166     }
167
168     pub fn group_digits(output: &mut String, input: &str, group_size: usize, partial_group_first: bool, pad: bool) {
169         debug_assert!(group_size > 0);
170
171         let mut digits = input.chars().filter(|&c| c != '_');
172
173         let first_group_size;
174
175         if partial_group_first {
176             first_group_size = (digits.clone().count() - 1) % group_size + 1;
177             if pad {
178                 for _ in 0..group_size - first_group_size {
179                     output.push('0');
180                 }
181             }
182         } else {
183             first_group_size = group_size;
184         }
185
186         for _ in 0..first_group_size {
187             if let Some(digit) = digits.next() {
188                 output.push(digit);
189             }
190         }
191
192         for (c, i) in digits.zip((0..group_size).cycle()) {
193             if i == 0 {
194                 output.push('_');
195             }
196             output.push(c);
197         }
198     }
199 }
200
201 fn split_suffix<'a>(src: &'a str, lit_kind: &LitKind) -> (&'a str, Option<&'a str>) {
202     debug_assert!(lit_kind.is_numeric());
203     lit_suffix_length(lit_kind).map_or((src, None), |suffix_length| {
204         let (unsuffixed, suffix) = src.split_at(src.len() - suffix_length);
205         (unsuffixed, Some(suffix))
206     })
207 }
208
209 fn lit_suffix_length(lit_kind: &LitKind) -> Option<usize> {
210     debug_assert!(lit_kind.is_numeric());
211     let suffix = match lit_kind {
212         LitKind::Int(_, int_lit_kind) => match int_lit_kind {
213             LitIntType::Signed(int_ty) => Some(int_ty.name_str()),
214             LitIntType::Unsigned(uint_ty) => Some(uint_ty.name_str()),
215             LitIntType::Unsuffixed => None,
216         },
217         LitKind::Float(_, float_lit_kind) => match float_lit_kind {
218             LitFloatType::Suffixed(float_ty) => Some(float_ty.name_str()),
219             LitFloatType::Unsuffixed => None,
220         },
221         _ => None,
222     };
223
224     suffix.map(str::len)
225 }