1 //! Checks for usage of `&Vec[_]` and `&String`.
4 use rustc::hir::map::NodeItem;
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};
13 /// **What it does:** This lint checks for function arguments of type `&String`
15 /// the references are mutable.
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.
23 /// **Known problems:** None.
27 /// fn foo(&Vec<u32>) { .. }
32 "fn arguments of the type `&Vec<...>` or `&String`, suggesting to use `&[...]` or `&str` \
33 instead, respectively"
36 /// **What it does:** This lint checks for equality comparisons with `ptr::null`
38 /// **Why is this bad?** It's easier and more readable to use the inherent
42 /// **Known problems:** None.
46 /// if x == ptr::null { .. }
51 "comparing a pointer to a null pointer, suggesting to use `.is_null()` instead."
54 /// **What it does:** This lint checks for functions that take immutable
55 /// references and return
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.
64 /// **Known problems:** To be on the conservative side, if there's at least one
66 /// with the output lifetime, this lint will not trigger. In practice, this
67 /// case is unlikely anyway.
71 /// fn foo(&Foo) -> &mut Bar { .. }
76 "fns that create mutable refs from immutable ref args"
79 #[derive(Copy, Clone)]
80 pub struct PointerPass;
82 impl LintPass for PointerPass {
83 fn get_lints(&self) -> LintArray {
84 lint_array!(PTR_ARG, CMP_NULL, MUT_FROM_REF)
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);
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
102 check_fn(cx, &sig.decl, item.id);
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);
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)) {
119 "Comparing with null is better expressed by the .is_null() method",
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();
131 for (arg, ty) in decl.inputs.iter().zip(fn_ty.inputs()) {
140 if match_type(cx, ty, &paths::VEC) {
141 let mut ty_snippet = None;
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,
147 ty_snippet = snippet_opt(cx, parameters.types[0].span);
154 "writing `&Vec<_>` instead of `&[_]` involves one more reference and cannot be used \
155 with non-Vec-based slices.",
157 if let Some(ref snippet) = ty_snippet {
158 db.span_suggestion(arg.span,
160 format!("&[{}]", snippet));
164 } else if match_type(cx, ty, &paths::STRING) {
169 "writing `&String` instead of `&str` involves a new object where a slice will do.",
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
182 .filter_map(|ty| get_rptr_lm(ty))
183 .filter(|&(lt, _, _)| lt.name == out.name)
185 if *mutbl == MutMutable {
188 immutables.push(*argspan);
190 if immutables.is_empty() {
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");
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))
209 fn is_null_path(expr: &Expr) -> bool {
210 if let ExprCall(ref pathexp, ref args) = expr.node {
212 if let ExprPath(ref path) = pathexp.node {
213 return match_qpath(path, &paths::PTR_NULL) || match_qpath(path, &paths::PTR_NULL_MUT);