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