]> git.lizzy.rs Git - rust.git/blob - src/librustc_lint/unused.rs
Auto merge of #63233 - RalfJung:get_unchecked, r=Centril
[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, "", "", false);
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_pre: &str,
137             descr_post: &str,
138             plural: bool,
139         ) -> bool {
140             if ty.is_unit() || cx.tcx.is_ty_uninhabited_from(
141                 cx.tcx.hir().get_module_parent(expr.hir_id), ty)
142             {
143                 return true;
144             }
145
146             let plural_suffix = if plural { "s" } else { "" };
147
148             match ty.sty {
149                 ty::Adt(..) if ty.is_box() => {
150                     let boxed_ty = ty.boxed_ty();
151                     let descr_pre = &format!("{}boxed ", descr_pre);
152                     check_must_use_ty(cx, boxed_ty, expr, span, descr_pre, descr_post, plural)
153                 }
154                 ty::Adt(def, _) => {
155                     check_must_use_def(cx, def.did, span, descr_pre, descr_post)
156                 }
157                 ty::Opaque(def, _) => {
158                     let mut has_emitted = false;
159                     for (predicate, _) in &cx.tcx.predicates_of(def).predicates {
160                         if let ty::Predicate::Trait(ref poly_trait_predicate) = predicate {
161                             let trait_ref = poly_trait_predicate.skip_binder().trait_ref;
162                             let def_id = trait_ref.def_id;
163                             let descr_pre = &format!(
164                                 "{}implementer{} of ",
165                                 descr_pre,
166                                 plural_suffix,
167                             );
168                             if check_must_use_def(cx, def_id, span, descr_pre, descr_post) {
169                                 has_emitted = true;
170                                 break;
171                             }
172                         }
173                     }
174                     has_emitted
175                 }
176                 ty::Dynamic(binder, _) => {
177                     let mut has_emitted = false;
178                     for predicate in binder.skip_binder().iter() {
179                         if let ty::ExistentialPredicate::Trait(ref trait_ref) = predicate {
180                             let def_id = trait_ref.def_id;
181                             let descr_post = &format!(
182                                 " trait object{}{}",
183                                 plural_suffix,
184                                 descr_post,
185                             );
186                             if check_must_use_def(cx, def_id, span, descr_pre, descr_post) {
187                                 has_emitted = true;
188                                 break;
189                             }
190                         }
191                     }
192                     has_emitted
193                 }
194                 ty::Tuple(ref tys) => {
195                     let mut has_emitted = false;
196                     let spans = if let hir::ExprKind::Tup(comps) = &expr.node {
197                         debug_assert_eq!(comps.len(), tys.len());
198                         comps.iter().map(|e| e.span).collect()
199                     } else {
200                         vec![]
201                     };
202                     for (i, ty) in tys.iter().map(|k| k.expect_ty()).enumerate() {
203                         let descr_post = &format!(" in tuple element {}", i);
204                         let span = *spans.get(i).unwrap_or(&span);
205                         if check_must_use_ty(cx, ty, expr, span, descr_pre, descr_post, plural) {
206                             has_emitted = true;
207                         }
208                     }
209                     has_emitted
210                 }
211                 ty::Array(ty, len) => match len.assert_usize(cx.tcx) {
212                     // If the array is definitely non-empty, we can do `#[must_use]` checking.
213                     Some(n) if n != 0 => {
214                         let descr_pre = &format!(
215                             "{}array{} of ",
216                             descr_pre,
217                             plural_suffix,
218                         );
219                         check_must_use_ty(cx, ty, expr, span, descr_pre, descr_post, true)
220                     }
221                     // Otherwise, we don't lint, to avoid false positives.
222                     _ => false,
223                 }
224                 _ => false,
225             }
226         }
227
228         // Returns whether an error has been emitted (and thus another does not need to be later).
229         fn check_must_use_def(
230             cx: &LateContext<'_, '_>,
231             def_id: DefId,
232             span: Span,
233             descr_pre_path: &str,
234             descr_post_path: &str,
235         ) -> bool {
236             for attr in cx.tcx.get_attrs(def_id).iter() {
237                 if attr.check_name(sym::must_use) {
238                     let msg = format!("unused {}`{}`{} that must be used",
239                         descr_pre_path, cx.tcx.def_path_str(def_id), descr_post_path);
240                     let mut err = cx.struct_span_lint(UNUSED_MUST_USE, span, &msg);
241                     // check for #[must_use = "..."]
242                     if let Some(note) = attr.value_str() {
243                         err.note(&note.as_str());
244                     }
245                     err.emit();
246                     return true;
247                 }
248             }
249             false
250         }
251     }
252 }
253
254 declare_lint! {
255     pub PATH_STATEMENTS,
256     Warn,
257     "path statements with no effect"
258 }
259
260 declare_lint_pass!(PathStatements => [PATH_STATEMENTS]);
261
262 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for PathStatements {
263     fn check_stmt(&mut self, cx: &LateContext<'_, '_>, s: &hir::Stmt) {
264         if let hir::StmtKind::Semi(ref expr) = s.node {
265             if let hir::ExprKind::Path(_) = expr.node {
266                 cx.span_lint(PATH_STATEMENTS, s.span, "path statement with no effect");
267             }
268         }
269     }
270 }
271
272 declare_lint! {
273     pub UNUSED_ATTRIBUTES,
274     Warn,
275     "detects attributes that were not used by the compiler"
276 }
277
278 #[derive(Copy, Clone)]
279 pub struct UnusedAttributes {
280     builtin_attributes: &'static FxHashMap<Symbol, &'static BuiltinAttribute>,
281 }
282
283 impl UnusedAttributes {
284     pub fn new() -> Self {
285         UnusedAttributes {
286             builtin_attributes: &*BUILTIN_ATTRIBUTE_MAP,
287         }
288     }
289 }
290
291 impl_lint_pass!(UnusedAttributes => [UNUSED_ATTRIBUTES]);
292
293 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedAttributes {
294     fn check_attribute(&mut self, cx: &LateContext<'_, '_>, attr: &ast::Attribute) {
295         debug!("checking attribute: {:?}", attr);
296
297         let attr_info = attr.ident().and_then(|ident| self.builtin_attributes.get(&ident.name));
298
299         if let Some(&&(name, ty, ..)) = attr_info {
300             match ty {
301                 AttributeType::Whitelisted => {
302                     debug!("{:?} is Whitelisted", name);
303                     return;
304                 }
305                 _ => (),
306             }
307         }
308
309         let plugin_attributes = cx.sess().plugin_attributes.borrow_mut();
310         for &(name, ty) in plugin_attributes.iter() {
311             if ty == AttributeType::Whitelisted && attr.check_name(name) {
312                 debug!("{:?} (plugin attr) is whitelisted with ty {:?}", name, ty);
313                 break;
314             }
315         }
316
317         let name = attr.name_or_empty();
318         if !attr::is_used(attr) {
319             debug!("emitting warning for: {:?}", attr);
320             cx.span_lint(UNUSED_ATTRIBUTES, attr.span, "unused attribute");
321             // Is it a builtin attribute that must be used at the crate level?
322             let known_crate = attr_info.map(|&&(_, ty, ..)| {
323                     ty == AttributeType::CrateLevel
324             }).unwrap_or(false);
325
326             // Has a plugin registered this attribute as one that must be used at
327             // the crate level?
328             let plugin_crate = plugin_attributes.iter()
329                 .find(|&&(x, t)| name == x && AttributeType::CrateLevel == t)
330                 .is_some();
331             if known_crate || plugin_crate {
332                 let msg = match attr.style {
333                     ast::AttrStyle::Outer => {
334                         "crate-level attribute should be an inner attribute: add an exclamation \
335                          mark: `#![foo]`"
336                     }
337                     ast::AttrStyle::Inner => "crate-level attribute should be in the root module",
338                 };
339                 cx.span_lint(UNUSED_ATTRIBUTES, attr.span, msg);
340             }
341         } else {
342             debug!("Attr was used: {:?}", attr);
343         }
344     }
345 }
346
347 declare_lint! {
348     pub(super) UNUSED_PARENS,
349     Warn,
350     "`if`, `match`, `while` and `return` do not need parentheses"
351 }
352
353 declare_lint_pass!(UnusedParens => [UNUSED_PARENS]);
354
355 impl UnusedParens {
356     fn check_unused_parens_expr(&self,
357                                 cx: &EarlyContext<'_>,
358                                 value: &ast::Expr,
359                                 msg: &str,
360                                 followed_by_block: bool) {
361         match value.node {
362             ast::ExprKind::Paren(ref inner) => {
363                 let necessary = followed_by_block && match inner.node {
364                     ast::ExprKind::Ret(_) | ast::ExprKind::Break(..) => true,
365                     _ => parser::contains_exterior_struct_lit(&inner),
366                 };
367                 if !necessary {
368                     let expr_text = if let Ok(snippet) = cx.sess().source_map()
369                         .span_to_snippet(value.span) {
370                             snippet
371                         } else {
372                             pprust::expr_to_string(value)
373                         };
374                     Self::remove_outer_parens(cx, value.span, &expr_text, msg);
375                 }
376             }
377             ast::ExprKind::Let(_, ref expr) => {
378                 // FIXME(#60336): Properly handle `let true = (false && true)`
379                 // actually needing the parenthesis.
380                 self.check_unused_parens_expr(cx, expr, "`let` head expression", followed_by_block);
381             }
382             _ => {}
383         }
384     }
385
386     fn check_unused_parens_pat(&self,
387                                 cx: &EarlyContext<'_>,
388                                 value: &ast::Pat,
389                                 msg: &str) {
390         if let ast::PatKind::Paren(_) = value.node {
391             let pattern_text = if let Ok(snippet) = cx.sess().source_map()
392                 .span_to_snippet(value.span) {
393                     snippet
394                 } else {
395                     pprust::pat_to_string(value)
396                 };
397             Self::remove_outer_parens(cx, value.span, &pattern_text, msg);
398         }
399     }
400
401     fn remove_outer_parens(cx: &EarlyContext<'_>, span: Span, pattern: &str, msg: &str) {
402         let span_msg = format!("unnecessary parentheses around {}", msg);
403         let mut err = cx.struct_span_lint(UNUSED_PARENS, span, &span_msg);
404         let mut ate_left_paren = false;
405         let mut ate_right_paren = false;
406         let parens_removed = pattern
407             .trim_matches(|c| {
408                 match c {
409                     '(' => {
410                         if ate_left_paren {
411                             false
412                         } else {
413                             ate_left_paren = true;
414                             true
415                         }
416                     },
417                     ')' => {
418                         if ate_right_paren {
419                             false
420                         } else {
421                             ate_right_paren = true;
422                             true
423                         }
424                     },
425                     _ => false,
426                 }
427             }).to_owned();
428         err.span_suggestion_short(
429             span,
430             "remove these parentheses",
431             parens_removed,
432             Applicability::MachineApplicable,
433         );
434         err.emit();
435     }
436 }
437
438 impl EarlyLintPass for UnusedParens {
439     fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
440         use syntax::ast::ExprKind::*;
441         let (value, msg, followed_by_block) = match e.node {
442             If(ref cond, ..) => (cond, "`if` condition", true),
443             While(ref cond, ..) => (cond, "`while` condition", true),
444             ForLoop(_, ref cond, ..) => (cond, "`for` head expression", true),
445             Match(ref head, _) => (head, "`match` head expression", true),
446             Ret(Some(ref value)) => (value, "`return` value", false),
447             Assign(_, ref value) => (value, "assigned value", false),
448             AssignOp(.., ref value) => (value, "assigned value", false),
449             // either function/method call, or something this lint doesn't care about
450             ref call_or_other => {
451                 let (args_to_check, call_kind) = match *call_or_other {
452                     Call(_, ref args) => (&args[..], "function"),
453                     // first "argument" is self (which sometimes needs parens)
454                     MethodCall(_, ref args) => (&args[1..], "method"),
455                     // actual catch-all arm
456                     _ => {
457                         return;
458                     }
459                 };
460                 // Don't lint if this is a nested macro expansion: otherwise, the lint could
461                 // trigger in situations that macro authors shouldn't have to care about, e.g.,
462                 // when a parenthesized token tree matched in one macro expansion is matched as
463                 // an expression in another and used as a fn/method argument (Issue #47775)
464                 if e.span.ctxt().outer_expn_info()
465                     .map_or(false, |info| info.call_site.ctxt().outer_expn_info().is_some()) {
466                         return;
467                 }
468                 let msg = format!("{} argument", call_kind);
469                 for arg in args_to_check {
470                     self.check_unused_parens_expr(cx, arg, &msg, false);
471                 }
472                 return;
473             }
474         };
475         self.check_unused_parens_expr(cx, &value, msg, followed_by_block);
476     }
477
478     fn check_pat(&mut self, cx: &EarlyContext<'_>, p: &ast::Pat) {
479         use ast::PatKind::{Paren, Range};
480         // The lint visitor will visit each subpattern of `p`. We do not want to lint any range
481         // pattern no matter where it occurs in the pattern. For something like `&(a..=b)`, there
482         // is a recursive `check_pat` on `a` and `b`, but we will assume that if there are
483         // unnecessary parens they serve a purpose of readability.
484         if let Paren(ref pat) = p.node {
485             match pat.node {
486                 Range(..) => {}
487                 _ => self.check_unused_parens_pat(cx, &p, "pattern")
488             }
489         }
490     }
491
492     fn check_stmt(&mut self, cx: &EarlyContext<'_>, s: &ast::Stmt) {
493         if let ast::StmtKind::Local(ref local) = s.node {
494             if let Some(ref value) = local.init {
495                 self.check_unused_parens_expr(cx, &value, "assigned value", false);
496             }
497         }
498     }
499 }
500
501 declare_lint! {
502     UNUSED_IMPORT_BRACES,
503     Allow,
504     "unnecessary braces around an imported item"
505 }
506
507 declare_lint_pass!(UnusedImportBraces => [UNUSED_IMPORT_BRACES]);
508
509 impl UnusedImportBraces {
510     fn check_use_tree(&self, cx: &EarlyContext<'_>, use_tree: &ast::UseTree, item: &ast::Item) {
511         if let ast::UseTreeKind::Nested(ref items) = use_tree.kind {
512             // Recursively check nested UseTrees
513             for &(ref tree, _) in items {
514                 self.check_use_tree(cx, tree, item);
515             }
516
517             // Trigger the lint only if there is one nested item
518             if items.len() != 1 {
519                 return;
520             }
521
522             // Trigger the lint if the nested item is a non-self single item
523             let node_ident;
524             match items[0].0.kind {
525                 ast::UseTreeKind::Simple(rename, ..) => {
526                     let orig_ident = items[0].0.prefix.segments.last().unwrap().ident;
527                     if orig_ident.name == kw::SelfLower {
528                         return;
529                     }
530                     node_ident = rename.unwrap_or(orig_ident);
531                 }
532                 ast::UseTreeKind::Glob => {
533                     node_ident = ast::Ident::from_str("*");
534                 }
535                 ast::UseTreeKind::Nested(_) => {
536                     return;
537                 }
538             }
539
540             let msg = format!("braces around {} is unnecessary", node_ident.name);
541             cx.span_lint(UNUSED_IMPORT_BRACES, item.span, &msg);
542         }
543     }
544 }
545
546 impl EarlyLintPass for UnusedImportBraces {
547     fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
548         if let ast::ItemKind::Use(ref use_tree) = item.node {
549             self.check_use_tree(cx, use_tree, item);
550         }
551     }
552 }
553
554 declare_lint! {
555     pub(super) UNUSED_ALLOCATION,
556     Warn,
557     "detects unnecessary allocations that can be eliminated"
558 }
559
560 declare_lint_pass!(UnusedAllocation => [UNUSED_ALLOCATION]);
561
562 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedAllocation {
563     fn check_expr(&mut self, cx: &LateContext<'_, '_>, e: &hir::Expr) {
564         match e.node {
565             hir::ExprKind::Box(_) => {}
566             _ => return,
567         }
568
569         for adj in cx.tables.expr_adjustments(e) {
570             if let adjustment::Adjust::Borrow(adjustment::AutoBorrow::Ref(_, m)) = adj.kind {
571                 let msg = match m {
572                     adjustment::AutoBorrowMutability::Immutable =>
573                         "unnecessary allocation, use `&` instead",
574                     adjustment::AutoBorrowMutability::Mutable { .. }=>
575                         "unnecessary allocation, use `&mut` instead"
576                 };
577                 cx.span_lint(UNUSED_ALLOCATION, e.span, msg);
578             }
579         }
580     }
581 }