]> git.lizzy.rs Git - rust.git/blob - src/ptr_arg.rs
939277fe66cb876cb55e7c1eb59aa6c57bbeeb33
[rust.git] / src / ptr_arg.rs
1 //! Checks for usage of &Vec[_] and &String
2 //!
3 //! This lint is **warn** by default
4
5 use rustc::plugin::Registry;
6 use rustc::lint::*;
7 use rustc::middle::const_eval::lookup_const_by_id;
8 use rustc::middle::def::*;
9 use syntax::ast::*;
10 use syntax::ast_util::{is_comparison_binop, binop_to_string};
11 use syntax::ptr::P;
12 use syntax::codemap::Span;
13 use types::match_ty_unwrap;
14 use utils::span_lint;
15
16 declare_lint! {
17     pub PTR_ARG,
18     Allow,
19     "Warn on declaration of a &Vec- or &String-typed method argument"
20 }
21
22 #[derive(Copy,Clone)]
23 pub struct PtrArg;
24
25 impl LintPass for PtrArg {
26     fn get_lints(&self) -> LintArray {
27         lint_array!(PTR_ARG)
28     }
29
30     fn check_item(&mut self, cx: &Context, item: &Item) {
31         if let &ItemFn(ref decl, _, _, _, _, _) = &item.node {
32             check_fn(cx, decl);
33         }
34     }
35
36     fn check_impl_item(&mut self, cx: &Context, item: &ImplItem) {
37         if let &MethodImplItem(ref sig, _) = &item.node {
38             check_fn(cx, &sig.decl);
39         }
40     }
41
42     fn check_trait_item(&mut self, cx: &Context, item: &TraitItem) {
43         if let &MethodTraitItem(ref sig, _) = &item.node {
44             check_fn(cx, &sig.decl);
45         }
46     }
47 }
48
49 fn check_fn(cx: &Context, decl: &FnDecl) {
50     for arg in &decl.inputs {
51         match &arg.ty.node {
52             &TyPtr(ref p) | &TyRptr(_, ref p) =>
53                 check_ptr_subtype(cx, arg.ty.span, &p.ty),
54             _ => ()
55         }
56     }
57 }
58
59 fn check_ptr_subtype(cx: &Context, span: Span, ty: &Ty) {
60     match_ty_unwrap(ty, &["Vec"]).map_or_else(|| match_ty_unwrap(ty,
61         &["String"]).map_or((), |_| {
62             span_lint(cx, PTR_ARG, span,
63                       "Writing '&String' instead of '&str' involves a new Object \
64                        where a slices will do. Consider changing the type to &str")
65         }), |_| span_lint(cx, PTR_ARG, span,
66                           "Writing '&Vec<_>' instead of \
67                            '&[_]' involves one more reference and cannot be used with \
68                            non-vec-based slices. Consider changing the type to &[...]"))
69 }