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