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