]> git.lizzy.rs Git - rust.git/blobdiff - clippy_lints/src/functions.rs
Merge branch 'macro-use' into HEAD
[rust.git] / clippy_lints / src / functions.rs
index 79d47b1e7dab7fecb6018c5a7d1468b4e6c12a80..d9f50d652d37bf284cb4e5d1f118946a6210fdb8 100644 (file)
@@ -1,11 +1,15 @@
+use matches::matches;
 use rustc::hir::intravisit;
 use rustc::hir;
 use rustc::lint::*;
+use rustc::{declare_lint, lint_array};
+use rustc::ty;
+use rustc::hir::def::Def;
 use std::collections::HashSet;
 use syntax::ast;
-use syntax::abi::Abi;
+use rustc_target::spec::abi::Abi;
 use syntax::codemap::Span;
-use utils::{span_lint, type_is_unsafe_function, iter_input_pats};
+use crate::utils::{iter_input_pats, span_lint, type_is_unsafe_function};
 
 /// **What it does:** Checks for functions with too many parameters.
 ///
 ///
 /// **Example:**
 /// ```rust
-/// fn foo(x: u32, y: u32, name: &str, c: Color, w: f32, h: f32, a: f32, b: f32) { .. }
+/// fn foo(x: u32, y: u32, name: &str, c: Color, w: f32, h: f32, a: f32, b:
+/// f32) { .. }
 /// ```
-declare_lint! {
+declare_clippy_lint! {
     pub TOO_MANY_ARGUMENTS,
-    Warn,
+    complexity,
     "functions with too many arguments"
 }
 
@@ -35,7 +40,8 @@
 /// **Known problems:**
 ///
 /// * It does not check functions recursively so if the pointer is passed to a
-/// private non-`unsafe` function which does the dereferencing, the lint won't trigger.
+/// private non-`unsafe` function which does the dereferencing, the lint won't
+/// trigger.
 /// * It only checks for arguments whose type are raw pointers, not raw pointers
 /// got from an argument in some other way (`fn foo(bar: &[*const u8])` or
 /// `some_argument.get_raw_ptr()`).
 /// ```rust
 /// pub fn foo(x: *const u8) { println!("{}", unsafe { *x }); }
 /// ```
-declare_lint! {
+declare_clippy_lint! {
     pub NOT_UNSAFE_PTR_ARG_DEREF,
-    Warn,
+    correctness,
     "public functions dereferencing raw pointer arguments but not marked `unsafe`"
 }
 
-#[derive(Copy,Clone)]
+#[derive(Copy, Clone)]
 pub struct Functions {
     threshold: u64,
 }
 
 impl Functions {
-    pub fn new(threshold: u64) -> Functions {
-        Functions { threshold: threshold }
+    pub fn new(threshold: u64) -> Self {
+        Self {
+            threshold,
+        }
     }
 }
 
@@ -75,19 +83,19 @@ fn check_fn(
         decl: &'tcx hir::FnDecl,
         body: &'tcx hir::Body,
         span: Span,
-        nodeid: ast::NodeId
+        nodeid: ast::NodeId,
     ) {
         use rustc::hir::map::Node::*;
 
         let is_impl = if let Some(NodeItem(item)) = cx.tcx.hir.find(cx.tcx.hir.get_parent_node(nodeid)) {
-            matches!(item.node, hir::ItemImpl(_, _, _, _, Some(_), _, _) | hir::ItemDefaultImpl(..))
+            matches!(item.node, hir::ItemKind::Impl(_, _, _, _, Some(_), _, _))
         } else {
             false
         };
 
         let unsafety = match kind {
-            hir::intravisit::FnKind::ItemFn(_, _, unsafety, _, _, _, _) => unsafety,
-            hir::intravisit::FnKind::Method(_, sig, _, _) => sig.unsafety,
+            hir::intravisit::FnKind::ItemFn(_, _, hir::FnHeader { unsafety, .. }, _, _) => unsafety,
+            hir::intravisit::FnKind::Method(_, sig, _, _) => sig.header.unsafety,
             hir::intravisit::FnKind::Closure(_) => return,
         };
 
@@ -95,8 +103,8 @@ fn check_fn(
         if !is_impl {
             // don't lint extern functions decls, it's not their fault either
             match kind {
-                hir::intravisit::FnKind::Method(_, &hir::MethodSig { abi: Abi::Rust, .. }, _, _) |
-                hir::intravisit::FnKind::ItemFn(_, _, _, _, Abi::Rust, _, _) => self.check_arg_number(cx, decl, span),
+                hir::intravisit::FnKind::Method(_, &hir::MethodSig { header: hir::FnHeader { abi: Abi::Rust, .. }, .. }, _, _) |
+                hir::intravisit::FnKind::ItemFn(_, _, hir::FnHeader { abi: Abi::Rust, .. }, _, _) => self.check_arg_number(cx, decl, span),
                 _ => {},
             }
         }
@@ -107,36 +115,38 @@ fn check_fn(
     fn check_trait_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx hir::TraitItem) {
         if let hir::TraitItemKind::Method(ref sig, ref eid) = item.node {
             // don't lint extern functions decls, it's not their fault
-            if sig.abi == Abi::Rust {
+            if sig.header.abi == Abi::Rust {
                 self.check_arg_number(cx, &sig.decl, item.span);
             }
 
             if let hir::TraitMethod::Provided(eid) = *eid {
                 let body = cx.tcx.hir.body(eid);
-                self.check_raw_ptr(cx, sig.unsafety, &sig.decl, body, item.id);
+                self.check_raw_ptr(cx, sig.header.unsafety, &sig.decl, body, item.id);
             }
         }
     }
 }
 
 impl<'a, 'tcx> Functions {
-    fn check_arg_number(&self, cx: &LateContext, decl: &hir::FnDecl, span: Span) {
+    fn check_arg_number(self, cx: &LateContext, decl: &hir::FnDecl, span: Span) {
         let args = decl.inputs.len() as u64;
         if args > self.threshold {
-            span_lint(cx,
-                      TOO_MANY_ARGUMENTS,
-                      span,
-                      &format!("this function has too many arguments ({}/{})", args, self.threshold));
+            span_lint(
+                cx,
+                TOO_MANY_ARGUMENTS,
+                span,
+                &format!("this function has too many arguments ({}/{})", args, self.threshold),
+            );
         }
     }
 
     fn check_raw_ptr(
-        &self,
+        self,
         cx: &LateContext<'a, 'tcx>,
         unsafety: hir::Unsafety,
         decl: &'tcx hir::FnDecl,
         body: &'tcx hir::Body,
-        nodeid: ast::NodeId
+        nodeid: ast::NodeId,
     ) {
         let expr = &body.value;
         if unsafety == hir::Unsafety::Normal && cx.access_levels.is_exported(nodeid) {
@@ -146,9 +156,11 @@ fn check_raw_ptr(
                 .collect::<HashSet<_>>();
 
             if !raw_ptrs.is_empty() {
+                let tables = cx.tcx.body_tables(body.id());
                 let mut v = DerefVisitor {
-                    cx: cx,
+                    cx,
                     ptrs: raw_ptrs,
+                    tables,
                 };
 
                 hir::intravisit::walk_expr(&mut v, expr);
@@ -157,9 +169,9 @@ fn check_raw_ptr(
     }
 }
 
-fn raw_ptr_arg(arg: &hir::Arg, ty: &hir::Ty) -> Option<hir::def_id::DefId> {
-    if let (&hir::PatKind::Binding(_, def_id, _, _), &hir::TyPtr(_)) = (&arg.pat.node, &ty.node) {
-        Some(def_id)
+fn raw_ptr_arg(arg: &hir::Arg, ty: &hir::Ty) -> Option<ast::NodeId> {
+    if let (&hir::PatKind::Binding(_, id, _, _), &hir::TyKind::Ptr(_)) = (&arg.pat.node, &ty.node) {
+        Some(id)
     } else {
         None
     }
@@ -167,14 +179,15 @@ fn raw_ptr_arg(arg: &hir::Arg, ty: &hir::Ty) -> Option<hir::def_id::DefId> {
 
 struct DerefVisitor<'a, 'tcx: 'a> {
     cx: &'a LateContext<'a, 'tcx>,
-    ptrs: HashSet<hir::def_id::DefId>,
+    ptrs: HashSet<ast::NodeId>,
+    tables: &'a ty::TypeckTables<'tcx>,
 }
 
 impl<'a, 'tcx> hir::intravisit::Visitor<'tcx> for DerefVisitor<'a, 'tcx> {
     fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
         match expr.node {
-            hir::ExprCall(ref f, ref args) => {
-                let ty = self.cx.tables.expr_ty(f);
+            hir::ExprKind::Call(ref f, ref args) => {
+                let ty = self.tables.expr_ty(f);
 
                 if type_is_unsafe_function(self.cx, ty) {
                     for arg in args {
@@ -182,8 +195,8 @@ fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
                     }
                 }
             },
-            hir::ExprMethodCall(_, _, ref args) => {
-                let def_id = self.cx.tables.type_dependent_defs[&expr.id].def_id();
+            hir::ExprKind::MethodCall(_, _, ref args) => {
+                let def_id = self.tables.type_dependent_defs()[expr.hir_id].def_id();
                 let base_type = self.cx.tcx.type_of(def_id);
 
                 if type_is_unsafe_function(self.cx, base_type) {
@@ -192,7 +205,7 @@ fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
                     }
                 }
             },
-            hir::ExprUnary(hir::UnDeref, ref ptr) => self.check_arg(ptr),
+            hir::ExprKind::Unary(hir::UnDeref, ref ptr) => self.check_arg(ptr),
             _ => (),
         }
 
@@ -205,13 +218,16 @@ fn nested_visit_map<'this>(&'this mut self) -> intravisit::NestedVisitorMap<'thi
 
 impl<'a, 'tcx: 'a> DerefVisitor<'a, 'tcx> {
     fn check_arg(&self, ptr: &hir::Expr) {
-        if let hir::ExprPath(ref qpath) = ptr.node {
-            let def = self.cx.tables.qpath_def(qpath, ptr.id);
-            if self.ptrs.contains(&def.def_id()) {
-                span_lint(self.cx,
-                          NOT_UNSAFE_PTR_ARG_DEREF,
-                          ptr.span,
-                          "this public function dereferences a raw pointer but is not marked `unsafe`");
+        if let hir::ExprKind::Path(ref qpath) = ptr.node {
+            if let Def::Local(id) = self.cx.tables.qpath_def(qpath, ptr.hir_id) {
+                if self.ptrs.contains(&id) {
+                    span_lint(
+                        self.cx,
+                        NOT_UNSAFE_PTR_ARG_DEREF,
+                        ptr.span,
+                        "this public function dereferences a raw pointer but is not marked `unsafe`",
+                    );
+                }
             }
         }
     }