]> git.lizzy.rs Git - rust.git/blobdiff - clippy_lints/src/neg_multiply.rs
Auto merge of #9148 - arieluy:then_some_unwrap_or, r=Jarcho
[rust.git] / clippy_lints / src / neg_multiply.rs
index 0d05c83ffe45ee05804556515df1ce330e118152..b087cfb36b1166968c1fde2c28b3e2bd42b872a4 100644 (file)
@@ -1,7 +1,9 @@
 use clippy_utils::consts::{self, Constant};
 use clippy_utils::diagnostics::span_lint_and_sugg;
 use clippy_utils::source::snippet_with_applicability;
+use clippy_utils::sugg::has_enclosing_paren;
 use if_chain::if_chain;
+use rustc_ast::util::parser::PREC_PREFIX;
 use rustc_errors::Applicability;
 use rustc_hir::{BinOpKind, Expr, ExprKind, UnOp};
 use rustc_lint::{LateContext, LateLintPass};
     /// This only catches integers (for now).
     ///
     /// ### Example
-    /// ```ignore
-    /// // Bad
+    /// ```rust,ignore
     /// let a = x * -1;
+    /// ```
     ///
-    /// // Good
-    /// let b = -x;
+    /// Use instead:
+    /// ```rust,ignore
+    /// let a = -x;
     /// ```
     #[clippy::version = "pre 1.29.0"]
     pub NEG_MULTIPLY,
@@ -34,7 +37,6 @@
 
 declare_lint_pass!(NegMultiply => [NEG_MULTIPLY]);
 
-#[allow(clippy::match_same_arms)]
 impl<'tcx> LateLintPass<'tcx> for NegMultiply {
     fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) {
         if let ExprKind::Binary(ref op, left, right) = e.kind {
@@ -53,12 +55,17 @@ fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) {
 fn check_mul(cx: &LateContext<'_>, span: Span, lit: &Expr<'_>, exp: &Expr<'_>) {
     if_chain! {
         if let ExprKind::Lit(ref l) = lit.kind;
-        if consts::lit_to_constant(&l.node, cx.typeck_results().expr_ty_opt(lit)) == Constant::Int(1);
+        if consts::lit_to_mir_constant(&l.node, cx.typeck_results().expr_ty_opt(lit)) == Constant::Int(1);
         if cx.typeck_results().expr_ty(exp).is_integral();
 
         then {
             let mut applicability = Applicability::MachineApplicable;
-            let suggestion = format!("-{}", snippet_with_applicability(cx, exp.span, "..", &mut applicability));
+            let snip = snippet_with_applicability(cx, exp.span, "..", &mut applicability);
+            let suggestion = if exp.precedence().order() < PREC_PREFIX && !has_enclosing_paren(&snip) {
+                format!("-({})", snip)
+            } else {
+                format!("-{}", snip)
+            };
             span_lint_and_sugg(
                     cx,
                     NEG_MULTIPLY,