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