]> git.lizzy.rs Git - rust.git/blob - src/librustc_lint/unused.rs
Regression test for issue #54477.
[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 expr_text = if let Ok(snippet) = cx.sess().source_map()
288                     .span_to_snippet(value.span) {
289                         snippet
290                     } else {
291                         pprust::expr_to_string(value)
292                     };
293                 Self::remove_outer_parens(cx, value.span, &expr_text, msg);
294             }
295         }
296     }
297
298     fn check_unused_parens_pat(&self,
299                                 cx: &EarlyContext,
300                                 value: &ast::Pat,
301                                 msg: &str) {
302         if let ast::PatKind::Paren(_) = value.node {
303             let pattern_text = if let Ok(snippet) = cx.sess().source_map()
304                 .span_to_snippet(value.span) {
305                     snippet
306                 } else {
307                     pprust::pat_to_string(value)
308                 };
309             Self::remove_outer_parens(cx, value.span, &pattern_text, msg);
310         }
311     }
312
313     fn remove_outer_parens(cx: &EarlyContext, span: Span, pattern: &str, msg: &str) {
314         let span_msg = format!("unnecessary parentheses around {}", msg);
315         let mut err = cx.struct_span_lint(UNUSED_PARENS, span, &span_msg);
316         let mut ate_left_paren = false;
317         let mut ate_right_paren = false;
318         let parens_removed = pattern
319             .trim_matches(|c| {
320                 match c {
321                     '(' => {
322                         if ate_left_paren {
323                             false
324                         } else {
325                             ate_left_paren = true;
326                             true
327                         }
328                     },
329                     ')' => {
330                         if ate_right_paren {
331                             false
332                         } else {
333                             ate_right_paren = true;
334                             true
335                         }
336                     },
337                     _ => false,
338                 }
339             }).to_owned();
340         err.span_suggestion_short_with_applicability(
341                 span,
342                 "remove these parentheses",
343                 parens_removed,
344                 Applicability::MachineApplicable
345             );
346         err.emit();
347     }
348 }
349
350 impl LintPass for UnusedParens {
351     fn get_lints(&self) -> LintArray {
352         lint_array!(UNUSED_PARENS)
353     }
354 }
355
356 impl EarlyLintPass for UnusedParens {
357     fn check_expr(&mut self, cx: &EarlyContext, e: &ast::Expr) {
358         use syntax::ast::ExprKind::*;
359         let (value, msg, followed_by_block) = match e.node {
360             If(ref cond, ..) => (cond, "`if` condition", true),
361             While(ref cond, ..) => (cond, "`while` condition", true),
362             IfLet(_, ref cond, ..) => (cond, "`if let` head expression", true),
363             WhileLet(_, ref cond, ..) => (cond, "`while let` head expression", true),
364             ForLoop(_, ref cond, ..) => (cond, "`for` head expression", true),
365             Match(ref head, _) => (head, "`match` head expression", true),
366             Ret(Some(ref value)) => (value, "`return` value", false),
367             Assign(_, ref value) => (value, "assigned value", false),
368             AssignOp(.., ref value) => (value, "assigned value", false),
369             // either function/method call, or something this lint doesn't care about
370             ref call_or_other => {
371                 let (args_to_check, call_kind) = match *call_or_other {
372                     Call(_, ref args) => (&args[..], "function"),
373                     // first "argument" is self (which sometimes needs parens)
374                     MethodCall(_, ref args) => (&args[1..], "method"),
375                     // actual catch-all arm
376                     _ => {
377                         return;
378                     }
379                 };
380                 // Don't lint if this is a nested macro expansion: otherwise, the lint could
381                 // trigger in situations that macro authors shouldn't have to care about, e.g.,
382                 // when a parenthesized token tree matched in one macro expansion is matched as
383                 // an expression in another and used as a fn/method argument (Issue #47775)
384                 if e.span.ctxt().outer().expn_info()
385                     .map_or(false, |info| info.call_site.ctxt().outer()
386                             .expn_info().is_some()) {
387                         return;
388                 }
389                 let msg = format!("{} argument", call_kind);
390                 for arg in args_to_check {
391                     self.check_unused_parens_expr(cx, arg, &msg, false);
392                 }
393                 return;
394             }
395         };
396         self.check_unused_parens_expr(cx, &value, msg, followed_by_block);
397     }
398
399     fn check_pat(&mut self, cx: &EarlyContext, p: &ast::Pat) {
400         use ast::PatKind::{Paren, Range};
401         // The lint visitor will visit each subpattern of `p`. We do not want to lint any range
402         // pattern no matter where it occurs in the pattern. For something like `&(a..=b)`, there
403         // is a recursive `check_pat` on `a` and `b`, but we will assume that if there are
404         // unnecessry parens they serve a purpose of readability.
405         if let Paren(ref pat) = p.node {
406             match pat.node {
407                 Range(..) => {}
408                 _ => self.check_unused_parens_pat(cx, &p, "pattern")
409             }
410         }
411     }
412
413     fn check_stmt(&mut self, cx: &EarlyContext, s: &ast::Stmt) {
414         if let ast::StmtKind::Local(ref local) = s.node {
415             if let Some(ref value) = local.init {
416                 self.check_unused_parens_expr(cx, &value, "assigned value", false);
417             }
418         }
419     }
420 }
421
422 declare_lint! {
423     UNUSED_IMPORT_BRACES,
424     Allow,
425     "unnecessary braces around an imported item"
426 }
427
428 #[derive(Copy, Clone)]
429 pub struct UnusedImportBraces;
430
431 impl UnusedImportBraces {
432     fn check_use_tree(&self, cx: &EarlyContext, use_tree: &ast::UseTree, item: &ast::Item) {
433         if let ast::UseTreeKind::Nested(ref items) = use_tree.kind {
434             // Recursively check nested UseTrees
435             for &(ref tree, _) in items {
436                 self.check_use_tree(cx, tree, item);
437             }
438
439             // Trigger the lint only if there is one nested item
440             if items.len() != 1 {
441                 return;
442             }
443
444             // Trigger the lint if the nested item is a non-self single item
445             let node_ident;
446             match items[0].0.kind {
447                 ast::UseTreeKind::Simple(rename, ..) => {
448                     let orig_ident = items[0].0.prefix.segments.last().unwrap().ident;
449                     if orig_ident.name == keywords::SelfValue.name() {
450                         return;
451                     }
452                     node_ident = rename.unwrap_or(orig_ident);
453                 }
454                 ast::UseTreeKind::Glob => {
455                     node_ident = ast::Ident::from_str("*");
456                 }
457                 ast::UseTreeKind::Nested(_) => {
458                     return;
459                 }
460             }
461
462             let msg = format!("braces around {} is unnecessary", node_ident.name);
463             cx.span_lint(UNUSED_IMPORT_BRACES, item.span, &msg);
464         }
465     }
466 }
467
468 impl LintPass for UnusedImportBraces {
469     fn get_lints(&self) -> LintArray {
470         lint_array!(UNUSED_IMPORT_BRACES)
471     }
472 }
473
474 impl EarlyLintPass for UnusedImportBraces {
475     fn check_item(&mut self, cx: &EarlyContext, item: &ast::Item) {
476         if let ast::ItemKind::Use(ref use_tree) = item.node {
477             self.check_use_tree(cx, use_tree, item);
478         }
479     }
480 }
481
482 declare_lint! {
483     pub(super) UNUSED_ALLOCATION,
484     Warn,
485     "detects unnecessary allocations that can be eliminated"
486 }
487
488 #[derive(Copy, Clone)]
489 pub struct UnusedAllocation;
490
491 impl LintPass for UnusedAllocation {
492     fn get_lints(&self) -> LintArray {
493         lint_array!(UNUSED_ALLOCATION)
494     }
495 }
496
497 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedAllocation {
498     fn check_expr(&mut self, cx: &LateContext, e: &hir::Expr) {
499         match e.node {
500             hir::ExprKind::Box(_) => {}
501             _ => return,
502         }
503
504         for adj in cx.tables.expr_adjustments(e) {
505             if let adjustment::Adjust::Borrow(adjustment::AutoBorrow::Ref(_, m)) = adj.kind {
506                 let msg = match m {
507                     adjustment::AutoBorrowMutability::Immutable =>
508                         "unnecessary allocation, use & instead",
509                     adjustment::AutoBorrowMutability::Mutable { .. }=>
510                         "unnecessary allocation, use &mut instead"
511                 };
512                 cx.span_lint(UNUSED_ALLOCATION, e.span, msg);
513             }
514         }
515     }
516 }