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