1 use rustc::hir::def::{Res, DefKind};
2 use rustc::hir::def_id::DefId;
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};
12 use syntax::errors::{Applicability, pluralise};
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, BytePos};
27 "unused result of a type flagged as `#[must_use]`",
28 report_in_external_macro
34 "unused result of an expression in a statement"
37 declare_lint_pass!(UnusedResults => [UNUSED_MUST_USE, UNUSED_RESULTS]);
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.kind {
42 hir::StmtKind::Semi(ref expr) => &**expr,
46 if let hir::ExprKind::Ret(..) = expr.kind {
50 let ty = cx.tables.expr_ty(&expr);
51 let type_permits_lack_of_use = check_must_use_ty(cx, ty, &expr, s.span, "", "", 1);
53 let mut fn_warned = false;
54 let mut op_warned = false;
55 let maybe_def_id = match expr.kind {
56 hir::ExprKind::Call(ref callee, _) => {
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
70 hir::ExprKind::MethodCall(..) => {
71 cx.tables.type_dependent_def_id(expr.hir_id)
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.)
83 let must_use_op = match expr.kind {
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, ..) => {
94 hir::BinOpKind::Gt => {
100 hir::BinOpKind::Mul |
101 hir::BinOpKind::Rem => {
102 Some("arithmetic operation")
104 hir::BinOpKind::And | hir::BinOpKind::Or => {
105 Some("logical operation")
107 hir::BinOpKind::BitXor |
108 hir::BinOpKind::BitAnd |
109 hir::BinOpKind::BitOr |
110 hir::BinOpKind::Shl |
111 hir::BinOpKind::Shr => {
112 Some("bitwise operation")
116 hir::ExprKind::Unary(..) => Some("unary operation"),
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));
126 if !(type_permits_lack_of_use || fn_warned || op_warned) {
127 cx.span_lint(UNUSED_RESULTS, s.span, "unused result");
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>,
140 if ty.is_unit() || cx.tcx.is_ty_uninhabited_from(
141 cx.tcx.hir().get_module_parent(expr.hir_id), ty)
146 let plural_suffix = pluralise!(plural_len);
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_len)
155 check_must_use_def(cx, def.did, span, descr_pre, descr_post)
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 ",
168 if check_must_use_def(cx, def_id, span, descr_pre, descr_post) {
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!(
186 if check_must_use_def(cx, def_id, span, descr_pre, descr_post) {
194 ty::Tuple(ref tys) => {
195 let mut has_emitted = false;
196 let spans = if let hir::ExprKind::Tup(comps) = &expr.kind {
197 debug_assert_eq!(comps.len(), tys.len());
198 comps.iter().map(|e| e.span).collect()
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(
219 ty::Array(ty, len) => match len.try_eval_usize(cx.tcx, cx.param_env) {
220 // If the array is definitely non-empty, we can do `#[must_use]` checking.
221 Some(n) if n != 0 => {
222 let descr_pre = &format!(
227 check_must_use_ty(cx, ty, expr, span, descr_pre, descr_post, n as usize + 1)
229 // Otherwise, we don't lint, to avoid false positives.
236 // Returns whether an error has been emitted (and thus another does not need to be later).
237 fn check_must_use_def(
238 cx: &LateContext<'_, '_>,
241 descr_pre_path: &str,
242 descr_post_path: &str,
244 for attr in cx.tcx.get_attrs(def_id).iter() {
245 if attr.check_name(sym::must_use) {
246 let msg = format!("unused {}`{}`{} that must be used",
247 descr_pre_path, cx.tcx.def_path_str(def_id), descr_post_path);
248 let mut err = cx.struct_span_lint(UNUSED_MUST_USE, span, &msg);
249 // check for #[must_use = "..."]
250 if let Some(note) = attr.value_str() {
251 err.note(¬e.as_str());
265 "path statements with no effect"
268 declare_lint_pass!(PathStatements => [PATH_STATEMENTS]);
270 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for PathStatements {
271 fn check_stmt(&mut self, cx: &LateContext<'_, '_>, s: &hir::Stmt) {
272 if let hir::StmtKind::Semi(ref expr) = s.kind {
273 if let hir::ExprKind::Path(_) = expr.kind {
274 cx.span_lint(PATH_STATEMENTS, s.span, "path statement with no effect");
281 pub UNUSED_ATTRIBUTES,
283 "detects attributes that were not used by the compiler"
286 #[derive(Copy, Clone)]
287 pub struct UnusedAttributes {
288 builtin_attributes: &'static FxHashMap<Symbol, &'static BuiltinAttribute>,
291 impl UnusedAttributes {
292 pub fn new() -> Self {
294 builtin_attributes: &*BUILTIN_ATTRIBUTE_MAP,
299 impl_lint_pass!(UnusedAttributes => [UNUSED_ATTRIBUTES]);
301 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedAttributes {
302 fn check_attribute(&mut self, cx: &LateContext<'_, '_>, attr: &ast::Attribute) {
303 debug!("checking attribute: {:?}", attr);
305 let attr_info = attr.ident().and_then(|ident| self.builtin_attributes.get(&ident.name));
307 if let Some(&&(name, ty, ..)) = attr_info {
309 AttributeType::Whitelisted => {
310 debug!("{:?} is Whitelisted", name);
317 let plugin_attributes = cx.sess().plugin_attributes.borrow_mut();
318 for &(name, ty) in plugin_attributes.iter() {
319 if ty == AttributeType::Whitelisted && attr.check_name(name) {
320 debug!("{:?} (plugin attr) is whitelisted with ty {:?}", name, ty);
325 let name = attr.name_or_empty();
326 if !attr::is_used(attr) {
327 debug!("emitting warning for: {:?}", attr);
328 cx.span_lint(UNUSED_ATTRIBUTES, attr.span, "unused attribute");
329 // Is it a builtin attribute that must be used at the crate level?
330 let known_crate = attr_info.map(|&&(_, ty, ..)| {
331 ty == AttributeType::CrateLevel
334 // Has a plugin registered this attribute as one that must be used at
336 let plugin_crate = plugin_attributes.iter()
337 .find(|&&(x, t)| name == x && AttributeType::CrateLevel == t)
339 if known_crate || plugin_crate {
340 let msg = match attr.style {
341 ast::AttrStyle::Outer => {
342 "crate-level attribute should be an inner attribute: add an exclamation \
345 ast::AttrStyle::Inner => "crate-level attribute should be in the root module",
347 cx.span_lint(UNUSED_ATTRIBUTES, attr.span, msg);
350 debug!("Attr was used: {:?}", attr);
356 pub(super) UNUSED_PARENS,
358 "`if`, `match`, `while` and `return` do not need parentheses"
361 declare_lint_pass!(UnusedParens => [UNUSED_PARENS]);
365 fn is_expr_parens_necessary(inner: &ast::Expr, followed_by_block: bool) -> bool {
366 followed_by_block && match inner.kind {
367 ast::ExprKind::Ret(_) | ast::ExprKind::Break(..) => true,
368 _ => parser::contains_exterior_struct_lit(&inner),
372 fn check_unused_parens_expr(&self,
373 cx: &EarlyContext<'_>,
376 followed_by_block: bool,
377 left_pos: Option<BytePos>,
378 right_pos: Option<BytePos>) {
380 ast::ExprKind::Paren(ref inner) => {
381 if !Self::is_expr_parens_necessary(inner, followed_by_block) &&
382 value.attrs.is_empty() {
383 let expr_text = if let Ok(snippet) = cx.sess().source_map()
384 .span_to_snippet(value.span) {
387 pprust::expr_to_string(value)
390 left_pos.map(|s| s >= value.span.lo()).unwrap_or(false),
391 right_pos.map(|s| s <= value.span.hi()).unwrap_or(false),
393 Self::remove_outer_parens(cx, value.span, &expr_text, msg, keep_space);
396 ast::ExprKind::Let(_, ref expr) => {
397 // FIXME(#60336): Properly handle `let true = (false && true)`
398 // actually needing the parenthesis.
399 self.check_unused_parens_expr(
401 "`let` head expression",
410 fn check_unused_parens_pat(
412 cx: &EarlyContext<'_>,
417 use ast::{PatKind, BindingMode::ByValue, Mutability::Mutable};
419 if let PatKind::Paren(inner) = &value.kind {
421 // The lint visitor will visit each subpattern of `p`. We do not want to lint
422 // any range pattern no matter where it occurs in the pattern. For something like
423 // `&(a..=b)`, there is a recursive `check_pat` on `a` and `b`, but we will assume
424 // that if there are unnecessary parens they serve a purpose of readability.
425 PatKind::Range(..) => return,
426 // Avoid `p0 | .. | pn` if we should.
427 PatKind::Or(..) if avoid_or => return,
428 // Avoid `mut x` and `mut x @ p` if we should:
429 PatKind::Ident(ByValue(Mutable), ..) if avoid_mut => return,
430 // Otherwise proceed with linting.
434 let pattern_text = if let Ok(snippet) = cx.sess().source_map()
435 .span_to_snippet(value.span) {
438 pprust::pat_to_string(value)
440 Self::remove_outer_parens(cx, value.span, &pattern_text, "pattern", (false, false));
444 fn remove_outer_parens(cx: &EarlyContext<'_>,
448 keep_space: (bool, bool)) {
449 let span_msg = format!("unnecessary parentheses around {}", msg);
450 let mut err = cx.struct_span_lint(UNUSED_PARENS, span, &span_msg);
451 let mut ate_left_paren = false;
452 let mut ate_right_paren = false;
453 let parens_removed = pattern
460 ate_left_paren = true;
468 ate_right_paren = true;
477 let mut replace = if keep_space.0 {
478 let mut s = String::from(" ");
479 s.push_str(parens_removed);
482 String::from(parens_removed)
491 err.span_suggestion_short(
493 "remove these parentheses",
495 Applicability::MachineApplicable,
501 impl EarlyLintPass for UnusedParens {
502 fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
503 use syntax::ast::ExprKind::*;
504 let (value, msg, followed_by_block, left_pos, right_pos) = match e.kind {
505 Let(ref pat, ..) => {
506 self.check_unused_parens_pat(cx, pat, false, false);
510 If(ref cond, ref block, ..) => {
511 let left = e.span.lo() + syntax_pos::BytePos(2);
512 let right = block.span.lo();
513 (cond, "`if` condition", true, Some(left), Some(right))
516 While(ref cond, ref block, ..) => {
517 let left = e.span.lo() + syntax_pos::BytePos(5);
518 let right = block.span.lo();
519 (cond, "`while` condition", true, Some(left), Some(right))
522 ForLoop(ref pat, ref cond, ref block, ..) => {
523 self.check_unused_parens_pat(cx, pat, false, false);
524 (cond, "`for` head expression", true, None, Some(block.span.lo()))
527 Match(ref head, _) => {
528 let left = e.span.lo() + syntax_pos::BytePos(5);
529 (head, "`match` head expression", true, Some(left), None)
532 Ret(Some(ref value)) => {
533 let left = e.span.lo() + syntax_pos::BytePos(3);
534 (value, "`return` value", false, Some(left), None)
537 Assign(_, ref value) => (value, "assigned value", false, None, None),
538 AssignOp(.., ref value) => (value, "assigned value", false, None, None),
539 // either function/method call, or something this lint doesn't care about
540 ref call_or_other => {
541 let (args_to_check, call_kind) = match *call_or_other {
542 Call(_, ref args) => (&args[..], "function"),
543 // first "argument" is self (which sometimes needs parens)
544 MethodCall(_, ref args) => (&args[1..], "method"),
545 // actual catch-all arm
550 // Don't lint if this is a nested macro expansion: otherwise, the lint could
551 // trigger in situations that macro authors shouldn't have to care about, e.g.,
552 // when a parenthesized token tree matched in one macro expansion is matched as
553 // an expression in another and used as a fn/method argument (Issue #47775)
554 if e.span.ctxt().outer_expn_data().call_site.from_expansion() {
557 let msg = format!("{} argument", call_kind);
558 for arg in args_to_check {
559 self.check_unused_parens_expr(cx, arg, &msg, false, None, None);
564 self.check_unused_parens_expr(cx, &value, msg, followed_by_block, left_pos, right_pos);
567 fn check_pat(&mut self, cx: &EarlyContext<'_>, p: &ast::Pat) {
568 use ast::{PatKind::*, Mutability};
570 // Do not lint on `(..)` as that will result in the other arms being useless.
572 // The other cases do not contain sub-patterns.
573 | Wild | Rest | Lit(..) | Mac(..) | Range(..) | Ident(.., None) | Path(..) => return,
574 // These are list-like patterns; parens can always be removed.
575 TupleStruct(_, ps) | Tuple(ps) | Slice(ps) | Or(ps) => for p in ps {
576 self.check_unused_parens_pat(cx, p, false, false);
578 Struct(_, fps, _) => for f in fps {
579 self.check_unused_parens_pat(cx, &f.pat, false, false);
581 // Avoid linting on `i @ (p0 | .. | pn)` and `box (p0 | .. | pn)`, #64106.
582 Ident(.., Some(p)) | Box(p) => self.check_unused_parens_pat(cx, p, true, false),
583 // Avoid linting on `&(mut x)` as `&mut x` has a different meaning, #55342.
584 // Also avoid linting on `& mut? (p0 | .. | pn)`, #64106.
585 Ref(p, m) => self.check_unused_parens_pat(cx, p, true, *m == Mutability::Immutable),
589 fn check_stmt(&mut self, cx: &EarlyContext<'_>, s: &ast::Stmt) {
590 if let ast::StmtKind::Local(ref local) = s.kind {
591 self.check_unused_parens_pat(cx, &local.pat, false, false);
593 if let Some(ref value) = local.init {
594 self.check_unused_parens_expr(cx, &value, "assigned value", false, None, None);
599 fn check_param(&mut self, cx: &EarlyContext<'_>, param: &ast::Param) {
600 self.check_unused_parens_pat(cx, ¶m.pat, true, false);
603 fn check_arm(&mut self, cx: &EarlyContext<'_>, arm: &ast::Arm) {
604 self.check_unused_parens_pat(cx, &arm.pat, false, false);
609 UNUSED_IMPORT_BRACES,
611 "unnecessary braces around an imported item"
614 declare_lint_pass!(UnusedImportBraces => [UNUSED_IMPORT_BRACES]);
616 impl UnusedImportBraces {
617 fn check_use_tree(&self, cx: &EarlyContext<'_>, use_tree: &ast::UseTree, item: &ast::Item) {
618 if let ast::UseTreeKind::Nested(ref items) = use_tree.kind {
619 // Recursively check nested UseTrees
620 for &(ref tree, _) in items {
621 self.check_use_tree(cx, tree, item);
624 // Trigger the lint only if there is one nested item
625 if items.len() != 1 {
629 // Trigger the lint if the nested item is a non-self single item
630 let node_name = match items[0].0.kind {
631 ast::UseTreeKind::Simple(rename, ..) => {
632 let orig_ident = items[0].0.prefix.segments.last().unwrap().ident;
633 if orig_ident.name == kw::SelfLower {
636 rename.unwrap_or(orig_ident).name
638 ast::UseTreeKind::Glob => Symbol::intern("*"),
639 ast::UseTreeKind::Nested(_) => return,
642 let msg = format!("braces around {} is unnecessary", node_name);
643 cx.span_lint(UNUSED_IMPORT_BRACES, item.span, &msg);
648 impl EarlyLintPass for UnusedImportBraces {
649 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
650 if let ast::ItemKind::Use(ref use_tree) = item.kind {
651 self.check_use_tree(cx, use_tree, item);
657 pub(super) UNUSED_ALLOCATION,
659 "detects unnecessary allocations that can be eliminated"
662 declare_lint_pass!(UnusedAllocation => [UNUSED_ALLOCATION]);
664 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedAllocation {
665 fn check_expr(&mut self, cx: &LateContext<'_, '_>, e: &hir::Expr) {
667 hir::ExprKind::Box(_) => {}
671 for adj in cx.tables.expr_adjustments(e) {
672 if let adjustment::Adjust::Borrow(adjustment::AutoBorrow::Ref(_, m)) = adj.kind {
674 adjustment::AutoBorrowMutability::Immutable =>
675 "unnecessary allocation, use `&` instead",
676 adjustment::AutoBorrowMutability::Mutable { .. }=>
677 "unnecessary allocation, use `&mut` instead"
679 cx.span_lint(UNUSED_ALLOCATION, e.span, msg);