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