]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_lint/src/unused.rs
Add test for eval order for a+=b
[rust.git] / compiler / rustc_lint / src / unused.rs
1 use crate::Lint;
2 use crate::{EarlyContext, EarlyLintPass, LateContext, LateLintPass, LintContext};
3 use rustc_ast as ast;
4 use rustc_ast::util::parser;
5 use rustc_ast::{ExprKind, StmtKind};
6 use rustc_ast_pretty::pprust;
7 use rustc_data_structures::fx::FxHashMap;
8 use rustc_errors::{pluralize, Applicability};
9 use rustc_feature::{AttributeType, BuiltinAttribute, BUILTIN_ATTRIBUTE_MAP};
10 use rustc_hir as hir;
11 use rustc_hir::def::{DefKind, Res};
12 use rustc_hir::def_id::DefId;
13 use rustc_middle::ty::adjustment;
14 use rustc_middle::ty::{self, Ty};
15 use rustc_session::lint::builtin::UNUSED_ATTRIBUTES;
16 use rustc_span::symbol::Symbol;
17 use rustc_span::symbol::{kw, sym};
18 use rustc_span::{BytePos, Span, DUMMY_SP};
19
20 use tracing::debug;
21
22 declare_lint! {
23     /// The `unused_must_use` lint detects unused result of a type flagged as
24     /// `#[must_use]`.
25     ///
26     /// ### Example
27     ///
28     /// ```rust
29     /// fn returns_result() -> Result<(), ()> {
30     ///     Ok(())
31     /// }
32     ///
33     /// fn main() {
34     ///     returns_result();
35     /// }
36     /// ```
37     ///
38     /// {{produces}}
39     ///
40     /// ### Explanation
41     ///
42     /// The `#[must_use]` attribute is an indicator that it is a mistake to
43     /// ignore the value. See [the reference] for more details.
44     ///
45     /// [the reference]: https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-must_use-attribute
46     pub UNUSED_MUST_USE,
47     Warn,
48     "unused result of a type flagged as `#[must_use]`",
49     report_in_external_macro
50 }
51
52 declare_lint! {
53     /// The `unused_results` lint checks for the unused result of an
54     /// expression in a statement.
55     ///
56     /// ### Example
57     ///
58     /// ```rust,compile_fail
59     /// #![deny(unused_results)]
60     /// fn foo<T>() -> T { panic!() }
61     ///
62     /// fn main() {
63     ///     foo::<usize>();
64     /// }
65     /// ```
66     ///
67     /// {{produces}}
68     ///
69     /// ### Explanation
70     ///
71     /// Ignoring the return value of a function may indicate a mistake. In
72     /// cases were it is almost certain that the result should be used, it is
73     /// recommended to annotate the function with the [`must_use` attribute].
74     /// Failure to use such a return value will trigger the [`unused_must_use`
75     /// lint] which is warn-by-default. The `unused_results` lint is
76     /// essentially the same, but triggers for *all* return values.
77     ///
78     /// This lint is "allow" by default because it can be noisy, and may not be
79     /// an actual problem. For example, calling the `remove` method of a `Vec`
80     /// or `HashMap` returns the previous value, which you may not care about.
81     /// Using this lint would require explicitly ignoring or discarding such
82     /// values.
83     ///
84     /// [`must_use` attribute]: https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-must_use-attribute
85     /// [`unused_must_use` lint]: warn-by-default.html#unused-must-use
86     pub UNUSED_RESULTS,
87     Allow,
88     "unused result of an expression in a statement"
89 }
90
91 declare_lint_pass!(UnusedResults => [UNUSED_MUST_USE, UNUSED_RESULTS]);
92
93 impl<'tcx> LateLintPass<'tcx> for UnusedResults {
94     fn check_stmt(&mut self, cx: &LateContext<'_>, s: &hir::Stmt<'_>) {
95         let expr = match s.kind {
96             hir::StmtKind::Semi(ref expr) => &**expr,
97             _ => return,
98         };
99
100         if let hir::ExprKind::Ret(..) = expr.kind {
101             return;
102         }
103
104         let ty = cx.typeck_results().expr_ty(&expr);
105         let type_permits_lack_of_use = check_must_use_ty(cx, ty, &expr, s.span, "", "", 1);
106
107         let mut fn_warned = false;
108         let mut op_warned = false;
109         let maybe_def_id = match expr.kind {
110             hir::ExprKind::Call(ref callee, _) => {
111                 match callee.kind {
112                     hir::ExprKind::Path(ref qpath) => {
113                         match cx.qpath_res(qpath, callee.hir_id) {
114                             Res::Def(DefKind::Fn | DefKind::AssocFn, def_id) => Some(def_id),
115                             // `Res::Local` if it was a closure, for which we
116                             // do not currently support must-use linting
117                             _ => None,
118                         }
119                     }
120                     _ => None,
121                 }
122             }
123             hir::ExprKind::MethodCall(..) => cx.typeck_results().type_dependent_def_id(expr.hir_id),
124             _ => None,
125         };
126         if let Some(def_id) = maybe_def_id {
127             fn_warned = check_must_use_def(cx, def_id, s.span, "return value of ", "");
128         } else if type_permits_lack_of_use {
129             // We don't warn about unused unit or uninhabited types.
130             // (See https://github.com/rust-lang/rust/issues/43806 for details.)
131             return;
132         }
133
134         let must_use_op = match expr.kind {
135             // Hardcoding operators here seemed more expedient than the
136             // refactoring that would be needed to look up the `#[must_use]`
137             // attribute which does exist on the comparison trait methods
138             hir::ExprKind::Binary(bin_op, ..) => match bin_op.node {
139                 hir::BinOpKind::Eq
140                 | hir::BinOpKind::Lt
141                 | hir::BinOpKind::Le
142                 | hir::BinOpKind::Ne
143                 | hir::BinOpKind::Ge
144                 | hir::BinOpKind::Gt => Some("comparison"),
145                 hir::BinOpKind::Add
146                 | hir::BinOpKind::Sub
147                 | hir::BinOpKind::Div
148                 | hir::BinOpKind::Mul
149                 | hir::BinOpKind::Rem => Some("arithmetic operation"),
150                 hir::BinOpKind::And | hir::BinOpKind::Or => Some("logical operation"),
151                 hir::BinOpKind::BitXor
152                 | hir::BinOpKind::BitAnd
153                 | hir::BinOpKind::BitOr
154                 | hir::BinOpKind::Shl
155                 | hir::BinOpKind::Shr => Some("bitwise operation"),
156             },
157             hir::ExprKind::Unary(..) => Some("unary operation"),
158             _ => None,
159         };
160
161         if let Some(must_use_op) = must_use_op {
162             cx.struct_span_lint(UNUSED_MUST_USE, expr.span, |lint| {
163                 lint.build(&format!("unused {} that must be used", must_use_op)).emit()
164             });
165             op_warned = true;
166         }
167
168         if !(type_permits_lack_of_use || fn_warned || op_warned) {
169             cx.struct_span_lint(UNUSED_RESULTS, s.span, |lint| lint.build("unused result").emit());
170         }
171
172         // Returns whether an error has been emitted (and thus another does not need to be later).
173         fn check_must_use_ty<'tcx>(
174             cx: &LateContext<'tcx>,
175             ty: Ty<'tcx>,
176             expr: &hir::Expr<'_>,
177             span: Span,
178             descr_pre: &str,
179             descr_post: &str,
180             plural_len: usize,
181         ) -> bool {
182             if ty.is_unit()
183                 || cx.tcx.is_ty_uninhabited_from(
184                     cx.tcx.parent_module(expr.hir_id).to_def_id(),
185                     ty,
186                     cx.param_env,
187                 )
188             {
189                 return true;
190             }
191
192             let plural_suffix = pluralize!(plural_len);
193
194             match *ty.kind() {
195                 ty::Adt(..) if ty.is_box() => {
196                     let boxed_ty = ty.boxed_ty();
197                     let descr_pre = &format!("{}boxed ", descr_pre);
198                     check_must_use_ty(cx, boxed_ty, expr, span, descr_pre, descr_post, plural_len)
199                 }
200                 ty::Adt(def, _) => check_must_use_def(cx, def.did, span, descr_pre, descr_post),
201                 ty::Opaque(def, _) => {
202                     let mut has_emitted = false;
203                     for &(predicate, _) in cx.tcx.explicit_item_bounds(def) {
204                         // We only look at the `DefId`, so it is safe to skip the binder here.
205                         if let ty::PredicateAtom::Trait(ref poly_trait_predicate, _) =
206                             predicate.skip_binders()
207                         {
208                             let def_id = poly_trait_predicate.trait_ref.def_id;
209                             let descr_pre =
210                                 &format!("{}implementer{} of ", descr_pre, plural_suffix,);
211                             if check_must_use_def(cx, def_id, span, descr_pre, descr_post) {
212                                 has_emitted = true;
213                                 break;
214                             }
215                         }
216                     }
217                     has_emitted
218                 }
219                 ty::Dynamic(binder, _) => {
220                     let mut has_emitted = false;
221                     for predicate in binder.skip_binder().iter() {
222                         if let ty::ExistentialPredicate::Trait(ref trait_ref) = predicate {
223                             let def_id = trait_ref.def_id;
224                             let descr_post =
225                                 &format!(" trait object{}{}", plural_suffix, descr_post,);
226                             if check_must_use_def(cx, def_id, span, descr_pre, descr_post) {
227                                 has_emitted = true;
228                                 break;
229                             }
230                         }
231                     }
232                     has_emitted
233                 }
234                 ty::Tuple(ref tys) => {
235                     let mut has_emitted = false;
236                     let spans = if let hir::ExprKind::Tup(comps) = &expr.kind {
237                         debug_assert_eq!(comps.len(), tys.len());
238                         comps.iter().map(|e| e.span).collect()
239                     } else {
240                         vec![]
241                     };
242                     for (i, ty) in tys.iter().map(|k| k.expect_ty()).enumerate() {
243                         let descr_post = &format!(" in tuple element {}", i);
244                         let span = *spans.get(i).unwrap_or(&span);
245                         if check_must_use_ty(cx, ty, expr, span, descr_pre, descr_post, plural_len)
246                         {
247                             has_emitted = true;
248                         }
249                     }
250                     has_emitted
251                 }
252                 ty::Array(ty, len) => match len.try_eval_usize(cx.tcx, cx.param_env) {
253                     // If the array is empty we don't lint, to avoid false positives
254                     Some(0) | None => false,
255                     // If the array is definitely non-empty, we can do `#[must_use]` checking.
256                     Some(n) => {
257                         let descr_pre = &format!("{}array{} of ", descr_pre, plural_suffix,);
258                         check_must_use_ty(cx, ty, expr, span, descr_pre, descr_post, n as usize + 1)
259                     }
260                 },
261                 ty::Closure(..) => {
262                     cx.struct_span_lint(UNUSED_MUST_USE, span, |lint| {
263                         let mut err = lint.build(&format!(
264                             "unused {}closure{}{} that must be used",
265                             descr_pre, plural_suffix, descr_post,
266                         ));
267                         err.note("closures are lazy and do nothing unless called");
268                         err.emit();
269                     });
270                     true
271                 }
272                 ty::Generator(..) => {
273                     cx.struct_span_lint(UNUSED_MUST_USE, span, |lint| {
274                         let mut err = lint.build(&format!(
275                             "unused {}generator{}{} that must be used",
276                             descr_pre, plural_suffix, descr_post,
277                         ));
278                         err.note("generators are lazy and do nothing unless resumed");
279                         err.emit();
280                     });
281                     true
282                 }
283                 _ => false,
284             }
285         }
286
287         // Returns whether an error has been emitted (and thus another does not need to be later).
288         // FIXME: Args desc_{pre,post}_path could be made lazy by taking Fn() -> &str, but this
289         // would make calling it a big awkward. Could also take String (so args are moved), but
290         // this would still require a copy into the format string, which would only be executed
291         // when needed.
292         fn check_must_use_def(
293             cx: &LateContext<'_>,
294             def_id: DefId,
295             span: Span,
296             descr_pre_path: &str,
297             descr_post_path: &str,
298         ) -> bool {
299             for attr in cx.tcx.get_attrs(def_id).iter() {
300                 if cx.sess().check_name(attr, sym::must_use) {
301                     cx.struct_span_lint(UNUSED_MUST_USE, span, |lint| {
302                         let msg = format!(
303                             "unused {}`{}`{} that must be used",
304                             descr_pre_path,
305                             cx.tcx.def_path_str(def_id),
306                             descr_post_path
307                         );
308                         let mut err = lint.build(&msg);
309                         // check for #[must_use = "..."]
310                         if let Some(note) = attr.value_str() {
311                             err.note(&note.as_str());
312                         }
313                         err.emit();
314                     });
315                     return true;
316                 }
317             }
318             false
319         }
320     }
321 }
322
323 declare_lint! {
324     /// The `path_statements` lint detects path statements with no effect.
325     ///
326     /// ### Example
327     ///
328     /// ```rust
329     /// let x = 42;
330     ///
331     /// x;
332     /// ```
333     ///
334     /// {{produces}}
335     ///
336     /// ### Explanation
337     ///
338     /// It is usually a mistake to have a statement that has no effect.
339     pub PATH_STATEMENTS,
340     Warn,
341     "path statements with no effect"
342 }
343
344 declare_lint_pass!(PathStatements => [PATH_STATEMENTS]);
345
346 impl<'tcx> LateLintPass<'tcx> for PathStatements {
347     fn check_stmt(&mut self, cx: &LateContext<'_>, s: &hir::Stmt<'_>) {
348         if let hir::StmtKind::Semi(expr) = s.kind {
349             if let hir::ExprKind::Path(_) = expr.kind {
350                 cx.struct_span_lint(PATH_STATEMENTS, s.span, |lint| {
351                     let ty = cx.typeck_results().expr_ty(expr);
352                     if ty.needs_drop(cx.tcx, cx.param_env) {
353                         let mut lint = lint.build("path statement drops value");
354                         if let Ok(snippet) = cx.sess().source_map().span_to_snippet(expr.span) {
355                             lint.span_suggestion(
356                                 s.span,
357                                 "use `drop` to clarify the intent",
358                                 format!("drop({});", snippet),
359                                 Applicability::MachineApplicable,
360                             );
361                         } else {
362                             lint.span_help(s.span, "use `drop` to clarify the intent");
363                         }
364                         lint.emit()
365                     } else {
366                         lint.build("path statement with no effect").emit()
367                     }
368                 });
369             }
370         }
371     }
372 }
373
374 #[derive(Copy, Clone)]
375 pub struct UnusedAttributes {
376     builtin_attributes: &'static FxHashMap<Symbol, &'static BuiltinAttribute>,
377 }
378
379 impl UnusedAttributes {
380     pub fn new() -> Self {
381         UnusedAttributes { builtin_attributes: &*BUILTIN_ATTRIBUTE_MAP }
382     }
383 }
384
385 impl_lint_pass!(UnusedAttributes => [UNUSED_ATTRIBUTES]);
386
387 impl<'tcx> LateLintPass<'tcx> for UnusedAttributes {
388     fn check_attribute(&mut self, cx: &LateContext<'_>, attr: &ast::Attribute) {
389         debug!("checking attribute: {:?}", attr);
390
391         if attr.is_doc_comment() {
392             return;
393         }
394
395         let attr_info = attr.ident().and_then(|ident| self.builtin_attributes.get(&ident.name));
396
397         if let Some(&&(name, ty, ..)) = attr_info {
398             if let AttributeType::AssumedUsed = ty {
399                 debug!("{:?} is AssumedUsed", name);
400                 return;
401             }
402         }
403
404         if !cx.sess().is_attr_used(attr) {
405             debug!("emitting warning for: {:?}", attr);
406             cx.struct_span_lint(UNUSED_ATTRIBUTES, attr.span, |lint| {
407                 lint.build("unused attribute").emit()
408             });
409             // Is it a builtin attribute that must be used at the crate level?
410             if attr_info.map_or(false, |(_, ty, ..)| ty == &AttributeType::CrateLevel) {
411                 cx.struct_span_lint(UNUSED_ATTRIBUTES, attr.span, |lint| {
412                     let msg = match attr.style {
413                         ast::AttrStyle::Outer => {
414                             "crate-level attribute should be an inner attribute: add an exclamation \
415                              mark: `#![foo]`"
416                         }
417                         ast::AttrStyle::Inner => "crate-level attribute should be in the root module",
418                     };
419                     lint.build(msg).emit()
420                 });
421             }
422         } else {
423             debug!("Attr was used: {:?}", attr);
424         }
425     }
426 }
427
428 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
429 enum UnusedDelimsCtx {
430     FunctionArg,
431     MethodArg,
432     AssignedValue,
433     IfCond,
434     WhileCond,
435     ForIterExpr,
436     MatchScrutineeExpr,
437     ReturnValue,
438     BlockRetValue,
439     LetScrutineeExpr,
440     ArrayLenExpr,
441     AnonConst,
442 }
443
444 impl From<UnusedDelimsCtx> for &'static str {
445     fn from(ctx: UnusedDelimsCtx) -> &'static str {
446         match ctx {
447             UnusedDelimsCtx::FunctionArg => "function argument",
448             UnusedDelimsCtx::MethodArg => "method argument",
449             UnusedDelimsCtx::AssignedValue => "assigned value",
450             UnusedDelimsCtx::IfCond => "`if` condition",
451             UnusedDelimsCtx::WhileCond => "`while` condition",
452             UnusedDelimsCtx::ForIterExpr => "`for` iterator expression",
453             UnusedDelimsCtx::MatchScrutineeExpr => "`match` scrutinee expression",
454             UnusedDelimsCtx::ReturnValue => "`return` value",
455             UnusedDelimsCtx::BlockRetValue => "block return value",
456             UnusedDelimsCtx::LetScrutineeExpr => "`let` scrutinee expression",
457             UnusedDelimsCtx::ArrayLenExpr | UnusedDelimsCtx::AnonConst => "const expression",
458         }
459     }
460 }
461
462 /// Used by both `UnusedParens` and `UnusedBraces` to prevent code duplication.
463 trait UnusedDelimLint {
464     const DELIM_STR: &'static str;
465
466     /// Due to `ref` pattern, there can be a difference between using
467     /// `{ expr }` and `expr` in pattern-matching contexts. This means
468     /// that we should only lint `unused_parens` and not `unused_braces`
469     /// in this case.
470     ///
471     /// ```rust
472     /// let mut a = 7;
473     /// let ref b = { a }; // We actually borrow a copy of `a` here.
474     /// a += 1; // By mutating `a` we invalidate any borrows of `a`.
475     /// assert_eq!(b + 1, a); // `b` does not borrow `a`, so we can still use it here.
476     /// ```
477     const LINT_EXPR_IN_PATTERN_MATCHING_CTX: bool;
478
479     // this cannot be a constant is it refers to a static.
480     fn lint(&self) -> &'static Lint;
481
482     fn check_unused_delims_expr(
483         &self,
484         cx: &EarlyContext<'_>,
485         value: &ast::Expr,
486         ctx: UnusedDelimsCtx,
487         followed_by_block: bool,
488         left_pos: Option<BytePos>,
489         right_pos: Option<BytePos>,
490     );
491
492     fn is_expr_delims_necessary(inner: &ast::Expr, followed_by_block: bool) -> bool {
493         // Prevent false-positives in cases like `fn x() -> u8 { ({ 0 } + 1) }`
494         let lhs_needs_parens = {
495             let mut innermost = inner;
496             loop {
497                 if let ExprKind::Binary(_, lhs, _rhs) = &innermost.kind {
498                     innermost = lhs;
499                     if !rustc_ast::util::classify::expr_requires_semi_to_be_stmt(innermost) {
500                         break true;
501                     }
502                 } else {
503                     break false;
504                 }
505             }
506         };
507
508         lhs_needs_parens
509             || (followed_by_block
510                 && match inner.kind {
511                     ExprKind::Ret(_) | ExprKind::Break(..) | ExprKind::Yield(..) => true,
512                     _ => parser::contains_exterior_struct_lit(&inner),
513                 })
514     }
515
516     fn emit_unused_delims_expr(
517         &self,
518         cx: &EarlyContext<'_>,
519         value: &ast::Expr,
520         ctx: UnusedDelimsCtx,
521         left_pos: Option<BytePos>,
522         right_pos: Option<BytePos>,
523     ) {
524         let expr_text = if let Ok(snippet) = cx.sess().source_map().span_to_snippet(value.span) {
525             snippet
526         } else {
527             pprust::expr_to_string(value)
528         };
529         let keep_space = (
530             left_pos.map(|s| s >= value.span.lo()).unwrap_or(false),
531             right_pos.map(|s| s <= value.span.hi()).unwrap_or(false),
532         );
533         self.emit_unused_delims(cx, value.span, &expr_text, ctx.into(), keep_space);
534     }
535
536     fn emit_unused_delims(
537         &self,
538         cx: &EarlyContext<'_>,
539         span: Span,
540         pattern: &str,
541         msg: &str,
542         keep_space: (bool, bool),
543     ) {
544         // FIXME(flip1995): Quick and dirty fix for #70814. This should be fixed in rustdoc
545         // properly.
546         if span == DUMMY_SP {
547             return;
548         }
549
550         cx.struct_span_lint(self.lint(), span, |lint| {
551             let span_msg = format!("unnecessary {} around {}", Self::DELIM_STR, msg);
552             let mut err = lint.build(&span_msg);
553             let mut ate_left_paren = false;
554             let mut ate_right_paren = false;
555             let parens_removed = pattern
556                 .trim_matches(|c| match c {
557                     '(' | '{' => {
558                         if ate_left_paren {
559                             false
560                         } else {
561                             ate_left_paren = true;
562                             true
563                         }
564                     }
565                     ')' | '}' => {
566                         if ate_right_paren {
567                             false
568                         } else {
569                             ate_right_paren = true;
570                             true
571                         }
572                     }
573                     _ => false,
574                 })
575                 .trim();
576
577             let replace = {
578                 let mut replace = if keep_space.0 {
579                     let mut s = String::from(" ");
580                     s.push_str(parens_removed);
581                     s
582                 } else {
583                     String::from(parens_removed)
584                 };
585
586                 if keep_space.1 {
587                     replace.push(' ');
588                 }
589                 replace
590             };
591
592             let suggestion = format!("remove these {}", Self::DELIM_STR);
593
594             err.span_suggestion_short(span, &suggestion, replace, Applicability::MachineApplicable);
595             err.emit();
596         });
597     }
598
599     fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
600         use rustc_ast::ExprKind::*;
601         let (value, ctx, followed_by_block, left_pos, right_pos) = match e.kind {
602             // Do not lint `unused_braces` in `if let` expressions.
603             If(ref cond, ref block, ..)
604                 if !matches!(cond.kind, Let(_, _)) || Self::LINT_EXPR_IN_PATTERN_MATCHING_CTX =>
605             {
606                 let left = e.span.lo() + rustc_span::BytePos(2);
607                 let right = block.span.lo();
608                 (cond, UnusedDelimsCtx::IfCond, true, Some(left), Some(right))
609             }
610
611             // Do not lint `unused_braces` in `while let` expressions.
612             While(ref cond, ref block, ..)
613                 if !matches!(cond.kind, Let(_, _)) || Self::LINT_EXPR_IN_PATTERN_MATCHING_CTX =>
614             {
615                 let left = e.span.lo() + rustc_span::BytePos(5);
616                 let right = block.span.lo();
617                 (cond, UnusedDelimsCtx::WhileCond, true, Some(left), Some(right))
618             }
619
620             ForLoop(_, ref cond, ref block, ..) => {
621                 (cond, UnusedDelimsCtx::ForIterExpr, true, None, Some(block.span.lo()))
622             }
623
624             Match(ref head, _) if Self::LINT_EXPR_IN_PATTERN_MATCHING_CTX => {
625                 let left = e.span.lo() + rustc_span::BytePos(5);
626                 (head, UnusedDelimsCtx::MatchScrutineeExpr, true, Some(left), None)
627             }
628
629             Ret(Some(ref value)) => {
630                 let left = e.span.lo() + rustc_span::BytePos(3);
631                 (value, UnusedDelimsCtx::ReturnValue, false, Some(left), None)
632             }
633
634             Assign(_, ref value, _) | AssignOp(.., ref value) => {
635                 (value, UnusedDelimsCtx::AssignedValue, false, None, None)
636             }
637             // either function/method call, or something this lint doesn't care about
638             ref call_or_other => {
639                 let (args_to_check, ctx) = match *call_or_other {
640                     Call(_, ref args) => (&args[..], UnusedDelimsCtx::FunctionArg),
641                     // first "argument" is self (which sometimes needs delims)
642                     MethodCall(_, ref args, _) => (&args[1..], UnusedDelimsCtx::MethodArg),
643                     // actual catch-all arm
644                     _ => {
645                         return;
646                     }
647                 };
648                 // Don't lint if this is a nested macro expansion: otherwise, the lint could
649                 // trigger in situations that macro authors shouldn't have to care about, e.g.,
650                 // when a parenthesized token tree matched in one macro expansion is matched as
651                 // an expression in another and used as a fn/method argument (Issue #47775)
652                 if e.span.ctxt().outer_expn_data().call_site.from_expansion() {
653                     return;
654                 }
655                 for arg in args_to_check {
656                     self.check_unused_delims_expr(cx, arg, ctx, false, None, None);
657                 }
658                 return;
659             }
660         };
661         self.check_unused_delims_expr(cx, &value, ctx, followed_by_block, left_pos, right_pos);
662     }
663
664     fn check_stmt(&mut self, cx: &EarlyContext<'_>, s: &ast::Stmt) {
665         match s.kind {
666             StmtKind::Local(ref local) if Self::LINT_EXPR_IN_PATTERN_MATCHING_CTX => {
667                 if let Some(ref value) = local.init {
668                     self.check_unused_delims_expr(
669                         cx,
670                         &value,
671                         UnusedDelimsCtx::AssignedValue,
672                         false,
673                         None,
674                         None,
675                     );
676                 }
677             }
678             StmtKind::Expr(ref expr) => {
679                 self.check_unused_delims_expr(
680                     cx,
681                     &expr,
682                     UnusedDelimsCtx::BlockRetValue,
683                     false,
684                     None,
685                     None,
686                 );
687             }
688             _ => {}
689         }
690     }
691
692     fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
693         use ast::ItemKind::*;
694
695         if let Const(.., Some(expr)) | Static(.., Some(expr)) = &item.kind {
696             self.check_unused_delims_expr(
697                 cx,
698                 expr,
699                 UnusedDelimsCtx::AssignedValue,
700                 false,
701                 None,
702                 None,
703             );
704         }
705     }
706 }
707
708 declare_lint! {
709     /// The `unused_parens` lint detects `if`, `match`, `while` and `return`
710     /// with parentheses; they do not need them.
711     ///
712     /// ### Examples
713     ///
714     /// ```rust
715     /// if(true) {}
716     /// ```
717     ///
718     /// {{produces}}
719     ///
720     /// ### Explanation
721     ///
722     /// The parenthesis are not needed, and should be removed. This is the
723     /// preferred style for writing these expressions.
724     pub(super) UNUSED_PARENS,
725     Warn,
726     "`if`, `match`, `while` and `return` do not need parentheses"
727 }
728
729 declare_lint_pass!(UnusedParens => [UNUSED_PARENS]);
730
731 impl UnusedDelimLint for UnusedParens {
732     const DELIM_STR: &'static str = "parentheses";
733
734     const LINT_EXPR_IN_PATTERN_MATCHING_CTX: bool = true;
735
736     fn lint(&self) -> &'static Lint {
737         UNUSED_PARENS
738     }
739
740     fn check_unused_delims_expr(
741         &self,
742         cx: &EarlyContext<'_>,
743         value: &ast::Expr,
744         ctx: UnusedDelimsCtx,
745         followed_by_block: bool,
746         left_pos: Option<BytePos>,
747         right_pos: Option<BytePos>,
748     ) {
749         match value.kind {
750             ast::ExprKind::Paren(ref inner) => {
751                 if !Self::is_expr_delims_necessary(inner, followed_by_block)
752                     && value.attrs.is_empty()
753                     && !value.span.from_expansion()
754                     && (ctx != UnusedDelimsCtx::LetScrutineeExpr
755                         || !matches!(inner.kind, ast::ExprKind::Binary(
756                                 rustc_span::source_map::Spanned { node, .. },
757                                 _,
758                                 _,
759                             ) if node.lazy()))
760                 {
761                     self.emit_unused_delims_expr(cx, value, ctx, left_pos, right_pos)
762                 }
763             }
764             ast::ExprKind::Let(_, ref expr) => {
765                 self.check_unused_delims_expr(
766                     cx,
767                     expr,
768                     UnusedDelimsCtx::LetScrutineeExpr,
769                     followed_by_block,
770                     None,
771                     None,
772                 );
773             }
774             _ => {}
775         }
776     }
777 }
778
779 impl UnusedParens {
780     fn check_unused_parens_pat(
781         &self,
782         cx: &EarlyContext<'_>,
783         value: &ast::Pat,
784         avoid_or: bool,
785         avoid_mut: bool,
786     ) {
787         use ast::{BindingMode, Mutability, PatKind};
788
789         if let PatKind::Paren(inner) = &value.kind {
790             match inner.kind {
791                 // The lint visitor will visit each subpattern of `p`. We do not want to lint
792                 // any range pattern no matter where it occurs in the pattern. For something like
793                 // `&(a..=b)`, there is a recursive `check_pat` on `a` and `b`, but we will assume
794                 // that if there are unnecessary parens they serve a purpose of readability.
795                 PatKind::Range(..) => return,
796                 // Avoid `p0 | .. | pn` if we should.
797                 PatKind::Or(..) if avoid_or => return,
798                 // Avoid `mut x` and `mut x @ p` if we should:
799                 PatKind::Ident(BindingMode::ByValue(Mutability::Mut), ..) if avoid_mut => return,
800                 // Otherwise proceed with linting.
801                 _ => {}
802             }
803
804             let pattern_text =
805                 if let Ok(snippet) = cx.sess().source_map().span_to_snippet(value.span) {
806                     snippet
807                 } else {
808                     pprust::pat_to_string(value)
809                 };
810             self.emit_unused_delims(cx, value.span, &pattern_text, "pattern", (false, false));
811         }
812     }
813 }
814
815 impl EarlyLintPass for UnusedParens {
816     fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
817         if let ExprKind::Let(ref pat, ..) | ExprKind::ForLoop(ref pat, ..) = e.kind {
818             self.check_unused_parens_pat(cx, pat, false, false);
819         }
820
821         <Self as UnusedDelimLint>::check_expr(self, cx, e)
822     }
823
824     fn check_pat(&mut self, cx: &EarlyContext<'_>, p: &ast::Pat) {
825         use ast::{Mutability, PatKind::*};
826         match &p.kind {
827             // Do not lint on `(..)` as that will result in the other arms being useless.
828             Paren(_)
829             // The other cases do not contain sub-patterns.
830             | Wild | Rest | Lit(..) | MacCall(..) | Range(..) | Ident(.., None) | Path(..) => {},
831             // These are list-like patterns; parens can always be removed.
832             TupleStruct(_, ps) | Tuple(ps) | Slice(ps) | Or(ps) => for p in ps {
833                 self.check_unused_parens_pat(cx, p, false, false);
834             },
835             Struct(_, fps, _) => for f in fps {
836                 self.check_unused_parens_pat(cx, &f.pat, false, false);
837             },
838             // Avoid linting on `i @ (p0 | .. | pn)` and `box (p0 | .. | pn)`, #64106.
839             Ident(.., Some(p)) | Box(p) => self.check_unused_parens_pat(cx, p, true, false),
840             // Avoid linting on `&(mut x)` as `&mut x` has a different meaning, #55342.
841             // Also avoid linting on `& mut? (p0 | .. | pn)`, #64106.
842             Ref(p, m) => self.check_unused_parens_pat(cx, p, true, *m == Mutability::Not),
843         }
844     }
845
846     fn check_stmt(&mut self, cx: &EarlyContext<'_>, s: &ast::Stmt) {
847         if let StmtKind::Local(ref local) = s.kind {
848             self.check_unused_parens_pat(cx, &local.pat, false, false);
849         }
850
851         <Self as UnusedDelimLint>::check_stmt(self, cx, s)
852     }
853
854     fn check_param(&mut self, cx: &EarlyContext<'_>, param: &ast::Param) {
855         self.check_unused_parens_pat(cx, &param.pat, true, false);
856     }
857
858     fn check_arm(&mut self, cx: &EarlyContext<'_>, arm: &ast::Arm) {
859         self.check_unused_parens_pat(cx, &arm.pat, false, false);
860     }
861
862     fn check_ty(&mut self, cx: &EarlyContext<'_>, ty: &ast::Ty) {
863         if let &ast::TyKind::Paren(ref r) = &ty.kind {
864             match &r.kind {
865                 &ast::TyKind::TraitObject(..) => {}
866                 &ast::TyKind::ImplTrait(_, ref bounds) if bounds.len() > 1 => {}
867                 &ast::TyKind::Array(_, ref len) => {
868                     self.check_unused_delims_expr(
869                         cx,
870                         &len.value,
871                         UnusedDelimsCtx::ArrayLenExpr,
872                         false,
873                         None,
874                         None,
875                     );
876                 }
877                 _ => {
878                     let pattern_text =
879                         if let Ok(snippet) = cx.sess().source_map().span_to_snippet(ty.span) {
880                             snippet
881                         } else {
882                             pprust::ty_to_string(ty)
883                         };
884
885                     self.emit_unused_delims(cx, ty.span, &pattern_text, "type", (false, false));
886                 }
887             }
888         }
889     }
890
891     fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
892         <Self as UnusedDelimLint>::check_item(self, cx, item)
893     }
894 }
895
896 declare_lint! {
897     /// The `unused_braces` lint detects unnecessary braces around an
898     /// expression.
899     ///
900     /// ### Example
901     ///
902     /// ```rust
903     /// if { true } {
904     ///     // ...
905     /// }
906     /// ```
907     ///
908     /// {{produces}}
909     ///
910     /// ### Explanation
911     ///
912     /// The braces are not needed, and should be removed. This is the
913     /// preferred style for writing these expressions.
914     pub(super) UNUSED_BRACES,
915     Warn,
916     "unnecessary braces around an expression"
917 }
918
919 declare_lint_pass!(UnusedBraces => [UNUSED_BRACES]);
920
921 impl UnusedDelimLint for UnusedBraces {
922     const DELIM_STR: &'static str = "braces";
923
924     const LINT_EXPR_IN_PATTERN_MATCHING_CTX: bool = false;
925
926     fn lint(&self) -> &'static Lint {
927         UNUSED_BRACES
928     }
929
930     fn check_unused_delims_expr(
931         &self,
932         cx: &EarlyContext<'_>,
933         value: &ast::Expr,
934         ctx: UnusedDelimsCtx,
935         followed_by_block: bool,
936         left_pos: Option<BytePos>,
937         right_pos: Option<BytePos>,
938     ) {
939         match value.kind {
940             ast::ExprKind::Block(ref inner, None)
941                 if inner.rules == ast::BlockCheckMode::Default =>
942             {
943                 // emit a warning under the following conditions:
944                 //
945                 // - the block does not have a label
946                 // - the block is not `unsafe`
947                 // - the block contains exactly one expression (do not lint `{ expr; }`)
948                 // - `followed_by_block` is true and the internal expr may contain a `{`
949                 // - the block is not multiline (do not lint multiline match arms)
950                 //      ```
951                 //      match expr {
952                 //          Pattern => {
953                 //              somewhat_long_expression
954                 //          }
955                 //          // ...
956                 //      }
957                 //      ```
958                 // - the block has no attribute and was not created inside a macro
959                 // - if the block is an `anon_const`, the inner expr must be a literal
960                 //      (do not lint `struct A<const N: usize>; let _: A<{ 2 + 3 }>;`)
961                 //
962                 // FIXME(const_generics): handle paths when #67075 is fixed.
963                 if let [stmt] = inner.stmts.as_slice() {
964                     if let ast::StmtKind::Expr(ref expr) = stmt.kind {
965                         if !Self::is_expr_delims_necessary(expr, followed_by_block)
966                             && (ctx != UnusedDelimsCtx::AnonConst
967                                 || matches!(expr.kind, ast::ExprKind::Lit(_)))
968                             && !cx.sess().source_map().is_multiline(value.span)
969                             && value.attrs.is_empty()
970                             && !value.span.from_expansion()
971                         {
972                             self.emit_unused_delims_expr(cx, value, ctx, left_pos, right_pos)
973                         }
974                     }
975                 }
976             }
977             ast::ExprKind::Let(_, ref expr) => {
978                 // FIXME(#60336): Properly handle `let true = (false && true)`
979                 // actually needing the parenthesis.
980                 self.check_unused_delims_expr(
981                     cx,
982                     expr,
983                     UnusedDelimsCtx::LetScrutineeExpr,
984                     followed_by_block,
985                     None,
986                     None,
987                 );
988             }
989             _ => {}
990         }
991     }
992 }
993
994 impl EarlyLintPass for UnusedBraces {
995     fn check_stmt(&mut self, cx: &EarlyContext<'_>, s: &ast::Stmt) {
996         <Self as UnusedDelimLint>::check_stmt(self, cx, s)
997     }
998
999     fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
1000         <Self as UnusedDelimLint>::check_expr(self, cx, e);
1001
1002         if let ExprKind::Repeat(_, ref anon_const) = e.kind {
1003             self.check_unused_delims_expr(
1004                 cx,
1005                 &anon_const.value,
1006                 UnusedDelimsCtx::AnonConst,
1007                 false,
1008                 None,
1009                 None,
1010             );
1011         }
1012     }
1013
1014     fn check_generic_arg(&mut self, cx: &EarlyContext<'_>, arg: &ast::GenericArg) {
1015         if let ast::GenericArg::Const(ct) = arg {
1016             self.check_unused_delims_expr(
1017                 cx,
1018                 &ct.value,
1019                 UnusedDelimsCtx::AnonConst,
1020                 false,
1021                 None,
1022                 None,
1023             );
1024         }
1025     }
1026
1027     fn check_variant(&mut self, cx: &EarlyContext<'_>, v: &ast::Variant) {
1028         if let Some(anon_const) = &v.disr_expr {
1029             self.check_unused_delims_expr(
1030                 cx,
1031                 &anon_const.value,
1032                 UnusedDelimsCtx::AnonConst,
1033                 false,
1034                 None,
1035                 None,
1036             );
1037         }
1038     }
1039
1040     fn check_ty(&mut self, cx: &EarlyContext<'_>, ty: &ast::Ty) {
1041         match ty.kind {
1042             ast::TyKind::Array(_, ref len) => {
1043                 self.check_unused_delims_expr(
1044                     cx,
1045                     &len.value,
1046                     UnusedDelimsCtx::ArrayLenExpr,
1047                     false,
1048                     None,
1049                     None,
1050                 );
1051             }
1052
1053             ast::TyKind::Typeof(ref anon_const) => {
1054                 self.check_unused_delims_expr(
1055                     cx,
1056                     &anon_const.value,
1057                     UnusedDelimsCtx::AnonConst,
1058                     false,
1059                     None,
1060                     None,
1061                 );
1062             }
1063
1064             _ => {}
1065         }
1066     }
1067
1068     fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
1069         <Self as UnusedDelimLint>::check_item(self, cx, item)
1070     }
1071 }
1072
1073 declare_lint! {
1074     /// The `unused_import_braces` lint catches unnecessary braces around an
1075     /// imported item.
1076     ///
1077     /// ### Example
1078     ///
1079     /// ```rust,compile_fail
1080     /// #![deny(unused_import_braces)]
1081     /// use test::{A};
1082     ///
1083     /// pub mod test {
1084     ///     pub struct A;
1085     /// }
1086     /// # fn main() {}
1087     /// ```
1088     ///
1089     /// {{produces}}
1090     ///
1091     /// ### Explanation
1092     ///
1093     /// If there is only a single item, then remove the braces (`use test::A;`
1094     /// for example).
1095     ///
1096     /// This lint is "allow" by default because it is only enforcing a
1097     /// stylistic choice.
1098     UNUSED_IMPORT_BRACES,
1099     Allow,
1100     "unnecessary braces around an imported item"
1101 }
1102
1103 declare_lint_pass!(UnusedImportBraces => [UNUSED_IMPORT_BRACES]);
1104
1105 impl UnusedImportBraces {
1106     fn check_use_tree(&self, cx: &EarlyContext<'_>, use_tree: &ast::UseTree, item: &ast::Item) {
1107         if let ast::UseTreeKind::Nested(ref items) = use_tree.kind {
1108             // Recursively check nested UseTrees
1109             for &(ref tree, _) in items {
1110                 self.check_use_tree(cx, tree, item);
1111             }
1112
1113             // Trigger the lint only if there is one nested item
1114             if items.len() != 1 {
1115                 return;
1116             }
1117
1118             // Trigger the lint if the nested item is a non-self single item
1119             let node_name = match items[0].0.kind {
1120                 ast::UseTreeKind::Simple(rename, ..) => {
1121                     let orig_ident = items[0].0.prefix.segments.last().unwrap().ident;
1122                     if orig_ident.name == kw::SelfLower {
1123                         return;
1124                     }
1125                     rename.unwrap_or(orig_ident).name
1126                 }
1127                 ast::UseTreeKind::Glob => Symbol::intern("*"),
1128                 ast::UseTreeKind::Nested(_) => return,
1129             };
1130
1131             cx.struct_span_lint(UNUSED_IMPORT_BRACES, item.span, |lint| {
1132                 lint.build(&format!("braces around {} is unnecessary", node_name)).emit()
1133             });
1134         }
1135     }
1136 }
1137
1138 impl EarlyLintPass for UnusedImportBraces {
1139     fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
1140         if let ast::ItemKind::Use(ref use_tree) = item.kind {
1141             self.check_use_tree(cx, use_tree, item);
1142         }
1143     }
1144 }
1145
1146 declare_lint! {
1147     /// The `unused_allocation` lint detects unnecessary allocations that can
1148     /// be eliminated.
1149     ///
1150     /// ### Example
1151     ///
1152     /// ```rust
1153     /// #![feature(box_syntax)]
1154     /// fn main() {
1155     ///     let a = (box [1,2,3]).len();
1156     /// }
1157     /// ```
1158     ///
1159     /// {{produces}}
1160     ///
1161     /// ### Explanation
1162     ///
1163     /// When a `box` expression is immediately coerced to a reference, then
1164     /// the allocation is unnecessary, and a reference (using `&` or `&mut`)
1165     /// should be used instead to avoid the allocation.
1166     pub(super) UNUSED_ALLOCATION,
1167     Warn,
1168     "detects unnecessary allocations that can be eliminated"
1169 }
1170
1171 declare_lint_pass!(UnusedAllocation => [UNUSED_ALLOCATION]);
1172
1173 impl<'tcx> LateLintPass<'tcx> for UnusedAllocation {
1174     fn check_expr(&mut self, cx: &LateContext<'_>, e: &hir::Expr<'_>) {
1175         match e.kind {
1176             hir::ExprKind::Box(_) => {}
1177             _ => return,
1178         }
1179
1180         for adj in cx.typeck_results().expr_adjustments(e) {
1181             if let adjustment::Adjust::Borrow(adjustment::AutoBorrow::Ref(_, m)) = adj.kind {
1182                 cx.struct_span_lint(UNUSED_ALLOCATION, e.span, |lint| {
1183                     let msg = match m {
1184                         adjustment::AutoBorrowMutability::Not => {
1185                             "unnecessary allocation, use `&` instead"
1186                         }
1187                         adjustment::AutoBorrowMutability::Mut { .. } => {
1188                             "unnecessary allocation, use `&mut` instead"
1189                         }
1190                     };
1191                     lint.build(msg).emit()
1192                 });
1193             }
1194         }
1195     }
1196 }