Skip to main content

rustc_lint/
unused.rs

1use rustc_ast::util::{classify, parser};
2use rustc_ast::{self as ast, ExprKind, FnRetTy, ForLoop, HasAttrs as _, StmtKind};
3use rustc_data_structures::fx::FxHashMap;
4use rustc_errors::MultiSpan;
5use rustc_hir as hir;
6use rustc_lint_defs::{declare_lint, declare_lint_pass, impl_lint_pass};
7use rustc_middle::ty::{self, adjustment};
8use rustc_span::edition::Edition::Edition2015;
9use rustc_span::{BytePos, Span, kw, sym};
10
11use crate::diagnostics::{
12    PathStatementDrop, PathStatementDropSub, PathStatementNoEffect, UnusedAllocationDiag,
13    UnusedAllocationMutDiag, UnusedDelim, UnusedDelimSuggestion, UnusedImportBracesDiag,
14};
15use crate::{EarlyContext, EarlyLintPass, LateContext, LateLintPass, Lint, LintContext};
16
17pub mod must_use;
18
19#[doc =
r" The `path_statements` lint detects path statements with no effect."]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust"]
#[doc = r" let x = 42;"]
#[doc = r""]
#[doc = r" x;"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc = r" It is usually a mistake to have a statement that has no effect."]
pub static PATH_STATEMENTS: &::rustc_lint_defs::Lint =
    &::rustc_lint_defs::Lint {
            name: "PATH_STATEMENTS",
            default_level: ::rustc_lint_defs::Warn,
            desc: "path statements with no effect",
            ..
        };declare_lint! {
20    /// The `path_statements` lint detects path statements with no effect.
21    ///
22    /// ### Example
23    ///
24    /// ```rust
25    /// let x = 42;
26    ///
27    /// x;
28    /// ```
29    ///
30    /// {{produces}}
31    ///
32    /// ### Explanation
33    ///
34    /// It is usually a mistake to have a statement that has no effect.
35    pub PATH_STATEMENTS,
36    Warn,
37    "path statements with no effect"
38}
39
40pub struct PathStatements;
#[automatically_derived]impl ::core::marker::Copy for PathStatements { }
#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for PathStatements {
}
#[automatically_derived]impl ::core::clone::Clone for PathStatements {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self { *self }
}
impl ::rustc_lint_defs::LintPass for PathStatements {
    fn name(&self) -> &'static str { "PathStatements" }
    fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [PATH_STATEMENTS]))
    }
}
impl PathStatements {
    #[allow(unused)]
    pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [PATH_STATEMENTS]))
    }
}declare_lint_pass!(PathStatements => [PATH_STATEMENTS]);
41
42impl<'tcx> LateLintPass<'tcx> for PathStatements {
43    fn check_stmt(&mut self, cx: &LateContext<'_>, s: &hir::Stmt<'_>) {
44        if let hir::StmtKind::Semi(expr) = s.kind
45            && let hir::ExprKind::Path(_) = expr.kind
46        {
47            let ty = cx.typeck_results().expr_ty(expr);
48            if ty.needs_drop(cx.tcx, cx.typing_env()) {
49                let sub = if let Ok(snippet) = cx.sess().source_map().span_to_snippet(expr.span) {
50                    PathStatementDropSub::Suggestion { span: s.span, snippet }
51                } else {
52                    PathStatementDropSub::Help { span: s.span }
53                };
54                cx.emit_span_lint(PATH_STATEMENTS, s.span, PathStatementDrop { sub })
55            } else {
56                cx.emit_span_lint(PATH_STATEMENTS, s.span, PathStatementNoEffect);
57            }
58        }
59    }
60}
61
62#[derive(#[automatically_derived]impl ::core::marker::Copy for UnusedDelimsCtx { }Copy, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for UnusedDelimsCtx {
}
#[automatically_derived]impl ::core::clone::Clone for UnusedDelimsCtx {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::fmt::Debug for UnusedDelimsCtx {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_c_like_enum_write_str(f,
            "FunctionArg MethodArg AssignedValue AssignedValueLetElse IfCond WhileCond ForIterExpr MatchScrutineeExpr ReturnValue BlockRetValue BreakValue LetScrutineeExpr ArrayLenExpr AnonConst MatchArmExpr IndexExpr ClosureBody",
            match self {
                UnusedDelimsCtx::FunctionArg => 0usize,
                UnusedDelimsCtx::MethodArg => 12usize,
                UnusedDelimsCtx::AssignedValue => 22usize,
                UnusedDelimsCtx::AssignedValueLetElse => 36usize,
                UnusedDelimsCtx::IfCond => 57usize,
                UnusedDelimsCtx::WhileCond => 64usize,
                UnusedDelimsCtx::ForIterExpr => 74usize,
                UnusedDelimsCtx::MatchScrutineeExpr => 86usize,
                UnusedDelimsCtx::ReturnValue => 105usize,
                UnusedDelimsCtx::BlockRetValue => 117usize,
                UnusedDelimsCtx::BreakValue => 131usize,
                UnusedDelimsCtx::LetScrutineeExpr => 142usize,
                UnusedDelimsCtx::ArrayLenExpr => 159usize,
                UnusedDelimsCtx::AnonConst => 172usize,
                UnusedDelimsCtx::MatchArmExpr => 182usize,
                UnusedDelimsCtx::IndexExpr => 195usize,
                UnusedDelimsCtx::ClosureBody => 205usize,
            })
    }
}Debug, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
    UnusedDelimsCtx {
}
#[automatically_derived]impl ::core::cmp::PartialEq for UnusedDelimsCtx {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
            ::core::intrinsics::discriminant_value(other)
    }
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for UnusedDelimsCtx { }Eq)]
63enum UnusedDelimsCtx {
64    FunctionArg,
65    MethodArg,
66    AssignedValue,
67    AssignedValueLetElse,
68    IfCond,
69    WhileCond,
70    ForIterExpr,
71    MatchScrutineeExpr,
72    ReturnValue,
73    BlockRetValue,
74    BreakValue,
75    LetScrutineeExpr,
76    ArrayLenExpr,
77    AnonConst,
78    MatchArmExpr,
79    IndexExpr,
80    ClosureBody,
81}
82
83impl From<UnusedDelimsCtx> for &'static str {
84    fn from(ctx: UnusedDelimsCtx) -> &'static str {
85        match ctx {
86            UnusedDelimsCtx::FunctionArg => "function argument",
87            UnusedDelimsCtx::MethodArg => "method argument",
88            UnusedDelimsCtx::AssignedValue | UnusedDelimsCtx::AssignedValueLetElse => {
89                "assigned value"
90            }
91            UnusedDelimsCtx::IfCond => "`if` condition",
92            UnusedDelimsCtx::WhileCond => "`while` condition",
93            UnusedDelimsCtx::ForIterExpr => "`for` iterator expression",
94            UnusedDelimsCtx::MatchScrutineeExpr => "`match` scrutinee expression",
95            UnusedDelimsCtx::ReturnValue => "`return` value",
96            UnusedDelimsCtx::BlockRetValue => "block return value",
97            UnusedDelimsCtx::BreakValue => "`break` value",
98            UnusedDelimsCtx::LetScrutineeExpr => "`let` scrutinee expression",
99            UnusedDelimsCtx::ArrayLenExpr | UnusedDelimsCtx::AnonConst => "const expression",
100            UnusedDelimsCtx::MatchArmExpr => "match arm expression",
101            UnusedDelimsCtx::IndexExpr => "index expression",
102            UnusedDelimsCtx::ClosureBody => "closure body",
103        }
104    }
105}
106
107/// Used by both `UnusedParens` and `UnusedBraces` to prevent code duplication.
108trait UnusedDelimLint {
109    const DELIM_STR: &'static str;
110
111    /// Due to `ref` pattern, there can be a difference between using
112    /// `{ expr }` and `expr` in pattern-matching contexts. This means
113    /// that we should only lint `unused_parens` and not `unused_braces`
114    /// in this case.
115    ///
116    /// ```rust
117    /// let mut a = 7;
118    /// let ref b = { a }; // We actually borrow a copy of `a` here.
119    /// a += 1; // By mutating `a` we invalidate any borrows of `a`.
120    /// assert_eq!(b + 1, a); // `b` does not borrow `a`, so we can still use it here.
121    /// ```
122    const LINT_EXPR_IN_PATTERN_MATCHING_CTX: bool;
123
124    // this cannot be a constant is it refers to a static.
125    fn lint(&self) -> &'static Lint;
126
127    fn check_unused_delims_expr(
128        &self,
129        cx: &EarlyContext<'_>,
130        value: &ast::Expr,
131        ctx: UnusedDelimsCtx,
132        followed_by_block: bool,
133        left_pos: Option<BytePos>,
134        right_pos: Option<BytePos>,
135        is_kw: bool,
136    );
137
138    /// Returns whether the outer braces of a single-expression function/method
139    /// argument block can be removed.
140    ///
141    /// In Rust 2024, `{ expr }` can drop tail-expression temporaries before the
142    /// call starts. Removing the block may extend those temporaries, so lint only
143    /// expression forms that are harmless here.
144    fn expr_allows_remove_arg_block(expr: &ast::Expr) -> bool {
145        use ast::ExprKind::*;
146
147        match &expr.peel_parens().kind {
148            Lit(_) | IncludedBytes(_) | Path(..) => true,
149            Unary(_, expr)
150            | Cast(expr, _)
151            | Type(expr, _)
152            | Use(expr, _)
153            | Await(expr, _)
154            | Try(expr)
155            | Move(expr, _)
156            | AddrOf(_, _, expr)
157            | RawHandle(expr)
158            | UnsafeBinderCast(_, expr, _) => Self::expr_allows_remove_arg_block(expr),
159            Array(exprs) | Tup(exprs) => {
160                exprs.iter().all(|expr| Self::expr_allows_remove_arg_block(expr))
161            }
162            Binary(_, lhs, rhs) | Assign(lhs, rhs, _) | AssignOp(_, lhs, rhs) => {
163                Self::expr_allows_remove_arg_block(lhs) && Self::expr_allows_remove_arg_block(rhs)
164            }
165            Index(base, index, _) => {
166                Self::expr_allows_remove_arg_block(base)
167                    && Self::expr_allows_remove_arg_block(index)
168            }
169            Range(start, end, _) => {
170                start.as_ref().is_none_or(|expr| Self::expr_allows_remove_arg_block(expr))
171                    && end.as_ref().is_none_or(|expr| Self::expr_allows_remove_arg_block(expr))
172            }
173            Struct(expr) => {
174                expr.fields.iter().all(|field| Self::expr_allows_remove_arg_block(&field.expr))
175                    && match &expr.rest {
176                        ast::StructRest::Base(expr) => Self::expr_allows_remove_arg_block(expr),
177                        ast::StructRest::Rest(_) | ast::StructRest::None => true,
178                        ast::StructRest::NoneWithError(_) => false,
179                    }
180            }
181            Repeat(expr, _) => Self::expr_allows_remove_arg_block(expr),
182            ConstBlock(_)
183            | If(..)
184            | While(..)
185            | ForLoop { .. }
186            | Loop(..)
187            | Match(..)
188            | Closure(_)
189            | Block(..)
190            | Gen(..)
191            | TryBlock(..)
192            | Break(..)
193            | Continue(_)
194            | Ret(_)
195            | InlineAsm(_)
196            | OffsetOf(..)
197            | Yield(_)
198            | Yeet(_)
199            | Paren(_)
200            | Become(_) => true,
201            Call(..) | MethodCall(_) | Let(..) | Field(..) | MacCall(_) | FormatArgs(_) => false,
202            // `gca!()` is invalid in function/method argument position.
203            Gca(_) => false,
204            // don't lint for placeholder/error-recovery
205            Underscore | Err(_) | Dummy => false,
206        }
207    }
208
209    /// Returns whether `{ expr }` must be kept in function/method argument
210    /// position to avoid changing temporary lifetime semantics.
211    fn needs_arg_block_to_preserve_temporaries(
212        ctx: UnusedDelimsCtx,
213        arg_block: &ast::Expr,
214        expr: &ast::Expr,
215    ) -> bool {
216        #[allow(non_exhaustive_omitted_patterns)] match ctx {
    UnusedDelimsCtx::FunctionArg | UnusedDelimsCtx::MethodArg => true,
    _ => false,
}matches!(ctx, UnusedDelimsCtx::FunctionArg | UnusedDelimsCtx::MethodArg)
217            && arg_block.span.edition().at_least_rust_2024()
218            && !Self::expr_allows_remove_arg_block(expr)
219    }
220
221    fn is_expr_delims_necessary(
222        inner: &ast::Expr,
223        ctx: UnusedDelimsCtx,
224        followed_by_block: bool,
225    ) -> bool {
226        let followed_by_else = ctx == UnusedDelimsCtx::AssignedValueLetElse;
227
228        if followed_by_else {
229            match inner.kind {
230                ast::ExprKind::Binary(op, ..) if op.node.is_lazy() => return true,
231                _ if classify::expr_trailing_brace(inner).is_some() => return true,
232                _ => {}
233            }
234        }
235
236        // Check it's range in LetScrutineeExpr
237        if let ast::ExprKind::Range(..) = inner.kind
238            && #[allow(non_exhaustive_omitted_patterns)] match ctx {
    UnusedDelimsCtx::LetScrutineeExpr => true,
    _ => false,
}matches!(ctx, UnusedDelimsCtx::LetScrutineeExpr)
239        {
240            return true;
241        }
242
243        // Do not lint against parentheses around `&raw [const|mut] expr`.
244        // These parentheses will have to be added e.g. when calling a method on the result of this
245        // expression, and we want to avoid churn wrt adding and removing parentheses.
246        if #[allow(non_exhaustive_omitted_patterns)] match inner.kind {
    ast::ExprKind::AddrOf(ast::BorrowKind::Raw, ..) => true,
    _ => false,
}matches!(inner.kind, ast::ExprKind::AddrOf(ast::BorrowKind::Raw, ..)) {
247            return true;
248        }
249
250        // Check if LHS needs parens to prevent false-positives in cases like
251        // `fn x() -> u8 { ({ 0 } + 1) }`.
252        //
253        // FIXME: https://github.com/rust-lang/rust/issues/119426
254        // The syntax tree in this code is from after macro expansion, so the
255        // current implementation has both false negatives and false positives
256        // related to expressions containing macros.
257        //
258        //     macro_rules! m1 {
259        //         () => {
260        //             1
261        //         };
262        //     }
263        //
264        //     fn f1() -> u8 {
265        //         // Lint says parens are not needed, but they are.
266        //         (m1! {} + 1)
267        //     }
268        //
269        //     macro_rules! m2 {
270        //         () => {
271        //             loop { break 1; }
272        //         };
273        //     }
274        //
275        //     fn f2() -> u8 {
276        //         // Lint says parens are needed, but they are not.
277        //         (m2!() + 1)
278        //     }
279        {
280            let mut innermost = inner;
281            loop {
282                innermost = match &innermost.kind {
283                    ExprKind::Binary(_op, lhs, _rhs) => lhs,
284                    ExprKind::Call(fn_, _params) => fn_,
285                    ExprKind::Cast(expr, _ty) => expr,
286                    ExprKind::Type(expr, _ty) => expr,
287                    ExprKind::Index(base, _subscript, _) => base,
288                    _ => break,
289                };
290                if !classify::expr_requires_semi_to_be_stmt(innermost) {
291                    return true;
292                }
293            }
294        }
295
296        // Check if RHS needs parens to prevent false-positives in cases like `if (() == return)
297        // {}`.
298        if !followed_by_block {
299            return false;
300        }
301
302        // Check if we need parens for `match &( Struct { field:  }) {}`.
303        {
304            let mut innermost = inner;
305            loop {
306                innermost = match &innermost.kind {
307                    ExprKind::AddrOf(_, _, expr) => expr,
308                    _ => {
309                        if parser::contains_exterior_struct_lit(innermost) {
310                            return true;
311                        } else {
312                            break;
313                        }
314                    }
315                }
316            }
317        }
318
319        let mut innermost = inner;
320        loop {
321            innermost = match &innermost.kind {
322                ExprKind::Unary(_op, expr) => expr,
323                ExprKind::Binary(_op, _lhs, rhs) => rhs,
324                ExprKind::AssignOp(_op, _lhs, rhs) => rhs,
325                ExprKind::Assign(_lhs, rhs, _span) => rhs,
326
327                ExprKind::Ret(_) | ExprKind::Yield(..) | ExprKind::Yeet(..) => return true,
328
329                ExprKind::Break(_label, None) => return false,
330                ExprKind::Break(_label, Some(break_expr)) => {
331                    // `if (break 'label i) { ... }` removing parens would make `i { ... }`
332                    // be parsed as a struct literal, so keep parentheses if the break value
333                    // ends with a path (which could be mistaken for a struct name).
334                    return #[allow(non_exhaustive_omitted_patterns)] match break_expr.kind {
    ExprKind::Block(..) | ExprKind::Path(..) => true,
    _ => false,
}matches!(break_expr.kind, ExprKind::Block(..) | ExprKind::Path(..));
335                }
336
337                ExprKind::Range(_lhs, Some(rhs), _limits) => {
338                    return #[allow(non_exhaustive_omitted_patterns)] match rhs.kind {
    ExprKind::Block(..) => true,
    _ => false,
}matches!(rhs.kind, ExprKind::Block(..));
339                }
340
341                _ => return parser::contains_exterior_struct_lit(inner),
342            }
343        }
344    }
345
346    fn emit_unused_delims_expr(
347        &self,
348        cx: &EarlyContext<'_>,
349        value: &ast::Expr,
350        ctx: UnusedDelimsCtx,
351        left_pos: Option<BytePos>,
352        right_pos: Option<BytePos>,
353        is_kw: bool,
354    ) {
355        let span_with_attrs = match value.kind {
356            ast::ExprKind::Block(ref block, None) if let [stmt] = block.stmts.as_slice() => {
357                // For the statements with attributes, like `{ #[allow()] println!("Hello!") }`,
358                // the span should contains the attributes, or the suggestion will remove them.
359                if let Some(attr_lo) = stmt.attrs().iter().map(|attr| attr.span.lo()).min() {
360                    stmt.span.with_lo(attr_lo)
361                } else {
362                    stmt.span
363                }
364            }
365            ast::ExprKind::Paren(ref expr) => {
366                // For the expr with attributes, like `let _ = (#[inline] || println!("Hello!"));`,
367                // the span should contains the attributes, or the suggestion will remove them.
368                if let Some(attr_lo) = expr.attrs.iter().map(|attr| attr.span.lo()).min() {
369                    expr.span.with_lo(attr_lo)
370                } else {
371                    expr.span
372                }
373            }
374            _ => return,
375        };
376        let spans = span_with_attrs
377            .find_ancestor_inside(value.span)
378            .map(|span| (value.span.with_hi(span.lo()), value.span.with_lo(span.hi())));
379        let keep_space = (
380            left_pos.is_some_and(|s| s >= value.span.lo()),
381            right_pos.is_some_and(|s| s <= value.span.hi()),
382        );
383        self.emit_unused_delims(cx, value.span, spans, ctx.into(), keep_space, is_kw);
384    }
385
386    fn emit_unused_delims(
387        &self,
388        cx: &EarlyContext<'_>,
389        value_span: Span,
390        spans: Option<(Span, Span)>,
391        msg: &str,
392        keep_space: (bool, bool),
393        is_kw: bool,
394    ) {
395        if cx.in_external_macro_item {
396            return;
397        }
398        let sm = cx.sess().source_map();
399        // The warning points at the delimiter alone. The help only does so if there is a comment
400        // between the delimiter and the inner value, so the comment is kept.
401        let shrink = |span: Span, open: bool, in_help: bool| -> Span {
402            if span.is_empty() {
403                return span;
404            }
405            let (delim, gap) = if open {
406                let delim = span.with_hi(span.lo() + BytePos(1));
407                (delim, span.with_lo(delim.hi()))
408            } else {
409                let delim = span.with_lo(span.hi() - BytePos(1));
410                (delim, span.with_hi(delim.lo()))
411            };
412            let is_delim =
413                sm.span_to_snippet(delim).is_ok_and(|s| #[allow(non_exhaustive_omitted_patterns)] match &*s {
    "(" | ")" | "{" | "}" => true,
    _ => false,
}matches!(&*s, "(" | ")" | "{" | "}"));
414            let has_comment = sm.span_to_snippet(gap).is_ok_and(|s| !s.trim().is_empty());
415            if is_delim && (!in_help || has_comment) { delim } else { span }
416        };
417        let primary_span = if let Some((lo, hi)) = spans {
418            if hi.is_empty() {
419                // do not point at delims that do not exist
420                return;
421            }
422            MultiSpan::from(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [shrink(lo, true, false), shrink(hi, false, false)]))vec![shrink(lo, true, false), shrink(hi, false, false)])
423        } else {
424            MultiSpan::from(value_span)
425        };
426        let suggestion = spans.map(|(lo, hi)| {
427            let (lo, hi) = (shrink(lo, true, true), shrink(hi, false, true));
428            let lo_replace = if (keep_space.0 || is_kw)
429                && let Ok(snip) = sm.span_to_prev_source(lo)
430                && !snip.ends_with(' ')
431            {
432                " "
433            } else if let Ok(snip) = sm.span_to_prev_source(value_span)
434                && snip.ends_with(|c: char| c.is_alphanumeric())
435            {
436                " "
437            } else {
438                ""
439            };
440
441            let hi_replace = if keep_space.1
442                && let Ok(snip) = sm.span_to_next_source(hi)
443                && !snip.starts_with(' ')
444            {
445                " "
446            } else if let Ok(snip) = sm.span_to_next_source(value_span)
447                && snip.starts_with(|c: char| c.is_alphanumeric())
448            {
449                " "
450            } else {
451                ""
452            };
453            UnusedDelimSuggestion {
454                start_span: lo,
455                start_replace: lo_replace,
456                end_span: hi,
457                end_replace: hi_replace,
458                delim: Self::DELIM_STR,
459            }
460        });
461        cx.emit_span_lint(
462            self.lint(),
463            primary_span,
464            UnusedDelim { delim: Self::DELIM_STR, item: msg, suggestion },
465        );
466    }
467
468    fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
469        use rustc_ast::ExprKind::*;
470        let (value, ctx, followed_by_block, left_pos, right_pos, is_kw) = match e.kind {
471            // Do not lint `unused_braces` in `if let` expressions.
472            If(ref cond, ref block, _)
473                if !#[allow(non_exhaustive_omitted_patterns)] match cond.kind {
    Let(..) => true,
    _ => false,
}matches!(cond.kind, Let(..)) || Self::LINT_EXPR_IN_PATTERN_MATCHING_CTX =>
474            {
475                let left = e.span.lo() + rustc_span::BytePos(2);
476                let right = block.span.lo();
477                (cond, UnusedDelimsCtx::IfCond, true, Some(left), Some(right), true)
478            }
479
480            // Do not lint `unused_braces` in `while let` expressions.
481            While(ref cond, ref block, ..)
482                if !#[allow(non_exhaustive_omitted_patterns)] match cond.kind {
    Let(..) => true,
    _ => false,
}matches!(cond.kind, Let(..)) || Self::LINT_EXPR_IN_PATTERN_MATCHING_CTX =>
483            {
484                let left = e.span.lo() + rustc_span::BytePos(5);
485                let right = block.span.lo();
486                (cond, UnusedDelimsCtx::WhileCond, true, Some(left), Some(right), true)
487            }
488
489            ForLoop(ast::ForLoop { ref iter, ref body, .. }) => {
490                (iter, UnusedDelimsCtx::ForIterExpr, true, None, Some(body.span.lo()), true)
491            }
492
493            Match(ref head, _, ast::MatchKind::Prefix)
494                if Self::LINT_EXPR_IN_PATTERN_MATCHING_CTX =>
495            {
496                let left = e.span.lo() + rustc_span::BytePos(5);
497                (head, UnusedDelimsCtx::MatchScrutineeExpr, true, Some(left), None, true)
498            }
499
500            Ret(Some(ref value)) => {
501                let left = e.span.lo() + rustc_span::BytePos(3);
502                (value, UnusedDelimsCtx::ReturnValue, false, Some(left), None, true)
503            }
504
505            Break(label, Some(ref value)) => {
506                // Don't lint on `break 'label ({...})` - the parens are necessary
507                // to disambiguate from `break 'label {...}` which would be a syntax error.
508                // This avoids conflicts with the `break_with_label_and_loop` lint.
509                if label.is_some()
510                    && #[allow(non_exhaustive_omitted_patterns)] match value.kind {
    ast::ExprKind::Paren(ref inner) if
        #[allow(non_exhaustive_omitted_patterns)] match inner.kind {
            ast::ExprKind::Block(..) => true,
            _ => false,
        } => true,
    _ => false,
}matches!(value.kind, ast::ExprKind::Paren(ref inner)
511                        if matches!(inner.kind, ast::ExprKind::Block(..)))
512                {
513                    return;
514                }
515                (value, UnusedDelimsCtx::BreakValue, false, None, None, true)
516            }
517
518            Index(_, ref value, _) => (value, UnusedDelimsCtx::IndexExpr, false, None, None, false),
519
520            Assign(_, ref value, _) | AssignOp(.., ref value) => {
521                (value, UnusedDelimsCtx::AssignedValue, false, None, None, false)
522            }
523            // either function/method call, or something this lint doesn't care about
524            ref call_or_other => {
525                let (args_to_check, ctx, callee_from_expansion) = match *call_or_other {
526                    Call(ref callee, ref args) => {
527                        (&args[..], UnusedDelimsCtx::FunctionArg, callee.span.from_expansion())
528                    }
529                    MethodCall(ref call) => (
530                        &call.args[..],
531                        UnusedDelimsCtx::MethodArg,
532                        call.seg.ident.span.from_expansion(),
533                    ),
534                    Closure(ref closure)
535                        if #[allow(non_exhaustive_omitted_patterns)] match closure.fn_decl.output {
    FnRetTy::Default(_) => true,
    _ => false,
}matches!(closure.fn_decl.output, FnRetTy::Default(_)) =>
536                    {
537                        (&[closure.body.clone()][..], UnusedDelimsCtx::ClosureBody, false)
538                    }
539                    // actual catch-all arm
540                    _ => {
541                        return;
542                    }
543                };
544                // Don't lint if this is a nested macro expansion: otherwise, the lint could
545                // trigger in situations that macro authors shouldn't have to care about, e.g.,
546                // when a parenthesized token tree matched in one macro expansion is matched as
547                // an expression in another and used as a fn/method argument (Issue #47775)
548                if e.span.ctxt().outer_expn_data().call_site.from_expansion() {
549                    return;
550                }
551                for arg in args_to_check {
552                    // Whether an expression is wrapped in a block can change which `macro_rules!`
553                    // arm is taken. Don't report the braces as unused in that case. (Issue #158747)
554                    if callee_from_expansion && Self::block_wraps_expanded_expr(arg) {
555                        continue;
556                    }
557                    self.check_unused_delims_expr(cx, arg, ctx, false, None, None, false);
558                }
559                return;
560            }
561        };
562        self.check_unused_delims_expr(
563            cx,
564            value,
565            ctx,
566            followed_by_block,
567            left_pos,
568            right_pos,
569            is_kw,
570        );
571    }
572
573    fn check_stmt(&mut self, cx: &EarlyContext<'_>, s: &ast::Stmt) {
574        match s.kind {
575            StmtKind::Let(ref local) if Self::LINT_EXPR_IN_PATTERN_MATCHING_CTX => {
576                if let Some((init, els)) = local.kind.init_else_opt() {
577                    if els.is_some()
578                        && let ExprKind::Paren(paren) = &init.kind
579                        && init.span.ctxt() != paren.span.ctxt()
580                    {
581                        // This branch prevents cases where parentheses wrap an expression
582                        // resulting from macro expansion, such as:
583                        // ```
584                        // macro_rules! x {
585                        // () => { None::<i32> };
586                        // }
587                        // let Some(_) = (x!{}) else { return };
588                        // // -> let Some(_) = (None::<i32>) else { return };
589                        // //                  ~           ~ No Lint
590                        // ```
591                        return;
592                    }
593                    let ctx = match els {
594                        None => UnusedDelimsCtx::AssignedValue,
595                        Some(_) => UnusedDelimsCtx::AssignedValueLetElse,
596                    };
597                    self.check_unused_delims_expr(cx, init, ctx, false, None, None, false);
598                }
599            }
600            StmtKind::Expr(ref expr) => {
601                self.check_unused_delims_expr(
602                    cx,
603                    expr,
604                    UnusedDelimsCtx::BlockRetValue,
605                    false,
606                    None,
607                    None,
608                    false,
609                );
610            }
611            _ => {}
612        }
613    }
614
615    fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
616        use ast::ItemKind::*;
617
618        let expr = if let Const(ast::ConstItem { body: Some(expr), .. }) = &item.kind {
619            expr
620        } else if let Static(ast::StaticItem { expr: Some(expr), .. }) = &item.kind {
621            expr
622        } else {
623            return;
624        };
625        self.check_unused_delims_expr(
626            cx,
627            expr,
628            UnusedDelimsCtx::AssignedValue,
629            false,
630            None,
631            None,
632            false,
633        );
634    }
635
636    // Returns true for a user-written block whose only expression came from a macro expansion.
637    fn block_wraps_expanded_expr(value: &ast::Expr) -> bool {
638        if let ast::ExprKind::Block(ref block, None) = value.kind
639            && block.rules == ast::BlockCheckMode::Default
640            && !value.span.from_expansion()
641            && let [stmt] = block.stmts.as_slice()
642            && let ast::StmtKind::Expr(ref expr) = stmt.kind
643        {
644            expr.span.from_expansion()
645        } else {
646            false
647        }
648    }
649}
650
651#[doc =
r" The `unused_parens` lint detects `if`, `match`, `while` and `return`"]
#[doc = r" with parentheses; they do not need them."]
#[doc = r""]
#[doc = r" ### Examples"]
#[doc = r""]
#[doc = r" ```rust"]
#[doc = r" if(true) {}"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc =
r" The parentheses are not needed, and should be removed. This is the"]
#[doc = r" preferred style for writing these expressions."]
pub(super) static UNUSED_PARENS: &::rustc_lint_defs::Lint =
    &::rustc_lint_defs::Lint {
            name: "UNUSED_PARENS",
            default_level: ::rustc_lint_defs::Warn,
            desc: "`if`, `match`, `while` and `return` do not need parentheses",
            ..
        };declare_lint! {
652    /// The `unused_parens` lint detects `if`, `match`, `while` and `return`
653    /// with parentheses; they do not need them.
654    ///
655    /// ### Examples
656    ///
657    /// ```rust
658    /// if(true) {}
659    /// ```
660    ///
661    /// {{produces}}
662    ///
663    /// ### Explanation
664    ///
665    /// The parentheses are not needed, and should be removed. This is the
666    /// preferred style for writing these expressions.
667    pub(super) UNUSED_PARENS,
668    Warn,
669    "`if`, `match`, `while` and `return` do not need parentheses"
670}
671
672#[derive(#[automatically_derived]impl ::core::default::Default for UnusedParens {
    #[inline]
    fn default() -> Self {
        UnusedParens {
            with_self_ty_parens: ::core::default::Default::default(),
            parens_in_cast_in_lt: ::core::default::Default::default(),
            in_no_bounds_pos: ::core::default::Default::default(),
        }
    }
}Default)]
673pub(crate) struct UnusedParens {
674    with_self_ty_parens: bool,
675    /// `1 as (i32) < 2` parses to ExprKind::Lt
676    /// `1 as i32 < 2` parses to i32::<2[missing angle bracket]
677    parens_in_cast_in_lt: Vec<ast::NodeId>,
678    /// Ty nodes in this map are in TypeNoBounds position. Any bounds they
679    /// contain may be ambiguous w/r/t trailing `+` operators.
680    in_no_bounds_pos: FxHashMap<ast::NodeId, NoBoundsException>,
681}
682
683/// Whether parentheses may be omitted from a type without resulting in ambiguity.
684///
685/// ```
686/// type Example = Box<dyn Fn() -> &'static (dyn Send) + Sync>;
687/// ```
688///
689/// Here, `&'static (dyn Send) + Sync` is a `TypeNoBounds`. As such, it may not directly
690/// contain `ImplTraitType` or `TraitObjectType` which is why `(dyn Send)` is parenthesized.
691/// However, an exception is made for `ImplTraitTypeOneBound` and `TraitObjectTypeOneBound`.
692/// The following is accepted because there is no `+`.
693///
694/// ```
695/// type Example = Box<dyn Fn() -> &'static dyn Send>;
696/// ```
697enum NoBoundsException {
698    /// The type must be parenthesized.
699    None,
700    /// The type is the last bound of the containing type expression. If it has exactly one bound,
701    /// parentheses around the type are unnecessary.
702    OneBound,
703}
704
705impl ::rustc_lint_defs::LintPass for UnusedParens {
    fn name(&self) -> &'static str { "UnusedParens" }
    fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [UNUSED_PARENS]))
    }
}
impl UnusedParens {
    #[allow(unused)]
    pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [UNUSED_PARENS]))
    }
}impl_lint_pass!(UnusedParens => [UNUSED_PARENS]);
706
707impl UnusedDelimLint for UnusedParens {
708    const DELIM_STR: &'static str = "parentheses";
709
710    const LINT_EXPR_IN_PATTERN_MATCHING_CTX: bool = true;
711
712    fn lint(&self) -> &'static Lint {
713        UNUSED_PARENS
714    }
715
716    fn check_unused_delims_expr(
717        &self,
718        cx: &EarlyContext<'_>,
719        value: &ast::Expr,
720        ctx: UnusedDelimsCtx,
721        followed_by_block: bool,
722        left_pos: Option<BytePos>,
723        right_pos: Option<BytePos>,
724        is_kw: bool,
725    ) {
726        match value.kind {
727            ast::ExprKind::Paren(ref inner) => {
728                if !Self::is_expr_delims_necessary(inner, ctx, followed_by_block)
729                    && value.attrs.is_empty()
730                    && !value.span.from_expansion()
731                    && (ctx != UnusedDelimsCtx::LetScrutineeExpr
732                        || !#[allow(non_exhaustive_omitted_patterns)] match inner.kind {
    ast::ExprKind::Binary(rustc_span::Spanned { node, .. }, _, _) if
        node.is_lazy() => true,
    _ => false,
}matches!(inner.kind, ast::ExprKind::Binary(
733                                rustc_span::Spanned { node, .. },
734                                _,
735                                _,
736                            ) if node.is_lazy()))
737                    && !((ctx == UnusedDelimsCtx::ReturnValue
738                        || ctx == UnusedDelimsCtx::BreakValue)
739                        && #[allow(non_exhaustive_omitted_patterns)] match inner.kind {
    ast::ExprKind::Assign(_, _, _) => true,
    _ => false,
}matches!(inner.kind, ast::ExprKind::Assign(_, _, _)))
740                {
741                    self.emit_unused_delims_expr(cx, value, ctx, left_pos, right_pos, is_kw)
742                }
743            }
744            ast::ExprKind::Let(_, ref expr, _, _) => {
745                self.check_unused_delims_expr(
746                    cx,
747                    expr,
748                    UnusedDelimsCtx::LetScrutineeExpr,
749                    followed_by_block,
750                    None,
751                    None,
752                    false,
753                );
754            }
755            _ => {}
756        }
757    }
758}
759
760impl UnusedParens {
761    fn check_unused_parens_pat(
762        &self,
763        cx: &EarlyContext<'_>,
764        value: &ast::Pat,
765        avoid_or: bool,
766        avoid_mut: bool,
767        keep_space: (bool, bool),
768    ) {
769        use ast::{BindingMode, ByRef, Mutability, PatKind, Pinnedness};
770
771        if let PatKind::Paren(inner) = &value.kind {
772            match inner.kind {
773                // The lint visitor will visit each subpattern of `p`. We do not want to lint
774                // any range pattern no matter where it occurs in the pattern. For something like
775                // `&(a..=b)`, there is a recursive `check_pat` on `a` and `b`, but we will assume
776                // that if there are unnecessary parens they serve a purpose of readability.
777                PatKind::Range(..) => return,
778                // Parentheses may be necessary to disambiguate precedence in guard patterns.
779                PatKind::Guard(..) => return,
780                // Avoid `p0 | .. | pn` if we should.
781                PatKind::Or(..) if avoid_or => return,
782                // Avoid bindings whose own binding mutability is `mut`, like `mut x`,
783                // `mut x @ p`, and `mut ref pin const x`, if we should.
784                PatKind::Ident(BindingMode(_, Mutability::Mut), ..) if avoid_mut => {
785                    return;
786                }
787                PatKind::Ref(_, Pinnedness::Pinned, _)
788                | PatKind::Ident(BindingMode(ByRef::Yes(Pinnedness::Pinned, _), _), ..)
789                    // FIXME(pin_ergonomics): Remove this gate once pinned patterns are stable.
790                    if !cx.builder.features().pin_ergonomics() =>
791                {
792                    return;
793                }
794                // Otherwise proceed with linting.
795                _ => {}
796            }
797            let spans = if !value.span.from_expansion() {
798                inner
799                    .span
800                    .find_ancestor_inside(value.span)
801                    .map(|inner| (value.span.with_hi(inner.lo()), value.span.with_lo(inner.hi())))
802            } else {
803                None
804            };
805            self.emit_unused_delims(cx, value.span, spans, "pattern", keep_space, false);
806        }
807    }
808
809    /// A pattern that a `macro_rules!` metavariable brings in from the call site keeps the call
810    /// site's syntax context, while the pattern's surroundings keep the macro's. Parentheses in
811    /// such a pattern can be required by the matcher even when they are redundant in the
812    /// expansion, so removing them would break the macro call. (Issue #86959)
813    fn pat_is_macro_arg(pat_span: Span, parent_span: Span) -> bool {
814        pat_span.ctxt() != parent_span.ctxt()
815    }
816
817    fn cast_followed_by_lt(&self, expr: &ast::Expr) -> Option<ast::NodeId> {
818        if let ExprKind::Binary(op, lhs, _rhs) = &expr.kind
819            && (op.node == ast::BinOpKind::Lt || op.node == ast::BinOpKind::Shl)
820        {
821            let mut cur = lhs;
822            while let ExprKind::Binary(_, _, rhs) = &cur.kind {
823                cur = rhs;
824            }
825
826            if let ExprKind::Cast(_, ty) = &cur.kind
827                && let ast::TyKind::Paren(_) = &ty.kind
828            {
829                return Some(ty.id);
830            }
831        }
832        None
833    }
834}
835
836impl EarlyLintPass for UnusedParens {
837    #[inline]
838    fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
839        if let Some(ty_id) = self.cast_followed_by_lt(e) {
840            self.parens_in_cast_in_lt.push(ty_id);
841        }
842
843        match e.kind {
844            ExprKind::Let(ref pat, _, _, _) | ExprKind::ForLoop(ForLoop { ref pat, .. }) => {
845                let avoid_or = Self::pat_is_macro_arg(pat.span, e.span);
846                self.check_unused_parens_pat(cx, pat, avoid_or, false, (true, true));
847            }
848            // We ignore parens in cases like `if (((let Some(0) = Some(1))))` because we already
849            // handle a hard error for them during AST lowering in `lower_expr_mut`, but we still
850            // want to complain about things like `if let 42 = (42)`.
851            ExprKind::If(ref cond, ref block, ref else_)
852                if #[allow(non_exhaustive_omitted_patterns)] match cond.peel_parens().kind {
    ExprKind::Let(..) => true,
    _ => false,
}matches!(cond.peel_parens().kind, ExprKind::Let(..)) =>
853            {
854                self.check_unused_delims_expr(
855                    cx,
856                    cond.peel_parens(),
857                    UnusedDelimsCtx::LetScrutineeExpr,
858                    true,
859                    None,
860                    None,
861                    true,
862                );
863                for stmt in &block.stmts {
864                    <Self as UnusedDelimLint>::check_stmt(self, cx, stmt);
865                }
866                if let Some(e) = else_ {
867                    <Self as UnusedDelimLint>::check_expr(self, cx, e);
868                }
869                return;
870            }
871            ExprKind::Match(ref _expr, ref arm, _) => {
872                for a in arm {
873                    if let Some(body) = &a.body {
874                        self.check_unused_delims_expr(
875                            cx,
876                            body,
877                            UnusedDelimsCtx::MatchArmExpr,
878                            false,
879                            None,
880                            None,
881                            true,
882                        );
883                    }
884                }
885            }
886            _ => {}
887        }
888
889        <Self as UnusedDelimLint>::check_expr(self, cx, e)
890    }
891
892    fn check_expr_post(&mut self, _cx: &EarlyContext<'_>, e: &ast::Expr) {
893        if let Some(ty_id) = self.cast_followed_by_lt(e) {
894            let id = self
895                .parens_in_cast_in_lt
896                .pop()
897                .expect("check_expr and check_expr_post must balance");
898            {
    match (&id, &ty_id) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val,
                    ::core::option::Option::Some(format_args!("check_expr, check_ty, and check_expr_post are called, in that order, by the visitor")));
            }
        }
    }
};assert_eq!(
899                id, ty_id,
900                "check_expr, check_ty, and check_expr_post are called, in that order, by the visitor"
901            );
902        }
903    }
904
905    fn check_pat(&mut self, cx: &EarlyContext<'_>, p: &ast::Pat) {
906        use ast::PatKind::*;
907        use ast::{Mutability, Pinnedness};
908        let keep_space = (false, false);
909        match &p.kind {
910            // Do not lint on `(..)` as that will result in the other arms being useless.
911            Paren(_) => {}
912            // The other cases do not contain sub-patterns.
913            Missing
914            | Wild
915            | Never
916            | Rest
917            | Expr(..)
918            | MacCall(..)
919            | Range(..)
920            | Ident(.., None)
921            | Path(..)
922            | Err(_) => {}
923            // These are list-like patterns; parens can always be removed.
924            TupleStruct(_, _, ps) | Tuple(ps) | Slice(ps) | Or(ps) => {
925                for sub in ps {
926                    let avoid_or = Self::pat_is_macro_arg(sub.span, p.span);
927                    self.check_unused_parens_pat(cx, sub, avoid_or, false, keep_space);
928                }
929            }
930            Struct(_, _, fps, _) => {
931                for f in fps {
932                    let avoid_or = Self::pat_is_macro_arg(f.pat.span, p.span);
933                    self.check_unused_parens_pat(cx, &f.pat, avoid_or, false, keep_space);
934                }
935            }
936            // Avoid linting on `i @ (p0 | .. | pn)`, #64106.
937            Ident(.., Some(p)) | Deref(p) | Guard(p, _) => {
938                self.check_unused_parens_pat(cx, p, true, false, keep_space)
939            }
940            // Avoid linting on `&(mut x)` as `&mut x` has a different meaning, #55342.
941            // This only applies to plain shared reference patterns. In `&pin const (mut x)`,
942            // `pin const` is consumed before parsing the subpattern, so removing the
943            // parentheses preserves `mut x` as a binding pattern.
944            // Also avoid linting on `& mut? (p0 | .. | pn)`, #64106.
945            Ref(p, pinned, m)
946                if *pinned != Pinnedness::Pinned
947                    // FIXME(pin_ergonomics): Remove this gate once pinned patterns are stable.
948                    || cx.builder.features().pin_ergonomics() =>
949            {
950                // Avoid linting on patterns like `&(x @ _)`, as without parens `&x @ _`
951                // it creates confusion and seems like `x` is binding by reference, #165636.
952                if let Paren(ref pat) = p.kind
953                    && *pinned == Pinnedness::Not
954                    && let Ident(_, _, Some(..)) = pat.kind
955                {
956                    return;
957                }
958                // Check other cases.
959                self.check_unused_parens_pat(
960                    cx,
961                    p,
962                    true,
963                    *pinned == Pinnedness::Not && *m == Mutability::Not,
964                    keep_space,
965                );
966            }
967            Ref(..) => {}
968        }
969    }
970
971    fn check_stmt(&mut self, cx: &EarlyContext<'_>, s: &ast::Stmt) {
972        if let StmtKind::Let(ref local) = s.kind {
973            self.check_unused_parens_pat(cx, &local.pat, true, false, (true, false));
974        }
975
976        <Self as UnusedDelimLint>::check_stmt(self, cx, s)
977    }
978
979    fn check_param(&mut self, cx: &EarlyContext<'_>, param: &ast::Param) {
980        self.check_unused_parens_pat(cx, &param.pat, true, false, (false, false));
981    }
982
983    fn check_arm(&mut self, cx: &EarlyContext<'_>, arm: &ast::Arm) {
984        let avoid_or = Self::pat_is_macro_arg(arm.pat.span, arm.span);
985        self.check_unused_parens_pat(cx, &arm.pat, avoid_or, false, (false, false));
986    }
987
988    fn check_ty(&mut self, cx: &EarlyContext<'_>, ty: &ast::Ty) {
989        if let ast::TyKind::Paren(_) = ty.kind
990            && Some(&ty.id) == self.parens_in_cast_in_lt.last()
991        {
992            return;
993        }
994        match &ty.kind {
995            ast::TyKind::Array(_, len) => {
996                self.check_unused_delims_expr(
997                    cx,
998                    &len.value,
999                    UnusedDelimsCtx::ArrayLenExpr,
1000                    false,
1001                    None,
1002                    None,
1003                    false,
1004                );
1005            }
1006            ast::TyKind::Paren(r) => {
1007                let unused_parens = match &r.kind {
1008                    ast::TyKind::ImplTrait(_, bounds) | ast::TyKind::TraitObject(bounds, _) => {
1009                        match self.in_no_bounds_pos.get(&ty.id) {
1010                            Some(NoBoundsException::None) => false,
1011                            Some(NoBoundsException::OneBound) => bounds.len() <= 1,
1012                            None => true,
1013                        }
1014                    }
1015                    ast::TyKind::FnPtr(b) => {
1016                        !self.with_self_ty_parens || b.generic_params.is_empty()
1017                    }
1018                    _ => true,
1019                };
1020
1021                if unused_parens {
1022                    let spans = (!ty.span.from_expansion())
1023                        .then(|| {
1024                            r.span
1025                                .find_ancestor_inside(ty.span)
1026                                .map(|r| (ty.span.with_hi(r.lo()), ty.span.with_lo(r.hi())))
1027                        })
1028                        .flatten();
1029
1030                    self.emit_unused_delims(cx, ty.span, spans, "type", (false, false), false);
1031                }
1032
1033                self.with_self_ty_parens = false;
1034            }
1035            ast::TyKind::Ref(_, inner_ty, _) | ast::TyKind::Ptr(inner_ty, _) => {
1036                // If this type itself appears in no-bounds position, we propagate its
1037                // potentially tighter constraint or risk a false posive (issue 143653).
1038                let own_constraint = self.in_no_bounds_pos.get(&ty.id);
1039                let constraint = match own_constraint {
1040                    Some(NoBoundsException::None) => NoBoundsException::None,
1041                    Some(NoBoundsException::OneBound) => NoBoundsException::OneBound,
1042                    None => NoBoundsException::OneBound,
1043                };
1044                self.in_no_bounds_pos.insert(inner_ty.id, constraint);
1045            }
1046            ast::TyKind::TraitObject(bounds, _) | ast::TyKind::ImplTrait(_, bounds) => {
1047                for i in 0..bounds.len() {
1048                    let is_last = i == bounds.len() - 1;
1049
1050                    if let ast::GenericBound::Trait(poly_trait_ref) = &bounds[i] {
1051                        let fn_with_explicit_ret_ty = if let [.., segment] =
1052                            &*poly_trait_ref.trait_ref.path.segments
1053                            && let Some(args) = segment.args.as_ref()
1054                            && let ast::GenericArgs::Parenthesized(paren_args) = &**args
1055                            && let ast::FnRetTy::Ty(ret_ty) = &paren_args.output
1056                        {
1057                            self.in_no_bounds_pos.insert(
1058                                ret_ty.id,
1059                                if is_last {
1060                                    NoBoundsException::OneBound
1061                                } else {
1062                                    NoBoundsException::None
1063                                },
1064                            );
1065
1066                            true
1067                        } else {
1068                            false
1069                        };
1070
1071                        // In edition 2015, dyn is a contextual keyword and `dyn::foo::Bar` is
1072                        // parsed as a path, so parens are necessary to disambiguate. See
1073                        //  - tests/ui/lint/unused/unused-parens-trait-obj-e2015.rs and
1074                        //  - https://doc.rust-lang.org/reference/types/trait-object.html#r-type.trait-object.syntax-edition2018
1075                        let dyn2015_exception = cx.sess().psess.edition == Edition2015
1076                            && #[allow(non_exhaustive_omitted_patterns)] match ty.kind {
    ast::TyKind::TraitObject(..) => true,
    _ => false,
}matches!(ty.kind, ast::TyKind::TraitObject(..))
1077                            && i == 0
1078                            && poly_trait_ref
1079                                .trait_ref
1080                                .path
1081                                .segments
1082                                .first()
1083                                .map(|s| s.ident.name == kw::PathRoot)
1084                                .unwrap_or(false);
1085
1086                        if let ast::Parens::Yes = poly_trait_ref.parens
1087                            && (is_last || !fn_with_explicit_ret_ty)
1088                            && !dyn2015_exception
1089                        {
1090                            let s = poly_trait_ref.span;
1091                            // Check that the span really is wrapped in single-byte ASCII parens
1092                            // before trimming a byte off each end, in case a macro does weird
1093                            // things with spans or parser recovery produced multibyte parens.
1094                            if !s.from_expansion()
1095                                && let Ok(snippet) = cx.sess().source_map().span_to_snippet(s)
1096                                && snippet.starts_with('(')
1097                                && snippet.ends_with(')')
1098                            {
1099                                let spans = Some((
1100                                    s.with_hi(s.lo() + rustc_span::BytePos(1)),
1101                                    s.with_lo(s.hi() - rustc_span::BytePos(1)),
1102                                ));
1103
1104                                self.emit_unused_delims(
1105                                    cx,
1106                                    poly_trait_ref.span,
1107                                    spans,
1108                                    "type",
1109                                    (false, false),
1110                                    false,
1111                                );
1112                            }
1113                        }
1114                    }
1115                }
1116            }
1117            _ => {}
1118        }
1119    }
1120
1121    fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
1122        <Self as UnusedDelimLint>::check_item(self, cx, item)
1123    }
1124
1125    fn check_item_post(&mut self, _: &EarlyContext<'_>, _: &rustc_ast::Item) {
1126        self.in_no_bounds_pos.clear();
1127    }
1128
1129    fn check_where_predicate(&mut self, _: &EarlyContext<'_>, pred: &ast::WherePredicate) {
1130        use rustc_ast::{WhereBoundPredicate, WherePredicateKind};
1131        if let WherePredicateKind::BoundPredicate(WhereBoundPredicate {
1132            bounded_ty,
1133            bound_generic_params,
1134            ..
1135        }) = &pred.kind
1136            && let ast::TyKind::Paren(_) = &bounded_ty.kind
1137            && bound_generic_params.is_empty()
1138        {
1139            self.with_self_ty_parens = true;
1140        }
1141    }
1142
1143    fn check_where_predicate_post(&mut self, _: &EarlyContext<'_>, _: &ast::WherePredicate) {
1144        if !!self.with_self_ty_parens {
    ::core::panicking::panic("assertion failed: !self.with_self_ty_parens")
};assert!(!self.with_self_ty_parens);
1145    }
1146}
1147
1148#[doc = r" The `unused_braces` lint detects unnecessary braces around an"]
#[doc = r" expression."]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust"]
#[doc = r" if { true } {"]
#[doc = r"     // ..."]
#[doc = r" }"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc = r" The braces are not needed, and should be removed. This is the"]
#[doc = r" preferred style for writing these expressions."]
pub(super) static UNUSED_BRACES: &::rustc_lint_defs::Lint =
    &::rustc_lint_defs::Lint {
            name: "UNUSED_BRACES",
            default_level: ::rustc_lint_defs::Warn,
            desc: "unnecessary braces around an expression",
            ..
        };declare_lint! {
1149    /// The `unused_braces` lint detects unnecessary braces around an
1150    /// expression.
1151    ///
1152    /// ### Example
1153    ///
1154    /// ```rust
1155    /// if { true } {
1156    ///     // ...
1157    /// }
1158    /// ```
1159    ///
1160    /// {{produces}}
1161    ///
1162    /// ### Explanation
1163    ///
1164    /// The braces are not needed, and should be removed. This is the
1165    /// preferred style for writing these expressions.
1166    pub(super) UNUSED_BRACES,
1167    Warn,
1168    "unnecessary braces around an expression"
1169}
1170
1171pub struct UnusedBraces;
#[automatically_derived]impl ::core::marker::Copy for UnusedBraces { }
#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for UnusedBraces {
}
#[automatically_derived]impl ::core::clone::Clone for UnusedBraces {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self { *self }
}
impl ::rustc_lint_defs::LintPass for UnusedBraces {
    fn name(&self) -> &'static str { "UnusedBraces" }
    fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [UNUSED_BRACES]))
    }
}
impl UnusedBraces {
    #[allow(unused)]
    pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [UNUSED_BRACES]))
    }
}declare_lint_pass!(UnusedBraces => [UNUSED_BRACES]);
1172
1173impl UnusedDelimLint for UnusedBraces {
1174    const DELIM_STR: &'static str = "braces";
1175
1176    const LINT_EXPR_IN_PATTERN_MATCHING_CTX: bool = false;
1177
1178    fn lint(&self) -> &'static Lint {
1179        UNUSED_BRACES
1180    }
1181
1182    fn check_unused_delims_expr(
1183        &self,
1184        cx: &EarlyContext<'_>,
1185        value: &ast::Expr,
1186        ctx: UnusedDelimsCtx,
1187        followed_by_block: bool,
1188        left_pos: Option<BytePos>,
1189        right_pos: Option<BytePos>,
1190        is_kw: bool,
1191    ) {
1192        match value.kind {
1193            ast::ExprKind::Block(ref inner, None)
1194                if inner.rules == ast::BlockCheckMode::Default =>
1195            {
1196                // emit a warning under the following conditions:
1197                //
1198                // - the block does not have a label
1199                // - the block is not `unsafe`
1200                // - the block contains exactly one expression (do not lint `{ expr; }`)
1201                // - `followed_by_block` is true and the internal expr may contain a `{`
1202                // - the block is not multiline (do not lint multiline match arms)
1203                //      ```
1204                //      match expr {
1205                //          Pattern => {
1206                //              somewhat_long_expression
1207                //          }
1208                //          // ...
1209                //      }
1210                //      ```
1211                // - the block has no attribute and was not created inside a macro
1212                // - if the block is an `anon_const`, the inner expr must be a literal
1213                //   not created by a macro, i.e. do not lint on:
1214                //      ```
1215                //      struct A<const N: usize>;
1216                //      let _: A<{ 2 + 3 }>;
1217                //      let _: A<{produces_literal!()}>;
1218                //      ```
1219                // FIXME(const_generics): handle paths when #67075 is fixed.
1220                if let [stmt] = inner.stmts.as_slice()
1221                    && let ast::StmtKind::Expr(ref expr) = stmt.kind
1222                    && !Self::is_expr_delims_necessary(expr, ctx, followed_by_block)
1223                    // In Rust 2024, this block may drop tail-expression temporaries, such as a
1224                    // lock guard, before the loop starts.
1225                    && !(ctx == UnusedDelimsCtx::ForIterExpr
1226                        && value.span.edition().at_least_rust_2024())
1227                    && !Self::needs_arg_block_to_preserve_temporaries(ctx, value, expr)
1228                    && (ctx != UnusedDelimsCtx::AnonConst
1229                        || (#[allow(non_exhaustive_omitted_patterns)] match expr.kind {
    ast::ExprKind::Lit(_) => true,
    _ => false,
}matches!(expr.kind, ast::ExprKind::Lit(_))
1230                            && !expr.span.from_expansion()))
1231                    && ctx != UnusedDelimsCtx::ClosureBody
1232                    && !cx.sess().source_map().is_multiline(value.span)
1233                    && value.attrs.is_empty()
1234                    && !value.span.from_expansion()
1235                    && !inner.span.from_expansion()
1236                {
1237                    self.emit_unused_delims_expr(cx, value, ctx, left_pos, right_pos, is_kw)
1238                }
1239            }
1240            ast::ExprKind::Let(_, ref expr, _, _) => {
1241                self.check_unused_delims_expr(
1242                    cx,
1243                    expr,
1244                    UnusedDelimsCtx::LetScrutineeExpr,
1245                    followed_by_block,
1246                    None,
1247                    None,
1248                    false,
1249                );
1250            }
1251            _ => {}
1252        }
1253    }
1254}
1255
1256impl EarlyLintPass for UnusedBraces {
1257    fn check_stmt(&mut self, cx: &EarlyContext<'_>, s: &ast::Stmt) {
1258        <Self as UnusedDelimLint>::check_stmt(self, cx, s)
1259    }
1260
1261    #[inline]
1262    fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
1263        <Self as UnusedDelimLint>::check_expr(self, cx, e);
1264
1265        if let ExprKind::Repeat(_, ref anon_const) = e.kind {
1266            self.check_unused_delims_expr(
1267                cx,
1268                &anon_const.value,
1269                UnusedDelimsCtx::AnonConst,
1270                false,
1271                None,
1272                None,
1273                false,
1274            );
1275        }
1276    }
1277
1278    fn check_generic_arg(&mut self, cx: &EarlyContext<'_>, arg: &ast::GenericArg) {
1279        if let ast::GenericArg::Const(ct) = arg {
1280            self.check_unused_delims_expr(
1281                cx,
1282                &ct.value,
1283                UnusedDelimsCtx::AnonConst,
1284                false,
1285                None,
1286                None,
1287                false,
1288            );
1289        }
1290    }
1291
1292    fn check_variant(&mut self, cx: &EarlyContext<'_>, v: &ast::Variant) {
1293        if let Some(anon_const) = &v.disr_expr {
1294            self.check_unused_delims_expr(
1295                cx,
1296                &anon_const.value,
1297                UnusedDelimsCtx::AnonConst,
1298                false,
1299                None,
1300                None,
1301                false,
1302            );
1303        }
1304    }
1305
1306    fn check_ty(&mut self, cx: &EarlyContext<'_>, ty: &ast::Ty) {
1307        match ty.kind {
1308            ast::TyKind::Array(_, ref len) => {
1309                self.check_unused_delims_expr(
1310                    cx,
1311                    &len.value,
1312                    UnusedDelimsCtx::ArrayLenExpr,
1313                    false,
1314                    None,
1315                    None,
1316                    false,
1317                );
1318            }
1319
1320            _ => {}
1321        }
1322    }
1323
1324    fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
1325        <Self as UnusedDelimLint>::check_item(self, cx, item)
1326    }
1327}
1328
1329#[doc =
r" The `unused_import_braces` lint catches unnecessary braces around an"]
#[doc = r" imported item."]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust,compile_fail"]
#[doc = r" #![deny(unused_import_braces)]"]
#[doc = r" use test::{A};"]
#[doc = r""]
#[doc = r" pub mod test {"]
#[doc = r"     pub struct A;"]
#[doc = r" }"]
#[doc = r" # fn main() {}"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc =
r" If there is only a single item, then remove the braces (`use test::A;`"]
#[doc = r" for example)."]
#[doc = r""]
#[doc = r#" This lint is "allow" by default because it is only enforcing a"#]
#[doc = r" stylistic choice."]
static UNUSED_IMPORT_BRACES: &::rustc_lint_defs::Lint =
    &::rustc_lint_defs::Lint {
            name: "UNUSED_IMPORT_BRACES",
            default_level: ::rustc_lint_defs::Allow,
            desc: "unnecessary braces around an imported item",
            ..
        };declare_lint! {
1330    /// The `unused_import_braces` lint catches unnecessary braces around an
1331    /// imported item.
1332    ///
1333    /// ### Example
1334    ///
1335    /// ```rust,compile_fail
1336    /// #![deny(unused_import_braces)]
1337    /// use test::{A};
1338    ///
1339    /// pub mod test {
1340    ///     pub struct A;
1341    /// }
1342    /// # fn main() {}
1343    /// ```
1344    ///
1345    /// {{produces}}
1346    ///
1347    /// ### Explanation
1348    ///
1349    /// If there is only a single item, then remove the braces (`use test::A;`
1350    /// for example).
1351    ///
1352    /// This lint is "allow" by default because it is only enforcing a
1353    /// stylistic choice.
1354    UNUSED_IMPORT_BRACES,
1355    Allow,
1356    "unnecessary braces around an imported item"
1357}
1358
1359pub struct UnusedImportBraces;
#[automatically_derived]impl ::core::marker::Copy for UnusedImportBraces { }
#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for UnusedImportBraces {
}
#[automatically_derived]impl ::core::clone::Clone for UnusedImportBraces {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self { *self }
}
impl ::rustc_lint_defs::LintPass for UnusedImportBraces {
    fn name(&self) -> &'static str { "UnusedImportBraces" }
    fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [UNUSED_IMPORT_BRACES]))
    }
}
impl UnusedImportBraces {
    #[allow(unused)]
    pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [UNUSED_IMPORT_BRACES]))
    }
}declare_lint_pass!(UnusedImportBraces => [UNUSED_IMPORT_BRACES]);
1360
1361impl UnusedImportBraces {
1362    fn check_use_tree(&self, cx: &EarlyContext<'_>, use_tree: &ast::UseTree, item: &ast::Item) {
1363        if let ast::UseTreeKind::Nested { ref items, .. } = use_tree.kind {
1364            // Recursively check nested UseTrees
1365            for tree in items {
1366                self.check_use_tree(cx, &tree.inner, item);
1367            }
1368
1369            // Trigger the lint only if there is one nested item
1370            let [tree] = items.as_slice() else { return };
1371
1372            // Trigger the lint if the nested item is a non-self single item
1373            let node_name = match tree.inner.kind {
1374                ast::UseTreeKind::Simple(rename) => {
1375                    let orig_ident = tree.inner.prefix.segments.last().unwrap().ident;
1376                    if orig_ident.name == kw::SelfLower {
1377                        return;
1378                    }
1379                    rename.unwrap_or(orig_ident).name
1380                }
1381                ast::UseTreeKind::Glob(_) => sym::asterisk,
1382                ast::UseTreeKind::Nested { .. } => return,
1383            };
1384
1385            cx.emit_span_lint(
1386                UNUSED_IMPORT_BRACES,
1387                item.span,
1388                UnusedImportBracesDiag { node: node_name },
1389            );
1390        }
1391    }
1392}
1393
1394impl EarlyLintPass for UnusedImportBraces {
1395    fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
1396        if let ast::ItemKind::Use(ref use_tree) = item.kind {
1397            self.check_use_tree(cx, use_tree, item);
1398        }
1399    }
1400}
1401
1402#[doc =
r" The `unused_allocation` lint detects unnecessary allocations that can"]
#[doc = r" be eliminated."]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust"]
#[doc = r" fn main() {"]
#[doc = r"     let a = Box::new([1, 2, 3]).len();"]
#[doc = r" }"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc =
r" When a `box` expression is immediately coerced to a reference, then"]
#[doc =
r" the allocation is unnecessary, and a reference (using `&` or `&mut`)"]
#[doc = r" should be used instead to avoid the allocation."]
pub(super) static UNUSED_ALLOCATION: &::rustc_lint_defs::Lint =
    &::rustc_lint_defs::Lint {
            name: "UNUSED_ALLOCATION",
            default_level: ::rustc_lint_defs::Warn,
            desc: "detects unnecessary allocations that can be eliminated",
            ..
        };declare_lint! {
1403    /// The `unused_allocation` lint detects unnecessary allocations that can
1404    /// be eliminated.
1405    ///
1406    /// ### Example
1407    ///
1408    /// ```rust
1409    /// fn main() {
1410    ///     let a = Box::new([1, 2, 3]).len();
1411    /// }
1412    /// ```
1413    ///
1414    /// {{produces}}
1415    ///
1416    /// ### Explanation
1417    ///
1418    /// When a `box` expression is immediately coerced to a reference, then
1419    /// the allocation is unnecessary, and a reference (using `&` or `&mut`)
1420    /// should be used instead to avoid the allocation.
1421    pub(super) UNUSED_ALLOCATION,
1422    Warn,
1423    "detects unnecessary allocations that can be eliminated"
1424}
1425
1426pub struct UnusedAllocation;
#[automatically_derived]impl ::core::marker::Copy for UnusedAllocation { }
#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for UnusedAllocation {
}
#[automatically_derived]impl ::core::clone::Clone for UnusedAllocation {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self { *self }
}
impl ::rustc_lint_defs::LintPass for UnusedAllocation {
    fn name(&self) -> &'static str { "UnusedAllocation" }
    fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [UNUSED_ALLOCATION]))
    }
}
impl UnusedAllocation {
    #[allow(unused)]
    pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [UNUSED_ALLOCATION]))
    }
}declare_lint_pass!(UnusedAllocation => [UNUSED_ALLOCATION]);
1427
1428impl<'tcx> LateLintPass<'tcx> for UnusedAllocation {
1429    fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &hir::Expr<'_>) {
1430        match e.kind {
1431            hir::ExprKind::Call(path_expr, [_])
1432                if let hir::ExprKind::Path(qpath) = &path_expr.kind
1433                    && let Some(did) = cx.qpath_res(qpath, path_expr.hir_id).opt_def_id()
1434                    && cx.tcx.is_diagnostic_item(sym::box_new, did) => {}
1435            _ => return,
1436        }
1437
1438        for adj in cx.typeck_results().expr_adjustments(e) {
1439            if let adjustment::Adjust::Borrow(adjustment::AutoBorrow::Ref(m)) = adj.kind {
1440                if let ty::Ref(_, inner_ty, _) = adj.target.kind()
1441                    && inner_ty.is_box()
1442                {
1443                    // If the target type is `&Box<T>` or `&mut Box<T>`, the allocation is necessary
1444                    continue;
1445                }
1446                match m {
1447                    adjustment::AutoBorrowMutability::Not => {
1448                        cx.emit_span_lint(UNUSED_ALLOCATION, e.span, UnusedAllocationDiag);
1449                    }
1450                    adjustment::AutoBorrowMutability::Mut { .. } => {
1451                        cx.emit_span_lint(UNUSED_ALLOCATION, e.span, UnusedAllocationMutDiag);
1452                    }
1453                };
1454            }
1455        }
1456    }
1457}