]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/ptr.rs
added test, fixed message & description, rustfmt
[rust.git] / clippy_lints / src / ptr.rs
1 //! Checks for usage of  `&Vec[_]` and `&String`.
2
3 use rustc::hir::*;
4 use rustc::hir::map::NodeItem;
5 use rustc::lint::*;
6 use rustc::ty;
7 use syntax::ast::NodeId;
8 use utils::{match_path, match_type, paths, span_lint};
9
10 /// **What it does:** This lint checks for function arguments of type `&String` or `&Vec` unless
11 /// the references are mutable.
12 ///
13 /// **Why is this bad?** Requiring the argument to be of the specific size makes the function less
14 /// useful for no benefit; slices in the form of `&[T]` or `&str` usually suffice and can be
15 /// obtained from other types, too.
16 ///
17 /// **Known problems:** None.
18 ///
19 /// **Example:**
20 /// ```rust
21 /// fn foo(&Vec<u32>) { .. }
22 /// ```
23 declare_lint! {
24     pub PTR_ARG,
25     Warn,
26     "fn arguments of the type `&Vec<...>` or `&String`, suggesting to use `&[...]` or `&str` \
27      instead, respectively"
28 }
29
30 /// **What it does:** This lint checks for equality comparisons with `ptr::null`
31 ///
32 /// **Why is this bad?** It's easier and more readable to use the inherent `.is_null()`
33 /// method instead
34 ///
35 /// **Known problems:** None.
36 ///
37 /// **Example:**
38 /// ```rust
39 /// if x == ptr::null { .. }
40 /// ```
41 declare_lint! {
42     pub CMP_NULL,
43     Warn,
44     "comparing a pointer to a null pointer, suggesting to use `.is_null()` instead."
45 }
46
47 /// **What it does:** This lint checks for functions that take immutable references and return
48 /// mutable ones.
49 ///
50 /// **Why is this bad?** This is trivially unsound, as one can create two mutable references
51 /// from the same (immutable!) source. This [error](https://github.com/rust-lang/rust/issues/39465)
52 /// actually lead to an interim Rust release 1.15.1.
53 ///
54 /// **Known problems:** To be on the conservative side, if there's at least one mutable reference
55 /// with the output lifetime, this lint will not trigger. In practice, this case is unlikely anyway.
56 ///
57 /// **Example:**
58 /// ```rust
59 /// fn foo(&Foo) -> &mut Bar { .. }
60 /// ```
61 declare_lint! {
62     pub MUT_FROM_REF,
63     Warn,
64     "fns that create mutable refs from immutable ref args"
65 }
66
67 #[derive(Copy,Clone)]
68 pub struct PointerPass;
69
70 impl LintPass for PointerPass {
71     fn get_lints(&self) -> LintArray {
72         lint_array!(PTR_ARG, CMP_NULL, MUT_FROM_REF)
73     }
74 }
75
76 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for PointerPass {
77     fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
78         if let ItemFn(ref decl, _, _, _, _, _) = item.node {
79             check_fn(cx, decl, item.id);
80         }
81     }
82
83     fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx ImplItem) {
84         if let ImplItemKind::Method(ref sig, _) = item.node {
85             if let Some(NodeItem(it)) = cx.tcx.hir.find(cx.tcx.hir.get_parent(item.id)) {
86                 if let ItemImpl(_, _, _, Some(_), _, _) = it.node {
87                     return; // ignore trait impls
88                 }
89             }
90             check_fn(cx, &sig.decl, item.id);
91         }
92     }
93
94     fn check_trait_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx TraitItem) {
95         if let TraitItemKind::Method(ref sig, _) = item.node {
96             check_fn(cx, &sig.decl, item.id);
97         }
98     }
99
100     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
101         if let ExprBinary(ref op, ref l, ref r) = expr.node {
102             if (op.node == BiEq || op.node == BiNe) && (is_null_path(l) || is_null_path(r)) {
103                 span_lint(cx,
104                           CMP_NULL,
105                           expr.span,
106                           "Comparing with null is better expressed by the .is_null() method");
107             }
108         }
109     }
110 }
111
112 fn check_fn(cx: &LateContext, decl: &FnDecl, fn_id: NodeId) {
113     let fn_def_id = cx.tcx.hir.local_def_id(fn_id);
114     let fn_ty = cx.tcx.item_type(fn_def_id).fn_sig().skip_binder();
115
116     for (arg, ty) in decl.inputs.iter().zip(fn_ty.inputs()) {
117         if let ty::TyRef(_, ty::TypeAndMut { ty, mutbl: MutImmutable }) = ty.sty {
118             if match_type(cx, ty, &paths::VEC) {
119                 span_lint(cx,
120                           PTR_ARG,
121                           arg.span,
122                           "writing `&Vec<_>` instead of `&[_]` involves one more reference and cannot be used \
123                            with non-Vec-based slices. Consider changing the type to `&[...]`");
124             } else if match_type(cx, ty, &paths::STRING) {
125                 span_lint(cx,
126                           PTR_ARG,
127                           arg.span,
128                           "writing `&String` instead of `&str` involves a new object where a slice will do. \
129                            Consider changing the type to `&str`");
130             }
131         }
132     }
133
134     if let FunctionRetTy::Return(ref ty) = decl.output {
135         if let Some((out, MutMutable)) = get_rptr_lm(ty) {
136             if let Some(MutImmutable) =
137                 decl.inputs
138                     .iter()
139                     .filter_map(|ty| get_rptr_lm(ty))
140                     .filter(|&(lt, _)| lt.name == out.name)
141                     .fold(None, |x, (_, m)| match (x, m) {
142                         (Some(MutMutable), _) |
143                         (_, MutMutable) => Some(MutMutable),
144                         (_, m) => Some(m),
145                     }) {
146                 span_lint(cx,
147                           MUT_FROM_REF,
148                           ty.span,
149                           "this function takes an immutable ref to return a mutable one");
150             }
151         }
152     }
153 }
154
155 fn get_rptr_lm(ty: &Ty) -> Option<(&Lifetime, Mutability)> {
156     if let Ty_::TyRptr(ref lt, ref m) = ty.node {
157         Some((lt, m.mutbl))
158     } else {
159         None
160     }
161 }
162
163 fn is_null_path(expr: &Expr) -> bool {
164     if let ExprCall(ref pathexp, ref args) = expr.node {
165         if args.is_empty() {
166             if let ExprPath(ref path) = pathexp.node {
167                 return match_path(path, &paths::PTR_NULL) || match_path(path, &paths::PTR_NULL_MUT);
168             }
169         }
170     }
171     false
172 }