1 //! Checks for usage of `&Vec[_]` and `&String`.
4 use rustc::hir::intravisit::{walk_expr, NestedVisitorMap, Visitor};
5 use rustc::hir::map::NodeItem;
8 use syntax::ast::{Name, NodeId};
9 use syntax::codemap::Span;
10 use syntax_pos::MultiSpan;
11 use utils::{get_pat_name, match_qpath, match_type, match_var, paths,
12 snippet, snippet_opt, span_lint, span_lint_and_then,
15 /// **What it does:** This lint checks for function arguments of type `&String`
16 /// or `&Vec` unless the references are mutable. It will also suggest you
17 /// replace `.clone()` calls with the appropriate `.to_owned()`/`to_string()`
20 /// **Why is this bad?** Requiring the argument to be of the specific size
21 /// makes the function less useful for no benefit; slices in the form of `&[T]`
22 /// or `&str` usually suffice and can be obtained from other types, too.
24 /// **Known problems:** The lint does not follow data. So if you have an
25 /// argument `x` and write `let y = x; y.clone()` the lint will not suggest
26 /// changing that `.clone()` to `.to_owned()`.
28 /// Other functions called from this function taking a `&String` or `&Vec`
29 /// argument may also fail to compile if you change the argument. Applying
30 /// this lint on them will fix the problem, but they may be in other crates.
32 /// Also there may be `fn(&Vec)`-typed references pointing to your function.
33 /// If you have them, you will get a compiler error after applying this lint's
34 /// suggestions. You then have the choice to undo your changes or change the
35 /// type of the reference.
37 /// Note that if the function is part of your public interface, there may be
38 /// other crates referencing it you may not be aware. Carefully deprecate the
39 /// function before applying the lint suggestions in this case.
43 /// fn foo(&Vec<u32>) { .. }
48 "fn arguments of the type `&Vec<...>` or `&String`, suggesting to use `&[...]` or `&str` \
49 instead, respectively"
52 /// **What it does:** This lint checks for equality comparisons with `ptr::null`
54 /// **Why is this bad?** It's easier and more readable to use the inherent
58 /// **Known problems:** None.
62 /// if x == ptr::null { .. }
67 "comparing a pointer to a null pointer, suggesting to use `.is_null()` instead."
70 /// **What it does:** This lint checks for functions that take immutable
71 /// references and return
74 /// **Why is this bad?** This is trivially unsound, as one can create two
75 /// mutable references
76 /// from the same (immutable!) source. This
77 /// [error](https://github.com/rust-lang/rust/issues/39465)
78 /// actually lead to an interim Rust release 1.15.1.
80 /// **Known problems:** To be on the conservative side, if there's at least one
82 /// with the output lifetime, this lint will not trigger. In practice, this
83 /// case is unlikely anyway.
87 /// fn foo(&Foo) -> &mut Bar { .. }
92 "fns that create mutable refs from immutable ref args"
95 #[derive(Copy, Clone)]
96 pub struct PointerPass;
98 impl LintPass for PointerPass {
99 fn get_lints(&self) -> LintArray {
100 lint_array!(PTR_ARG, CMP_NULL, MUT_FROM_REF)
104 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for PointerPass {
105 fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
106 if let ItemFn(ref decl, _, _, _, _, body_id) = item.node {
107 check_fn(cx, decl, item.id, Some(body_id));
111 fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx ImplItem) {
112 if let ImplItemKind::Method(ref sig, body_id) = item.node {
113 if let Some(NodeItem(it)) = cx.tcx.hir.find(cx.tcx.hir.get_parent(item.id)) {
114 if let ItemImpl(_, _, _, _, Some(_), _, _) = it.node {
115 return; // ignore trait impls
118 check_fn(cx, &sig.decl, item.id, Some(body_id));
122 fn check_trait_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx TraitItem) {
123 if let TraitItemKind::Method(ref sig, ref trait_method) = item.node {
124 let body_id = if let TraitMethod::Provided(b) = *trait_method { Some(b) } else { None };
125 check_fn(cx, &sig.decl, item.id, body_id);
129 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
130 if let ExprBinary(ref op, ref l, ref r) = expr.node {
131 if (op.node == BiEq || op.node == BiNe) && (is_null_path(l) || is_null_path(r)) {
136 "Comparing with null is better expressed by the .is_null() method",
143 fn check_fn(cx: &LateContext, decl: &FnDecl, fn_id: NodeId, opt_body_id: Option<BodyId>) {
144 let fn_def_id = cx.tcx.hir.local_def_id(fn_id);
145 let sig = cx.tcx.fn_sig(fn_def_id);
146 let fn_ty = sig.skip_binder();
148 for (idx, (arg, ty)) in decl.inputs.iter().zip(fn_ty.inputs()).enumerate() {
157 if match_type(cx, ty, &paths::VEC) {
158 let mut ty_snippet = None;
160 let TyPath(QPath::Resolved(_, ref path)) = walk_ptrs_hir_ty(arg).node,
161 let Some(&PathSegment{ref parameters, ..}) = path.segments.last(),
162 parameters.types.len() == 1,
164 ty_snippet = snippet_opt(cx, parameters.types[0].span);
166 let spans = get_spans(cx, opt_body_id, idx, "to_owned");
171 "writing `&Vec<_>` instead of `&[_]` involves one more reference and cannot be used \
172 with non-Vec-based slices.",
174 if let Some(ref snippet) = ty_snippet {
175 db.span_suggestion(arg.span,
177 format!("&[{}]", snippet));
179 for (clonespan, suggestion) in spans {
180 db.span_suggestion(clonespan,
181 "change the `.clone()` to",
186 } else if match_type(cx, ty, &paths::STRING) {
187 let spans = get_spans(cx, opt_body_id, idx, "to_string");
192 "writing `&String` instead of `&str` involves a new object where a slice will do.",
194 db.span_suggestion(arg.span,
197 for (clonespan, suggestion) in spans {
198 db.span_suggestion_short(clonespan,
199 "change the `.clone` to ",
208 if let FunctionRetTy::Return(ref ty) = decl.output {
209 if let Some((out, MutMutable, _)) = get_rptr_lm(ty) {
210 let mut immutables = vec![];
211 for (_, ref mutbl, ref argspan) in decl.inputs
213 .filter_map(|ty| get_rptr_lm(ty))
214 .filter(|&(lt, _, _)| lt.name == out.name)
216 if *mutbl == MutMutable {
219 immutables.push(*argspan);
221 if immutables.is_empty() {
224 span_lint_and_then(cx, MUT_FROM_REF, ty.span, "mutable borrow from immutable input(s)", |db| {
225 let ms = MultiSpan::from_spans(immutables);
226 db.span_note(ms, "immutable borrow here");
232 fn get_spans(cx: &LateContext, opt_body_id: Option<BodyId>, idx: usize, fn_name: &'static str) -> Vec<(Span, String)> {
233 if let Some(body) = opt_body_id.map(|id| cx.tcx.hir.body(id)) {
234 get_binding_name(&body.arguments[idx]).map_or_else(Vec::new,
235 |name| extract_clone_suggestions(cx, name, fn_name, body))
241 fn extract_clone_suggestions<'a, 'tcx: 'a>(cx: &LateContext<'a, 'tcx>, name: Name, fn_name: &'static str, body: &'tcx Body) -> Vec<(Span, String)> {
242 let mut visitor = PtrCloneVisitor {
248 visitor.visit_body(body);
252 struct PtrCloneVisitor<'a, 'tcx: 'a> {
253 cx: &'a LateContext<'a, 'tcx>,
255 fn_name: &'static str,
256 spans: Vec<(Span, String)>,
259 impl<'a, 'tcx: 'a> Visitor<'tcx> for PtrCloneVisitor<'a, 'tcx> {
260 fn visit_expr(&mut self, expr: &'tcx Expr) {
261 if let ExprMethodCall(ref seg, _, ref args) = expr.node {
262 if args.len() == 1 && match_var(&args[0], self.name) && seg.name == "clone" {
263 self.spans.push((expr.span, format!("{}.{}()", snippet(self.cx, args[0].span, "_"), self.fn_name)));
267 walk_expr(self, expr);
270 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
271 NestedVisitorMap::None
276 fn get_binding_name(arg: &Arg) -> Option<Name> {
277 get_pat_name(&arg.pat)
280 fn get_rptr_lm(ty: &Ty) -> Option<(&Lifetime, Mutability, Span)> {
281 if let Ty_::TyRptr(ref lt, ref m) = ty.node {
282 Some((lt, m.mutbl, ty.span))
288 fn is_null_path(expr: &Expr) -> bool {
289 if let ExprCall(ref pathexp, ref args) = expr.node {
291 if let ExprPath(ref path) = pathexp.node {
292 return match_qpath(path, &paths::PTR_NULL) || match_qpath(path, &paths::PTR_NULL_MUT);