1 use rustc::hir::def::{Def, DefKind};
2 use rustc::hir::def_id::DefId;
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::keywords;
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 t = cx.tables.expr_ty(&expr);
51 let type_permits_lack_of_use = if t.is_unit()
52 || cx.tcx.is_ty_uninhabited_from(
53 cx.tcx.hir().get_module_parent_by_hir_id(expr.hir_id), t)
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 ", "") {
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") {
88 let mut fn_warned = false;
89 let mut op_warned = false;
90 let maybe_def_id = match expr.node {
91 hir::ExprKind::Call(ref callee, _) => {
93 hir::ExprKind::Path(ref qpath) => {
94 let def = cx.tables.qpath_def(qpath, callee.hir_id);
96 Def::Def(DefKind::Fn, def_id)
97 | Def::Def(DefKind::Method, def_id) => Some(def_id),
98 // `Def::Local` if it was a closure, for which we
99 // do not currently support must-use linting
106 hir::ExprKind::MethodCall(..) => {
107 cx.tables.type_dependent_def_id(expr.hir_id)
111 if let Some(def_id) = maybe_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.)
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, ..) => {
130 hir::BinOpKind::Gt => {
133 hir::BinOpKind::Add |
134 hir::BinOpKind::Sub |
135 hir::BinOpKind::Div |
136 hir::BinOpKind::Mul |
137 hir::BinOpKind::Rem => {
138 Some("arithmetic operation")
140 hir::BinOpKind::And | hir::BinOpKind::Or => {
141 Some("logical operation")
143 hir::BinOpKind::BitXor |
144 hir::BinOpKind::BitAnd |
145 hir::BinOpKind::BitOr |
146 hir::BinOpKind::Shl |
147 hir::BinOpKind::Shr => {
148 Some("bitwise operation")
152 hir::ExprKind::Unary(..) => Some("unary operation"),
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));
162 if !(type_permits_lack_of_use || fn_warned || op_warned) {
163 cx.span_lint(UNUSED_RESULTS, s.span, "unused result");
167 cx: &LateContext<'_, '_>,
170 descr_pre_path: &str,
171 descr_post_path: &str,
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.def_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(¬e.as_str());
194 "path statements with no effect"
197 declare_lint_pass!(PathStatements => [PATH_STATEMENTS]);
199 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for PathStatements {
200 fn check_stmt(&mut self, cx: &LateContext<'_, '_>, s: &hir::Stmt) {
201 if let hir::StmtKind::Semi(ref expr) = s.node {
202 if let hir::ExprKind::Path(_) = expr.node {
203 cx.span_lint(PATH_STATEMENTS, s.span, "path statement with no effect");
210 pub UNUSED_ATTRIBUTES,
212 "detects attributes that were not used by the compiler"
215 #[derive(Copy, Clone)]
216 pub struct UnusedAttributes {
217 builtin_attributes: &'static FxHashMap<Symbol, &'static BuiltinAttribute>,
220 impl UnusedAttributes {
221 pub fn new() -> Self {
223 builtin_attributes: &*BUILTIN_ATTRIBUTE_MAP,
228 impl_lint_pass!(UnusedAttributes => [UNUSED_ATTRIBUTES]);
230 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedAttributes {
231 fn check_attribute(&mut self, cx: &LateContext<'_, '_>, attr: &ast::Attribute) {
232 debug!("checking attribute: {:?}", attr);
234 let attr_info = attr.ident().and_then(|ident| self.builtin_attributes.get(&ident.name));
236 if let Some(&&(name, ty, ..)) = attr_info {
238 AttributeType::Whitelisted => {
239 debug!("{:?} is Whitelisted", name);
246 let plugin_attributes = cx.sess().plugin_attributes.borrow_mut();
247 for &(ref name, ty) in plugin_attributes.iter() {
248 if ty == AttributeType::Whitelisted && attr.check_name(&**name) {
249 debug!("{:?} (plugin attr) is whitelisted with ty {:?}", name, ty);
254 let name = attr.name_or_empty();
255 if !attr::is_used(attr) {
256 debug!("Emitting warning for: {:?}", attr);
257 cx.span_lint(UNUSED_ATTRIBUTES, attr.span, "unused attribute");
258 // Is it a builtin attribute that must be used at the crate level?
259 let known_crate = attr_info.map(|&&(_, ty, ..)| {
260 ty == AttributeType::CrateLevel
263 // Has a plugin registered this attribute as one that must be used at
265 let plugin_crate = plugin_attributes.iter()
266 .find(|&&(ref x, t)| name == x.as_str() && AttributeType::CrateLevel == t)
268 if known_crate || plugin_crate {
269 let msg = match attr.style {
270 ast::AttrStyle::Outer => {
271 "crate-level attribute should be an inner attribute: add an exclamation \
274 ast::AttrStyle::Inner => "crate-level attribute should be in the root module",
276 cx.span_lint(UNUSED_ATTRIBUTES, attr.span, msg);
279 debug!("Attr was used: {:?}", attr);
285 pub(super) UNUSED_PARENS,
287 "`if`, `match`, `while` and `return` do not need parentheses"
290 declare_lint_pass!(UnusedParens => [UNUSED_PARENS]);
293 fn check_unused_parens_expr(&self,
294 cx: &EarlyContext<'_>,
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),
304 let expr_text = if let Ok(snippet) = cx.sess().source_map()
305 .span_to_snippet(value.span) {
308 pprust::expr_to_string(value)
310 Self::remove_outer_parens(cx, value.span, &expr_text, msg);
315 fn check_unused_parens_pat(&self,
316 cx: &EarlyContext<'_>,
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) {
324 pprust::pat_to_string(value)
326 Self::remove_outer_parens(cx, value.span, &pattern_text, msg);
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
342 ate_left_paren = true;
350 ate_right_paren = true;
357 err.span_suggestion_short(
359 "remove these parentheses",
361 Applicability::MachineApplicable,
367 impl EarlyLintPass for UnusedParens {
368 fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
369 use syntax::ast::ExprKind::*;
370 let (value, msg, followed_by_block) = match e.node {
371 If(ref cond, ..) => (cond, "`if` condition", true),
372 While(ref cond, ..) => (cond, "`while` condition", true),
373 IfLet(_, ref cond, ..) => (cond, "`if let` head expression", true),
374 WhileLet(_, ref cond, ..) => (cond, "`while let` head expression", true),
375 ForLoop(_, ref cond, ..) => (cond, "`for` head expression", true),
376 Match(ref head, _) => (head, "`match` head expression", true),
377 Ret(Some(ref value)) => (value, "`return` value", false),
378 Assign(_, ref value) => (value, "assigned value", false),
379 AssignOp(.., ref value) => (value, "assigned value", false),
380 // either function/method call, or something this lint doesn't care about
381 ref call_or_other => {
382 let (args_to_check, call_kind) = match *call_or_other {
383 Call(_, ref args) => (&args[..], "function"),
384 // first "argument" is self (which sometimes needs parens)
385 MethodCall(_, ref args) => (&args[1..], "method"),
386 // actual catch-all arm
391 // Don't lint if this is a nested macro expansion: otherwise, the lint could
392 // trigger in situations that macro authors shouldn't have to care about, e.g.,
393 // when a parenthesized token tree matched in one macro expansion is matched as
394 // an expression in another and used as a fn/method argument (Issue #47775)
395 if e.span.ctxt().outer().expn_info()
396 .map_or(false, |info| info.call_site.ctxt().outer()
397 .expn_info().is_some()) {
400 let msg = format!("{} argument", call_kind);
401 for arg in args_to_check {
402 self.check_unused_parens_expr(cx, arg, &msg, false);
407 self.check_unused_parens_expr(cx, &value, msg, followed_by_block);
410 fn check_pat(&mut self, cx: &EarlyContext<'_>, p: &ast::Pat) {
411 use ast::PatKind::{Paren, Range};
412 // The lint visitor will visit each subpattern of `p`. We do not want to lint any range
413 // pattern no matter where it occurs in the pattern. For something like `&(a..=b)`, there
414 // is a recursive `check_pat` on `a` and `b`, but we will assume that if there are
415 // unnecessary parens they serve a purpose of readability.
416 if let Paren(ref pat) = p.node {
419 _ => self.check_unused_parens_pat(cx, &p, "pattern")
424 fn check_stmt(&mut self, cx: &EarlyContext<'_>, s: &ast::Stmt) {
425 if let ast::StmtKind::Local(ref local) = s.node {
426 if let Some(ref value) = local.init {
427 self.check_unused_parens_expr(cx, &value, "assigned value", false);
434 UNUSED_IMPORT_BRACES,
436 "unnecessary braces around an imported item"
439 declare_lint_pass!(UnusedImportBraces => [UNUSED_IMPORT_BRACES]);
441 impl UnusedImportBraces {
442 fn check_use_tree(&self, cx: &EarlyContext<'_>, use_tree: &ast::UseTree, item: &ast::Item) {
443 if let ast::UseTreeKind::Nested(ref items) = use_tree.kind {
444 // Recursively check nested UseTrees
445 for &(ref tree, _) in items {
446 self.check_use_tree(cx, tree, item);
449 // Trigger the lint only if there is one nested item
450 if items.len() != 1 {
454 // Trigger the lint if the nested item is a non-self single item
456 match items[0].0.kind {
457 ast::UseTreeKind::Simple(rename, ..) => {
458 let orig_ident = items[0].0.prefix.segments.last().unwrap().ident;
459 if orig_ident.name == keywords::SelfLower.name() {
462 node_ident = rename.unwrap_or(orig_ident);
464 ast::UseTreeKind::Glob => {
465 node_ident = ast::Ident::from_str("*");
467 ast::UseTreeKind::Nested(_) => {
472 let msg = format!("braces around {} is unnecessary", node_ident.name);
473 cx.span_lint(UNUSED_IMPORT_BRACES, item.span, &msg);
478 impl EarlyLintPass for UnusedImportBraces {
479 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
480 if let ast::ItemKind::Use(ref use_tree) = item.node {
481 self.check_use_tree(cx, use_tree, item);
487 pub(super) UNUSED_ALLOCATION,
489 "detects unnecessary allocations that can be eliminated"
492 declare_lint_pass!(UnusedAllocation => [UNUSED_ALLOCATION]);
494 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedAllocation {
495 fn check_expr(&mut self, cx: &LateContext<'_, '_>, e: &hir::Expr) {
497 hir::ExprKind::Box(_) => {}
501 for adj in cx.tables.expr_adjustments(e) {
502 if let adjustment::Adjust::Borrow(adjustment::AutoBorrow::Ref(_, m)) = adj.kind {
504 adjustment::AutoBorrowMutability::Immutable =>
505 "unnecessary allocation, use & instead",
506 adjustment::AutoBorrowMutability::Mutable { .. }=>
507 "unnecessary allocation, use &mut instead"
509 cx.span_lint(UNUSED_ALLOCATION, e.span, msg);