]> git.lizzy.rs Git - rust.git/blob - src/librustc_lint/unused.rs
rustbuild: fix remap-debuginfo when building a release
[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::Def;
12 use rustc::hir::def_id::DefId;
13 use rustc::ty;
14 use rustc::ty::adjustment;
15 use lint::{LateContext, EarlyContext, LintContext, LintArray};
16 use lint::{LintPass, EarlyLintPass, LateLintPass};
17
18 use syntax::ast;
19 use syntax::attr;
20 use syntax::errors::Applicability;
21 use syntax::feature_gate::{BUILTIN_ATTRIBUTES, AttributeType};
22 use syntax::print::pprust;
23 use syntax::symbol::keywords;
24 use syntax::util::parser;
25 use syntax_pos::Span;
26
27 use rustc::hir;
28
29 declare_lint! {
30     pub UNUSED_MUST_USE,
31     Warn,
32     "unused result of a type flagged as #[must_use]"
33 }
34
35 declare_lint! {
36     pub UNUSED_RESULTS,
37     Allow,
38     "unused result of an expression in a statement"
39 }
40
41 #[derive(Copy, Clone)]
42 pub struct UnusedResults;
43
44 impl LintPass for UnusedResults {
45     fn get_lints(&self) -> LintArray {
46         lint_array!(UNUSED_MUST_USE, UNUSED_RESULTS)
47     }
48 }
49
50 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedResults {
51     fn check_stmt(&mut self, cx: &LateContext, s: &hir::Stmt) {
52         let expr = match s.node {
53             hir::StmtKind::Semi(ref expr, _) => &**expr,
54             _ => return,
55         };
56
57         if let hir::ExprKind::Ret(..) = expr.node {
58             return;
59         }
60
61         let t = cx.tables.expr_ty(&expr);
62         // FIXME(varkor): replace with `t.is_unit() || t.conservative_is_uninhabited()`.
63         let type_permits_no_use = match t.sty {
64             ty::Tuple(ref tys) if tys.is_empty() => true,
65             ty::Never => true,
66             ty::Adt(def, _) => {
67                 if def.variants.is_empty() {
68                     true
69                 } else {
70                     check_must_use(cx, def.did, s.span, "")
71                 }
72             }
73             _ => false,
74         };
75
76         let mut fn_warned = false;
77         let mut op_warned = false;
78         let maybe_def = match expr.node {
79             hir::ExprKind::Call(ref callee, _) => {
80                 match callee.node {
81                     hir::ExprKind::Path(ref qpath) => {
82                         let def = cx.tables.qpath_def(qpath, callee.hir_id);
83                         match def {
84                             Def::Fn(_) | Def::Method(_) => Some(def),
85                             // `Def::Local` if it was a closure, for which we
86                             // do not currently support must-use linting
87                             _ => None
88                         }
89                     },
90                     _ => None
91                 }
92             },
93             hir::ExprKind::MethodCall(..) => {
94                 cx.tables.type_dependent_defs().get(expr.hir_id).cloned()
95             },
96             _ => None
97         };
98         if let Some(def) = maybe_def {
99             let def_id = def.def_id();
100             fn_warned = check_must_use(cx, def_id, s.span, "return value of ");
101         } else if type_permits_no_use {
102             // We don't warn about unused unit or uninhabited types.
103             // (See https://github.com/rust-lang/rust/issues/43806 for details.)
104             return;
105         }
106
107         let must_use_op = match expr.node {
108             // Hardcoding operators here seemed more expedient than the
109             // refactoring that would be needed to look up the `#[must_use]`
110             // attribute which does exist on the comparison trait methods
111             hir::ExprKind::Binary(bin_op, ..)  => {
112                 match bin_op.node {
113                     hir::BinOpKind::Eq |
114                     hir::BinOpKind::Lt |
115                     hir::BinOpKind::Le |
116                     hir::BinOpKind::Ne |
117                     hir::BinOpKind::Ge |
118                     hir::BinOpKind::Gt => {
119                         Some("comparison")
120                     },
121                     hir::BinOpKind::Add |
122                     hir::BinOpKind::Sub |
123                     hir::BinOpKind::Div |
124                     hir::BinOpKind::Mul |
125                     hir::BinOpKind::Rem => {
126                         Some("arithmetic operation")
127                     },
128                     hir::BinOpKind::And | hir::BinOpKind::Or => {
129                         Some("logical operation")
130                     },
131                     hir::BinOpKind::BitXor |
132                     hir::BinOpKind::BitAnd |
133                     hir::BinOpKind::BitOr |
134                     hir::BinOpKind::Shl |
135                     hir::BinOpKind::Shr => {
136                         Some("bitwise operation")
137                     },
138                 }
139             },
140             hir::ExprKind::Unary(..) => Some("unary operation"),
141             _ => None
142         };
143
144         if let Some(must_use_op) = must_use_op {
145             cx.span_lint(UNUSED_MUST_USE, expr.span,
146                          &format!("unused {} that must be used", must_use_op));
147             op_warned = true;
148         }
149
150         if !(type_permits_no_use || fn_warned || op_warned) {
151             cx.span_lint(UNUSED_RESULTS, s.span, "unused result");
152         }
153
154         fn check_must_use(cx: &LateContext, def_id: DefId, sp: Span, describe_path: &str) -> bool {
155             for attr in cx.tcx.get_attrs(def_id).iter() {
156                 if attr.check_name("must_use") {
157                     let msg = format!("unused {}`{}` that must be used",
158                                           describe_path, cx.tcx.item_path_str(def_id));
159                     let mut err = cx.struct_span_lint(UNUSED_MUST_USE, sp, &msg);
160                     // check for #[must_use = "..."]
161                     if let Some(note) = attr.value_str() {
162                         err.note(&note.as_str());
163                     }
164                     err.emit();
165                     return true;
166                 }
167             }
168             false
169         }
170     }
171 }
172
173 declare_lint! {
174     pub PATH_STATEMENTS,
175     Warn,
176     "path statements with no effect"
177 }
178
179 #[derive(Copy, Clone)]
180 pub struct PathStatements;
181
182 impl LintPass for PathStatements {
183     fn get_lints(&self) -> LintArray {
184         lint_array!(PATH_STATEMENTS)
185     }
186 }
187
188 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for PathStatements {
189     fn check_stmt(&mut self, cx: &LateContext, s: &hir::Stmt) {
190         if let hir::StmtKind::Semi(ref expr, _) = s.node {
191             if let hir::ExprKind::Path(_) = expr.node {
192                 cx.span_lint(PATH_STATEMENTS, s.span, "path statement with no effect");
193             }
194         }
195     }
196 }
197
198 declare_lint! {
199     pub UNUSED_ATTRIBUTES,
200     Warn,
201     "detects attributes that were not used by the compiler"
202 }
203
204 #[derive(Copy, Clone)]
205 pub struct UnusedAttributes;
206
207 impl LintPass for UnusedAttributes {
208     fn get_lints(&self) -> LintArray {
209         lint_array!(UNUSED_ATTRIBUTES)
210     }
211 }
212
213 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedAttributes {
214     fn check_attribute(&mut self, cx: &LateContext, attr: &ast::Attribute) {
215         debug!("checking attribute: {:?}", attr);
216         // Note that check_name() marks the attribute as used if it matches.
217         for &(ref name, ty, _) in BUILTIN_ATTRIBUTES {
218             match ty {
219                 AttributeType::Whitelisted if attr.check_name(name) => {
220                     debug!("{:?} is Whitelisted", name);
221                     break;
222                 }
223                 _ => (),
224             }
225         }
226
227         let plugin_attributes = cx.sess().plugin_attributes.borrow_mut();
228         for &(ref name, ty) in plugin_attributes.iter() {
229             if ty == AttributeType::Whitelisted && attr.check_name(&name) {
230                 debug!("{:?} (plugin attr) is whitelisted with ty {:?}", name, ty);
231                 break;
232             }
233         }
234
235         let name = attr.name();
236         if !attr::is_used(attr) {
237             debug!("Emitting warning for: {:?}", attr);
238             cx.span_lint(UNUSED_ATTRIBUTES, attr.span, "unused attribute");
239             // Is it a builtin attribute that must be used at the crate level?
240             let known_crate = BUILTIN_ATTRIBUTES.iter()
241                 .find(|&&(builtin, ty, _)| name == builtin && ty == AttributeType::CrateLevel)
242                 .is_some();
243
244             // Has a plugin registered this attribute as one that must be used at
245             // the crate level?
246             let plugin_crate = plugin_attributes.iter()
247                 .find(|&&(ref x, t)| name == &**x && AttributeType::CrateLevel == t)
248                 .is_some();
249             if known_crate || plugin_crate {
250                 let msg = match attr.style {
251                     ast::AttrStyle::Outer => {
252                         "crate-level attribute should be an inner attribute: add an exclamation \
253                          mark: #![foo]"
254                     }
255                     ast::AttrStyle::Inner => "crate-level attribute should be in the root module",
256                 };
257                 cx.span_lint(UNUSED_ATTRIBUTES, attr.span, msg);
258             }
259         } else {
260             debug!("Attr was used: {:?}", attr);
261         }
262     }
263 }
264
265 declare_lint! {
266     pub(super) UNUSED_PARENS,
267     Warn,
268     "`if`, `match`, `while` and `return` do not need parentheses"
269 }
270
271 #[derive(Copy, Clone)]
272 pub struct UnusedParens;
273
274 impl UnusedParens {
275     fn check_unused_parens_expr(&self,
276                                 cx: &EarlyContext,
277                                 value: &ast::Expr,
278                                 msg: &str,
279                                 followed_by_block: bool) {
280         if let ast::ExprKind::Paren(ref inner) = value.node {
281             let necessary = followed_by_block && if let ast::ExprKind::Ret(_) = inner.node {
282                 true
283             } else {
284                 parser::contains_exterior_struct_lit(&inner)
285             };
286             if !necessary {
287                 let pattern = pprust::expr_to_string(value);
288                 Self::remove_outer_parens(cx, value.span, &pattern, msg);
289             }
290         }
291     }
292
293     fn check_unused_parens_pat(&self,
294                                 cx: &EarlyContext,
295                                 value: &ast::Pat,
296                                 msg: &str) {
297         if let ast::PatKind::Paren(_) = value.node {
298             let pattern = pprust::pat_to_string(value);
299             Self::remove_outer_parens(cx, value.span, &pattern, msg);
300         }
301     }
302
303     fn remove_outer_parens(cx: &EarlyContext, span: Span, pattern: &str, msg: &str) {
304         let span_msg = format!("unnecessary parentheses around {}", msg);
305         let mut err = cx.struct_span_lint(UNUSED_PARENS, span, &span_msg);
306         let mut ate_left_paren = false;
307         let mut ate_right_paren = false;
308         let parens_removed = pattern
309             .trim_matches(|c| {
310                 match c {
311                     '(' => {
312                         if ate_left_paren {
313                             false
314                         } else {
315                             ate_left_paren = true;
316                             true
317                         }
318                     },
319                     ')' => {
320                         if ate_right_paren {
321                             false
322                         } else {
323                             ate_right_paren = true;
324                             true
325                         }
326                     },
327                     _ => false,
328                 }
329             }).to_owned();
330         err.span_suggestion_short_with_applicability(
331                 span,
332                 "remove these parentheses",
333                 parens_removed,
334                 Applicability::MachineApplicable
335             );
336         err.emit();
337     }
338 }
339
340 impl LintPass for UnusedParens {
341     fn get_lints(&self) -> LintArray {
342         lint_array!(UNUSED_PARENS)
343     }
344 }
345
346 impl EarlyLintPass for UnusedParens {
347     fn check_expr(&mut self, cx: &EarlyContext, e: &ast::Expr) {
348         use syntax::ast::ExprKind::*;
349         let (value, msg, followed_by_block) = match e.node {
350             If(ref cond, ..) => (cond, "`if` condition", true),
351             While(ref cond, ..) => (cond, "`while` condition", true),
352             IfLet(_, ref cond, ..) => (cond, "`if let` head expression", true),
353             WhileLet(_, ref cond, ..) => (cond, "`while let` head expression", true),
354             ForLoop(_, ref cond, ..) => (cond, "`for` head expression", true),
355             Match(ref head, _) => (head, "`match` head expression", true),
356             Ret(Some(ref value)) => (value, "`return` value", false),
357             Assign(_, ref value) => (value, "assigned value", false),
358             AssignOp(.., ref value) => (value, "assigned value", false),
359             // either function/method call, or something this lint doesn't care about
360             ref call_or_other => {
361                 let (args_to_check, call_kind) = match *call_or_other {
362                     Call(_, ref args) => (&args[..], "function"),
363                     // first "argument" is self (which sometimes needs parens)
364                     MethodCall(_, ref args) => (&args[1..], "method"),
365                     // actual catch-all arm
366                     _ => {
367                         return;
368                     }
369                 };
370                 // Don't lint if this is a nested macro expansion: otherwise, the lint could
371                 // trigger in situations that macro authors shouldn't have to care about, e.g.,
372                 // when a parenthesized token tree matched in one macro expansion is matched as
373                 // an expression in another and used as a fn/method argument (Issue #47775)
374                 if e.span.ctxt().outer().expn_info()
375                     .map_or(false, |info| info.call_site.ctxt().outer()
376                             .expn_info().is_some()) {
377                         return;
378                 }
379                 let msg = format!("{} argument", call_kind);
380                 for arg in args_to_check {
381                     self.check_unused_parens_expr(cx, arg, &msg, false);
382                 }
383                 return;
384             }
385         };
386         self.check_unused_parens_expr(cx, &value, msg, followed_by_block);
387     }
388
389     fn check_pat(&mut self, cx: &EarlyContext, p: &ast::Pat) {
390         use ast::PatKind::{Paren, Range};
391         // The lint visitor will visit each subpattern of `p`. We do not want to lint any range
392         // pattern no matter where it occurs in the pattern. For something like `&(a..=b)`, there
393         // is a recursive `check_pat` on `a` and `b`, but we will assume that if there are
394         // unnecessry parens they serve a purpose of readability.
395         if let Paren(ref pat) = p.node {
396             match pat.node {
397                 Range(..) => {}
398                 _ => self.check_unused_parens_pat(cx, &p, "pattern")
399             }
400         }
401     }
402
403     fn check_stmt(&mut self, cx: &EarlyContext, s: &ast::Stmt) {
404         if let ast::StmtKind::Local(ref local) = s.node {
405             if let Some(ref value) = local.init {
406                 self.check_unused_parens_expr(cx, &value, "assigned value", false);
407             }
408         }
409     }
410 }
411
412 declare_lint! {
413     UNUSED_IMPORT_BRACES,
414     Allow,
415     "unnecessary braces around an imported item"
416 }
417
418 #[derive(Copy, Clone)]
419 pub struct UnusedImportBraces;
420
421 impl UnusedImportBraces {
422     fn check_use_tree(&self, cx: &EarlyContext, use_tree: &ast::UseTree, item: &ast::Item) {
423         if let ast::UseTreeKind::Nested(ref items) = use_tree.kind {
424             // Recursively check nested UseTrees
425             for &(ref tree, _) in items {
426                 self.check_use_tree(cx, tree, item);
427             }
428
429             // Trigger the lint only if there is one nested item
430             if items.len() != 1 {
431                 return;
432             }
433
434             // Trigger the lint if the nested item is a non-self single item
435             let node_ident;
436             match items[0].0.kind {
437                 ast::UseTreeKind::Simple(rename, ..) => {
438                     let orig_ident = items[0].0.prefix.segments.last().unwrap().ident;
439                     if orig_ident.name == keywords::SelfValue.name() {
440                         return;
441                     }
442                     node_ident = rename.unwrap_or(orig_ident);
443                 }
444                 ast::UseTreeKind::Glob => {
445                     node_ident = ast::Ident::from_str("*");
446                 }
447                 ast::UseTreeKind::Nested(_) => {
448                     return;
449                 }
450             }
451
452             let msg = format!("braces around {} is unnecessary", node_ident.name);
453             cx.span_lint(UNUSED_IMPORT_BRACES, item.span, &msg);
454         }
455     }
456 }
457
458 impl LintPass for UnusedImportBraces {
459     fn get_lints(&self) -> LintArray {
460         lint_array!(UNUSED_IMPORT_BRACES)
461     }
462 }
463
464 impl EarlyLintPass for UnusedImportBraces {
465     fn check_item(&mut self, cx: &EarlyContext, item: &ast::Item) {
466         if let ast::ItemKind::Use(ref use_tree) = item.node {
467             self.check_use_tree(cx, use_tree, item);
468         }
469     }
470 }
471
472 declare_lint! {
473     pub(super) UNUSED_ALLOCATION,
474     Warn,
475     "detects unnecessary allocations that can be eliminated"
476 }
477
478 #[derive(Copy, Clone)]
479 pub struct UnusedAllocation;
480
481 impl LintPass for UnusedAllocation {
482     fn get_lints(&self) -> LintArray {
483         lint_array!(UNUSED_ALLOCATION)
484     }
485 }
486
487 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedAllocation {
488     fn check_expr(&mut self, cx: &LateContext, e: &hir::Expr) {
489         match e.node {
490             hir::ExprKind::Box(_) => {}
491             _ => return,
492         }
493
494         for adj in cx.tables.expr_adjustments(e) {
495             if let adjustment::Adjust::Borrow(adjustment::AutoBorrow::Ref(_, m)) = adj.kind {
496                 let msg = match m {
497                     adjustment::AutoBorrowMutability::Immutable =>
498                         "unnecessary allocation, use & instead",
499                     adjustment::AutoBorrowMutability::Mutable { .. }=>
500                         "unnecessary allocation, use &mut instead"
501                 };
502                 cx.span_lint(UNUSED_ALLOCATION, e.span, msg);
503             }
504         }
505     }
506 }