2017-07-19 23:56:32 +00:00
|
|
|
//! Lints concerned with the grouping of digits with underscores in integral or
|
|
|
|
//! floating-point literal expressions.
|
|
|
|
|
2018-07-24 06:55:38 +00:00
|
|
|
use crate::utils::{snippet_opt, span_lint_and_sugg};
|
2018-10-23 21:54:27 +00:00
|
|
|
use if_chain::if_chain;
|
2018-12-29 15:04:45 +00:00
|
|
|
use rustc::lint::{in_external_macro, EarlyContext, EarlyLintPass, LintArray, LintContext, LintPass};
|
2019-04-08 20:43:55 +00:00
|
|
|
use rustc::{declare_lint_pass, declare_tool_lint, impl_lint_pass};
|
2018-12-29 15:04:45 +00:00
|
|
|
use rustc_errors::Applicability;
|
|
|
|
use syntax::ast::*;
|
|
|
|
use syntax_pos;
|
2017-07-19 23:56:32 +00:00
|
|
|
|
2018-03-28 13:24:26 +00:00
|
|
|
declare_clippy_lint! {
|
2019-03-05 16:50:33 +00:00
|
|
|
/// **What it does:** Warns if a long integral or floating-point constant does
|
|
|
|
/// not contain underscores.
|
|
|
|
///
|
|
|
|
/// **Why is this bad?** Reading long numbers is difficult without separators.
|
|
|
|
///
|
|
|
|
/// **Known problems:** None.
|
|
|
|
///
|
|
|
|
/// **Example:**
|
|
|
|
///
|
|
|
|
/// ```rust
|
2019-03-05 22:23:50 +00:00
|
|
|
/// let x: u64 = 61864918973511;
|
2019-03-05 16:50:33 +00:00
|
|
|
/// ```
|
2017-07-19 23:56:32 +00:00
|
|
|
pub UNREADABLE_LITERAL,
|
2018-03-28 13:24:26 +00:00
|
|
|
style,
|
2017-07-19 23:56:32 +00:00
|
|
|
"long integer literal without underscores"
|
|
|
|
}
|
|
|
|
|
2018-09-02 21:07:55 +00:00
|
|
|
declare_clippy_lint! {
|
2019-03-05 16:50:33 +00:00
|
|
|
/// **What it does:** Warns for mistyped suffix in literals
|
|
|
|
///
|
|
|
|
/// **Why is this bad?** This is most probably a typo
|
|
|
|
///
|
|
|
|
/// **Known problems:**
|
|
|
|
/// - Recommends a signed suffix, even though the number might be too big and an unsigned
|
|
|
|
/// suffix is required
|
|
|
|
/// - Does not match on `_128` since that is a valid grouping for decimal and octal numbers
|
|
|
|
///
|
|
|
|
/// **Example:**
|
|
|
|
///
|
|
|
|
/// ```rust
|
2019-03-05 22:23:50 +00:00
|
|
|
/// 2_32;
|
2019-03-05 16:50:33 +00:00
|
|
|
/// ```
|
2018-09-02 21:07:55 +00:00
|
|
|
pub MISTYPED_LITERAL_SUFFIXES,
|
|
|
|
correctness,
|
|
|
|
"mistyped literal suffix"
|
|
|
|
}
|
|
|
|
|
2018-03-28 13:24:26 +00:00
|
|
|
declare_clippy_lint! {
|
2019-03-05 16:50:33 +00:00
|
|
|
/// **What it does:** Warns if an integral or floating-point constant is
|
|
|
|
/// grouped inconsistently with underscores.
|
|
|
|
///
|
|
|
|
/// **Why is this bad?** Readers may incorrectly interpret inconsistently
|
|
|
|
/// grouped digits.
|
|
|
|
///
|
|
|
|
/// **Known problems:** None.
|
|
|
|
///
|
|
|
|
/// **Example:**
|
|
|
|
///
|
|
|
|
/// ```rust
|
2019-03-05 22:23:50 +00:00
|
|
|
/// let x: u64 = 618_64_9189_73_511;
|
2019-03-05 16:50:33 +00:00
|
|
|
/// ```
|
2017-07-19 23:56:32 +00:00
|
|
|
pub INCONSISTENT_DIGIT_GROUPING,
|
2018-03-28 13:24:26 +00:00
|
|
|
style,
|
2017-07-19 23:56:32 +00:00
|
|
|
"integer literals with digits grouped inconsistently"
|
|
|
|
}
|
|
|
|
|
2018-03-28 13:24:26 +00:00
|
|
|
declare_clippy_lint! {
|
2019-03-05 16:50:33 +00:00
|
|
|
/// **What it does:** Warns if the digits of an integral or floating-point
|
|
|
|
/// constant are grouped into groups that
|
|
|
|
/// are too large.
|
|
|
|
///
|
|
|
|
/// **Why is this bad?** Negatively impacts readability.
|
|
|
|
///
|
|
|
|
/// **Known problems:** None.
|
|
|
|
///
|
|
|
|
/// **Example:**
|
|
|
|
///
|
|
|
|
/// ```rust
|
2019-03-05 22:23:50 +00:00
|
|
|
/// let x: u64 = 6186491_8973511;
|
2019-03-05 16:50:33 +00:00
|
|
|
/// ```
|
2017-07-19 23:56:32 +00:00
|
|
|
pub LARGE_DIGIT_GROUPS,
|
2018-12-02 00:46:03 +00:00
|
|
|
pedantic,
|
2017-07-19 23:56:32 +00:00
|
|
|
"grouping digits into groups that are too large"
|
|
|
|
}
|
|
|
|
|
2018-03-28 13:24:26 +00:00
|
|
|
declare_clippy_lint! {
|
2019-03-05 16:50:33 +00:00
|
|
|
/// **What it does:** Warns if there is a better representation for a numeric literal.
|
|
|
|
///
|
|
|
|
/// **Why is this bad?** Especially for big powers of 2 a hexadecimal representation is more
|
|
|
|
/// readable than a decimal representation.
|
|
|
|
///
|
|
|
|
/// **Known problems:** None.
|
|
|
|
///
|
|
|
|
/// **Example:**
|
|
|
|
///
|
|
|
|
/// `255` => `0xFF`
|
|
|
|
/// `65_535` => `0xFFFF`
|
|
|
|
/// `4_042_322_160` => `0xF0F0_F0F0`
|
2018-01-23 14:29:31 +00:00
|
|
|
pub DECIMAL_LITERAL_REPRESENTATION,
|
2018-03-28 13:24:26 +00:00
|
|
|
restriction,
|
2018-01-16 13:01:07 +00:00
|
|
|
"using decimal representation when hexadecimal would be better"
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Debug, PartialEq)]
|
2018-05-02 18:40:52 +00:00
|
|
|
pub(super) enum Radix {
|
2017-07-30 22:33:15 +00:00
|
|
|
Binary,
|
|
|
|
Octal,
|
|
|
|
Decimal,
|
|
|
|
Hexadecimal,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Radix {
|
2019-01-31 01:15:29 +00:00
|
|
|
/// Returns a reasonable digit group size for this radix.
|
2018-06-25 18:50:20 +00:00
|
|
|
crate fn suggest_grouping(&self) -> usize {
|
2017-07-30 22:33:15 +00:00
|
|
|
match *self {
|
|
|
|
Radix::Binary | Radix::Hexadecimal => 4,
|
|
|
|
Radix::Octal | Radix::Decimal => 3,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Debug)]
|
2018-05-02 18:40:52 +00:00
|
|
|
pub(super) struct DigitInfo<'a> {
|
2017-07-30 22:33:15 +00:00
|
|
|
/// Characters of a literal between the radix prefix and type suffix.
|
2018-06-25 18:50:20 +00:00
|
|
|
crate digits: &'a str,
|
2017-07-30 22:33:15 +00:00
|
|
|
/// Which radix the literal was represented in.
|
2018-06-25 18:50:20 +00:00
|
|
|
crate radix: Radix,
|
2017-07-30 22:33:15 +00:00
|
|
|
/// The radix prefix, if present.
|
2018-06-25 18:50:20 +00:00
|
|
|
crate prefix: Option<&'a str>,
|
2017-07-30 22:33:15 +00:00
|
|
|
/// The type suffix, including preceding underscore if present.
|
2018-06-25 18:50:20 +00:00
|
|
|
crate suffix: Option<&'a str>,
|
2017-07-30 22:33:15 +00:00
|
|
|
/// True for floating-point literals.
|
2018-06-25 18:50:20 +00:00
|
|
|
crate float: bool,
|
2017-07-30 22:33:15 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl<'a> DigitInfo<'a> {
|
2018-06-25 18:50:20 +00:00
|
|
|
crate fn new(lit: &'a str, float: bool) -> Self {
|
2017-07-30 22:33:15 +00:00
|
|
|
// Determine delimiter for radix prefix, if present, and radix.
|
|
|
|
let radix = if lit.starts_with("0x") {
|
|
|
|
Radix::Hexadecimal
|
|
|
|
} else if lit.starts_with("0b") {
|
|
|
|
Radix::Binary
|
|
|
|
} else if lit.starts_with("0o") {
|
|
|
|
Radix::Octal
|
|
|
|
} else {
|
|
|
|
Radix::Decimal
|
|
|
|
};
|
|
|
|
|
|
|
|
// Grab part of the literal after prefix, if present.
|
|
|
|
let (prefix, sans_prefix) = if let Radix::Decimal = radix {
|
|
|
|
(None, lit)
|
|
|
|
} else {
|
|
|
|
let (p, s) = lit.split_at(2);
|
|
|
|
(Some(p), s)
|
|
|
|
};
|
|
|
|
|
2018-09-06 14:26:17 +00:00
|
|
|
let len = sans_prefix.len();
|
2017-07-30 22:33:15 +00:00
|
|
|
let mut last_d = '\0';
|
|
|
|
for (d_idx, d) in sans_prefix.char_indices() {
|
2018-10-23 21:54:27 +00:00
|
|
|
let suffix_start = if last_d == '_' { d_idx - 1 } else { d_idx };
|
|
|
|
if float
|
|
|
|
&& (d == 'f'
|
|
|
|
|| is_possible_float_suffix_index(&sans_prefix, suffix_start, len)
|
|
|
|
|| ((d == 'E' || d == 'e') && !has_possible_float_suffix(&sans_prefix)))
|
|
|
|
|| !float && (d == 'i' || d == 'u' || is_possible_suffix_index(&sans_prefix, suffix_start, len))
|
|
|
|
{
|
|
|
|
let (digits, suffix) = sans_prefix.split_at(suffix_start);
|
|
|
|
return Self {
|
|
|
|
digits,
|
|
|
|
radix,
|
|
|
|
prefix,
|
|
|
|
suffix: Some(suffix),
|
|
|
|
float,
|
|
|
|
};
|
2017-07-30 22:33:15 +00:00
|
|
|
}
|
|
|
|
last_d = d
|
|
|
|
}
|
|
|
|
|
|
|
|
// No suffix found
|
2017-08-21 11:32:12 +00:00
|
|
|
Self {
|
2017-07-30 22:33:15 +00:00
|
|
|
digits: sans_prefix,
|
2018-03-15 15:07:15 +00:00
|
|
|
radix,
|
|
|
|
prefix,
|
2017-07-30 22:33:15 +00:00
|
|
|
suffix: None,
|
2018-03-15 15:07:15 +00:00
|
|
|
float,
|
2017-07-30 22:33:15 +00:00
|
|
|
}
|
|
|
|
}
|
2017-07-30 22:37:11 +00:00
|
|
|
|
2018-09-02 21:07:55 +00:00
|
|
|
/// Returns literal formatted in a sensible way.
|
2018-06-25 18:50:20 +00:00
|
|
|
crate fn grouping_hint(&self) -> String {
|
2017-07-30 22:37:11 +00:00
|
|
|
let group_size = self.radix.suggest_grouping();
|
|
|
|
if self.digits.contains('.') {
|
2017-08-01 07:55:17 +00:00
|
|
|
let mut parts = self.digits.split('.');
|
2017-08-09 07:30:56 +00:00
|
|
|
let int_part_hint = parts
|
|
|
|
.next()
|
2017-08-01 11:05:57 +00:00
|
|
|
.expect("split always returns at least one element")
|
2017-07-30 22:37:11 +00:00
|
|
|
.chars()
|
|
|
|
.rev()
|
|
|
|
.filter(|&c| c != '_')
|
|
|
|
.collect::<Vec<_>>()
|
|
|
|
.chunks(group_size)
|
2018-10-22 03:44:09 +00:00
|
|
|
.map(|chunk| chunk.iter().rev().collect())
|
2017-07-30 22:37:11 +00:00
|
|
|
.rev()
|
|
|
|
.collect::<Vec<String>>()
|
|
|
|
.join("_");
|
2017-08-09 07:30:56 +00:00
|
|
|
let frac_part_hint = parts
|
|
|
|
.next()
|
2017-08-01 11:05:57 +00:00
|
|
|
.expect("already checked that there is a `.`")
|
2017-07-30 22:37:11 +00:00
|
|
|
.chars()
|
|
|
|
.filter(|&c| c != '_')
|
|
|
|
.collect::<Vec<_>>()
|
|
|
|
.chunks(group_size)
|
2018-10-22 03:44:09 +00:00
|
|
|
.map(|chunk| chunk.iter().collect())
|
2017-07-30 22:37:11 +00:00
|
|
|
.collect::<Vec<String>>()
|
|
|
|
.join("_");
|
2018-10-23 21:54:27 +00:00
|
|
|
let suffix_hint = match self.suffix {
|
|
|
|
Some(suffix) if is_mistyped_float_suffix(suffix) => format!("_f{}", &suffix[1..]),
|
|
|
|
Some(suffix) => suffix.to_string(),
|
|
|
|
None => String::new(),
|
|
|
|
};
|
|
|
|
format!("{}.{}{}", int_part_hint, frac_part_hint, suffix_hint)
|
2018-11-04 17:39:54 +00:00
|
|
|
} else if self.float && (self.digits.contains('E') || self.digits.contains('e')) {
|
2018-11-01 00:09:56 +00:00
|
|
|
let which_e = if self.digits.contains('E') { 'E' } else { 'e' };
|
2018-10-23 21:54:27 +00:00
|
|
|
let parts: Vec<&str> = self.digits.split(which_e).collect();
|
|
|
|
let filtered_digits_vec_0 = parts[0].chars().filter(|&c| c != '_').rev().collect::<Vec<_>>();
|
|
|
|
let filtered_digits_vec_1 = parts[1].chars().filter(|&c| c != '_').rev().collect::<Vec<_>>();
|
|
|
|
let before_e_hint = filtered_digits_vec_0
|
|
|
|
.chunks(group_size)
|
2018-11-04 17:39:54 +00:00
|
|
|
.map(|chunk| chunk.iter().rev().collect())
|
2018-10-23 21:54:27 +00:00
|
|
|
.rev()
|
|
|
|
.collect::<Vec<String>>()
|
|
|
|
.join("_");
|
|
|
|
let after_e_hint = filtered_digits_vec_1
|
|
|
|
.chunks(group_size)
|
2018-11-04 17:39:54 +00:00
|
|
|
.map(|chunk| chunk.iter().rev().collect())
|
2018-10-23 21:54:27 +00:00
|
|
|
.rev()
|
|
|
|
.collect::<Vec<String>>()
|
|
|
|
.join("_");
|
|
|
|
let suffix_hint = match self.suffix {
|
|
|
|
Some(suffix) if is_mistyped_float_suffix(suffix) => format!("_f{}", &suffix[1..]),
|
|
|
|
Some(suffix) => suffix.to_string(),
|
|
|
|
None => String::new(),
|
|
|
|
};
|
2018-01-16 13:01:07 +00:00
|
|
|
format!(
|
2018-10-23 21:54:27 +00:00
|
|
|
"{}{}{}{}{}",
|
|
|
|
self.prefix.unwrap_or(""),
|
|
|
|
before_e_hint,
|
|
|
|
which_e,
|
|
|
|
after_e_hint,
|
|
|
|
suffix_hint
|
2018-01-16 13:01:07 +00:00
|
|
|
)
|
2017-07-30 22:37:11 +00:00
|
|
|
} else {
|
2018-10-23 21:54:27 +00:00
|
|
|
let filtered_digits_vec = self.digits.chars().filter(|&c| c != '_').rev().collect::<Vec<_>>();
|
2018-06-03 10:26:50 +00:00
|
|
|
let mut hint = filtered_digits_vec
|
2017-07-30 22:37:11 +00:00
|
|
|
.chunks(group_size)
|
2018-10-22 03:44:09 +00:00
|
|
|
.map(|chunk| chunk.iter().rev().collect())
|
2017-07-30 22:37:11 +00:00
|
|
|
.rev()
|
|
|
|
.collect::<Vec<String>>()
|
|
|
|
.join("_");
|
2018-05-28 11:55:27 +00:00
|
|
|
// Forces hexadecimal values to be grouped by 4 being filled with zeroes (e.g 0x00ab_cdef)
|
2018-06-03 10:26:50 +00:00
|
|
|
let nb_digits_to_fill = filtered_digits_vec.len() % 4;
|
2018-05-28 11:55:27 +00:00
|
|
|
if self.radix == Radix::Hexadecimal && nb_digits_to_fill != 0 {
|
2018-05-28 12:12:20 +00:00
|
|
|
hint = format!("{:0>4}{}", &hint[..nb_digits_to_fill], &hint[nb_digits_to_fill..]);
|
2018-05-28 11:55:27 +00:00
|
|
|
}
|
2018-09-02 21:07:55 +00:00
|
|
|
let suffix_hint = match self.suffix {
|
2018-10-23 21:54:27 +00:00
|
|
|
Some(suffix) if is_mistyped_suffix(suffix) => format!("_i{}", &suffix[1..]),
|
2018-09-02 21:07:55 +00:00
|
|
|
Some(suffix) => suffix.to_string(),
|
2018-10-23 21:54:27 +00:00
|
|
|
None => String::new(),
|
2018-09-02 21:07:55 +00:00
|
|
|
};
|
2018-10-23 21:54:27 +00:00
|
|
|
format!("{}{}{}", self.prefix.unwrap_or(""), hint, suffix_hint)
|
2017-07-30 22:37:11 +00:00
|
|
|
}
|
|
|
|
}
|
2017-07-30 22:33:15 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
enum WarningType {
|
|
|
|
UnreadableLiteral,
|
|
|
|
InconsistentDigitGrouping,
|
|
|
|
LargeDigitGroups,
|
2018-01-23 14:29:31 +00:00
|
|
|
DecimalRepresentation,
|
2018-10-23 21:54:27 +00:00
|
|
|
MistypedLiteralSuffix,
|
2017-07-30 22:33:15 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl WarningType {
|
2018-07-23 11:01:12 +00:00
|
|
|
crate fn display(&self, grouping_hint: &str, cx: &EarlyContext<'_>, span: syntax_pos::Span) {
|
2018-05-31 18:15:48 +00:00
|
|
|
match self {
|
2018-10-23 21:54:27 +00:00
|
|
|
WarningType::MistypedLiteralSuffix => span_lint_and_sugg(
|
|
|
|
cx,
|
|
|
|
MISTYPED_LITERAL_SUFFIXES,
|
|
|
|
span,
|
|
|
|
"mistyped literal suffix",
|
|
|
|
"did you mean to write",
|
|
|
|
grouping_hint.to_string(),
|
2018-11-27 15:59:39 +00:00
|
|
|
Applicability::MaybeIncorrect,
|
2018-10-23 21:54:27 +00:00
|
|
|
),
|
2018-03-01 15:15:41 +00:00
|
|
|
WarningType::UnreadableLiteral => span_lint_and_sugg(
|
2017-09-05 09:33:04 +00:00
|
|
|
cx,
|
|
|
|
UNREADABLE_LITERAL,
|
2018-05-31 18:15:48 +00:00
|
|
|
span,
|
2017-09-05 09:33:04 +00:00
|
|
|
"long literal lacking separators",
|
2018-03-01 15:15:41 +00:00
|
|
|
"consider",
|
|
|
|
grouping_hint.to_owned(),
|
2018-11-27 14:13:57 +00:00
|
|
|
Applicability::MachineApplicable,
|
2017-09-05 09:33:04 +00:00
|
|
|
),
|
2018-03-01 15:15:41 +00:00
|
|
|
WarningType::LargeDigitGroups => span_lint_and_sugg(
|
2017-09-05 09:33:04 +00:00
|
|
|
cx,
|
|
|
|
LARGE_DIGIT_GROUPS,
|
2018-05-31 18:15:48 +00:00
|
|
|
span,
|
2017-09-05 09:33:04 +00:00
|
|
|
"digit groups should be smaller",
|
2018-03-01 15:15:41 +00:00
|
|
|
"consider",
|
|
|
|
grouping_hint.to_owned(),
|
2018-11-27 14:13:57 +00:00
|
|
|
Applicability::MachineApplicable,
|
2017-09-05 09:33:04 +00:00
|
|
|
),
|
2018-03-01 15:15:41 +00:00
|
|
|
WarningType::InconsistentDigitGrouping => span_lint_and_sugg(
|
2017-09-05 09:33:04 +00:00
|
|
|
cx,
|
|
|
|
INCONSISTENT_DIGIT_GROUPING,
|
2018-05-31 18:15:48 +00:00
|
|
|
span,
|
2017-09-05 09:33:04 +00:00
|
|
|
"digits grouped inconsistently by underscores",
|
2018-03-01 15:15:41 +00:00
|
|
|
"consider",
|
|
|
|
grouping_hint.to_owned(),
|
2018-11-27 14:13:57 +00:00
|
|
|
Applicability::MachineApplicable,
|
2017-09-05 09:33:04 +00:00
|
|
|
),
|
2018-03-01 15:15:41 +00:00
|
|
|
WarningType::DecimalRepresentation => span_lint_and_sugg(
|
2018-01-16 13:01:07 +00:00
|
|
|
cx,
|
2018-01-23 14:29:31 +00:00
|
|
|
DECIMAL_LITERAL_REPRESENTATION,
|
2018-05-31 18:15:48 +00:00
|
|
|
span,
|
2018-01-23 14:29:31 +00:00
|
|
|
"integer literal has a better hexadecimal representation",
|
2018-03-01 15:15:41 +00:00
|
|
|
"consider",
|
|
|
|
grouping_hint.to_owned(),
|
2018-11-27 14:13:57 +00:00
|
|
|
Applicability::MachineApplicable,
|
2018-01-16 13:01:07 +00:00
|
|
|
),
|
2017-07-30 22:33:15 +00:00
|
|
|
};
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-04-08 20:43:55 +00:00
|
|
|
declare_lint_pass!(LiteralDigitGrouping => [
|
|
|
|
UNREADABLE_LITERAL,
|
|
|
|
INCONSISTENT_DIGIT_GROUPING,
|
|
|
|
LARGE_DIGIT_GROUPS,
|
|
|
|
MISTYPED_LITERAL_SUFFIXES,
|
|
|
|
]);
|
2017-07-19 23:56:32 +00:00
|
|
|
|
|
|
|
impl EarlyLintPass for LiteralDigitGrouping {
|
2018-07-23 11:01:12 +00:00
|
|
|
fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr) {
|
2018-07-24 06:55:38 +00:00
|
|
|
if in_external_macro(cx.sess(), expr.span) {
|
2017-07-19 23:56:32 +00:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2017-07-22 23:54:44 +00:00
|
|
|
if let ExprKind::Lit(ref lit) = expr.node {
|
|
|
|
self.check_lit(cx, lit)
|
2017-07-19 23:56:32 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl LiteralDigitGrouping {
|
2018-07-23 11:01:12 +00:00
|
|
|
fn check_lit(self, cx: &EarlyContext<'_>, lit: &Lit) {
|
2018-03-04 15:28:34 +00:00
|
|
|
match lit.node {
|
|
|
|
LitKind::Int(..) => {
|
|
|
|
// Lint integral literals.
|
|
|
|
if_chain! {
|
|
|
|
if let Some(src) = snippet_opt(cx, lit.span);
|
|
|
|
if let Some(firstch) = src.chars().next();
|
|
|
|
if char::to_digit(firstch, 10).is_some();
|
|
|
|
then {
|
|
|
|
let digit_info = DigitInfo::new(&src, false);
|
2018-09-02 21:07:55 +00:00
|
|
|
let _ = Self::do_lint(digit_info.digits, digit_info.suffix).map_err(|warning_type| {
|
2018-05-31 18:15:48 +00:00
|
|
|
warning_type.display(&digit_info.grouping_hint(), cx, lit.span)
|
2018-03-04 15:28:34 +00:00
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
},
|
|
|
|
LitKind::Float(..) | LitKind::FloatUnsuffixed(..) => {
|
|
|
|
// Lint floating-point literals.
|
|
|
|
if_chain! {
|
|
|
|
if let Some(src) = snippet_opt(cx, lit.span);
|
|
|
|
if let Some(firstch) = src.chars().next();
|
|
|
|
if char::to_digit(firstch, 10).is_some();
|
|
|
|
then {
|
|
|
|
let digit_info = DigitInfo::new(&src, true);
|
|
|
|
// Separate digits into integral and fractional parts.
|
|
|
|
let parts: Vec<&str> = digit_info
|
|
|
|
.digits
|
|
|
|
.split_terminator('.')
|
|
|
|
.collect();
|
2017-07-19 23:56:32 +00:00
|
|
|
|
2018-03-04 15:28:34 +00:00
|
|
|
// Lint integral and fractional parts separately, and then check consistency of digit
|
|
|
|
// groups if both pass.
|
2018-10-23 21:54:27 +00:00
|
|
|
let _ = Self::do_lint(parts[0], digit_info.suffix)
|
2018-03-04 15:28:34 +00:00
|
|
|
.map(|integral_group_size| {
|
|
|
|
if parts.len() > 1 {
|
|
|
|
// Lint the fractional part of literal just like integral part, but reversed.
|
|
|
|
let fractional_part = &parts[1].chars().rev().collect::<String>();
|
2018-09-02 21:07:55 +00:00
|
|
|
let _ = Self::do_lint(fractional_part, None)
|
2018-03-04 15:28:34 +00:00
|
|
|
.map(|fractional_group_size| {
|
|
|
|
let consistent = Self::parts_consistent(integral_group_size,
|
|
|
|
fractional_group_size,
|
|
|
|
parts[0].len(),
|
|
|
|
parts[1].len());
|
2018-10-23 21:54:27 +00:00
|
|
|
if !consistent {
|
2018-11-27 20:14:15 +00:00
|
|
|
WarningType::InconsistentDigitGrouping.display(
|
|
|
|
&digit_info.grouping_hint(),
|
|
|
|
cx,
|
|
|
|
lit.span,
|
|
|
|
);
|
2018-10-23 21:54:27 +00:00
|
|
|
}
|
2018-03-04 15:28:34 +00:00
|
|
|
})
|
|
|
|
.map_err(|warning_type| warning_type.display(&digit_info.grouping_hint(),
|
|
|
|
cx,
|
2018-05-31 18:15:48 +00:00
|
|
|
lit.span));
|
2018-03-04 15:28:34 +00:00
|
|
|
}
|
|
|
|
})
|
2018-05-31 18:15:48 +00:00
|
|
|
.map_err(|warning_type| warning_type.display(&digit_info.grouping_hint(), cx, lit.span));
|
2018-03-04 15:28:34 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
},
|
|
|
|
_ => (),
|
2017-10-23 19:18:02 +00:00
|
|
|
}
|
2017-07-19 23:56:32 +00:00
|
|
|
}
|
|
|
|
|
2017-07-30 22:54:56 +00:00
|
|
|
/// Given the sizes of the digit groups of both integral and fractional
|
|
|
|
/// parts, and the length
|
|
|
|
/// of both parts, determine if the digits have been grouped consistently.
|
|
|
|
fn parts_consistent(int_group_size: usize, frac_group_size: usize, int_size: usize, frac_size: usize) -> bool {
|
|
|
|
match (int_group_size, frac_group_size) {
|
|
|
|
// No groups on either side of decimal point - trivially consistent.
|
|
|
|
(0, 0) => true,
|
|
|
|
// Integral part has grouped digits, fractional part does not.
|
|
|
|
(_, 0) => frac_size <= int_group_size,
|
|
|
|
// Fractional part has grouped digits, integral part does not.
|
|
|
|
(0, _) => int_size <= frac_group_size,
|
|
|
|
// Both parts have grouped digits. Groups should be the same size.
|
|
|
|
(_, _) => int_group_size == frac_group_size,
|
2017-07-19 23:56:32 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-07-30 22:46:41 +00:00
|
|
|
/// Performs lint on `digits` (no decimal point) and returns the group
|
|
|
|
/// size on success or `WarningType` when emitting a warning.
|
2018-09-02 21:07:55 +00:00
|
|
|
fn do_lint(digits: &str, suffix: Option<&str>) -> Result<usize, WarningType> {
|
|
|
|
if let Some(suffix) = suffix {
|
|
|
|
if is_mistyped_suffix(suffix) {
|
|
|
|
return Err(WarningType::MistypedLiteralSuffix);
|
|
|
|
}
|
|
|
|
}
|
2017-07-19 23:56:32 +00:00
|
|
|
// Grab underscore indices with respect to the units digit.
|
2017-08-09 07:30:56 +00:00
|
|
|
let underscore_positions: Vec<usize> = digits
|
|
|
|
.chars()
|
2017-07-30 22:46:41 +00:00
|
|
|
.rev()
|
|
|
|
.enumerate()
|
|
|
|
.filter_map(|(idx, digit)| if digit == '_' { Some(idx) } else { None })
|
2017-07-19 23:56:32 +00:00
|
|
|
.collect();
|
|
|
|
|
|
|
|
if underscore_positions.is_empty() {
|
|
|
|
// Check if literal needs underscores.
|
2018-03-06 13:06:27 +00:00
|
|
|
if digits.len() > 5 {
|
2017-08-01 07:45:36 +00:00
|
|
|
Err(WarningType::UnreadableLiteral)
|
2017-07-19 23:56:32 +00:00
|
|
|
} else {
|
2017-08-01 07:45:36 +00:00
|
|
|
Ok(0)
|
2017-07-19 23:56:32 +00:00
|
|
|
}
|
|
|
|
} else {
|
|
|
|
// Check consistency and the sizes of the groups.
|
|
|
|
let group_size = underscore_positions[0];
|
|
|
|
let consistent = underscore_positions
|
|
|
|
.windows(2)
|
|
|
|
.all(|ps| ps[1] - ps[0] == group_size + 1)
|
|
|
|
// number of digits to the left of the last group cannot be bigger than group size.
|
2017-09-20 21:59:23 +00:00
|
|
|
&& (digits.len() - underscore_positions.last()
|
|
|
|
.expect("there's at least one element") <= group_size + 1);
|
2017-07-19 23:56:32 +00:00
|
|
|
|
|
|
|
if !consistent {
|
2017-07-30 22:46:41 +00:00
|
|
|
return Err(WarningType::InconsistentDigitGrouping);
|
2017-07-19 23:56:32 +00:00
|
|
|
} else if group_size > 4 {
|
2017-07-30 22:46:41 +00:00
|
|
|
return Err(WarningType::LargeDigitGroups);
|
2017-07-19 23:56:32 +00:00
|
|
|
}
|
2017-08-01 07:45:36 +00:00
|
|
|
Ok(group_size)
|
2017-07-19 23:56:32 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2018-01-16 13:01:07 +00:00
|
|
|
|
2019-04-08 20:43:55 +00:00
|
|
|
#[allow(clippy::module_name_repetitions)]
|
2018-01-16 13:01:07 +00:00
|
|
|
#[derive(Copy, Clone)]
|
2019-04-08 20:43:55 +00:00
|
|
|
pub struct DecimalLiteralRepresentation {
|
2018-01-23 11:34:40 +00:00
|
|
|
threshold: u64,
|
|
|
|
}
|
2018-01-16 13:01:07 +00:00
|
|
|
|
2019-04-08 20:43:55 +00:00
|
|
|
impl_lint_pass!(DecimalLiteralRepresentation => [DECIMAL_LITERAL_REPRESENTATION]);
|
2018-01-16 13:01:07 +00:00
|
|
|
|
2019-04-08 20:43:55 +00:00
|
|
|
impl EarlyLintPass for DecimalLiteralRepresentation {
|
2018-07-23 11:01:12 +00:00
|
|
|
fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr) {
|
2018-07-24 06:55:38 +00:00
|
|
|
if in_external_macro(cx.sess(), expr.span) {
|
2018-01-16 13:01:07 +00:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
if let ExprKind::Lit(ref lit) = expr.node {
|
|
|
|
self.check_lit(cx, lit)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-04-08 20:43:55 +00:00
|
|
|
impl DecimalLiteralRepresentation {
|
2018-01-23 11:34:40 +00:00
|
|
|
pub fn new(threshold: u64) -> Self {
|
2018-10-23 21:54:27 +00:00
|
|
|
Self { threshold }
|
2018-01-23 11:34:40 +00:00
|
|
|
}
|
2018-07-23 11:01:12 +00:00
|
|
|
fn check_lit(self, cx: &EarlyContext<'_>, lit: &Lit) {
|
2018-01-16 13:01:07 +00:00
|
|
|
// Lint integral literals.
|
|
|
|
if_chain! {
|
|
|
|
if let LitKind::Int(..) = lit.node;
|
|
|
|
if let Some(src) = snippet_opt(cx, lit.span);
|
|
|
|
if let Some(firstch) = src.chars().next();
|
|
|
|
if char::to_digit(firstch, 10).is_some();
|
2019-04-10 19:05:56 +00:00
|
|
|
let digit_info = DigitInfo::new(&src, false);
|
|
|
|
if digit_info.radix == Radix::Decimal;
|
|
|
|
if let Ok(val) = digit_info.digits
|
|
|
|
.chars()
|
|
|
|
.filter(|&c| c != '_')
|
|
|
|
.collect::<String>()
|
|
|
|
.parse::<u128>();
|
|
|
|
if val >= u128::from(self.threshold);
|
2018-01-16 13:01:07 +00:00
|
|
|
then {
|
2019-04-10 19:05:56 +00:00
|
|
|
let hex = format!("{:#X}", val);
|
|
|
|
let digit_info = DigitInfo::new(&hex, false);
|
|
|
|
let _ = Self::do_lint(digit_info.digits).map_err(|warning_type| {
|
|
|
|
warning_type.display(&digit_info.grouping_hint(), cx, lit.span)
|
|
|
|
});
|
2018-01-16 13:01:07 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn do_lint(digits: &str) -> Result<(), WarningType> {
|
2018-01-23 11:34:40 +00:00
|
|
|
if digits.len() == 1 {
|
|
|
|
// Lint for 1 digit literals, if someone really sets the threshold that low
|
2018-10-23 21:54:27 +00:00
|
|
|
if digits == "1"
|
|
|
|
|| digits == "2"
|
|
|
|
|| digits == "4"
|
|
|
|
|| digits == "8"
|
|
|
|
|| digits == "3"
|
|
|
|
|| digits == "7"
|
2018-01-23 11:34:40 +00:00
|
|
|
|| digits == "F"
|
|
|
|
{
|
2018-01-23 14:29:31 +00:00
|
|
|
return Err(WarningType::DecimalRepresentation);
|
2018-01-23 11:34:40 +00:00
|
|
|
}
|
|
|
|
} else if digits.len() < 4 {
|
|
|
|
// Lint for Literals with a hex-representation of 2 or 3 digits
|
2018-01-16 13:01:07 +00:00
|
|
|
let f = &digits[0..1]; // first digit
|
|
|
|
let s = &digits[1..]; // suffix
|
2018-11-01 21:43:40 +00:00
|
|
|
|
2018-01-23 11:34:40 +00:00
|
|
|
// Powers of 2
|
|
|
|
if ((f.eq("1") || f.eq("2") || f.eq("4") || f.eq("8")) && s.chars().all(|c| c == '0'))
|
|
|
|
// Powers of 2 minus 1
|
|
|
|
|| ((f.eq("1") || f.eq("3") || f.eq("7") || f.eq("F")) && s.chars().all(|c| c == 'F'))
|
|
|
|
{
|
2018-01-23 14:29:31 +00:00
|
|
|
return Err(WarningType::DecimalRepresentation);
|
2018-01-16 13:01:07 +00:00
|
|
|
}
|
2018-01-23 11:34:40 +00:00
|
|
|
} else {
|
2018-01-16 13:01:07 +00:00
|
|
|
// Lint for Literals with a hex-representation of 4 digits or more
|
|
|
|
let f = &digits[0..1]; // first digit
|
|
|
|
let m = &digits[1..digits.len() - 1]; // middle digits, except last
|
|
|
|
let s = &digits[1..]; // suffix
|
2018-11-01 21:43:40 +00:00
|
|
|
|
2018-01-23 11:34:40 +00:00
|
|
|
// Powers of 2 with a margin of +15/-16
|
2018-01-16 13:01:07 +00:00
|
|
|
if ((f.eq("1") || f.eq("2") || f.eq("4") || f.eq("8")) && m.chars().all(|c| c == '0'))
|
|
|
|
|| ((f.eq("1") || f.eq("3") || f.eq("7") || f.eq("F")) && m.chars().all(|c| c == 'F'))
|
|
|
|
// Lint for representations with only 0s and Fs, while allowing 7 as the first
|
|
|
|
// digit
|
|
|
|
|| ((f.eq("7") || f.eq("F")) && s.chars().all(|c| c == '0' || c == 'F'))
|
|
|
|
{
|
2018-01-23 14:29:31 +00:00
|
|
|
return Err(WarningType::DecimalRepresentation);
|
2018-01-16 13:01:07 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
}
|
2018-09-02 21:07:55 +00:00
|
|
|
|
|
|
|
fn is_mistyped_suffix(suffix: &str) -> bool {
|
|
|
|
["_8", "_16", "_32", "_64"].contains(&suffix)
|
|
|
|
}
|
2018-09-06 14:26:17 +00:00
|
|
|
|
|
|
|
fn is_possible_suffix_index(lit: &str, idx: usize, len: usize) -> bool {
|
2018-10-23 21:54:27 +00:00
|
|
|
((len > 3 && idx == len - 3) || (len > 2 && idx == len - 2)) && is_mistyped_suffix(lit.split_at(idx).1)
|
2018-09-06 14:26:17 +00:00
|
|
|
}
|
2018-10-12 04:15:01 +00:00
|
|
|
|
|
|
|
fn is_mistyped_float_suffix(suffix: &str) -> bool {
|
|
|
|
["_32", "_64"].contains(&suffix)
|
|
|
|
}
|
|
|
|
|
|
|
|
fn is_possible_float_suffix_index(lit: &str, idx: usize, len: usize) -> bool {
|
2018-10-23 21:54:27 +00:00
|
|
|
(len > 3 && idx == len - 3) && is_mistyped_float_suffix(lit.split_at(idx).1)
|
|
|
|
}
|
|
|
|
|
|
|
|
fn has_possible_float_suffix(lit: &str) -> bool {
|
|
|
|
lit.ends_with("_32") || lit.ends_with("_64")
|
2018-09-06 14:26:17 +00:00
|
|
|
}
|