]> git.lizzy.rs Git - rust.git/blob - src/librustc_lint/unused.rs
4dc1a5e4f5e9f6dda3e8bc63fa9ffab1af28c15e
[rust.git] / src / librustc_lint / unused.rs
1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use rustc::hir::pat_util;
12 use rustc::ty;
13 use rustc::ty::adjustment;
14 use util::nodemap::FnvHashMap;
15 use lint::{LateContext, EarlyContext, LintContext, LintArray};
16 use lint::{LintPass, EarlyLintPass, LateLintPass};
17
18 use std::collections::hash_map::Entry::{Occupied, Vacant};
19
20 use syntax::ast;
21 use syntax::attr::{self, AttrMetaMethods};
22 use syntax::feature_gate::{KNOWN_ATTRIBUTES, AttributeType};
23 use syntax::ptr::P;
24 use syntax_pos::Span;
25
26 use rustc_back::slice;
27 use rustc::hir;
28 use rustc::hir::intravisit::FnKind;
29
30 declare_lint! {
31     pub UNUSED_MUT,
32     Warn,
33     "detect mut variables which don't need to be mutable"
34 }
35
36 #[derive(Copy, Clone)]
37 pub struct UnusedMut;
38
39 impl UnusedMut {
40     fn check_unused_mut_pat(&self, cx: &LateContext, pats: &[P<hir::Pat>]) {
41         // collect all mutable pattern and group their NodeIDs by their Identifier to
42         // avoid false warnings in match arms with multiple patterns
43
44         let mut mutables = FnvHashMap();
45         for p in pats {
46             pat_util::pat_bindings(p, |mode, id, _, path1| {
47                 let name = path1.node;
48                 if let hir::BindByValue(hir::MutMutable) = mode {
49                     if !name.as_str().starts_with("_") {
50                         match mutables.entry(name.0 as usize) {
51                             Vacant(entry) => { entry.insert(vec![id]); },
52                             Occupied(mut entry) => { entry.get_mut().push(id); },
53                         }
54                     }
55                 }
56             });
57         }
58
59         let used_mutables = cx.tcx.used_mut_nodes.borrow();
60         for (_, v) in &mutables {
61             if !v.iter().any(|e| used_mutables.contains(e)) {
62                 cx.span_lint(UNUSED_MUT, cx.tcx.map.span(v[0]),
63                              "variable does not need to be mutable");
64             }
65         }
66     }
67 }
68
69 impl LintPass for UnusedMut {
70     fn get_lints(&self) -> LintArray {
71         lint_array!(UNUSED_MUT)
72     }
73 }
74
75 impl LateLintPass for UnusedMut {
76     fn check_expr(&mut self, cx: &LateContext, e: &hir::Expr) {
77         if let hir::ExprMatch(_, ref arms, _) = e.node {
78             for a in arms {
79                 self.check_unused_mut_pat(cx, &a.pats)
80             }
81         }
82     }
83
84     fn check_stmt(&mut self, cx: &LateContext, s: &hir::Stmt) {
85         if let hir::StmtDecl(ref d, _) = s.node {
86             if let hir::DeclLocal(ref l) = d.node {
87                 self.check_unused_mut_pat(cx, slice::ref_slice(&l.pat));
88             }
89         }
90     }
91
92     fn check_fn(&mut self, cx: &LateContext,
93                 _: FnKind, decl: &hir::FnDecl,
94                 _: &hir::Block, _: Span, _: ast::NodeId) {
95         for a in &decl.inputs {
96             self.check_unused_mut_pat(cx, slice::ref_slice(&a.pat));
97         }
98     }
99 }
100
101 declare_lint! {
102     pub UNUSED_MUST_USE,
103     Warn,
104     "unused result of a type flagged as #[must_use]"
105 }
106
107 declare_lint! {
108     pub UNUSED_RESULTS,
109     Allow,
110     "unused result of an expression in a statement"
111 }
112
113 #[derive(Copy, Clone)]
114 pub struct UnusedResults;
115
116 impl LintPass for UnusedResults {
117     fn get_lints(&self) -> LintArray {
118         lint_array!(UNUSED_MUST_USE, UNUSED_RESULTS)
119     }
120 }
121
122 impl LateLintPass for UnusedResults {
123     fn check_stmt(&mut self, cx: &LateContext, s: &hir::Stmt) {
124         let expr = match s.node {
125             hir::StmtSemi(ref expr, _) => &**expr,
126             _ => return
127         };
128
129         if let hir::ExprRet(..) = expr.node {
130             return;
131         }
132
133         let t = cx.tcx.expr_ty(&expr);
134         let warned = match t.sty {
135             ty::TyTuple(ref tys) if tys.is_empty() => return,
136             ty::TyBool => return,
137             ty::TyStruct(def, _) |
138             ty::TyEnum(def, _) => {
139                 let attrs = cx.tcx.get_attrs(def.did);
140                 check_must_use(cx, &attrs[..], s.span)
141             }
142             _ => false,
143         };
144         if !warned {
145             cx.span_lint(UNUSED_RESULTS, s.span, "unused result");
146         }
147
148         fn check_must_use(cx: &LateContext, attrs: &[ast::Attribute], sp: Span) -> bool {
149             for attr in attrs {
150                 if attr.check_name("must_use") {
151                     let mut msg = "unused result which must be used".to_string();
152                     // check for #[must_use="..."]
153                     if let Some(s) = attr.value_str() {
154                         msg.push_str(": ");
155                         msg.push_str(&s);
156                     }
157                     cx.span_lint(UNUSED_MUST_USE, sp, &msg);
158                     return true;
159                 }
160             }
161             false
162         }
163     }
164 }
165
166 declare_lint! {
167     pub UNUSED_UNSAFE,
168     Warn,
169     "unnecessary use of an `unsafe` block"
170 }
171
172 #[derive(Copy, Clone)]
173 pub struct UnusedUnsafe;
174
175 impl LintPass for UnusedUnsafe {
176     fn get_lints(&self) -> LintArray {
177         lint_array!(UNUSED_UNSAFE)
178     }
179 }
180
181 impl LateLintPass for UnusedUnsafe {
182     fn check_expr(&mut self, cx: &LateContext, e: &hir::Expr) {
183         if let hir::ExprBlock(ref blk) = e.node {
184             // Don't warn about generated blocks, that'll just pollute the output.
185             if blk.rules == hir::UnsafeBlock(hir::UserProvided) &&
186                 !cx.tcx.used_unsafe.borrow().contains(&blk.id) {
187                     cx.span_lint(UNUSED_UNSAFE, blk.span, "unnecessary `unsafe` block");
188             }
189         }
190     }
191 }
192
193 declare_lint! {
194     pub PATH_STATEMENTS,
195     Warn,
196     "path statements with no effect"
197 }
198
199 #[derive(Copy, Clone)]
200 pub struct PathStatements;
201
202 impl LintPass for PathStatements {
203     fn get_lints(&self) -> LintArray {
204         lint_array!(PATH_STATEMENTS)
205     }
206 }
207
208 impl LateLintPass for PathStatements {
209     fn check_stmt(&mut self, cx: &LateContext, s: &hir::Stmt) {
210         if let hir::StmtSemi(ref expr, _) = s.node {
211             if let hir::ExprPath(..) = expr.node {
212                 cx.span_lint(PATH_STATEMENTS, s.span,
213                              "path statement with no effect");
214             }
215         }
216     }
217 }
218
219 declare_lint! {
220     pub UNUSED_ATTRIBUTES,
221     Warn,
222     "detects attributes that were not used by the compiler"
223 }
224
225 #[derive(Copy, Clone)]
226 pub struct UnusedAttributes;
227
228 impl LintPass for UnusedAttributes {
229     fn get_lints(&self) -> LintArray {
230         lint_array!(UNUSED_ATTRIBUTES)
231     }
232 }
233
234 impl LateLintPass for UnusedAttributes {
235     fn check_attribute(&mut self, cx: &LateContext, attr: &ast::Attribute) {
236         // Note that check_name() marks the attribute as used if it matches.
237         for &(ref name, ty, _) in KNOWN_ATTRIBUTES {
238             match ty {
239                 AttributeType::Whitelisted if attr.check_name(name) => {
240                     break;
241                 },
242                 _ => ()
243             }
244         }
245
246         let plugin_attributes = cx.sess().plugin_attributes.borrow_mut();
247         for &(ref name, ty) in plugin_attributes.iter() {
248             if ty == AttributeType::Whitelisted && attr.check_name(&name) {
249                 break;
250             }
251         }
252
253         if !attr::is_used(attr) {
254             cx.span_lint(UNUSED_ATTRIBUTES, attr.span, "unused attribute");
255             // Is it a builtin attribute that must be used at the crate level?
256             let known_crate = KNOWN_ATTRIBUTES.iter().find(|&&(name, ty, _)| {
257                 attr.name() == name &&
258                 ty == AttributeType::CrateLevel
259             }).is_some();
260
261             // Has a plugin registered this attribute as one which must be used at
262             // the crate level?
263             let plugin_crate = plugin_attributes.iter()
264                                                 .find(|&&(ref x, t)| {
265                                                         &*attr.name() == x &&
266                                                         AttributeType::CrateLevel == t
267                                                     }).is_some();
268             if  known_crate || plugin_crate {
269                 let msg = match attr.node.style {
270                     ast::AttrStyle::Outer => "crate-level attribute should be an inner \
271                                               attribute: add an exclamation mark: #![foo]",
272                     ast::AttrStyle::Inner => "crate-level attribute should be in the \
273                                               root module",
274                 };
275                 cx.span_lint(UNUSED_ATTRIBUTES, attr.span, msg);
276             }
277         }
278     }
279 }
280
281 declare_lint! {
282     UNUSED_PARENS,
283     Warn,
284     "`if`, `match`, `while` and `return` do not need parentheses"
285 }
286
287 #[derive(Copy, Clone)]
288 pub struct UnusedParens;
289
290 impl UnusedParens {
291     fn check_unused_parens_core(&self, cx: &EarlyContext, value: &ast::Expr, msg: &str,
292                                 struct_lit_needs_parens: bool) {
293         if let ast::ExprKind::Paren(ref inner) = value.node {
294             let necessary = struct_lit_needs_parens && contains_exterior_struct_lit(&inner);
295             if !necessary {
296                 cx.span_lint(UNUSED_PARENS, value.span,
297                              &format!("unnecessary parentheses around {}", msg))
298             }
299         }
300
301         /// Expressions that syntactically contain an "exterior" struct
302         /// literal i.e. not surrounded by any parens or other
303         /// delimiters, e.g. `X { y: 1 }`, `X { y: 1 }.method()`, `foo
304         /// == X { y: 1 }` and `X { y: 1 } == foo` all do, but `(X {
305         /// y: 1 }) == foo` does not.
306         fn contains_exterior_struct_lit(value: &ast::Expr) -> bool {
307             match value.node {
308                 ast::ExprKind::Struct(..) => true,
309
310                 ast::ExprKind::Assign(ref lhs, ref rhs) |
311                 ast::ExprKind::AssignOp(_, ref lhs, ref rhs) |
312                 ast::ExprKind::Binary(_, ref lhs, ref rhs) => {
313                     // X { y: 1 } + X { y: 2 }
314                     contains_exterior_struct_lit(&lhs) ||
315                         contains_exterior_struct_lit(&rhs)
316                 }
317                 ast::ExprKind::Unary(_, ref x) |
318                 ast::ExprKind::Cast(ref x, _) |
319                 ast::ExprKind::Type(ref x, _) |
320                 ast::ExprKind::Field(ref x, _) |
321                 ast::ExprKind::TupField(ref x, _) |
322                 ast::ExprKind::Index(ref x, _) => {
323                     // &X { y: 1 }, X { y: 1 }.y
324                     contains_exterior_struct_lit(&x)
325                 }
326
327                 ast::ExprKind::MethodCall(_, _, ref exprs) => {
328                     // X { y: 1 }.bar(...)
329                     contains_exterior_struct_lit(&exprs[0])
330                 }
331
332                 _ => false
333             }
334         }
335     }
336 }
337
338 impl LintPass for UnusedParens {
339     fn get_lints(&self) -> LintArray {
340         lint_array!(UNUSED_PARENS)
341     }
342 }
343
344 impl EarlyLintPass for UnusedParens {
345     fn check_expr(&mut self, cx: &EarlyContext, e: &ast::Expr) {
346         use syntax::ast::ExprKind::*;
347         let (value, msg, struct_lit_needs_parens) = match e.node {
348             If(ref cond, _, _) => (cond, "`if` condition", true),
349             While(ref cond, _, _) => (cond, "`while` condition", true),
350             IfLet(_, ref cond, _, _) => (cond, "`if let` head expression", true),
351             WhileLet(_, ref cond, _, _) => (cond, "`while let` head expression", true),
352             ForLoop(_, ref cond, _, _) => (cond, "`for` head expression", true),
353             Match(ref head, _) => (head, "`match` head expression", true),
354             Ret(Some(ref value)) => (value, "`return` value", false),
355             Assign(_, ref value) => (value, "assigned value", false),
356             AssignOp(_, _, ref value) => (value, "assigned value", false),
357             InPlace(_, ref value) => (value, "emplacement value", false),
358             _ => return
359         };
360         self.check_unused_parens_core(cx, &value, msg, struct_lit_needs_parens);
361     }
362
363     fn check_stmt(&mut self, cx: &EarlyContext, s: &ast::Stmt) {
364         let (value, msg) = match s.node {
365             ast::StmtKind::Local(ref local) => match local.init {
366                 Some(ref value) => (value, "assigned value"),
367                 None => return
368             },
369             _ => return
370         };
371         self.check_unused_parens_core(cx, &value, msg, false);
372     }
373 }
374
375 declare_lint! {
376     UNUSED_IMPORT_BRACES,
377     Allow,
378     "unnecessary braces around an imported item"
379 }
380
381 #[derive(Copy, Clone)]
382 pub struct UnusedImportBraces;
383
384 impl LintPass for UnusedImportBraces {
385     fn get_lints(&self) -> LintArray {
386         lint_array!(UNUSED_IMPORT_BRACES)
387     }
388 }
389
390 impl LateLintPass for UnusedImportBraces {
391     fn check_item(&mut self, cx: &LateContext, item: &hir::Item) {
392         if let hir::ItemUse(ref view_path) = item.node {
393             if let hir::ViewPathList(_, ref items) = view_path.node {
394                 if items.len() == 1 {
395                     if let hir::PathListIdent {ref name, ..} = items[0].node {
396                         let m = format!("braces around {} is unnecessary",
397                                         name);
398                         cx.span_lint(UNUSED_IMPORT_BRACES, item.span,
399                                      &m[..]);
400                     }
401                 }
402             }
403         }
404     }
405 }
406
407 declare_lint! {
408     UNUSED_ALLOCATION,
409     Warn,
410     "detects unnecessary allocations that can be eliminated"
411 }
412
413 #[derive(Copy, Clone)]
414 pub struct UnusedAllocation;
415
416 impl LintPass for UnusedAllocation {
417     fn get_lints(&self) -> LintArray {
418         lint_array!(UNUSED_ALLOCATION)
419     }
420 }
421
422 impl LateLintPass for UnusedAllocation {
423     fn check_expr(&mut self, cx: &LateContext, e: &hir::Expr) {
424         match e.node {
425             hir::ExprBox(_) => {}
426             _ => return
427         }
428
429         if let Some(adjustment) = cx.tcx.tables.borrow().adjustments.get(&e.id) {
430             if let adjustment::AdjustDerefRef(adjustment::AutoDerefRef {
431                 ref autoref, ..
432             }) = *adjustment {
433                 match autoref {
434                     &Some(adjustment::AutoPtr(_, hir::MutImmutable)) => {
435                         cx.span_lint(UNUSED_ALLOCATION, e.span,
436                                      "unnecessary allocation, use & instead");
437                     }
438                     &Some(adjustment::AutoPtr(_, hir::MutMutable)) => {
439                         cx.span_lint(UNUSED_ALLOCATION, e.span,
440                                      "unnecessary allocation, use &mut instead");
441                     }
442                     _ => ()
443                 }
444             }
445         }
446     }
447 }