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