Skip to content

Commit

Permalink
submodules: update clippy from 8b7f7e6 to 329923e
Browse files Browse the repository at this point in the history
Changes:
````
Apply suggestions from code review
Simplify if_chain.
Move NumericLiteral to its own module.
Included binary and octal cases.
Resolve false positives for hex int cast.
Test for unnecessary_cast of hex int literal.
run-rustfix
Lint `if let Some` in question_mark lint
Add restrictive pat use in full binded struct
Update test case answers to match cargo dev fmt
Ran cargo dev fmt
Rustup to rust-lang/rust#69506
Recommended changes from flip1995
Revive rls integration test
use question mark operator
Add regression test
Use `try_eval_usize` over `eval_usize`
Add path for display trait
Use lang items instead of get_trait_def_id where possible
Update stderr
Don't lint debug formatting in debug impl
Whitelist unused attribute for use items.
Fix one last test issue
Refactor suggested by krishna-veerareddy
Fixed compile error from merging
Changed test output to reflect cargo fmt
Run cargo dev fmt
Finished checking for cases of absolute values
add test for rust-lang#5238
Some bugfixing
Created floating point abs lint and test, but not yet run
````
  • Loading branch information
matthiaskrgr committed Mar 4, 2020
1 parent 5fc2ac4 commit 302d2e5
Show file tree
Hide file tree
Showing 43 changed files with 1,289 additions and 435 deletions.
3 changes: 1 addition & 2 deletions .github/workflows/clippy_bors.yml
Original file line number Diff line number Diff line change
Expand Up @@ -231,8 +231,7 @@ jobs:
matrix:
integration:
- 'rust-lang/cargo'
# FIXME: Re-enable once we can test with rls again.
# - 'rust-lang/rls'
- 'rust-lang/rls'
- 'rust-lang/chalk'
- 'rust-lang/rustfmt'
- 'Marwes/combine'
Expand Down
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -1321,6 +1321,7 @@ Released 2018-09-13
[`ref_in_deref`]: https://rust-lang.github.io/rust-clippy/master/index.html#ref_in_deref
[`regex_macro`]: https://rust-lang.github.io/rust-clippy/master/index.html#regex_macro
[`replace_consts`]: https://rust-lang.github.io/rust-clippy/master/index.html#replace_consts
[`rest_pat_in_fully_bound_structs`]: https://rust-lang.github.io/rust-clippy/master/index.html#rest_pat_in_fully_bound_structs
[`result_expect_used`]: https://rust-lang.github.io/rust-clippy/master/index.html#result_expect_used
[`result_map_unit_fn`]: https://rust-lang.github.io/rust-clippy/master/index.html#result_map_unit_fn
[`result_map_unwrap_or_else`]: https://rust-lang.github.io/rust-clippy/master/index.html#result_map_unwrap_or_else
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

A collection of lints to catch common mistakes and improve your [Rust](https://github.com/rust-lang/rust) code.

[There are 358 lints included in this crate!](https://rust-lang.github.io/rust-clippy/master/index.html)
[There are 359 lints included in this crate!](https://rust-lang.github.io/rust-clippy/master/index.html)

We have a bunch of lint categories to allow you to choose how much Clippy is supposed to ~~annoy~~ help you:

Expand Down
1 change: 1 addition & 0 deletions clippy_lints/src/attrs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -248,6 +248,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Attributes {
if is_word(lint, sym!(unused_imports))
|| is_word(lint, sym!(deprecated))
|| is_word(lint, sym!(unreachable_pub))
|| is_word(lint, sym!(unused))
{
return;
}
Expand Down
2 changes: 1 addition & 1 deletion clippy_lints/src/consts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -231,7 +231,7 @@ impl<'c, 'cc> ConstEvalLateContext<'c, 'cc> {
ExprKind::Tup(ref tup) => self.multi(tup).map(Constant::Tuple),
ExprKind::Repeat(ref value, _) => {
let n = match self.tables.expr_ty(e).kind {
ty::Array(_, n) => n.eval_usize(self.lcx.tcx, self.lcx.param_env),
ty::Array(_, n) => n.try_eval_usize(self.lcx.tcx, self.lcx.param_env)?,
_ => span_bug!(e.span, "typeck error"),
};
self.expr(value).map(|v| Constant::Repeat(Box::new(v), n))
Expand Down
4 changes: 2 additions & 2 deletions clippy_lints/src/doc.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::utils::{get_trait_def_id, implements_trait, is_entrypoint_fn, match_type, paths, return_ty, span_lint};
use crate::utils::{implements_trait, is_entrypoint_fn, match_type, paths, return_ty, span_lint};
use if_chain::if_chain;
use itertools::Itertools;
use rustc::lint::in_external_macro;
Expand Down Expand Up @@ -227,7 +227,7 @@ fn lint_for_missing_headers<'a, 'tcx>(
} else {
if_chain! {
if let Some(body_id) = body_id;
if let Some(future) = get_trait_def_id(cx, &paths::FUTURE);
if let Some(future) = cx.tcx.lang_items().future_trait();
let def_id = cx.tcx.hir().body_owner_def_id(body_id);
let mir = cx.tcx.optimized_mir(def_id);
let ret_ty = mir.return_ty();
Expand Down
7 changes: 3 additions & 4 deletions clippy_lints/src/float_literal.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
use crate::utils::span_lint_and_sugg;
use crate::utils::sugg::format_numeric_literal;
use crate::utils::{numeric_literal, span_lint_and_sugg};
use if_chain::if_chain;
use rustc::ty;
use rustc_ast::ast::{FloatTy, LitFloatType, LitKind};
Expand Down Expand Up @@ -109,7 +108,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for FloatLiteral {
expr.span,
"literal cannot be represented as the underlying type without loss of precision",
"consider changing the type or replacing it with",
format_numeric_literal(&float_str, type_suffix, true),
numeric_literal::format(&float_str, type_suffix, true),
Applicability::MachineApplicable,
);
}
Expand All @@ -120,7 +119,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for FloatLiteral {
expr.span,
"float has excessive precision",
"consider changing the type or truncating it to",
format_numeric_literal(&float_str, type_suffix, true),
numeric_literal::format(&float_str, type_suffix, true),
Applicability::MachineApplicable,
);
}
Expand Down
131 changes: 127 additions & 4 deletions clippy_lints/src/floating_point_arithmetic.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use crate::consts::{
constant, Constant,
constant, constant_simple, Constant,
Constant::{F32, F64},
};
use crate::utils::{span_lint_and_sugg, sugg};
use crate::utils::{higher, numeric_literal, span_lint_and_sugg, sugg, SpanlessEq};
use if_chain::if_chain;
use rustc::ty;
use rustc_errors::Applicability;
Expand All @@ -14,7 +14,7 @@ use rustc_span::source_map::Spanned;
use rustc_ast::ast;
use std::f32::consts as f32_consts;
use std::f64::consts as f64_consts;
use sugg::{format_numeric_literal, Sugg};
use sugg::Sugg;

declare_clippy_lint! {
/// **What it does:** Looks for floating-point expressions that
Expand Down Expand Up @@ -72,6 +72,16 @@ declare_clippy_lint! {
/// let _ = a.log(E);
/// let _ = a.powf(2.0);
/// let _ = a * 2.0 + 4.0;
/// let _ = if a < 0.0 {
/// -a
/// } else {
/// a
/// };
/// let _ = if a < 0.0 {
/// a
/// } else {
/// -a
/// };
/// ```
///
/// is better expressed as
Expand All @@ -88,6 +98,8 @@ declare_clippy_lint! {
/// let _ = a.ln();
/// let _ = a.powi(2);
/// let _ = a.mul_add(2.0, 4.0);
/// let _ = a.abs();
/// let _ = -a.abs();
/// ```
pub SUBOPTIMAL_FLOPS,
nursery,
Expand Down Expand Up @@ -264,7 +276,7 @@ fn check_powf(cx: &LateContext<'_, '_>, expr: &Expr<'_>, args: &[Expr<'_>]) {
format!(
"{}.powi({})",
Sugg::hir(cx, &args[0], ".."),
format_numeric_literal(&exponent.to_string(), None, false)
numeric_literal::format(&exponent.to_string(), None, false)
),
)
} else {
Expand Down Expand Up @@ -359,6 +371,116 @@ fn check_mul_add(cx: &LateContext<'_, '_>, expr: &Expr<'_>) {
}
}

/// Returns true iff expr is an expression which tests whether or not
/// test is positive or an expression which tests whether or not test
/// is nonnegative.
/// Used for check-custom-abs function below
fn is_testing_positive(cx: &LateContext<'_, '_>, expr: &Expr<'_>, test: &Expr<'_>) -> bool {
if let ExprKind::Binary(Spanned { node: op, .. }, left, right) = expr.kind {
match op {
BinOpKind::Gt | BinOpKind::Ge => is_zero(cx, right) && are_exprs_equal(cx, left, test),
BinOpKind::Lt | BinOpKind::Le => is_zero(cx, left) && are_exprs_equal(cx, right, test),
_ => false,
}
} else {
false
}
}

/// See [`is_testing_positive`]
fn is_testing_negative(cx: &LateContext<'_, '_>, expr: &Expr<'_>, test: &Expr<'_>) -> bool {
if let ExprKind::Binary(Spanned { node: op, .. }, left, right) = expr.kind {
match op {
BinOpKind::Gt | BinOpKind::Ge => is_zero(cx, left) && are_exprs_equal(cx, right, test),
BinOpKind::Lt | BinOpKind::Le => is_zero(cx, right) && are_exprs_equal(cx, left, test),
_ => false,
}
} else {
false
}
}

fn are_exprs_equal(cx: &LateContext<'_, '_>, expr1: &Expr<'_>, expr2: &Expr<'_>) -> bool {
SpanlessEq::new(cx).ignore_fn().eq_expr(expr1, expr2)
}

/// Returns true iff expr is some zero literal
fn is_zero(cx: &LateContext<'_, '_>, expr: &Expr<'_>) -> bool {
match constant_simple(cx, cx.tables, expr) {
Some(Constant::Int(i)) => i == 0,
Some(Constant::F32(f)) => f == 0.0,
Some(Constant::F64(f)) => f == 0.0,
_ => false,
}
}

/// If the two expressions are negations of each other, then it returns
/// a tuple, in which the first element is true iff expr1 is the
/// positive expressions, and the second element is the positive
/// one of the two expressions
/// If the two expressions are not negations of each other, then it
/// returns None.
fn are_negated<'a>(cx: &LateContext<'_, '_>, expr1: &'a Expr<'a>, expr2: &'a Expr<'a>) -> Option<(bool, &'a Expr<'a>)> {
if let ExprKind::Unary(UnOp::UnNeg, expr1_negated) = &expr1.kind {
if are_exprs_equal(cx, expr1_negated, expr2) {
return Some((false, expr2));
}
}
if let ExprKind::Unary(UnOp::UnNeg, expr2_negated) = &expr2.kind {
if are_exprs_equal(cx, expr1, expr2_negated) {
return Some((true, expr1));
}
}
None
}

fn check_custom_abs(cx: &LateContext<'_, '_>, expr: &Expr<'_>) {
if_chain! {
if let Some((cond, body, Some(else_body))) = higher::if_block(&expr);
if let ExprKind::Block(block, _) = body.kind;
if block.stmts.is_empty();
if let Some(if_body_expr) = block.expr;
if let ExprKind::Block(else_block, _) = else_body.kind;
if else_block.stmts.is_empty();
if let Some(else_body_expr) = else_block.expr;
if let Some((if_expr_positive, body)) = are_negated(cx, if_body_expr, else_body_expr);
then {
let positive_abs_sugg = (
"manual implementation of `abs` method",
format!("{}.abs()", Sugg::hir(cx, body, "..")),
);
let negative_abs_sugg = (
"manual implementation of negation of `abs` method",
format!("-{}.abs()", Sugg::hir(cx, body, "..")),
);
let sugg = if is_testing_positive(cx, cond, body) {
if if_expr_positive {
positive_abs_sugg
} else {
negative_abs_sugg
}
} else if is_testing_negative(cx, cond, body) {
if if_expr_positive {
negative_abs_sugg
} else {
positive_abs_sugg
}
} else {
return;
};
span_lint_and_sugg(
cx,
SUBOPTIMAL_FLOPS,
expr.span,
sugg.0,
"try",
sugg.1,
Applicability::MachineApplicable,
);
}
}
}

impl<'a, 'tcx> LateLintPass<'a, 'tcx> for FloatingPointArithmetic {
fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) {
if let ExprKind::MethodCall(ref path, _, args) = &expr.kind {
Expand All @@ -375,6 +497,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for FloatingPointArithmetic {
} else {
check_expm1(cx, expr);
check_mul_add(cx, expr);
check_custom_abs(cx, expr);
}
}
}
6 changes: 5 additions & 1 deletion clippy_lints/src/indexing_slicing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,11 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for IndexingSlicing {
if let Some(range) = higher::range(cx, index) {
// Ranged indexes, i.e., &x[n..m], &x[n..], &x[..n] and &x[..]
if let ty::Array(_, s) = ty.kind {
let size: u128 = s.eval_usize(cx.tcx, cx.param_env).into();
let size: u128 = if let Some(size) = s.try_eval_usize(cx.tcx, cx.param_env) {
size.into()
} else {
return;
};

let const_range = to_const_range(cx, range, size);

Expand Down
3 changes: 1 addition & 2 deletions clippy_lints/src/inherent_to_string.rs
Original file line number Diff line number Diff line change
Expand Up @@ -120,8 +120,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for InherentToString {
}

fn show_lint(cx: &LateContext<'_, '_>, item: &ImplItem<'_>) {
let display_trait_id =
get_trait_def_id(cx, &["core", "fmt", "Display"]).expect("Failed to get trait ID of `Display`!");
let display_trait_id = get_trait_def_id(cx, &paths::DISPLAY_TRAIT).expect("Failed to get trait ID of `Display`!");

// Get the real type of 'self'
let fn_def_id = cx.tcx.hir().local_def_id(item.hir_id);
Expand Down
4 changes: 3 additions & 1 deletion clippy_lints/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -330,7 +330,7 @@ mod reexport {
///
/// Used in `./src/driver.rs`.
pub fn register_pre_expansion_lints(store: &mut rustc_lint::LintStore, conf: &Conf) {
store.register_pre_expansion_pass(|| box write::Write);
store.register_pre_expansion_pass(|| box write::Write::default());
store.register_pre_expansion_pass(|| box redundant_field_names::RedundantFieldNames);
let single_char_binding_names_threshold = conf.single_char_binding_names_threshold;
store.register_pre_expansion_pass(move || box non_expressive_names::NonExpressiveNames {
Expand Down Expand Up @@ -610,6 +610,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
&matches::MATCH_REF_PATS,
&matches::MATCH_SINGLE_BINDING,
&matches::MATCH_WILD_ERR_ARM,
&matches::REST_PAT_IN_FULLY_BOUND_STRUCTS,
&matches::SINGLE_MATCH,
&matches::SINGLE_MATCH_ELSE,
&matches::WILDCARD_ENUM_MATCH_ARM,
Expand Down Expand Up @@ -1026,6 +1027,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
LintId::of(&integer_division::INTEGER_DIVISION),
LintId::of(&let_underscore::LET_UNDERSCORE_MUST_USE),
LintId::of(&literal_representation::DECIMAL_LITERAL_REPRESENTATION),
LintId::of(&matches::REST_PAT_IN_FULLY_BOUND_STRUCTS),
LintId::of(&matches::WILDCARD_ENUM_MATCH_ARM),
LintId::of(&mem_forget::MEM_FORGET),
LintId::of(&methods::CLONE_ON_REF_PTR),
Expand Down
Loading

0 comments on commit 302d2e5

Please sign in to comment.