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;
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: true
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.node {
42 hir::StmtKind::Semi(ref expr) => &**expr,
46 if let hir::ExprKind::Ret(..) = expr.node {
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);
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, _) => {
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.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, ..) => {
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 = if plural { "s" } else { "" };
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)
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.node {
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(cx, ty, expr, span, descr_pre, descr_post, plural) {
211 ty::Array(ty, len) => match len.try_eval_usize(cx.tcx, cx.param_env) {
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!(
219 check_must_use_ty(cx, ty, expr, span, descr_pre, descr_post, true)
221 // Otherwise, we don't lint, to avoid false positives.
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<'_, '_>,
233 descr_pre_path: &str,
234 descr_post_path: &str,
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(¬e.as_str());
257 "path statements with no effect"
260 declare_lint_pass!(PathStatements => [PATH_STATEMENTS]);
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");
273 pub UNUSED_ATTRIBUTES,
275 "detects attributes that were not used by the compiler"
278 #[derive(Copy, Clone)]
279 pub struct UnusedAttributes {
280 builtin_attributes: &'static FxHashMap<Symbol, &'static BuiltinAttribute>,
283 impl UnusedAttributes {
284 pub fn new() -> Self {
286 builtin_attributes: &*BUILTIN_ATTRIBUTE_MAP,
291 impl_lint_pass!(UnusedAttributes => [UNUSED_ATTRIBUTES]);
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);
297 let attr_info = attr.ident().and_then(|ident| self.builtin_attributes.get(&ident.name));
299 if let Some(&&(name, ty, ..)) = attr_info {
301 AttributeType::Whitelisted => {
302 debug!("{:?} is Whitelisted", name);
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);
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
326 // Has a plugin registered this attribute as one that must be used at
328 let plugin_crate = plugin_attributes.iter()
329 .find(|&&(x, t)| name == x && AttributeType::CrateLevel == t)
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 \
337 ast::AttrStyle::Inner => "crate-level attribute should be in the root module",
339 cx.span_lint(UNUSED_ATTRIBUTES, attr.span, msg);
342 debug!("Attr was used: {:?}", attr);
348 pub(super) UNUSED_PARENS,
350 "`if`, `match`, `while` and `return` do not need parentheses"
353 declare_lint_pass!(UnusedParens => [UNUSED_PARENS]);
357 fn is_expr_parens_necessary(inner: &ast::Expr, followed_by_block: bool) -> bool {
358 followed_by_block && match inner.node {
359 ast::ExprKind::Ret(_) | ast::ExprKind::Break(..) => true,
360 _ => parser::contains_exterior_struct_lit(&inner),
364 fn check_unused_parens_expr(&self,
365 cx: &EarlyContext<'_>,
368 followed_by_block: bool,
369 left_pos: Option<BytePos>,
370 right_pos: Option<BytePos>) {
372 ast::ExprKind::Paren(ref inner) => {
373 if !Self::is_expr_parens_necessary(inner, followed_by_block) {
374 let expr_text = if let Ok(snippet) = cx.sess().source_map()
375 .span_to_snippet(value.span) {
378 pprust::expr_to_string(value)
381 left_pos.map(|s| s >= value.span.lo()).unwrap_or(false),
382 right_pos.map(|s| s <= value.span.hi()).unwrap_or(false),
384 Self::remove_outer_parens(cx, value.span, &expr_text, msg, keep_space);
387 ast::ExprKind::Let(_, ref expr) => {
388 // FIXME(#60336): Properly handle `let true = (false && true)`
389 // actually needing the parenthesis.
390 self.check_unused_parens_expr(
392 "`let` head expression",
401 fn check_unused_parens_pat(&self,
402 cx: &EarlyContext<'_>,
405 if let ast::PatKind::Paren(_) = value.node {
406 let pattern_text = if let Ok(snippet) = cx.sess().source_map()
407 .span_to_snippet(value.span) {
410 pprust::pat_to_string(value)
412 Self::remove_outer_parens(cx, value.span, &pattern_text, msg, (false, false));
416 fn remove_outer_parens(cx: &EarlyContext<'_>,
420 keep_space: (bool, bool)) {
421 let span_msg = format!("unnecessary parentheses around {}", msg);
422 let mut err = cx.struct_span_lint(UNUSED_PARENS, span, &span_msg);
423 let mut ate_left_paren = false;
424 let mut ate_right_paren = false;
425 let parens_removed = pattern
432 ate_left_paren = true;
440 ate_right_paren = true;
449 let mut replace = if keep_space.0 {
450 let mut s = String::from(" ");
451 s.push_str(parens_removed);
454 String::from(parens_removed)
463 err.span_suggestion_short(
465 "remove these parentheses",
467 Applicability::MachineApplicable,
473 impl EarlyLintPass for UnusedParens {
474 fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
475 use syntax::ast::ExprKind::*;
476 let (value, msg, followed_by_block, left_pos, right_pos) = match e.node {
477 If(ref cond, ref block, ..) => {
478 let left = e.span.lo() + syntax_pos::BytePos(2);
479 let right = block.span.lo();
480 (cond, "`if` condition", true, Some(left), Some(right))
483 While(ref cond, ref block, ..) => {
484 let left = e.span.lo() + syntax_pos::BytePos(5);
485 let right = block.span.lo();
486 (cond, "`while` condition", true, Some(left), Some(right))
489 ForLoop(_, ref cond, ref block, ..) => {
490 (cond, "`for` head expression", true, None, Some(block.span.lo()))
493 Match(ref head, _) => {
494 let left = e.span.lo() + syntax_pos::BytePos(5);
495 (head, "`match` head expression", true, Some(left), None)
498 Ret(Some(ref value)) => {
499 let left = e.span.lo() + syntax_pos::BytePos(3);
500 (value, "`return` value", false, Some(left), None)
503 Assign(_, ref value) => (value, "assigned value", false, None, None),
504 AssignOp(.., ref value) => (value, "assigned value", false, None, None),
505 // either function/method call, or something this lint doesn't care about
506 ref call_or_other => {
507 let (args_to_check, call_kind) = match *call_or_other {
508 Call(_, ref args) => (&args[..], "function"),
509 // first "argument" is self (which sometimes needs parens)
510 MethodCall(_, ref args) => (&args[1..], "method"),
511 // actual catch-all arm
516 // Don't lint if this is a nested macro expansion: otherwise, the lint could
517 // trigger in situations that macro authors shouldn't have to care about, e.g.,
518 // when a parenthesized token tree matched in one macro expansion is matched as
519 // an expression in another and used as a fn/method argument (Issue #47775)
520 if e.span.ctxt().outer_expn_data().call_site.from_expansion() {
523 let msg = format!("{} argument", call_kind);
524 for arg in args_to_check {
525 self.check_unused_parens_expr(cx, arg, &msg, false, None, None);
530 self.check_unused_parens_expr(cx, &value, msg, followed_by_block, left_pos, right_pos);
533 fn check_pat(&mut self, cx: &EarlyContext<'_>, p: &ast::Pat) {
534 use ast::PatKind::{Paren, Range};
535 // The lint visitor will visit each subpattern of `p`. We do not want to lint any range
536 // pattern no matter where it occurs in the pattern. For something like `&(a..=b)`, there
537 // is a recursive `check_pat` on `a` and `b`, but we will assume that if there are
538 // unnecessary parens they serve a purpose of readability.
539 if let Paren(ref pat) = p.node {
542 _ => self.check_unused_parens_pat(cx, &p, "pattern")
547 fn check_stmt(&mut self, cx: &EarlyContext<'_>, s: &ast::Stmt) {
548 if let ast::StmtKind::Local(ref local) = s.node {
549 if let Some(ref value) = local.init {
550 self.check_unused_parens_expr(cx, &value, "assigned value", false, None, None);
557 UNUSED_IMPORT_BRACES,
559 "unnecessary braces around an imported item"
562 declare_lint_pass!(UnusedImportBraces => [UNUSED_IMPORT_BRACES]);
564 impl UnusedImportBraces {
565 fn check_use_tree(&self, cx: &EarlyContext<'_>, use_tree: &ast::UseTree, item: &ast::Item) {
566 if let ast::UseTreeKind::Nested(ref items) = use_tree.kind {
567 // Recursively check nested UseTrees
568 for &(ref tree, _) in items {
569 self.check_use_tree(cx, tree, item);
572 // Trigger the lint only if there is one nested item
573 if items.len() != 1 {
577 // Trigger the lint if the nested item is a non-self single item
579 match items[0].0.kind {
580 ast::UseTreeKind::Simple(rename, ..) => {
581 let orig_ident = items[0].0.prefix.segments.last().unwrap().ident;
582 if orig_ident.name == kw::SelfLower {
585 node_ident = rename.unwrap_or(orig_ident);
587 ast::UseTreeKind::Glob => {
588 node_ident = ast::Ident::from_str("*");
590 ast::UseTreeKind::Nested(_) => {
595 let msg = format!("braces around {} is unnecessary", node_ident.name);
596 cx.span_lint(UNUSED_IMPORT_BRACES, item.span, &msg);
601 impl EarlyLintPass for UnusedImportBraces {
602 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
603 if let ast::ItemKind::Use(ref use_tree) = item.node {
604 self.check_use_tree(cx, use_tree, item);
610 pub(super) UNUSED_ALLOCATION,
612 "detects unnecessary allocations that can be eliminated"
615 declare_lint_pass!(UnusedAllocation => [UNUSED_ALLOCATION]);
617 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedAllocation {
618 fn check_expr(&mut self, cx: &LateContext<'_, '_>, e: &hir::Expr) {
620 hir::ExprKind::Box(_) => {}
624 for adj in cx.tables.expr_adjustments(e) {
625 if let adjustment::Adjust::Borrow(adjustment::AutoBorrow::Ref(_, m)) = adj.kind {
627 adjustment::AutoBorrowMutability::Immutable =>
628 "unnecessary allocation, use `&` instead",
629 adjustment::AutoBorrowMutability::Mutable { .. }=>
630 "unnecessary allocation, use `&mut` instead"
632 cx.span_lint(UNUSED_ALLOCATION, e.span, msg);