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