]> git.lizzy.rs Git - rust.git/blobdiff - clippy_lints/src/ranges.rs
range_plus_one suggestion should not remove braces fix
[rust.git] / clippy_lints / src / ranges.rs
index fd303bb6ab4f8dd39ebde8de2e3dada1c9b32e5a..d86f264addab99df26b4fc4dac7f558fabff08bf 100644 (file)
@@ -1,10 +1,10 @@
-use rustc::lint::*;
+use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
 use rustc::{declare_lint, lint_array};
 use if_chain::if_chain;
 use rustc::hir::*;
 use syntax::ast::RangeLimits;
-use syntax::codemap::Spanned;
-use crate::utils::{is_integer_literal, paths, snippet, span_lint, span_lint_and_then};
+use syntax::source_map::Spanned;
+use crate::utils::{is_integer_literal, paths, snippet, span_lint, span_lint_and_then, snippet_opt};
 use crate::utils::{get_trait_def_id, higher, implements_trait, SpanlessEq};
 use crate::utils::sugg::Sugg;
 
 /// **Why is this bad?** The code is more readable with an inclusive range
 /// like `x..=y`.
 ///
-/// **Known problems:** None.
+/// **Known problems:** Will add unnecessary pair of parentheses when the
+/// expression is not wrapped in a pair but starts with a opening parenthesis
+/// and ends with a closing one.
+/// I.e: let _ = (f()+1)..(f()+1) results in let _ = ((f()+1)..(f()+1)).
 ///
 /// **Example:**
 /// ```rust
@@ -57,7 +60,7 @@
 /// ```
 declare_clippy_lint! {
     pub RANGE_PLUS_ONE,
-    nursery,
+    complexity,
     "`x..(y+1)` reads better as `x..=y`"
 }
 
@@ -75,7 +78,7 @@
 /// ```
 declare_clippy_lint! {
     pub RANGE_MINUS_ONE,
-    style,
+    complexity,
     "`x..=(y-1)` reads better as `x..y`"
 }
 
@@ -145,9 +148,17 @@ fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
                     |db| {
                         let start = start.map_or("".to_owned(), |x| Sugg::hir(cx, x, "x").to_string());
                         let end = Sugg::hir(cx, y, "y");
-                        db.span_suggestion(expr.span,
+                        if let Some(is_wrapped) = &snippet_opt(cx, expr.span) {
+                            if is_wrapped.starts_with("(") && is_wrapped.ends_with(")") {
+                                db.span_suggestion(expr.span,
+                                           "use",
+                                           format!("({}..={})", start, end));
+                            } else {
+                                db.span_suggestion(expr.span,
                                            "use",
                                            format!("{}..={}", start, end));
+                            }
+                        }
                     },
                 );
             }