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