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