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