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