]> git.lizzy.rs Git - rust.git/blobdiff - clippy_lints/src/regex.rs
Auto merge of #4947 - rust-lang:doc-main-extern-crate, r=flip1995
[rust.git] / clippy_lints / src / regex.rs
index 6ac40c5a1d26a03f194384ddf9b0deaa80a05c2a..c60912ddb2cac57b7ec61ce42017b80b0a6d3309 100644 (file)
@@ -1,84 +1,81 @@
-use regex_syntax;
+use crate::consts::{constant, Constant};
+use crate::utils::{is_expn_of, match_def_path, match_type, paths, span_help_and_lint, span_lint};
+use if_chain::if_chain;
 use rustc::hir::*;
+use rustc::impl_lint_pass;
 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
-use rustc::{declare_tool_lint, lint_array};
-use if_chain::if_chain;
-use std::collections::HashSet;
-use syntax::ast::{LitKind, NodeId, StrStyle};
+use rustc_data_structures::fx::FxHashSet;
+use rustc_session::declare_tool_lint;
+use std::convert::TryFrom;
+use syntax::ast::{LitKind, StrStyle};
 use syntax::source_map::{BytePos, Span};
-use crate::utils::{is_expn_of, match_def_path, match_type, opt_def_id, paths, span_help_and_lint, span_lint};
-use crate::consts::{constant, Constant};
 
-/// **What it does:** Checks [regex](https://crates.io/crates/regex) creation
-/// (with `Regex::new`,`RegexBuilder::new` or `RegexSet::new`) for correct
-/// regex syntax.
-///
-/// **Why is this bad?** This will lead to a runtime panic.
-///
-/// **Known problems:** None.
-///
-/// **Example:**
-/// ```rust
-/// Regex::new("|")
-/// ```
 declare_clippy_lint! {
+    /// **What it does:** Checks [regex](https://crates.io/crates/regex) creation
+    /// (with `Regex::new`,`RegexBuilder::new` or `RegexSet::new`) for correct
+    /// regex syntax.
+    ///
+    /// **Why is this bad?** This will lead to a runtime panic.
+    ///
+    /// **Known problems:** None.
+    ///
+    /// **Example:**
+    /// ```ignore
+    /// Regex::new("|")
+    /// ```
     pub INVALID_REGEX,
     correctness,
     "invalid regular expressions"
 }
 
-/// **What it does:** Checks for trivial [regex](https://crates.io/crates/regex)
-/// creation (with `Regex::new`, `RegexBuilder::new` or `RegexSet::new`).
-///
-/// **Why is this bad?** Matching the regex can likely be replaced by `==` or
-/// `str::starts_with`, `str::ends_with` or `std::contains` or other `str`
-/// methods.
-///
-/// **Known problems:** None.
-///
-/// **Example:**
-/// ```rust
-/// Regex::new("^foobar")
-/// ```
 declare_clippy_lint! {
+    /// **What it does:** Checks for trivial [regex](https://crates.io/crates/regex)
+    /// creation (with `Regex::new`, `RegexBuilder::new` or `RegexSet::new`).
+    ///
+    /// **Why is this bad?** Matching the regex can likely be replaced by `==` or
+    /// `str::starts_with`, `str::ends_with` or `std::contains` or other `str`
+    /// methods.
+    ///
+    /// **Known problems:** None.
+    ///
+    /// **Example:**
+    /// ```ignore
+    /// Regex::new("^foobar")
+    /// ```
     pub TRIVIAL_REGEX,
     style,
     "trivial regular expressions"
 }
 
-/// **What it does:** Checks for usage of `regex!(_)` which (as of now) is
-/// usually slower than `Regex::new(_)` unless called in a loop (which is a bad
-/// idea anyway).
-///
-/// **Why is this bad?** Performance, at least for now. The macro version is
-/// likely to catch up long-term, but for now the dynamic version is faster.
-///
-/// **Known problems:** None.
-///
-/// **Example:**
-/// ```rust
-/// regex!("foo|bar")
-/// ```
 declare_clippy_lint! {
+    /// **What it does:** Checks for usage of `regex!(_)` which (as of now) is
+    /// usually slower than `Regex::new(_)` unless called in a loop (which is a bad
+    /// idea anyway).
+    ///
+    /// **Why is this bad?** Performance, at least for now. The macro version is
+    /// likely to catch up long-term, but for now the dynamic version is faster.
+    ///
+    /// **Known problems:** None.
+    ///
+    /// **Example:**
+    /// ```ignore
+    /// regex!("foo|bar")
+    /// ```
     pub REGEX_MACRO,
     style,
     "use of `regex!(_)` instead of `Regex::new(_)`"
 }
 
 #[derive(Clone, Default)]
-pub struct Pass {
-    spans: HashSet<Span>,
-    last: Option<NodeId>,
+pub struct Regex {
+    spans: FxHashSet<Span>,
+    last: Option<HirId>,
 }
 
-impl LintPass for Pass {
-    fn get_lints(&self) -> LintArray {
-        lint_array!(INVALID_REGEX, REGEX_MACRO, TRIVIAL_REGEX)
-    }
-}
+impl_lint_pass!(Regex => [INVALID_REGEX, REGEX_MACRO, TRIVIAL_REGEX]);
 
-impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
-    fn check_crate(&mut self, _: &LateContext<'a, 'tcx>, _: &'tcx Crate) {
+impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Regex {
+    fn check_crate(&mut self, _: &LateContext<'a, 'tcx>, _: &'tcx Crate<'_>) {
         self.spans.clear();
     }
 
@@ -97,33 +94,33 @@ fn check_block(&mut self, cx: &LateContext<'a, 'tcx>, block: &'tcx Block) {
                               Please use `Regex::new(_)`, which is faster for now.");
                     self.spans.insert(span);
                 }
-                self.last = Some(block.id);
+                self.last = Some(block.hir_id);
             }
         }
     }
 
     fn check_block_post(&mut self, _: &LateContext<'a, 'tcx>, block: &'tcx Block) {
-        if self.last.map_or(false, |id| block.id == id) {
+        if self.last.map_or(false, |id| block.hir_id == id) {
             self.last = None;
         }
     }
 
     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
         if_chain! {
-            if let ExprKind::Call(ref fun, ref args) = expr.node;
-            if let ExprKind::Path(ref qpath) = fun.node;
+            if let ExprKind::Call(ref fun, ref args) = expr.kind;
+            if let ExprKind::Path(ref qpath) = fun.kind;
             if args.len() == 1;
-            if let Some(def_id) = opt_def_id(cx.tables.qpath_def(qpath, fun.hir_id));
+            if let Some(def_id) = cx.tables.qpath_res(qpath, fun.hir_id).opt_def_id();
             then {
-                if match_def_path(cx.tcx, def_id, &paths::REGEX_NEW) ||
-                   match_def_path(cx.tcx, def_id, &paths::REGEX_BUILDER_NEW) {
+                if match_def_path(cx, def_id, &paths::REGEX_NEW) ||
+                   match_def_path(cx, def_id, &paths::REGEX_BUILDER_NEW) {
                     check_regex(cx, &args[0], true);
-                } else if match_def_path(cx.tcx, def_id, &paths::REGEX_BYTES_NEW) ||
-                   match_def_path(cx.tcx, def_id, &paths::REGEX_BYTES_BUILDER_NEW) {
+                } else if match_def_path(cx, def_id, &paths::REGEX_BYTES_NEW) ||
+                   match_def_path(cx, def_id, &paths::REGEX_BYTES_BUILDER_NEW) {
                     check_regex(cx, &args[0], false);
-                } else if match_def_path(cx.tcx, def_id, &paths::REGEX_SET_NEW) {
+                } else if match_def_path(cx, def_id, &paths::REGEX_SET_NEW) {
                     check_set(cx, &args[0], true);
-                } else if match_def_path(cx.tcx, def_id, &paths::REGEX_BYTES_SET_NEW) {
+                } else if match_def_path(cx, def_id, &paths::REGEX_BYTES_SET_NEW) {
                     check_set(cx, &args[0], false);
                 }
             }
@@ -131,10 +128,12 @@ fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
     }
 }
 
+#[allow(clippy::cast_possible_truncation)] // truncation very unlikely here
+#[must_use]
 fn str_span(base: Span, c: regex_syntax::ast::Span, offset: u16) -> Span {
     let offset = u32::from(offset);
-    let end = base.lo() + BytePos(c.end.offset as u32 + offset);
-    let start = base.lo() + BytePos(c.start.offset as u32 + offset);
+    let end = base.lo() + BytePos(u32::try_from(c.end.offset).expect("offset too large") + offset);
+    let start = base.lo() + BytePos(u32::try_from(c.start.offset).expect("offset too large") + offset);
     assert!(start <= end);
     Span::new(start, end, base.ctxt())
 }
@@ -147,28 +146,37 @@ fn const_str<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) -> Option<Stri
 }
 
 fn is_trivial_regex(s: &regex_syntax::hir::Hir) -> Option<&'static str> {
-    use regex_syntax::hir::HirKind::*;
     use regex_syntax::hir::Anchor::*;
+    use regex_syntax::hir::HirKind::*;
 
-    let is_literal = |e: &[regex_syntax::hir::Hir]| e.iter().all(|e| match *e.kind() {
-        Literal(_) => true,
-        _ => false,
-    });
+    let is_literal = |e: &[regex_syntax::hir::Hir]| {
+        e.iter().all(|e| match *e.kind() {
+            Literal(_) => true,
+            _ => false,
+        })
+    };
 
     match *s.kind() {
-        Empty |
-        Anchor(_) => Some("the regex is unlikely to be useful as it is"),
+        Empty | Anchor(_) => Some("the regex is unlikely to be useful as it is"),
         Literal(_) => Some("consider using `str::contains`"),
-        Alternation(ref exprs) => if exprs.iter().all(|e| e.kind().is_empty()) {
-            Some("the regex is unlikely to be useful as it is")
-        } else {
-            None
+        Alternation(ref exprs) => {
+            if exprs.iter().all(|e| e.kind().is_empty()) {
+                Some("the regex is unlikely to be useful as it is")
+            } else {
+                None
+            }
         },
         Concat(ref exprs) => match (exprs[0].kind(), exprs[exprs.len() - 1].kind()) {
-            (&Anchor(StartText), &Anchor(EndText)) if exprs[1..(exprs.len() - 1)].is_empty() => Some("consider using `str::is_empty`"),
-            (&Anchor(StartText), &Anchor(EndText)) if is_literal(&exprs[1..(exprs.len() - 1)]) => Some("consider using `==` on `str`s"),
+            (&Anchor(StartText), &Anchor(EndText)) if exprs[1..(exprs.len() - 1)].is_empty() => {
+                Some("consider using `str::is_empty`")
+            },
+            (&Anchor(StartText), &Anchor(EndText)) if is_literal(&exprs[1..(exprs.len() - 1)]) => {
+                Some("consider using `==` on `str`s")
+            },
             (&Anchor(StartText), &Literal(_)) if is_literal(&exprs[1..]) => Some("consider using `str::starts_with`"),
-            (&Literal(_), &Anchor(EndText)) if is_literal(&exprs[1..(exprs.len() - 1)]) => Some("consider using `str::ends_with`"),
+            (&Literal(_), &Anchor(EndText)) if is_literal(&exprs[1..(exprs.len() - 1)]) => {
+                Some("consider using `str::ends_with`")
+            },
             _ if is_literal(exprs) => Some("consider using `str::contains`"),
             _ => None,
         },
@@ -178,8 +186,8 @@ fn is_trivial_regex(s: &regex_syntax::hir::Hir) -> Option<&'static str> {
 
 fn check_set<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr, utf8: bool) {
     if_chain! {
-        if let ExprKind::AddrOf(_, ref expr) = expr.node;
-        if let ExprKind::Array(ref exprs) = expr.node;
+        if let ExprKind::AddrOf(BorrowKind::Ref, _, ref expr) = expr.kind;
+        if let ExprKind::Array(ref exprs) = expr.kind;
         then {
             for expr in exprs {
                 check_regex(cx, expr, utf8);
@@ -194,19 +202,15 @@ fn check_regex<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr, utf8: boo
         .allow_invalid_utf8(!utf8)
         .build();
 
-    if let ExprKind::Lit(ref lit) = expr.node {
+    if let ExprKind::Lit(ref lit) = expr.kind {
         if let LitKind::Str(ref r, style) = lit.node {
             let r = &r.as_str();
             let offset = if let StrStyle::Raw(n) = style { 2 + n } else { 1 };
             match parser.parse(r) {
-                Ok(r) => if let Some(repl) = is_trivial_regex(&r) {
-                    span_help_and_lint(
-                        cx,
-                        TRIVIAL_REGEX,
-                        expr.span,
-                        "trivial regex",
-                        repl,
-                    );
+                Ok(r) => {
+                    if let Some(repl) = is_trivial_regex(&r) {
+                        span_help_and_lint(cx, TRIVIAL_REGEX, expr.span, "trivial regex", repl);
+                    }
                 },
                 Err(regex_syntax::Error::Parse(e)) => {
                     span_lint(
@@ -225,25 +229,16 @@ fn check_regex<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr, utf8: boo
                     );
                 },
                 Err(e) => {
-                    span_lint(
-                        cx,
-                        INVALID_REGEX,
-                        expr.span,
-                        &format!("regex syntax error: {}", e),
-                    );
+                    span_lint(cx, INVALID_REGEX, expr.span, &format!("regex syntax error: {}", e));
                 },
             }
         }
     } else if let Some(r) = const_str(cx, expr) {
         match parser.parse(&r) {
-            Ok(r) => if let Some(repl) = is_trivial_regex(&r) {
-                span_help_and_lint(
-                    cx,
-                    TRIVIAL_REGEX,
-                    expr.span,
-                    "trivial regex",
-                    repl,
-                );
+            Ok(r) => {
+                if let Some(repl) = is_trivial_regex(&r) {
+                    span_help_and_lint(cx, TRIVIAL_REGEX, expr.span, "trivial regex", repl);
+                }
             },
             Err(regex_syntax::Error::Parse(e)) => {
                 span_lint(
@@ -262,12 +257,7 @@ fn check_regex<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr, utf8: boo
                 );
             },
             Err(e) => {
-                span_lint(
-                    cx,
-                    INVALID_REGEX,
-                    expr.span,
-                    &format!("regex syntax error: {}", e),
-                );
+                span_lint(cx, INVALID_REGEX, expr.span, &format!("regex syntax error: {}", e));
             },
         }
     }