]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/ptr.rs
avoid linting `ptr_arg` if `.capacity()` is called. Also suggest removing `.as_str...
[rust.git] / clippy_lints / src / ptr.rs
1 //! Checks for usage of  `&Vec[_]` and `&String`.
2
3 use std::borrow::Cow;
4 use rustc::hir::*;
5 use rustc::hir::intravisit::{walk_expr, NestedVisitorMap, Visitor};
6 use rustc::hir::map::NodeItem;
7 use rustc::lint::*;
8 use rustc::ty;
9 use syntax::ast::{Name, NodeId};
10 use syntax::codemap::Span;
11 use syntax_pos::MultiSpan;
12 use utils::{get_pat_name, match_qpath, match_type, match_var, paths,
13             snippet, snippet_opt, span_lint, span_lint_and_then,
14             walk_ptrs_hir_ty};
15
16 /// **What it does:** This lint checks for function arguments of type `&String`
17 /// or `&Vec` unless the references are mutable. It will also suggest you
18 /// replace `.clone()` calls with the appropriate `.to_owned()`/`to_string()`
19 /// calls.
20 ///
21 /// **Why is this bad?** Requiring the argument to be of the specific size
22 /// makes the function less useful for no benefit; slices in the form of `&[T]`
23 /// or `&str` usually suffice and can be obtained from other types, too.
24 ///
25 /// **Known problems:** The lint does not follow data. So if you have an
26 /// argument `x` and write `let y = x; y.clone()` the lint will not suggest
27 /// changing that `.clone()` to `.to_owned()`.
28 ///
29 /// Other functions called from this function taking a `&String` or `&Vec`
30 /// argument may also fail to compile if you change the argument. Applying
31 /// this lint on them will fix the problem, but they may be in other crates.
32 ///
33 /// Also there may be `fn(&Vec)`-typed references pointing to your function.
34 /// If you have them, you will get a compiler error after applying this lint's
35 /// suggestions. You then have the choice to undo your changes or change the
36 /// type of the reference.
37 ///
38 /// Note that if the function is part of your public interface, there may be
39 /// other crates referencing it you may not be aware. Carefully deprecate the
40 /// function before applying the lint suggestions in this case.
41 ///
42 /// **Example:**
43 /// ```rust
44 /// fn foo(&Vec<u32>) { .. }
45 /// ```
46 declare_lint! {
47     pub PTR_ARG,
48     Warn,
49     "fn arguments of the type `&Vec<...>` or `&String`, suggesting to use `&[...]` or `&str` \
50      instead, respectively"
51 }
52
53 /// **What it does:** This lint checks for equality comparisons with `ptr::null`
54 ///
55 /// **Why is this bad?** It's easier and more readable to use the inherent
56 /// `.is_null()`
57 /// method instead
58 ///
59 /// **Known problems:** None.
60 ///
61 /// **Example:**
62 /// ```rust
63 /// if x == ptr::null { .. }
64 /// ```
65 declare_lint! {
66     pub CMP_NULL,
67     Warn,
68     "comparing a pointer to a null pointer, suggesting to use `.is_null()` instead."
69 }
70
71 /// **What it does:** This lint checks for functions that take immutable
72 /// references and return
73 /// mutable ones.
74 ///
75 /// **Why is this bad?** This is trivially unsound, as one can create two
76 /// mutable references
77 /// from the same (immutable!) source. This
78 /// [error](https://github.com/rust-lang/rust/issues/39465)
79 /// actually lead to an interim Rust release 1.15.1.
80 ///
81 /// **Known problems:** To be on the conservative side, if there's at least one
82 /// mutable reference
83 /// with the output lifetime, this lint will not trigger. In practice, this
84 /// case is unlikely anyway.
85 ///
86 /// **Example:**
87 /// ```rust
88 /// fn foo(&Foo) -> &mut Bar { .. }
89 /// ```
90 declare_lint! {
91     pub MUT_FROM_REF,
92     Warn,
93     "fns that create mutable refs from immutable ref args"
94 }
95
96 #[derive(Copy, Clone)]
97 pub struct PointerPass;
98
99 impl LintPass for PointerPass {
100     fn get_lints(&self) -> LintArray {
101         lint_array!(PTR_ARG, CMP_NULL, MUT_FROM_REF)
102     }
103 }
104
105 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for PointerPass {
106     fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
107         if let ItemFn(ref decl, _, _, _, _, body_id) = item.node {
108             check_fn(cx, decl, item.id, Some(body_id));
109         }
110     }
111
112     fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx ImplItem) {
113         if let ImplItemKind::Method(ref sig, body_id) = item.node {
114             if let Some(NodeItem(it)) = cx.tcx.hir.find(cx.tcx.hir.get_parent(item.id)) {
115                 if let ItemImpl(_, _, _, _, Some(_), _, _) = it.node {
116                     return; // ignore trait impls
117                 }
118             }
119             check_fn(cx, &sig.decl, item.id, Some(body_id));
120         }
121     }
122
123     fn check_trait_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx TraitItem) {
124         if let TraitItemKind::Method(ref sig, ref trait_method) = item.node {
125             let body_id = if let TraitMethod::Provided(b) = *trait_method { Some(b) } else { None };
126             check_fn(cx, &sig.decl, item.id, body_id);
127         }
128     }
129
130     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
131         if let ExprBinary(ref op, ref l, ref r) = expr.node {
132             if (op.node == BiEq || op.node == BiNe) && (is_null_path(l) || is_null_path(r)) {
133                 span_lint(
134                     cx,
135                     CMP_NULL,
136                     expr.span,
137                     "Comparing with null is better expressed by the .is_null() method",
138                 );
139             }
140         }
141     }
142 }
143
144 fn check_fn(cx: &LateContext, decl: &FnDecl, fn_id: NodeId, opt_body_id: Option<BodyId>) {
145     let fn_def_id = cx.tcx.hir.local_def_id(fn_id);
146     let sig = cx.tcx.fn_sig(fn_def_id);
147     let fn_ty = sig.skip_binder();
148
149     for (idx, (arg, ty)) in decl.inputs.iter().zip(fn_ty.inputs()).enumerate() {
150         if let ty::TyRef(
151             _,
152             ty::TypeAndMut {
153                 ty,
154                 mutbl: MutImmutable,
155             },
156         ) = ty.sty
157         {
158             if match_type(cx, ty, &paths::VEC) {
159                 let mut ty_snippet = None;
160                 if_let_chain!([
161                     let TyPath(QPath::Resolved(_, ref path)) = walk_ptrs_hir_ty(arg).node,
162                     let Some(&PathSegment{ref parameters, ..}) = path.segments.last(),
163                     parameters.types.len() == 1,
164                 ], {
165                     ty_snippet = snippet_opt(cx, parameters.types[0].span);
166                 });
167                 if let Ok(spans) = get_spans(cx, opt_body_id, idx, &[("clone", ".to_owned()")]) {
168                     span_lint_and_then(
169                         cx,
170                         PTR_ARG,
171                         arg.span,
172                         "writing `&Vec<_>` instead of `&[_]` involves one more reference and cannot be used \
173                          with non-Vec-based slices.",
174                         |db| {
175                             if let Some(ref snippet) = ty_snippet {
176                                 db.span_suggestion(arg.span,
177                                                    "change this to",
178                                                    format!("&[{}]", snippet));
179                             }
180                             for (clonespan, suggestion) in spans {
181                                 db.span_suggestion(clonespan,
182                                                    &snippet_opt(cx, clonespan).map_or("change the call to".into(),
183                                                         |x| Cow::Owned(format!("change `{}` to", x))),
184                                                    suggestion.into());
185                             }
186                         }
187                     );
188                 }
189             } else if match_type(cx, ty, &paths::STRING) {
190                 if let Ok(spans) = get_spans(cx, opt_body_id, idx, &[("clone", ".to_string()"), ("as_str", "")]) {
191                     span_lint_and_then(
192                         cx,
193                         PTR_ARG,
194                         arg.span,
195                         "writing `&String` instead of `&str` involves a new object where a slice will do.",
196                         |db| {
197                             db.span_suggestion(arg.span,
198                                                "change this to",
199                                                "&str".into());
200                             for (clonespan, suggestion) in spans {
201                                 db.span_suggestion_short(clonespan,
202                                                    &snippet_opt(cx, clonespan).map_or("change the call to".into(),
203                                                         |x| Cow::Owned(format!("change `{}` to", x))),
204                                                    suggestion.into());
205                             }
206                         }
207                     );
208                 }
209             }
210         }
211     }
212
213     if let FunctionRetTy::Return(ref ty) = decl.output {
214         if let Some((out, MutMutable, _)) = get_rptr_lm(ty) {
215             let mut immutables = vec![];
216             for (_, ref mutbl, ref argspan) in decl.inputs
217                 .iter()
218                 .filter_map(|ty| get_rptr_lm(ty))
219                 .filter(|&(lt, _, _)| lt.name == out.name)
220             {
221                 if *mutbl == MutMutable {
222                     return;
223                 }
224                 immutables.push(*argspan);
225             }
226             if immutables.is_empty() {
227                 return;
228             }
229             span_lint_and_then(cx, MUT_FROM_REF, ty.span, "mutable borrow from immutable input(s)", |db| {
230                 let ms = MultiSpan::from_spans(immutables);
231                 db.span_note(ms, "immutable borrow here");
232             });
233         }
234     }
235 }
236
237 fn get_spans(cx: &LateContext, opt_body_id: Option<BodyId>, idx: usize, replacements: &'static [(&'static str, &'static str)]) -> Result<Vec<(Span, Cow<'static, str>)>, ()> {
238     if let Some(body) = opt_body_id.map(|id| cx.tcx.hir.body(id)) {
239         get_binding_name(&body.arguments[idx]).map_or_else(|| Ok(vec![]),
240                                                 |name| extract_clone_suggestions(cx, name, replacements, body))
241     } else {
242         Ok(vec![])
243     }
244 }
245
246 fn extract_clone_suggestions<'a, 'tcx: 'a>(cx: &LateContext<'a, 'tcx>, name: Name, replace: &'static [(&'static str, &'static str)], body: &'tcx Body) -> Result<Vec<(Span, Cow<'static, str>)>, ()> {
247     let mut visitor = PtrCloneVisitor {
248         cx,
249         name,
250         replace,
251         spans: vec![],
252         abort: false,
253     };
254     visitor.visit_body(body);
255     if visitor.abort { Err(()) } else { Ok(visitor.spans) }
256 }
257
258 struct PtrCloneVisitor<'a, 'tcx: 'a> {
259     cx: &'a LateContext<'a, 'tcx>,
260     name: Name,
261     replace: &'static [(&'static str, &'static str)],
262     spans: Vec<(Span, Cow<'static, str>)>,
263     abort: bool,
264 }
265
266 impl<'a, 'tcx: 'a> Visitor<'tcx> for PtrCloneVisitor<'a, 'tcx> {
267     fn visit_expr(&mut self, expr: &'tcx Expr) {
268         if self.abort { return; }
269         if let ExprMethodCall(ref seg, _, ref args) = expr.node {
270             if args.len() == 1 && match_var(&args[0], self.name) {
271                 if seg.name == "capacity" {
272                     self.abort = true;
273                     return;
274                 }
275                 for &(fn_name, suffix) in self.replace {
276                     if seg.name == fn_name {
277                         self.spans.push((expr.span, snippet(self.cx, args[0].span, "_") + suffix));
278                         return;
279                     }
280                 }
281             }
282             return;
283         }
284         walk_expr(self, expr);
285     }
286
287     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
288         NestedVisitorMap::None
289     }
290
291 }
292
293 fn get_binding_name(arg: &Arg) -> Option<Name> {
294     get_pat_name(&arg.pat)
295 }
296
297 fn get_rptr_lm(ty: &Ty) -> Option<(&Lifetime, Mutability, Span)> {
298     if let Ty_::TyRptr(ref lt, ref m) = ty.node {
299         Some((lt, m.mutbl, ty.span))
300     } else {
301         None
302     }
303 }
304
305 fn is_null_path(expr: &Expr) -> bool {
306     if let ExprCall(ref pathexp, ref args) = expr.node {
307         if args.is_empty() {
308             if let ExprPath(ref path) = pathexp.node {
309                 return match_qpath(path, &paths::PTR_NULL) || match_qpath(path, &paths::PTR_NULL_MUT);
310             }
311         }
312     }
313     false
314 }