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;
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]);
356 fn check_unused_parens_expr(&self,
357 cx: &EarlyContext<'_>,
360 followed_by_block: bool) {
362 ast::ExprKind::Paren(ref inner) => {
363 let necessary = followed_by_block && match inner.node {
364 ast::ExprKind::Ret(_) | ast::ExprKind::Break(..) => true,
365 _ => parser::contains_exterior_struct_lit(&inner),
368 let expr_text = if let Ok(snippet) = cx.sess().source_map()
369 .span_to_snippet(value.span) {
372 pprust::expr_to_string(value)
374 Self::remove_outer_parens(cx, value.span, &expr_text, msg);
377 ast::ExprKind::Let(_, ref expr) => {
378 // FIXME(#60336): Properly handle `let true = (false && true)`
379 // actually needing the parenthesis.
380 self.check_unused_parens_expr(cx, expr, "`let` head expression", followed_by_block);
386 fn check_unused_parens_pat(&self,
387 cx: &EarlyContext<'_>,
390 if let ast::PatKind::Paren(_) = value.node {
391 let pattern_text = if let Ok(snippet) = cx.sess().source_map()
392 .span_to_snippet(value.span) {
395 pprust::pat_to_string(value)
397 Self::remove_outer_parens(cx, value.span, &pattern_text, msg);
401 fn remove_outer_parens(cx: &EarlyContext<'_>, span: Span, pattern: &str, msg: &str) {
402 let span_msg = format!("unnecessary parentheses around {}", msg);
403 let mut err = cx.struct_span_lint(UNUSED_PARENS, span, &span_msg);
404 let mut ate_left_paren = false;
405 let mut ate_right_paren = false;
406 let parens_removed = pattern
413 ate_left_paren = true;
421 ate_right_paren = true;
428 err.span_suggestion_short(
430 "remove these parentheses",
432 Applicability::MachineApplicable,
438 impl EarlyLintPass for UnusedParens {
439 fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
440 use syntax::ast::ExprKind::*;
441 let (value, msg, followed_by_block) = match e.node {
442 If(ref cond, ..) => (cond, "`if` condition", true),
443 While(ref cond, ..) => (cond, "`while` condition", true),
444 ForLoop(_, ref cond, ..) => (cond, "`for` head expression", true),
445 Match(ref head, _) => (head, "`match` head expression", true),
446 Ret(Some(ref value)) => (value, "`return` value", false),
447 Assign(_, ref value) => (value, "assigned value", false),
448 AssignOp(.., ref value) => (value, "assigned value", false),
449 // either function/method call, or something this lint doesn't care about
450 ref call_or_other => {
451 let (args_to_check, call_kind) = match *call_or_other {
452 Call(_, ref args) => (&args[..], "function"),
453 // first "argument" is self (which sometimes needs parens)
454 MethodCall(_, ref args) => (&args[1..], "method"),
455 // actual catch-all arm
460 // Don't lint if this is a nested macro expansion: otherwise, the lint could
461 // trigger in situations that macro authors shouldn't have to care about, e.g.,
462 // when a parenthesized token tree matched in one macro expansion is matched as
463 // an expression in another and used as a fn/method argument (Issue #47775)
464 if e.span.ctxt().outer_expn_info()
465 .map_or(false, |info| info.call_site.ctxt().outer_expn_info().is_some()) {
468 let msg = format!("{} argument", call_kind);
469 for arg in args_to_check {
470 self.check_unused_parens_expr(cx, arg, &msg, false);
475 self.check_unused_parens_expr(cx, &value, msg, followed_by_block);
478 fn check_pat(&mut self, cx: &EarlyContext<'_>, p: &ast::Pat) {
479 use ast::PatKind::{Paren, Range};
480 // The lint visitor will visit each subpattern of `p`. We do not want to lint any range
481 // pattern no matter where it occurs in the pattern. For something like `&(a..=b)`, there
482 // is a recursive `check_pat` on `a` and `b`, but we will assume that if there are
483 // unnecessary parens they serve a purpose of readability.
484 if let Paren(ref pat) = p.node {
487 _ => self.check_unused_parens_pat(cx, &p, "pattern")
492 fn check_stmt(&mut self, cx: &EarlyContext<'_>, s: &ast::Stmt) {
493 if let ast::StmtKind::Local(ref local) = s.node {
494 if let Some(ref value) = local.init {
495 self.check_unused_parens_expr(cx, &value, "assigned value", false);
502 UNUSED_IMPORT_BRACES,
504 "unnecessary braces around an imported item"
507 declare_lint_pass!(UnusedImportBraces => [UNUSED_IMPORT_BRACES]);
509 impl UnusedImportBraces {
510 fn check_use_tree(&self, cx: &EarlyContext<'_>, use_tree: &ast::UseTree, item: &ast::Item) {
511 if let ast::UseTreeKind::Nested(ref items) = use_tree.kind {
512 // Recursively check nested UseTrees
513 for &(ref tree, _) in items {
514 self.check_use_tree(cx, tree, item);
517 // Trigger the lint only if there is one nested item
518 if items.len() != 1 {
522 // Trigger the lint if the nested item is a non-self single item
524 match items[0].0.kind {
525 ast::UseTreeKind::Simple(rename, ..) => {
526 let orig_ident = items[0].0.prefix.segments.last().unwrap().ident;
527 if orig_ident.name == kw::SelfLower {
530 node_ident = rename.unwrap_or(orig_ident);
532 ast::UseTreeKind::Glob => {
533 node_ident = ast::Ident::from_str("*");
535 ast::UseTreeKind::Nested(_) => {
540 let msg = format!("braces around {} is unnecessary", node_ident.name);
541 cx.span_lint(UNUSED_IMPORT_BRACES, item.span, &msg);
546 impl EarlyLintPass for UnusedImportBraces {
547 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
548 if let ast::ItemKind::Use(ref use_tree) = item.node {
549 self.check_use_tree(cx, use_tree, item);
555 pub(super) UNUSED_ALLOCATION,
557 "detects unnecessary allocations that can be eliminated"
560 declare_lint_pass!(UnusedAllocation => [UNUSED_ALLOCATION]);
562 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedAllocation {
563 fn check_expr(&mut self, cx: &LateContext<'_, '_>, e: &hir::Expr) {
565 hir::ExprKind::Box(_) => {}
569 for adj in cx.tables.expr_adjustments(e) {
570 if let adjustment::Adjust::Borrow(adjustment::AutoBorrow::Ref(_, m)) = adj.kind {
572 adjustment::AutoBorrowMutability::Immutable =>
573 "unnecessary allocation, use `&` instead",
574 adjustment::AutoBorrowMutability::Mutable { .. }=>
575 "unnecessary allocation, use `&mut` instead"
577 cx.span_lint(UNUSED_ALLOCATION, e.span, msg);