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 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
107trait UnusedDelimLint {
109 const DELIM_STR: &'static str;
110
111 const LINT_EXPR_IN_PATTERN_MATCHING_CTX: bool;
123
124 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 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 | UnsafeBinderCast(_, expr, _) => Self::expr_allows_remove_arg_block(expr),
158 Array(exprs) | Tup(exprs) => {
159 exprs.iter().all(|expr| Self::expr_allows_remove_arg_block(expr))
160 }
161 Binary(_, lhs, rhs) | Assign(lhs, rhs, _) | AssignOp(_, lhs, rhs) => {
162 Self::expr_allows_remove_arg_block(lhs) && Self::expr_allows_remove_arg_block(rhs)
163 }
164 Index(base, index, _) => {
165 Self::expr_allows_remove_arg_block(base)
166 && Self::expr_allows_remove_arg_block(index)
167 }
168 Range(start, end, _) => {
169 start.as_ref().is_none_or(|expr| Self::expr_allows_remove_arg_block(expr))
170 && end.as_ref().is_none_or(|expr| Self::expr_allows_remove_arg_block(expr))
171 }
172 Struct(expr) => {
173 expr.fields.iter().all(|field| Self::expr_allows_remove_arg_block(&field.expr))
174 && match &expr.rest {
175 ast::StructRest::Base(expr) => Self::expr_allows_remove_arg_block(expr),
176 ast::StructRest::Rest(_) | ast::StructRest::None => true,
177 ast::StructRest::NoneWithError(_) => false,
178 }
179 }
180 Repeat(expr, _) => Self::expr_allows_remove_arg_block(expr),
181 ConstBlock(_)
182 | If(..)
183 | While(..)
184 | ForLoop { .. }
185 | Loop(..)
186 | Match(..)
187 | Closure(_)
188 | Block(..)
189 | Gen(..)
190 | TryBlock(..)
191 | Break(..)
192 | Continue(_)
193 | Ret(_)
194 | InlineAsm(_)
195 | OffsetOf(..)
196 | Yield(_)
197 | Yeet(_)
198 | Paren(_)
199 | Become(_) => true,
200 Call(..) | MethodCall(_) | Let(..) | Field(..) | MacCall(_) | FormatArgs(_) => false,
201 GcaMacro(_) => false,
203 Underscore | Err(_) | Dummy => false,
205 }
206 }
207
208 fn needs_arg_block_to_preserve_temporaries(
211 ctx: UnusedDelimsCtx,
212 arg_block: &ast::Expr,
213 expr: &ast::Expr,
214 ) -> bool {
215 #[allow(non_exhaustive_omitted_patterns)] match ctx {
UnusedDelimsCtx::FunctionArg | UnusedDelimsCtx::MethodArg => true,
_ => false,
}matches!(ctx, UnusedDelimsCtx::FunctionArg | UnusedDelimsCtx::MethodArg)
216 && arg_block.span.edition().at_least_rust_2024()
217 && !Self::expr_allows_remove_arg_block(expr)
218 }
219
220 fn is_expr_delims_necessary(
221 inner: &ast::Expr,
222 ctx: UnusedDelimsCtx,
223 followed_by_block: bool,
224 ) -> bool {
225 let followed_by_else = ctx == UnusedDelimsCtx::AssignedValueLetElse;
226
227 if followed_by_else {
228 match inner.kind {
229 ast::ExprKind::Binary(op, ..) if op.node.is_lazy() => return true,
230 _ if classify::expr_trailing_brace(inner).is_some() => return true,
231 _ => {}
232 }
233 }
234
235 if let ast::ExprKind::Range(..) = inner.kind
237 && #[allow(non_exhaustive_omitted_patterns)] match ctx {
UnusedDelimsCtx::LetScrutineeExpr => true,
_ => false,
}matches!(ctx, UnusedDelimsCtx::LetScrutineeExpr)
238 {
239 return true;
240 }
241
242 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, ..)) {
246 return true;
247 }
248
249 {
279 let mut innermost = inner;
280 loop {
281 innermost = match &innermost.kind {
282 ExprKind::Binary(_op, lhs, _rhs) => lhs,
283 ExprKind::Call(fn_, _params) => fn_,
284 ExprKind::Cast(expr, _ty) => expr,
285 ExprKind::Type(expr, _ty) => expr,
286 ExprKind::Index(base, _subscript, _) => base,
287 _ => break,
288 };
289 if !classify::expr_requires_semi_to_be_stmt(innermost) {
290 return true;
291 }
292 }
293 }
294
295 if !followed_by_block {
298 return false;
299 }
300
301 {
303 let mut innermost = inner;
304 loop {
305 innermost = match &innermost.kind {
306 ExprKind::AddrOf(_, _, expr) => expr,
307 _ => {
308 if parser::contains_exterior_struct_lit(innermost) {
309 return true;
310 } else {
311 break;
312 }
313 }
314 }
315 }
316 }
317
318 let mut innermost = inner;
319 loop {
320 innermost = match &innermost.kind {
321 ExprKind::Unary(_op, expr) => expr,
322 ExprKind::Binary(_op, _lhs, rhs) => rhs,
323 ExprKind::AssignOp(_op, _lhs, rhs) => rhs,
324 ExprKind::Assign(_lhs, rhs, _span) => rhs,
325
326 ExprKind::Ret(_) | ExprKind::Yield(..) | ExprKind::Yeet(..) => return true,
327
328 ExprKind::Break(_label, None) => return false,
329 ExprKind::Break(_label, Some(break_expr)) => {
330 return #[allow(non_exhaustive_omitted_patterns)] match break_expr.kind {
ExprKind::Block(..) | ExprKind::Path(..) => true,
_ => false,
}matches!(break_expr.kind, ExprKind::Block(..) | ExprKind::Path(..));
334 }
335
336 ExprKind::Range(_lhs, Some(rhs), _limits) => {
337 return #[allow(non_exhaustive_omitted_patterns)] match rhs.kind {
ExprKind::Block(..) => true,
_ => false,
}matches!(rhs.kind, ExprKind::Block(..));
338 }
339
340 _ => return parser::contains_exterior_struct_lit(inner),
341 }
342 }
343 }
344
345 fn emit_unused_delims_expr(
346 &self,
347 cx: &EarlyContext<'_>,
348 value: &ast::Expr,
349 ctx: UnusedDelimsCtx,
350 left_pos: Option<BytePos>,
351 right_pos: Option<BytePos>,
352 is_kw: bool,
353 ) {
354 let span_with_attrs = match value.kind {
355 ast::ExprKind::Block(ref block, None) if let [stmt] = block.stmts.as_slice() => {
356 if let Some(attr_lo) = stmt.attrs().iter().map(|attr| attr.span.lo()).min() {
359 stmt.span.with_lo(attr_lo)
360 } else {
361 stmt.span
362 }
363 }
364 ast::ExprKind::Paren(ref expr) => {
365 if let Some(attr_lo) = expr.attrs.iter().map(|attr| attr.span.lo()).min() {
368 expr.span.with_lo(attr_lo)
369 } else {
370 expr.span
371 }
372 }
373 _ => return,
374 };
375 let spans = span_with_attrs
376 .find_ancestor_inside(value.span)
377 .map(|span| (value.span.with_hi(span.lo()), value.span.with_lo(span.hi())));
378 let keep_space = (
379 left_pos.is_some_and(|s| s >= value.span.lo()),
380 right_pos.is_some_and(|s| s <= value.span.hi()),
381 );
382 self.emit_unused_delims(cx, value.span, spans, ctx.into(), keep_space, is_kw);
383 }
384
385 fn emit_unused_delims(
386 &self,
387 cx: &EarlyContext<'_>,
388 value_span: Span,
389 spans: Option<(Span, Span)>,
390 msg: &str,
391 keep_space: (bool, bool),
392 is_kw: bool,
393 ) {
394 let sm = cx.sess().source_map();
395 let shrink = |span: Span, open: bool, in_help: bool| -> Span {
398 if span.is_empty() {
399 return span;
400 }
401 let (delim, gap) = if open {
402 let delim = span.with_hi(span.lo() + BytePos(1));
403 (delim, span.with_lo(delim.hi()))
404 } else {
405 let delim = span.with_lo(span.hi() - BytePos(1));
406 (delim, span.with_hi(delim.lo()))
407 };
408 let is_delim =
409 sm.span_to_snippet(delim).is_ok_and(|s| #[allow(non_exhaustive_omitted_patterns)] match &*s {
"(" | ")" | "{" | "}" => true,
_ => false,
}matches!(&*s, "(" | ")" | "{" | "}"));
410 let has_comment = sm.span_to_snippet(gap).is_ok_and(|s| !s.trim().is_empty());
411 if is_delim && (!in_help || has_comment) { delim } else { span }
412 };
413 let primary_span = if let Some((lo, hi)) = spans {
414 if hi.is_empty() {
415 return;
417 }
418 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)])
419 } else {
420 MultiSpan::from(value_span)
421 };
422 let suggestion = spans.map(|(lo, hi)| {
423 let (lo, hi) = (shrink(lo, true, true), shrink(hi, false, true));
424 let lo_replace = if (keep_space.0 || is_kw)
425 && let Ok(snip) = sm.span_to_prev_source(lo)
426 && !snip.ends_with(' ')
427 {
428 " "
429 } else if let Ok(snip) = sm.span_to_prev_source(value_span)
430 && snip.ends_with(|c: char| c.is_alphanumeric())
431 {
432 " "
433 } else {
434 ""
435 };
436
437 let hi_replace = if keep_space.1
438 && let Ok(snip) = sm.span_to_next_source(hi)
439 && !snip.starts_with(' ')
440 {
441 " "
442 } else if let Ok(snip) = sm.span_to_next_source(value_span)
443 && snip.starts_with(|c: char| c.is_alphanumeric())
444 {
445 " "
446 } else {
447 ""
448 };
449 UnusedDelimSuggestion {
450 start_span: lo,
451 start_replace: lo_replace,
452 end_span: hi,
453 end_replace: hi_replace,
454 delim: Self::DELIM_STR,
455 }
456 });
457 cx.emit_span_lint(
458 self.lint(),
459 primary_span,
460 UnusedDelim { delim: Self::DELIM_STR, item: msg, suggestion },
461 );
462 }
463
464 fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
465 use rustc_ast::ExprKind::*;
466 let (value, ctx, followed_by_block, left_pos, right_pos, is_kw) = match e.kind {
467 If(ref cond, ref block, _)
469 if !#[allow(non_exhaustive_omitted_patterns)] match cond.kind {
Let(..) => true,
_ => false,
}matches!(cond.kind, Let(..)) || Self::LINT_EXPR_IN_PATTERN_MATCHING_CTX =>
470 {
471 let left = e.span.lo() + rustc_span::BytePos(2);
472 let right = block.span.lo();
473 (cond, UnusedDelimsCtx::IfCond, true, Some(left), Some(right), true)
474 }
475
476 While(ref cond, ref block, ..)
478 if !#[allow(non_exhaustive_omitted_patterns)] match cond.kind {
Let(..) => true,
_ => false,
}matches!(cond.kind, Let(..)) || Self::LINT_EXPR_IN_PATTERN_MATCHING_CTX =>
479 {
480 let left = e.span.lo() + rustc_span::BytePos(5);
481 let right = block.span.lo();
482 (cond, UnusedDelimsCtx::WhileCond, true, Some(left), Some(right), true)
483 }
484
485 ForLoop(ast::ForLoop { ref iter, ref body, .. }) => {
486 (iter, UnusedDelimsCtx::ForIterExpr, true, None, Some(body.span.lo()), true)
487 }
488
489 Match(ref head, _, ast::MatchKind::Prefix)
490 if Self::LINT_EXPR_IN_PATTERN_MATCHING_CTX =>
491 {
492 let left = e.span.lo() + rustc_span::BytePos(5);
493 (head, UnusedDelimsCtx::MatchScrutineeExpr, true, Some(left), None, true)
494 }
495
496 Ret(Some(ref value)) => {
497 let left = e.span.lo() + rustc_span::BytePos(3);
498 (value, UnusedDelimsCtx::ReturnValue, false, Some(left), None, true)
499 }
500
501 Break(label, Some(ref value)) => {
502 if label.is_some()
506 && #[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)
507 if matches!(inner.kind, ast::ExprKind::Block(..)))
508 {
509 return;
510 }
511 (value, UnusedDelimsCtx::BreakValue, false, None, None, true)
512 }
513
514 Index(_, ref value, _) => (value, UnusedDelimsCtx::IndexExpr, false, None, None, false),
515
516 Assign(_, ref value, _) | AssignOp(.., ref value) => {
517 (value, UnusedDelimsCtx::AssignedValue, false, None, None, false)
518 }
519 ref call_or_other => {
521 let (args_to_check, ctx, callee_from_expansion) = match *call_or_other {
522 Call(ref callee, ref args) => {
523 (&args[..], UnusedDelimsCtx::FunctionArg, callee.span.from_expansion())
524 }
525 MethodCall(ref call) => (
526 &call.args[..],
527 UnusedDelimsCtx::MethodArg,
528 call.seg.ident.span.from_expansion(),
529 ),
530 Closure(ref closure)
531 if #[allow(non_exhaustive_omitted_patterns)] match closure.fn_decl.output {
FnRetTy::Default(_) => true,
_ => false,
}matches!(closure.fn_decl.output, FnRetTy::Default(_)) =>
532 {
533 (&[closure.body.clone()][..], UnusedDelimsCtx::ClosureBody, false)
534 }
535 _ => {
537 return;
538 }
539 };
540 if e.span.ctxt().outer_expn_data().call_site.from_expansion() {
545 return;
546 }
547 for arg in args_to_check {
548 if callee_from_expansion && Self::block_wraps_expanded_expr(arg) {
551 continue;
552 }
553 self.check_unused_delims_expr(cx, arg, ctx, false, None, None, false);
554 }
555 return;
556 }
557 };
558 self.check_unused_delims_expr(
559 cx,
560 value,
561 ctx,
562 followed_by_block,
563 left_pos,
564 right_pos,
565 is_kw,
566 );
567 }
568
569 fn check_stmt(&mut self, cx: &EarlyContext<'_>, s: &ast::Stmt) {
570 match s.kind {
571 StmtKind::Let(ref local) if Self::LINT_EXPR_IN_PATTERN_MATCHING_CTX => {
572 if let Some((init, els)) = local.kind.init_else_opt() {
573 if els.is_some()
574 && let ExprKind::Paren(paren) = &init.kind
575 && init.span.ctxt() != paren.span.ctxt()
576 {
577 return;
588 }
589 let ctx = match els {
590 None => UnusedDelimsCtx::AssignedValue,
591 Some(_) => UnusedDelimsCtx::AssignedValueLetElse,
592 };
593 self.check_unused_delims_expr(cx, init, ctx, false, None, None, false);
594 }
595 }
596 StmtKind::Expr(ref expr) => {
597 self.check_unused_delims_expr(
598 cx,
599 expr,
600 UnusedDelimsCtx::BlockRetValue,
601 false,
602 None,
603 None,
604 false,
605 );
606 }
607 _ => {}
608 }
609 }
610
611 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
612 use ast::ItemKind::*;
613
614 let expr = if let Const(ast::ConstItem { body: Some(expr), .. }) = &item.kind {
615 expr
616 } else if let Static(ast::StaticItem { expr: Some(expr), .. }) = &item.kind {
617 expr
618 } else {
619 return;
620 };
621 self.check_unused_delims_expr(
622 cx,
623 expr,
624 UnusedDelimsCtx::AssignedValue,
625 false,
626 None,
627 None,
628 false,
629 );
630 }
631
632 fn block_wraps_expanded_expr(value: &ast::Expr) -> bool {
634 if let ast::ExprKind::Block(ref block, None) = value.kind
635 && block.rules == ast::BlockCheckMode::Default
636 && !value.span.from_expansion()
637 && let [stmt] = block.stmts.as_slice()
638 && let ast::StmtKind::Expr(ref expr) = stmt.kind
639 {
640 expr.span.from_expansion()
641 } else {
642 false
643 }
644 }
645}
646
647#[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! {
648 pub(super) UNUSED_PARENS,
664 Warn,
665 "`if`, `match`, `while` and `return` do not need parentheses"
666}
667
668#[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)]
669pub(crate) struct UnusedParens {
670 with_self_ty_parens: bool,
671 parens_in_cast_in_lt: Vec<ast::NodeId>,
674 in_no_bounds_pos: FxHashMap<ast::NodeId, NoBoundsException>,
677}
678
679enum NoBoundsException {
694 None,
696 OneBound,
699}
700
701impl ::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]);
702
703impl UnusedDelimLint for UnusedParens {
704 const DELIM_STR: &'static str = "parentheses";
705
706 const LINT_EXPR_IN_PATTERN_MATCHING_CTX: bool = true;
707
708 fn lint(&self) -> &'static Lint {
709 UNUSED_PARENS
710 }
711
712 fn check_unused_delims_expr(
713 &self,
714 cx: &EarlyContext<'_>,
715 value: &ast::Expr,
716 ctx: UnusedDelimsCtx,
717 followed_by_block: bool,
718 left_pos: Option<BytePos>,
719 right_pos: Option<BytePos>,
720 is_kw: bool,
721 ) {
722 match value.kind {
723 ast::ExprKind::Paren(ref inner) => {
724 if !Self::is_expr_delims_necessary(inner, ctx, followed_by_block)
725 && value.attrs.is_empty()
726 && !value.span.from_expansion()
727 && (ctx != UnusedDelimsCtx::LetScrutineeExpr
728 || !#[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(
729 rustc_span::Spanned { node, .. },
730 _,
731 _,
732 ) if node.is_lazy()))
733 && !((ctx == UnusedDelimsCtx::ReturnValue
734 || ctx == UnusedDelimsCtx::BreakValue)
735 && #[allow(non_exhaustive_omitted_patterns)] match inner.kind {
ast::ExprKind::Assign(_, _, _) => true,
_ => false,
}matches!(inner.kind, ast::ExprKind::Assign(_, _, _)))
736 {
737 self.emit_unused_delims_expr(cx, value, ctx, left_pos, right_pos, is_kw)
738 }
739 }
740 ast::ExprKind::Let(_, ref expr, _, _) => {
741 self.check_unused_delims_expr(
742 cx,
743 expr,
744 UnusedDelimsCtx::LetScrutineeExpr,
745 followed_by_block,
746 None,
747 None,
748 false,
749 );
750 }
751 _ => {}
752 }
753 }
754}
755
756impl UnusedParens {
757 fn check_unused_parens_pat(
758 &self,
759 cx: &EarlyContext<'_>,
760 value: &ast::Pat,
761 avoid_or: bool,
762 avoid_mut: bool,
763 keep_space: (bool, bool),
764 ) {
765 use ast::{BindingMode, ByRef, Mutability, PatKind, Pinnedness};
766
767 if let PatKind::Paren(inner) = &value.kind {
768 match inner.kind {
769 PatKind::Range(..) => return,
774 PatKind::Guard(..) => return,
776 PatKind::Or(..) if avoid_or => return,
778 PatKind::Ident(BindingMode(_, Mutability::Mut), ..) if avoid_mut => {
781 return;
782 }
783 PatKind::Ref(_, Pinnedness::Pinned, _)
784 | PatKind::Ident(BindingMode(ByRef::Yes(Pinnedness::Pinned, _), _), ..)
785 if !cx.builder.features().pin_ergonomics() =>
787 {
788 return;
789 }
790 _ => {}
792 }
793 let spans = if !value.span.from_expansion() {
794 inner
795 .span
796 .find_ancestor_inside(value.span)
797 .map(|inner| (value.span.with_hi(inner.lo()), value.span.with_lo(inner.hi())))
798 } else {
799 None
800 };
801 self.emit_unused_delims(cx, value.span, spans, "pattern", keep_space, false);
802 }
803 }
804
805 fn pat_is_macro_arg(pat_span: Span, parent_span: Span) -> bool {
810 pat_span.ctxt() != parent_span.ctxt()
811 }
812
813 fn cast_followed_by_lt(&self, expr: &ast::Expr) -> Option<ast::NodeId> {
814 if let ExprKind::Binary(op, lhs, _rhs) = &expr.kind
815 && (op.node == ast::BinOpKind::Lt || op.node == ast::BinOpKind::Shl)
816 {
817 let mut cur = lhs;
818 while let ExprKind::Binary(_, _, rhs) = &cur.kind {
819 cur = rhs;
820 }
821
822 if let ExprKind::Cast(_, ty) = &cur.kind
823 && let ast::TyKind::Paren(_) = &ty.kind
824 {
825 return Some(ty.id);
826 }
827 }
828 None
829 }
830}
831
832impl EarlyLintPass for UnusedParens {
833 #[inline]
834 fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
835 if let Some(ty_id) = self.cast_followed_by_lt(e) {
836 self.parens_in_cast_in_lt.push(ty_id);
837 }
838
839 match e.kind {
840 ExprKind::Let(ref pat, _, _, _) | ExprKind::ForLoop(ForLoop { ref pat, .. }) => {
841 let avoid_or = Self::pat_is_macro_arg(pat.span, e.span);
842 self.check_unused_parens_pat(cx, pat, avoid_or, false, (true, true));
843 }
844 ExprKind::If(ref cond, ref block, ref else_)
848 if #[allow(non_exhaustive_omitted_patterns)] match cond.peel_parens().kind {
ExprKind::Let(..) => true,
_ => false,
}matches!(cond.peel_parens().kind, ExprKind::Let(..)) =>
849 {
850 self.check_unused_delims_expr(
851 cx,
852 cond.peel_parens(),
853 UnusedDelimsCtx::LetScrutineeExpr,
854 true,
855 None,
856 None,
857 true,
858 );
859 for stmt in &block.stmts {
860 <Self as UnusedDelimLint>::check_stmt(self, cx, stmt);
861 }
862 if let Some(e) = else_ {
863 <Self as UnusedDelimLint>::check_expr(self, cx, e);
864 }
865 return;
866 }
867 ExprKind::Match(ref _expr, ref arm, _) => {
868 for a in arm {
869 if let Some(body) = &a.body {
870 self.check_unused_delims_expr(
871 cx,
872 body,
873 UnusedDelimsCtx::MatchArmExpr,
874 false,
875 None,
876 None,
877 true,
878 );
879 }
880 }
881 }
882 _ => {}
883 }
884
885 <Self as UnusedDelimLint>::check_expr(self, cx, e)
886 }
887
888 fn check_expr_post(&mut self, _cx: &EarlyContext<'_>, e: &ast::Expr) {
889 if let Some(ty_id) = self.cast_followed_by_lt(e) {
890 let id = self
891 .parens_in_cast_in_lt
892 .pop()
893 .expect("check_expr and check_expr_post must balance");
894 {
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!(
895 id, ty_id,
896 "check_expr, check_ty, and check_expr_post are called, in that order, by the visitor"
897 );
898 }
899 }
900
901 fn check_pat(&mut self, cx: &EarlyContext<'_>, p: &ast::Pat) {
902 use ast::PatKind::*;
903 use ast::{Mutability, Pinnedness};
904 let keep_space = (false, false);
905 match &p.kind {
906 Paren(_) => {}
908 Missing
910 | Wild
911 | Never
912 | Rest
913 | Expr(..)
914 | MacCall(..)
915 | Range(..)
916 | Ident(.., None)
917 | Path(..)
918 | Err(_) => {}
919 TupleStruct(_, _, ps) | Tuple(ps) | Slice(ps) | Or(ps) => {
921 for sub in ps {
922 let avoid_or = Self::pat_is_macro_arg(sub.span, p.span);
923 self.check_unused_parens_pat(cx, sub, avoid_or, false, keep_space);
924 }
925 }
926 Struct(_, _, fps, _) => {
927 for f in fps {
928 let avoid_or = Self::pat_is_macro_arg(f.pat.span, p.span);
929 self.check_unused_parens_pat(cx, &f.pat, avoid_or, false, keep_space);
930 }
931 }
932 Ident(.., Some(p)) | Deref(p) | Guard(p, _) => {
934 self.check_unused_parens_pat(cx, p, true, false, keep_space)
935 }
936 Ref(p, pinned, m)
942 if *pinned != Pinnedness::Pinned
943 || cx.builder.features().pin_ergonomics() =>
945 {
946 self.check_unused_parens_pat(
947 cx,
948 p,
949 true,
950 *pinned == Pinnedness::Not && *m == Mutability::Not,
951 keep_space,
952 );
953 }
954 Ref(..) => {}
955 }
956 }
957
958 fn check_stmt(&mut self, cx: &EarlyContext<'_>, s: &ast::Stmt) {
959 if let StmtKind::Let(ref local) = s.kind {
960 self.check_unused_parens_pat(cx, &local.pat, true, false, (true, false));
961 }
962
963 <Self as UnusedDelimLint>::check_stmt(self, cx, s)
964 }
965
966 fn check_param(&mut self, cx: &EarlyContext<'_>, param: &ast::Param) {
967 self.check_unused_parens_pat(cx, ¶m.pat, true, false, (false, false));
968 }
969
970 fn check_arm(&mut self, cx: &EarlyContext<'_>, arm: &ast::Arm) {
971 let avoid_or = Self::pat_is_macro_arg(arm.pat.span, arm.span);
972 self.check_unused_parens_pat(cx, &arm.pat, avoid_or, false, (false, false));
973 }
974
975 fn check_ty(&mut self, cx: &EarlyContext<'_>, ty: &ast::Ty) {
976 if let ast::TyKind::Paren(_) = ty.kind
977 && Some(&ty.id) == self.parens_in_cast_in_lt.last()
978 {
979 return;
980 }
981 match &ty.kind {
982 ast::TyKind::Array(_, len) => {
983 self.check_unused_delims_expr(
984 cx,
985 &len.value,
986 UnusedDelimsCtx::ArrayLenExpr,
987 false,
988 None,
989 None,
990 false,
991 );
992 }
993 ast::TyKind::Paren(r) => {
994 let unused_parens = match &r.kind {
995 ast::TyKind::ImplTrait(_, bounds) | ast::TyKind::TraitObject(bounds, _) => {
996 match self.in_no_bounds_pos.get(&ty.id) {
997 Some(NoBoundsException::None) => false,
998 Some(NoBoundsException::OneBound) => bounds.len() <= 1,
999 None => true,
1000 }
1001 }
1002 ast::TyKind::FnPtr(b) => {
1003 !self.with_self_ty_parens || b.generic_params.is_empty()
1004 }
1005 _ => true,
1006 };
1007
1008 if unused_parens {
1009 let spans = (!ty.span.from_expansion())
1010 .then(|| {
1011 r.span
1012 .find_ancestor_inside(ty.span)
1013 .map(|r| (ty.span.with_hi(r.lo()), ty.span.with_lo(r.hi())))
1014 })
1015 .flatten();
1016
1017 self.emit_unused_delims(cx, ty.span, spans, "type", (false, false), false);
1018 }
1019
1020 self.with_self_ty_parens = false;
1021 }
1022 ast::TyKind::Ref(_, inner_ty, _) | ast::TyKind::Ptr(inner_ty, _) => {
1023 let own_constraint = self.in_no_bounds_pos.get(&ty.id);
1026 let constraint = match own_constraint {
1027 Some(NoBoundsException::None) => NoBoundsException::None,
1028 Some(NoBoundsException::OneBound) => NoBoundsException::OneBound,
1029 None => NoBoundsException::OneBound,
1030 };
1031 self.in_no_bounds_pos.insert(inner_ty.id, constraint);
1032 }
1033 ast::TyKind::TraitObject(bounds, _) | ast::TyKind::ImplTrait(_, bounds) => {
1034 for i in 0..bounds.len() {
1035 let is_last = i == bounds.len() - 1;
1036
1037 if let ast::GenericBound::Trait(poly_trait_ref) = &bounds[i] {
1038 let fn_with_explicit_ret_ty = if let [.., segment] =
1039 &*poly_trait_ref.trait_ref.path.segments
1040 && let Some(args) = segment.args.as_ref()
1041 && let ast::GenericArgs::Parenthesized(paren_args) = &**args
1042 && let ast::FnRetTy::Ty(ret_ty) = &paren_args.output
1043 {
1044 self.in_no_bounds_pos.insert(
1045 ret_ty.id,
1046 if is_last {
1047 NoBoundsException::OneBound
1048 } else {
1049 NoBoundsException::None
1050 },
1051 );
1052
1053 true
1054 } else {
1055 false
1056 };
1057
1058 let dyn2015_exception = cx.sess().psess.edition == Edition2015
1063 && #[allow(non_exhaustive_omitted_patterns)] match ty.kind {
ast::TyKind::TraitObject(..) => true,
_ => false,
}matches!(ty.kind, ast::TyKind::TraitObject(..))
1064 && i == 0
1065 && poly_trait_ref
1066 .trait_ref
1067 .path
1068 .segments
1069 .first()
1070 .map(|s| s.ident.name == kw::PathRoot)
1071 .unwrap_or(false);
1072
1073 if let ast::Parens::Yes = poly_trait_ref.parens
1074 && (is_last || !fn_with_explicit_ret_ty)
1075 && !dyn2015_exception
1076 {
1077 let s = poly_trait_ref.span;
1078 if !s.from_expansion()
1082 && let Ok(snippet) = cx.sess().source_map().span_to_snippet(s)
1083 && snippet.starts_with('(')
1084 && snippet.ends_with(')')
1085 {
1086 let spans = Some((
1087 s.with_hi(s.lo() + rustc_span::BytePos(1)),
1088 s.with_lo(s.hi() - rustc_span::BytePos(1)),
1089 ));
1090
1091 self.emit_unused_delims(
1092 cx,
1093 poly_trait_ref.span,
1094 spans,
1095 "type",
1096 (false, false),
1097 false,
1098 );
1099 }
1100 }
1101 }
1102 }
1103 }
1104 _ => {}
1105 }
1106 }
1107
1108 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
1109 <Self as UnusedDelimLint>::check_item(self, cx, item)
1110 }
1111
1112 fn check_item_post(&mut self, _: &EarlyContext<'_>, _: &rustc_ast::Item) {
1113 self.in_no_bounds_pos.clear();
1114 }
1115
1116 fn check_where_predicate(&mut self, _: &EarlyContext<'_>, pred: &ast::WherePredicate) {
1117 use rustc_ast::{WhereBoundPredicate, WherePredicateKind};
1118 if let WherePredicateKind::BoundPredicate(WhereBoundPredicate {
1119 bounded_ty,
1120 bound_generic_params,
1121 ..
1122 }) = &pred.kind
1123 && let ast::TyKind::Paren(_) = &bounded_ty.kind
1124 && bound_generic_params.is_empty()
1125 {
1126 self.with_self_ty_parens = true;
1127 }
1128 }
1129
1130 fn check_where_predicate_post(&mut self, _: &EarlyContext<'_>, _: &ast::WherePredicate) {
1131 if !!self.with_self_ty_parens {
::core::panicking::panic("assertion failed: !self.with_self_ty_parens")
};assert!(!self.with_self_ty_parens);
1132 }
1133}
1134
1135#[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! {
1136 pub(super) UNUSED_BRACES,
1154 Warn,
1155 "unnecessary braces around an expression"
1156}
1157
1158pub 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]);
1159
1160impl UnusedDelimLint for UnusedBraces {
1161 const DELIM_STR: &'static str = "braces";
1162
1163 const LINT_EXPR_IN_PATTERN_MATCHING_CTX: bool = false;
1164
1165 fn lint(&self) -> &'static Lint {
1166 UNUSED_BRACES
1167 }
1168
1169 fn check_unused_delims_expr(
1170 &self,
1171 cx: &EarlyContext<'_>,
1172 value: &ast::Expr,
1173 ctx: UnusedDelimsCtx,
1174 followed_by_block: bool,
1175 left_pos: Option<BytePos>,
1176 right_pos: Option<BytePos>,
1177 is_kw: bool,
1178 ) {
1179 match value.kind {
1180 ast::ExprKind::Block(ref inner, None)
1181 if inner.rules == ast::BlockCheckMode::Default =>
1182 {
1183 if let [stmt] = inner.stmts.as_slice()
1208 && let ast::StmtKind::Expr(ref expr) = stmt.kind
1209 && !Self::is_expr_delims_necessary(expr, ctx, followed_by_block)
1210 && !(ctx == UnusedDelimsCtx::ForIterExpr
1213 && value.span.edition().at_least_rust_2024())
1214 && !Self::needs_arg_block_to_preserve_temporaries(ctx, value, expr)
1215 && (ctx != UnusedDelimsCtx::AnonConst
1216 || (#[allow(non_exhaustive_omitted_patterns)] match expr.kind {
ast::ExprKind::Lit(_) => true,
_ => false,
}matches!(expr.kind, ast::ExprKind::Lit(_))
1217 && !expr.span.from_expansion()))
1218 && ctx != UnusedDelimsCtx::ClosureBody
1219 && !cx.sess().source_map().is_multiline(value.span)
1220 && value.attrs.is_empty()
1221 && !value.span.from_expansion()
1222 && !inner.span.from_expansion()
1223 {
1224 self.emit_unused_delims_expr(cx, value, ctx, left_pos, right_pos, is_kw)
1225 }
1226 }
1227 ast::ExprKind::Let(_, ref expr, _, _) => {
1228 self.check_unused_delims_expr(
1229 cx,
1230 expr,
1231 UnusedDelimsCtx::LetScrutineeExpr,
1232 followed_by_block,
1233 None,
1234 None,
1235 false,
1236 );
1237 }
1238 _ => {}
1239 }
1240 }
1241}
1242
1243impl EarlyLintPass for UnusedBraces {
1244 fn check_stmt(&mut self, cx: &EarlyContext<'_>, s: &ast::Stmt) {
1245 <Self as UnusedDelimLint>::check_stmt(self, cx, s)
1246 }
1247
1248 #[inline]
1249 fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
1250 <Self as UnusedDelimLint>::check_expr(self, cx, e);
1251
1252 if let ExprKind::Repeat(_, ref anon_const) = e.kind {
1253 self.check_unused_delims_expr(
1254 cx,
1255 &anon_const.value,
1256 UnusedDelimsCtx::AnonConst,
1257 false,
1258 None,
1259 None,
1260 false,
1261 );
1262 }
1263 }
1264
1265 fn check_generic_arg(&mut self, cx: &EarlyContext<'_>, arg: &ast::GenericArg) {
1266 if let ast::GenericArg::Const(ct) = arg {
1267 self.check_unused_delims_expr(
1268 cx,
1269 &ct.value,
1270 UnusedDelimsCtx::AnonConst,
1271 false,
1272 None,
1273 None,
1274 false,
1275 );
1276 }
1277 }
1278
1279 fn check_variant(&mut self, cx: &EarlyContext<'_>, v: &ast::Variant) {
1280 if let Some(anon_const) = &v.disr_expr {
1281 self.check_unused_delims_expr(
1282 cx,
1283 &anon_const.value,
1284 UnusedDelimsCtx::AnonConst,
1285 false,
1286 None,
1287 None,
1288 false,
1289 );
1290 }
1291 }
1292
1293 fn check_ty(&mut self, cx: &EarlyContext<'_>, ty: &ast::Ty) {
1294 match ty.kind {
1295 ast::TyKind::Array(_, ref len) => {
1296 self.check_unused_delims_expr(
1297 cx,
1298 &len.value,
1299 UnusedDelimsCtx::ArrayLenExpr,
1300 false,
1301 None,
1302 None,
1303 false,
1304 );
1305 }
1306
1307 _ => {}
1308 }
1309 }
1310
1311 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
1312 <Self as UnusedDelimLint>::check_item(self, cx, item)
1313 }
1314}
1315
1316#[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! {
1317 UNUSED_IMPORT_BRACES,
1342 Allow,
1343 "unnecessary braces around an imported item"
1344}
1345
1346pub 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]);
1347
1348impl UnusedImportBraces {
1349 fn check_use_tree(&self, cx: &EarlyContext<'_>, use_tree: &ast::UseTree, item: &ast::Item) {
1350 if let ast::UseTreeKind::Nested { ref items, .. } = use_tree.kind {
1351 for tree in items {
1353 self.check_use_tree(cx, &tree.inner, item);
1354 }
1355
1356 let [tree] = items.as_slice() else { return };
1358
1359 let node_name = match tree.inner.kind {
1361 ast::UseTreeKind::Simple(rename) => {
1362 let orig_ident = tree.inner.prefix.segments.last().unwrap().ident;
1363 if orig_ident.name == kw::SelfLower {
1364 return;
1365 }
1366 rename.unwrap_or(orig_ident).name
1367 }
1368 ast::UseTreeKind::Glob(_) => sym::asterisk,
1369 ast::UseTreeKind::Nested { .. } => return,
1370 };
1371
1372 cx.emit_span_lint(
1373 UNUSED_IMPORT_BRACES,
1374 item.span,
1375 UnusedImportBracesDiag { node: node_name },
1376 );
1377 }
1378 }
1379}
1380
1381impl EarlyLintPass for UnusedImportBraces {
1382 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
1383 if let ast::ItemKind::Use(ref use_tree) = item.kind {
1384 self.check_use_tree(cx, use_tree, item);
1385 }
1386 }
1387}
1388
1389#[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! {
1390 pub(super) UNUSED_ALLOCATION,
1409 Warn,
1410 "detects unnecessary allocations that can be eliminated"
1411}
1412
1413pub 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]);
1414
1415impl<'tcx> LateLintPass<'tcx> for UnusedAllocation {
1416 fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &hir::Expr<'_>) {
1417 match e.kind {
1418 hir::ExprKind::Call(path_expr, [_])
1419 if let hir::ExprKind::Path(qpath) = &path_expr.kind
1420 && let Some(did) = cx.qpath_res(qpath, path_expr.hir_id).opt_def_id()
1421 && cx.tcx.is_diagnostic_item(sym::box_new, did) => {}
1422 _ => return,
1423 }
1424
1425 for adj in cx.typeck_results().expr_adjustments(e) {
1426 if let adjustment::Adjust::Borrow(adjustment::AutoBorrow::Ref(m)) = adj.kind {
1427 if let ty::Ref(_, inner_ty, _) = adj.target.kind()
1428 && inner_ty.is_box()
1429 {
1430 continue;
1432 }
1433 match m {
1434 adjustment::AutoBorrowMutability::Not => {
1435 cx.emit_span_lint(UNUSED_ALLOCATION, e.span, UnusedAllocationDiag);
1436 }
1437 adjustment::AutoBorrowMutability::Mut { .. } => {
1438 cx.emit_span_lint(UNUSED_ALLOCATION, e.span, UnusedAllocationMutDiag);
1439 }
1440 };
1441 }
1442 }
1443 }
1444}