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 | RawHandle(expr)
158 | UnsafeBinderCast(_, expr, _) => Self::expr_allows_remove_arg_block(expr),
159 Array(exprs) | Tup(exprs) => {
160 exprs.iter().all(|expr| Self::expr_allows_remove_arg_block(expr))
161 }
162 Binary(_, lhs, rhs) | Assign(lhs, rhs, _) | AssignOp(_, lhs, rhs) => {
163 Self::expr_allows_remove_arg_block(lhs) && Self::expr_allows_remove_arg_block(rhs)
164 }
165 Index(base, index, _) => {
166 Self::expr_allows_remove_arg_block(base)
167 && Self::expr_allows_remove_arg_block(index)
168 }
169 Range(start, end, _) => {
170 start.as_ref().is_none_or(|expr| Self::expr_allows_remove_arg_block(expr))
171 && end.as_ref().is_none_or(|expr| Self::expr_allows_remove_arg_block(expr))
172 }
173 Struct(expr) => {
174 expr.fields.iter().all(|field| Self::expr_allows_remove_arg_block(&field.expr))
175 && match &expr.rest {
176 ast::StructRest::Base(expr) => Self::expr_allows_remove_arg_block(expr),
177 ast::StructRest::Rest(_) | ast::StructRest::None => true,
178 ast::StructRest::NoneWithError(_) => false,
179 }
180 }
181 Repeat(expr, _) => Self::expr_allows_remove_arg_block(expr),
182 ConstBlock(_)
183 | If(..)
184 | While(..)
185 | ForLoop { .. }
186 | Loop(..)
187 | Match(..)
188 | Closure(_)
189 | Block(..)
190 | Gen(..)
191 | TryBlock(..)
192 | Break(..)
193 | Continue(_)
194 | Ret(_)
195 | InlineAsm(_)
196 | OffsetOf(..)
197 | Yield(_)
198 | Yeet(_)
199 | Paren(_)
200 | Become(_) => true,
201 Call(..) | MethodCall(_) | Let(..) | Field(..) | MacCall(_) | FormatArgs(_) => false,
202 Gca(_) => false,
204 Underscore | Err(_) | Dummy => false,
206 }
207 }
208
209 fn needs_arg_block_to_preserve_temporaries(
212 ctx: UnusedDelimsCtx,
213 arg_block: &ast::Expr,
214 expr: &ast::Expr,
215 ) -> bool {
216 #[allow(non_exhaustive_omitted_patterns)] match ctx {
UnusedDelimsCtx::FunctionArg | UnusedDelimsCtx::MethodArg => true,
_ => false,
}matches!(ctx, UnusedDelimsCtx::FunctionArg | UnusedDelimsCtx::MethodArg)
217 && arg_block.span.edition().at_least_rust_2024()
218 && !Self::expr_allows_remove_arg_block(expr)
219 }
220
221 fn is_expr_delims_necessary(
222 inner: &ast::Expr,
223 ctx: UnusedDelimsCtx,
224 followed_by_block: bool,
225 ) -> bool {
226 let followed_by_else = ctx == UnusedDelimsCtx::AssignedValueLetElse;
227
228 if followed_by_else {
229 match inner.kind {
230 ast::ExprKind::Binary(op, ..) if op.node.is_lazy() => return true,
231 _ if classify::expr_trailing_brace(inner).is_some() => return true,
232 _ => {}
233 }
234 }
235
236 if let ast::ExprKind::Range(..) = inner.kind
238 && #[allow(non_exhaustive_omitted_patterns)] match ctx {
UnusedDelimsCtx::LetScrutineeExpr => true,
_ => false,
}matches!(ctx, UnusedDelimsCtx::LetScrutineeExpr)
239 {
240 return true;
241 }
242
243 if #[allow(non_exhaustive_omitted_patterns)] match inner.kind {
ast::ExprKind::AddrOf(ast::BorrowKind::Raw, ..) => true,
_ => false,
}matches!(inner.kind, ast::ExprKind::AddrOf(ast::BorrowKind::Raw, ..)) {
247 return true;
248 }
249
250 {
280 let mut innermost = inner;
281 loop {
282 innermost = match &innermost.kind {
283 ExprKind::Binary(_op, lhs, _rhs) => lhs,
284 ExprKind::Call(fn_, _params) => fn_,
285 ExprKind::Cast(expr, _ty) => expr,
286 ExprKind::Type(expr, _ty) => expr,
287 ExprKind::Index(base, _subscript, _) => base,
288 _ => break,
289 };
290 if !classify::expr_requires_semi_to_be_stmt(innermost) {
291 return true;
292 }
293 }
294 }
295
296 if !followed_by_block {
299 return false;
300 }
301
302 {
304 let mut innermost = inner;
305 loop {
306 innermost = match &innermost.kind {
307 ExprKind::AddrOf(_, _, expr) => expr,
308 _ => {
309 if parser::contains_exterior_struct_lit(innermost) {
310 return true;
311 } else {
312 break;
313 }
314 }
315 }
316 }
317 }
318
319 let mut innermost = inner;
320 loop {
321 innermost = match &innermost.kind {
322 ExprKind::Unary(_op, expr) => expr,
323 ExprKind::Binary(_op, _lhs, rhs) => rhs,
324 ExprKind::AssignOp(_op, _lhs, rhs) => rhs,
325 ExprKind::Assign(_lhs, rhs, _span) => rhs,
326
327 ExprKind::Ret(_) | ExprKind::Yield(..) | ExprKind::Yeet(..) => return true,
328
329 ExprKind::Break(_label, None) => return false,
330 ExprKind::Break(_label, Some(break_expr)) => {
331 return #[allow(non_exhaustive_omitted_patterns)] match break_expr.kind {
ExprKind::Block(..) | ExprKind::Path(..) => true,
_ => false,
}matches!(break_expr.kind, ExprKind::Block(..) | ExprKind::Path(..));
335 }
336
337 ExprKind::Range(_lhs, Some(rhs), _limits) => {
338 return #[allow(non_exhaustive_omitted_patterns)] match rhs.kind {
ExprKind::Block(..) => true,
_ => false,
}matches!(rhs.kind, ExprKind::Block(..));
339 }
340
341 _ => return parser::contains_exterior_struct_lit(inner),
342 }
343 }
344 }
345
346 fn emit_unused_delims_expr(
347 &self,
348 cx: &EarlyContext<'_>,
349 value: &ast::Expr,
350 ctx: UnusedDelimsCtx,
351 left_pos: Option<BytePos>,
352 right_pos: Option<BytePos>,
353 is_kw: bool,
354 ) {
355 let span_with_attrs = match value.kind {
356 ast::ExprKind::Block(ref block, None) if let [stmt] = block.stmts.as_slice() => {
357 if let Some(attr_lo) = stmt.attrs().iter().map(|attr| attr.span.lo()).min() {
360 stmt.span.with_lo(attr_lo)
361 } else {
362 stmt.span
363 }
364 }
365 ast::ExprKind::Paren(ref expr) => {
366 if let Some(attr_lo) = expr.attrs.iter().map(|attr| attr.span.lo()).min() {
369 expr.span.with_lo(attr_lo)
370 } else {
371 expr.span
372 }
373 }
374 _ => return,
375 };
376 let spans = span_with_attrs
377 .find_ancestor_inside(value.span)
378 .map(|span| (value.span.with_hi(span.lo()), value.span.with_lo(span.hi())));
379 let keep_space = (
380 left_pos.is_some_and(|s| s >= value.span.lo()),
381 right_pos.is_some_and(|s| s <= value.span.hi()),
382 );
383 self.emit_unused_delims(cx, value.span, spans, ctx.into(), keep_space, is_kw);
384 }
385
386 fn emit_unused_delims(
387 &self,
388 cx: &EarlyContext<'_>,
389 value_span: Span,
390 spans: Option<(Span, Span)>,
391 msg: &str,
392 keep_space: (bool, bool),
393 is_kw: bool,
394 ) {
395 if cx.in_external_macro_item {
396 return;
397 }
398 let sm = cx.sess().source_map();
399 let shrink = |span: Span, open: bool, in_help: bool| -> Span {
402 if span.is_empty() {
403 return span;
404 }
405 let (delim, gap) = if open {
406 let delim = span.with_hi(span.lo() + BytePos(1));
407 (delim, span.with_lo(delim.hi()))
408 } else {
409 let delim = span.with_lo(span.hi() - BytePos(1));
410 (delim, span.with_hi(delim.lo()))
411 };
412 let is_delim =
413 sm.span_to_snippet(delim).is_ok_and(|s| #[allow(non_exhaustive_omitted_patterns)] match &*s {
"(" | ")" | "{" | "}" => true,
_ => false,
}matches!(&*s, "(" | ")" | "{" | "}"));
414 let has_comment = sm.span_to_snippet(gap).is_ok_and(|s| !s.trim().is_empty());
415 if is_delim && (!in_help || has_comment) { delim } else { span }
416 };
417 let primary_span = if let Some((lo, hi)) = spans {
418 if hi.is_empty() {
419 return;
421 }
422 MultiSpan::from(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[shrink(lo, true, false), shrink(hi, false, false)]))vec![shrink(lo, true, false), shrink(hi, false, false)])
423 } else {
424 MultiSpan::from(value_span)
425 };
426 let suggestion = spans.map(|(lo, hi)| {
427 let (lo, hi) = (shrink(lo, true, true), shrink(hi, false, true));
428 let lo_replace = if (keep_space.0 || is_kw)
429 && let Ok(snip) = sm.span_to_prev_source(lo)
430 && !snip.ends_with(' ')
431 {
432 " "
433 } else if let Ok(snip) = sm.span_to_prev_source(value_span)
434 && snip.ends_with(|c: char| c.is_alphanumeric())
435 {
436 " "
437 } else {
438 ""
439 };
440
441 let hi_replace = if keep_space.1
442 && let Ok(snip) = sm.span_to_next_source(hi)
443 && !snip.starts_with(' ')
444 {
445 " "
446 } else if let Ok(snip) = sm.span_to_next_source(value_span)
447 && snip.starts_with(|c: char| c.is_alphanumeric())
448 {
449 " "
450 } else {
451 ""
452 };
453 UnusedDelimSuggestion {
454 start_span: lo,
455 start_replace: lo_replace,
456 end_span: hi,
457 end_replace: hi_replace,
458 delim: Self::DELIM_STR,
459 }
460 });
461 cx.emit_span_lint(
462 self.lint(),
463 primary_span,
464 UnusedDelim { delim: Self::DELIM_STR, item: msg, suggestion },
465 );
466 }
467
468 fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
469 use rustc_ast::ExprKind::*;
470 let (value, ctx, followed_by_block, left_pos, right_pos, is_kw) = match e.kind {
471 If(ref cond, ref block, _)
473 if !#[allow(non_exhaustive_omitted_patterns)] match cond.kind {
Let(..) => true,
_ => false,
}matches!(cond.kind, Let(..)) || Self::LINT_EXPR_IN_PATTERN_MATCHING_CTX =>
474 {
475 let left = e.span.lo() + rustc_span::BytePos(2);
476 let right = block.span.lo();
477 (cond, UnusedDelimsCtx::IfCond, true, Some(left), Some(right), true)
478 }
479
480 While(ref cond, ref block, ..)
482 if !#[allow(non_exhaustive_omitted_patterns)] match cond.kind {
Let(..) => true,
_ => false,
}matches!(cond.kind, Let(..)) || Self::LINT_EXPR_IN_PATTERN_MATCHING_CTX =>
483 {
484 let left = e.span.lo() + rustc_span::BytePos(5);
485 let right = block.span.lo();
486 (cond, UnusedDelimsCtx::WhileCond, true, Some(left), Some(right), true)
487 }
488
489 ForLoop(ast::ForLoop { ref iter, ref body, .. }) => {
490 (iter, UnusedDelimsCtx::ForIterExpr, true, None, Some(body.span.lo()), true)
491 }
492
493 Match(ref head, _, ast::MatchKind::Prefix)
494 if Self::LINT_EXPR_IN_PATTERN_MATCHING_CTX =>
495 {
496 let left = e.span.lo() + rustc_span::BytePos(5);
497 (head, UnusedDelimsCtx::MatchScrutineeExpr, true, Some(left), None, true)
498 }
499
500 Ret(Some(ref value)) => {
501 let left = e.span.lo() + rustc_span::BytePos(3);
502 (value, UnusedDelimsCtx::ReturnValue, false, Some(left), None, true)
503 }
504
505 Break(label, Some(ref value)) => {
506 if label.is_some()
510 && #[allow(non_exhaustive_omitted_patterns)] match value.kind {
ast::ExprKind::Paren(ref inner) if
#[allow(non_exhaustive_omitted_patterns)] match inner.kind {
ast::ExprKind::Block(..) => true,
_ => false,
} => true,
_ => false,
}matches!(value.kind, ast::ExprKind::Paren(ref inner)
511 if matches!(inner.kind, ast::ExprKind::Block(..)))
512 {
513 return;
514 }
515 (value, UnusedDelimsCtx::BreakValue, false, None, None, true)
516 }
517
518 Index(_, ref value, _) => (value, UnusedDelimsCtx::IndexExpr, false, None, None, false),
519
520 Assign(_, ref value, _) | AssignOp(.., ref value) => {
521 (value, UnusedDelimsCtx::AssignedValue, false, None, None, false)
522 }
523 ref call_or_other => {
525 let (args_to_check, ctx, callee_from_expansion) = match *call_or_other {
526 Call(ref callee, ref args) => {
527 (&args[..], UnusedDelimsCtx::FunctionArg, callee.span.from_expansion())
528 }
529 MethodCall(ref call) => (
530 &call.args[..],
531 UnusedDelimsCtx::MethodArg,
532 call.seg.ident.span.from_expansion(),
533 ),
534 Closure(ref closure)
535 if #[allow(non_exhaustive_omitted_patterns)] match closure.fn_decl.output {
FnRetTy::Default(_) => true,
_ => false,
}matches!(closure.fn_decl.output, FnRetTy::Default(_)) =>
536 {
537 (&[closure.body.clone()][..], UnusedDelimsCtx::ClosureBody, false)
538 }
539 _ => {
541 return;
542 }
543 };
544 if e.span.ctxt().outer_expn_data().call_site.from_expansion() {
549 return;
550 }
551 for arg in args_to_check {
552 if callee_from_expansion && Self::block_wraps_expanded_expr(arg) {
555 continue;
556 }
557 self.check_unused_delims_expr(cx, arg, ctx, false, None, None, false);
558 }
559 return;
560 }
561 };
562 self.check_unused_delims_expr(
563 cx,
564 value,
565 ctx,
566 followed_by_block,
567 left_pos,
568 right_pos,
569 is_kw,
570 );
571 }
572
573 fn check_stmt(&mut self, cx: &EarlyContext<'_>, s: &ast::Stmt) {
574 match s.kind {
575 StmtKind::Let(ref local) if Self::LINT_EXPR_IN_PATTERN_MATCHING_CTX => {
576 if let Some((init, els)) = local.kind.init_else_opt() {
577 if els.is_some()
578 && let ExprKind::Paren(paren) = &init.kind
579 && init.span.ctxt() != paren.span.ctxt()
580 {
581 return;
592 }
593 let ctx = match els {
594 None => UnusedDelimsCtx::AssignedValue,
595 Some(_) => UnusedDelimsCtx::AssignedValueLetElse,
596 };
597 self.check_unused_delims_expr(cx, init, ctx, false, None, None, false);
598 }
599 }
600 StmtKind::Expr(ref expr) => {
601 self.check_unused_delims_expr(
602 cx,
603 expr,
604 UnusedDelimsCtx::BlockRetValue,
605 false,
606 None,
607 None,
608 false,
609 );
610 }
611 _ => {}
612 }
613 }
614
615 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
616 use ast::ItemKind::*;
617
618 let expr = if let Const(ast::ConstItem { body: Some(expr), .. }) = &item.kind {
619 expr
620 } else if let Static(ast::StaticItem { expr: Some(expr), .. }) = &item.kind {
621 expr
622 } else {
623 return;
624 };
625 self.check_unused_delims_expr(
626 cx,
627 expr,
628 UnusedDelimsCtx::AssignedValue,
629 false,
630 None,
631 None,
632 false,
633 );
634 }
635
636 fn block_wraps_expanded_expr(value: &ast::Expr) -> bool {
638 if let ast::ExprKind::Block(ref block, None) = value.kind
639 && block.rules == ast::BlockCheckMode::Default
640 && !value.span.from_expansion()
641 && let [stmt] = block.stmts.as_slice()
642 && let ast::StmtKind::Expr(ref expr) = stmt.kind
643 {
644 expr.span.from_expansion()
645 } else {
646 false
647 }
648 }
649}
650
651#[doc =
r" The `unused_parens` lint detects `if`, `match`, `while` and `return`"]
#[doc = r" with parentheses; they do not need them."]
#[doc = r""]
#[doc = r" ### Examples"]
#[doc = r""]
#[doc = r" ```rust"]
#[doc = r" if(true) {}"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc =
r" The parentheses are not needed, and should be removed. This is the"]
#[doc = r" preferred style for writing these expressions."]
pub(super) static UNUSED_PARENS: &::rustc_lint_defs::Lint =
&::rustc_lint_defs::Lint {
name: "UNUSED_PARENS",
default_level: ::rustc_lint_defs::Warn,
desc: "`if`, `match`, `while` and `return` do not need parentheses",
..
};declare_lint! {
652 pub(super) UNUSED_PARENS,
668 Warn,
669 "`if`, `match`, `while` and `return` do not need parentheses"
670}
671
672#[derive(#[automatically_derived]impl ::core::default::Default for UnusedParens {
#[inline]
fn default() -> Self {
UnusedParens {
with_self_ty_parens: ::core::default::Default::default(),
parens_in_cast_in_lt: ::core::default::Default::default(),
in_no_bounds_pos: ::core::default::Default::default(),
}
}
}Default)]
673pub(crate) struct UnusedParens {
674 with_self_ty_parens: bool,
675 parens_in_cast_in_lt: Vec<ast::NodeId>,
678 in_no_bounds_pos: FxHashMap<ast::NodeId, NoBoundsException>,
681}
682
683enum NoBoundsException {
698 None,
700 OneBound,
703}
704
705impl ::rustc_lint_defs::LintPass for UnusedParens {
fn name(&self) -> &'static str { "UnusedParens" }
fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[UNUSED_PARENS]))
}
}
impl UnusedParens {
#[allow(unused)]
pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[UNUSED_PARENS]))
}
}impl_lint_pass!(UnusedParens => [UNUSED_PARENS]);
706
707impl UnusedDelimLint for UnusedParens {
708 const DELIM_STR: &'static str = "parentheses";
709
710 const LINT_EXPR_IN_PATTERN_MATCHING_CTX: bool = true;
711
712 fn lint(&self) -> &'static Lint {
713 UNUSED_PARENS
714 }
715
716 fn check_unused_delims_expr(
717 &self,
718 cx: &EarlyContext<'_>,
719 value: &ast::Expr,
720 ctx: UnusedDelimsCtx,
721 followed_by_block: bool,
722 left_pos: Option<BytePos>,
723 right_pos: Option<BytePos>,
724 is_kw: bool,
725 ) {
726 match value.kind {
727 ast::ExprKind::Paren(ref inner) => {
728 if !Self::is_expr_delims_necessary(inner, ctx, followed_by_block)
729 && value.attrs.is_empty()
730 && !value.span.from_expansion()
731 && (ctx != UnusedDelimsCtx::LetScrutineeExpr
732 || !#[allow(non_exhaustive_omitted_patterns)] match inner.kind {
ast::ExprKind::Binary(rustc_span::Spanned { node, .. }, _, _) if
node.is_lazy() => true,
_ => false,
}matches!(inner.kind, ast::ExprKind::Binary(
733 rustc_span::Spanned { node, .. },
734 _,
735 _,
736 ) if node.is_lazy()))
737 && !((ctx == UnusedDelimsCtx::ReturnValue
738 || ctx == UnusedDelimsCtx::BreakValue)
739 && #[allow(non_exhaustive_omitted_patterns)] match inner.kind {
ast::ExprKind::Assign(_, _, _) => true,
_ => false,
}matches!(inner.kind, ast::ExprKind::Assign(_, _, _)))
740 {
741 self.emit_unused_delims_expr(cx, value, ctx, left_pos, right_pos, is_kw)
742 }
743 }
744 ast::ExprKind::Let(_, ref expr, _, _) => {
745 self.check_unused_delims_expr(
746 cx,
747 expr,
748 UnusedDelimsCtx::LetScrutineeExpr,
749 followed_by_block,
750 None,
751 None,
752 false,
753 );
754 }
755 _ => {}
756 }
757 }
758}
759
760impl UnusedParens {
761 fn check_unused_parens_pat(
762 &self,
763 cx: &EarlyContext<'_>,
764 value: &ast::Pat,
765 avoid_or: bool,
766 avoid_mut: bool,
767 keep_space: (bool, bool),
768 ) {
769 use ast::{BindingMode, ByRef, Mutability, PatKind, Pinnedness};
770
771 if let PatKind::Paren(inner) = &value.kind {
772 match inner.kind {
773 PatKind::Range(..) => return,
778 PatKind::Guard(..) => return,
780 PatKind::Or(..) if avoid_or => return,
782 PatKind::Ident(BindingMode(_, Mutability::Mut), ..) if avoid_mut => {
785 return;
786 }
787 PatKind::Ref(_, Pinnedness::Pinned, _)
788 | PatKind::Ident(BindingMode(ByRef::Yes(Pinnedness::Pinned, _), _), ..)
789 if !cx.builder.features().pin_ergonomics() =>
791 {
792 return;
793 }
794 _ => {}
796 }
797 let spans = if !value.span.from_expansion() {
798 inner
799 .span
800 .find_ancestor_inside(value.span)
801 .map(|inner| (value.span.with_hi(inner.lo()), value.span.with_lo(inner.hi())))
802 } else {
803 None
804 };
805 self.emit_unused_delims(cx, value.span, spans, "pattern", keep_space, false);
806 }
807 }
808
809 fn pat_is_macro_arg(pat_span: Span, parent_span: Span) -> bool {
814 pat_span.ctxt() != parent_span.ctxt()
815 }
816
817 fn cast_followed_by_lt(&self, expr: &ast::Expr) -> Option<ast::NodeId> {
818 if let ExprKind::Binary(op, lhs, _rhs) = &expr.kind
819 && (op.node == ast::BinOpKind::Lt || op.node == ast::BinOpKind::Shl)
820 {
821 let mut cur = lhs;
822 while let ExprKind::Binary(_, _, rhs) = &cur.kind {
823 cur = rhs;
824 }
825
826 if let ExprKind::Cast(_, ty) = &cur.kind
827 && let ast::TyKind::Paren(_) = &ty.kind
828 {
829 return Some(ty.id);
830 }
831 }
832 None
833 }
834}
835
836impl EarlyLintPass for UnusedParens {
837 #[inline]
838 fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
839 if let Some(ty_id) = self.cast_followed_by_lt(e) {
840 self.parens_in_cast_in_lt.push(ty_id);
841 }
842
843 match e.kind {
844 ExprKind::Let(ref pat, _, _, _) | ExprKind::ForLoop(ForLoop { ref pat, .. }) => {
845 let avoid_or = Self::pat_is_macro_arg(pat.span, e.span);
846 self.check_unused_parens_pat(cx, pat, avoid_or, false, (true, true));
847 }
848 ExprKind::If(ref cond, ref block, ref else_)
852 if #[allow(non_exhaustive_omitted_patterns)] match cond.peel_parens().kind {
ExprKind::Let(..) => true,
_ => false,
}matches!(cond.peel_parens().kind, ExprKind::Let(..)) =>
853 {
854 self.check_unused_delims_expr(
855 cx,
856 cond.peel_parens(),
857 UnusedDelimsCtx::LetScrutineeExpr,
858 true,
859 None,
860 None,
861 true,
862 );
863 for stmt in &block.stmts {
864 <Self as UnusedDelimLint>::check_stmt(self, cx, stmt);
865 }
866 if let Some(e) = else_ {
867 <Self as UnusedDelimLint>::check_expr(self, cx, e);
868 }
869 return;
870 }
871 ExprKind::Match(ref _expr, ref arm, _) => {
872 for a in arm {
873 if let Some(body) = &a.body {
874 self.check_unused_delims_expr(
875 cx,
876 body,
877 UnusedDelimsCtx::MatchArmExpr,
878 false,
879 None,
880 None,
881 true,
882 );
883 }
884 }
885 }
886 _ => {}
887 }
888
889 <Self as UnusedDelimLint>::check_expr(self, cx, e)
890 }
891
892 fn check_expr_post(&mut self, _cx: &EarlyContext<'_>, e: &ast::Expr) {
893 if let Some(ty_id) = self.cast_followed_by_lt(e) {
894 let id = self
895 .parens_in_cast_in_lt
896 .pop()
897 .expect("check_expr and check_expr_post must balance");
898 {
match (&id, &ty_id) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val,
::core::option::Option::Some(format_args!("check_expr, check_ty, and check_expr_post are called, in that order, by the visitor")));
}
}
}
};assert_eq!(
899 id, ty_id,
900 "check_expr, check_ty, and check_expr_post are called, in that order, by the visitor"
901 );
902 }
903 }
904
905 fn check_pat(&mut self, cx: &EarlyContext<'_>, p: &ast::Pat) {
906 use ast::PatKind::*;
907 use ast::{Mutability, Pinnedness};
908 let keep_space = (false, false);
909 match &p.kind {
910 Paren(_) => {}
912 Missing
914 | Wild
915 | Never
916 | Rest
917 | Expr(..)
918 | MacCall(..)
919 | Range(..)
920 | Ident(.., None)
921 | Path(..)
922 | Err(_) => {}
923 TupleStruct(_, _, ps) | Tuple(ps) | Slice(ps) | Or(ps) => {
925 for sub in ps {
926 let avoid_or = Self::pat_is_macro_arg(sub.span, p.span);
927 self.check_unused_parens_pat(cx, sub, avoid_or, false, keep_space);
928 }
929 }
930 Struct(_, _, fps, _) => {
931 for f in fps {
932 let avoid_or = Self::pat_is_macro_arg(f.pat.span, p.span);
933 self.check_unused_parens_pat(cx, &f.pat, avoid_or, false, keep_space);
934 }
935 }
936 Ident(.., Some(p)) | Deref(p) | Guard(p, _) => {
938 self.check_unused_parens_pat(cx, p, true, false, keep_space)
939 }
940 Ref(p, pinned, m)
946 if *pinned != Pinnedness::Pinned
947 || cx.builder.features().pin_ergonomics() =>
949 {
950 if let Paren(ref pat) = p.kind
953 && *pinned == Pinnedness::Not
954 && let Ident(_, _, Some(..)) = pat.kind
955 {
956 return;
957 }
958 self.check_unused_parens_pat(
960 cx,
961 p,
962 true,
963 *pinned == Pinnedness::Not && *m == Mutability::Not,
964 keep_space,
965 );
966 }
967 Ref(..) => {}
968 }
969 }
970
971 fn check_stmt(&mut self, cx: &EarlyContext<'_>, s: &ast::Stmt) {
972 if let StmtKind::Let(ref local) = s.kind {
973 self.check_unused_parens_pat(cx, &local.pat, true, false, (true, false));
974 }
975
976 <Self as UnusedDelimLint>::check_stmt(self, cx, s)
977 }
978
979 fn check_param(&mut self, cx: &EarlyContext<'_>, param: &ast::Param) {
980 self.check_unused_parens_pat(cx, ¶m.pat, true, false, (false, false));
981 }
982
983 fn check_arm(&mut self, cx: &EarlyContext<'_>, arm: &ast::Arm) {
984 let avoid_or = Self::pat_is_macro_arg(arm.pat.span, arm.span);
985 self.check_unused_parens_pat(cx, &arm.pat, avoid_or, false, (false, false));
986 }
987
988 fn check_ty(&mut self, cx: &EarlyContext<'_>, ty: &ast::Ty) {
989 if let ast::TyKind::Paren(_) = ty.kind
990 && Some(&ty.id) == self.parens_in_cast_in_lt.last()
991 {
992 return;
993 }
994 match &ty.kind {
995 ast::TyKind::Array(_, len) => {
996 self.check_unused_delims_expr(
997 cx,
998 &len.value,
999 UnusedDelimsCtx::ArrayLenExpr,
1000 false,
1001 None,
1002 None,
1003 false,
1004 );
1005 }
1006 ast::TyKind::Paren(r) => {
1007 let unused_parens = match &r.kind {
1008 ast::TyKind::ImplTrait(_, bounds) | ast::TyKind::TraitObject(bounds, _) => {
1009 match self.in_no_bounds_pos.get(&ty.id) {
1010 Some(NoBoundsException::None) => false,
1011 Some(NoBoundsException::OneBound) => bounds.len() <= 1,
1012 None => true,
1013 }
1014 }
1015 ast::TyKind::FnPtr(b) => {
1016 !self.with_self_ty_parens || b.generic_params.is_empty()
1017 }
1018 _ => true,
1019 };
1020
1021 if unused_parens {
1022 let spans = (!ty.span.from_expansion())
1023 .then(|| {
1024 r.span
1025 .find_ancestor_inside(ty.span)
1026 .map(|r| (ty.span.with_hi(r.lo()), ty.span.with_lo(r.hi())))
1027 })
1028 .flatten();
1029
1030 self.emit_unused_delims(cx, ty.span, spans, "type", (false, false), false);
1031 }
1032
1033 self.with_self_ty_parens = false;
1034 }
1035 ast::TyKind::Ref(_, inner_ty, _) | ast::TyKind::Ptr(inner_ty, _) => {
1036 let own_constraint = self.in_no_bounds_pos.get(&ty.id);
1039 let constraint = match own_constraint {
1040 Some(NoBoundsException::None) => NoBoundsException::None,
1041 Some(NoBoundsException::OneBound) => NoBoundsException::OneBound,
1042 None => NoBoundsException::OneBound,
1043 };
1044 self.in_no_bounds_pos.insert(inner_ty.id, constraint);
1045 }
1046 ast::TyKind::TraitObject(bounds, _) | ast::TyKind::ImplTrait(_, bounds) => {
1047 for i in 0..bounds.len() {
1048 let is_last = i == bounds.len() - 1;
1049
1050 if let ast::GenericBound::Trait(poly_trait_ref) = &bounds[i] {
1051 let fn_with_explicit_ret_ty = if let [.., segment] =
1052 &*poly_trait_ref.trait_ref.path.segments
1053 && let Some(args) = segment.args.as_ref()
1054 && let ast::GenericArgs::Parenthesized(paren_args) = &**args
1055 && let ast::FnRetTy::Ty(ret_ty) = &paren_args.output
1056 {
1057 self.in_no_bounds_pos.insert(
1058 ret_ty.id,
1059 if is_last {
1060 NoBoundsException::OneBound
1061 } else {
1062 NoBoundsException::None
1063 },
1064 );
1065
1066 true
1067 } else {
1068 false
1069 };
1070
1071 let dyn2015_exception = cx.sess().psess.edition == Edition2015
1076 && #[allow(non_exhaustive_omitted_patterns)] match ty.kind {
ast::TyKind::TraitObject(..) => true,
_ => false,
}matches!(ty.kind, ast::TyKind::TraitObject(..))
1077 && i == 0
1078 && poly_trait_ref
1079 .trait_ref
1080 .path
1081 .segments
1082 .first()
1083 .map(|s| s.ident.name == kw::PathRoot)
1084 .unwrap_or(false);
1085
1086 if let ast::Parens::Yes = poly_trait_ref.parens
1087 && (is_last || !fn_with_explicit_ret_ty)
1088 && !dyn2015_exception
1089 {
1090 let s = poly_trait_ref.span;
1091 if !s.from_expansion()
1095 && let Ok(snippet) = cx.sess().source_map().span_to_snippet(s)
1096 && snippet.starts_with('(')
1097 && snippet.ends_with(')')
1098 {
1099 let spans = Some((
1100 s.with_hi(s.lo() + rustc_span::BytePos(1)),
1101 s.with_lo(s.hi() - rustc_span::BytePos(1)),
1102 ));
1103
1104 self.emit_unused_delims(
1105 cx,
1106 poly_trait_ref.span,
1107 spans,
1108 "type",
1109 (false, false),
1110 false,
1111 );
1112 }
1113 }
1114 }
1115 }
1116 }
1117 _ => {}
1118 }
1119 }
1120
1121 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
1122 <Self as UnusedDelimLint>::check_item(self, cx, item)
1123 }
1124
1125 fn check_item_post(&mut self, _: &EarlyContext<'_>, _: &rustc_ast::Item) {
1126 self.in_no_bounds_pos.clear();
1127 }
1128
1129 fn check_where_predicate(&mut self, _: &EarlyContext<'_>, pred: &ast::WherePredicate) {
1130 use rustc_ast::{WhereBoundPredicate, WherePredicateKind};
1131 if let WherePredicateKind::BoundPredicate(WhereBoundPredicate {
1132 bounded_ty,
1133 bound_generic_params,
1134 ..
1135 }) = &pred.kind
1136 && let ast::TyKind::Paren(_) = &bounded_ty.kind
1137 && bound_generic_params.is_empty()
1138 {
1139 self.with_self_ty_parens = true;
1140 }
1141 }
1142
1143 fn check_where_predicate_post(&mut self, _: &EarlyContext<'_>, _: &ast::WherePredicate) {
1144 if !!self.with_self_ty_parens {
::core::panicking::panic("assertion failed: !self.with_self_ty_parens")
};assert!(!self.with_self_ty_parens);
1145 }
1146}
1147
1148#[doc = r" The `unused_braces` lint detects unnecessary braces around an"]
#[doc = r" expression."]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust"]
#[doc = r" if { true } {"]
#[doc = r" // ..."]
#[doc = r" }"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc = r" The braces are not needed, and should be removed. This is the"]
#[doc = r" preferred style for writing these expressions."]
pub(super) static UNUSED_BRACES: &::rustc_lint_defs::Lint =
&::rustc_lint_defs::Lint {
name: "UNUSED_BRACES",
default_level: ::rustc_lint_defs::Warn,
desc: "unnecessary braces around an expression",
..
};declare_lint! {
1149 pub(super) UNUSED_BRACES,
1167 Warn,
1168 "unnecessary braces around an expression"
1169}
1170
1171pub struct UnusedBraces;
#[automatically_derived]impl ::core::marker::Copy for UnusedBraces { }
#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for UnusedBraces {
}
#[automatically_derived]impl ::core::clone::Clone for UnusedBraces {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self { *self }
}
impl ::rustc_lint_defs::LintPass for UnusedBraces {
fn name(&self) -> &'static str { "UnusedBraces" }
fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[UNUSED_BRACES]))
}
}
impl UnusedBraces {
#[allow(unused)]
pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[UNUSED_BRACES]))
}
}declare_lint_pass!(UnusedBraces => [UNUSED_BRACES]);
1172
1173impl UnusedDelimLint for UnusedBraces {
1174 const DELIM_STR: &'static str = "braces";
1175
1176 const LINT_EXPR_IN_PATTERN_MATCHING_CTX: bool = false;
1177
1178 fn lint(&self) -> &'static Lint {
1179 UNUSED_BRACES
1180 }
1181
1182 fn check_unused_delims_expr(
1183 &self,
1184 cx: &EarlyContext<'_>,
1185 value: &ast::Expr,
1186 ctx: UnusedDelimsCtx,
1187 followed_by_block: bool,
1188 left_pos: Option<BytePos>,
1189 right_pos: Option<BytePos>,
1190 is_kw: bool,
1191 ) {
1192 match value.kind {
1193 ast::ExprKind::Block(ref inner, None)
1194 if inner.rules == ast::BlockCheckMode::Default =>
1195 {
1196 if let [stmt] = inner.stmts.as_slice()
1221 && let ast::StmtKind::Expr(ref expr) = stmt.kind
1222 && !Self::is_expr_delims_necessary(expr, ctx, followed_by_block)
1223 && !(ctx == UnusedDelimsCtx::ForIterExpr
1226 && value.span.edition().at_least_rust_2024())
1227 && !Self::needs_arg_block_to_preserve_temporaries(ctx, value, expr)
1228 && (ctx != UnusedDelimsCtx::AnonConst
1229 || (#[allow(non_exhaustive_omitted_patterns)] match expr.kind {
ast::ExprKind::Lit(_) => true,
_ => false,
}matches!(expr.kind, ast::ExprKind::Lit(_))
1230 && !expr.span.from_expansion()))
1231 && ctx != UnusedDelimsCtx::ClosureBody
1232 && !cx.sess().source_map().is_multiline(value.span)
1233 && value.attrs.is_empty()
1234 && !value.span.from_expansion()
1235 && !inner.span.from_expansion()
1236 {
1237 self.emit_unused_delims_expr(cx, value, ctx, left_pos, right_pos, is_kw)
1238 }
1239 }
1240 ast::ExprKind::Let(_, ref expr, _, _) => {
1241 self.check_unused_delims_expr(
1242 cx,
1243 expr,
1244 UnusedDelimsCtx::LetScrutineeExpr,
1245 followed_by_block,
1246 None,
1247 None,
1248 false,
1249 );
1250 }
1251 _ => {}
1252 }
1253 }
1254}
1255
1256impl EarlyLintPass for UnusedBraces {
1257 fn check_stmt(&mut self, cx: &EarlyContext<'_>, s: &ast::Stmt) {
1258 <Self as UnusedDelimLint>::check_stmt(self, cx, s)
1259 }
1260
1261 #[inline]
1262 fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
1263 <Self as UnusedDelimLint>::check_expr(self, cx, e);
1264
1265 if let ExprKind::Repeat(_, ref anon_const) = e.kind {
1266 self.check_unused_delims_expr(
1267 cx,
1268 &anon_const.value,
1269 UnusedDelimsCtx::AnonConst,
1270 false,
1271 None,
1272 None,
1273 false,
1274 );
1275 }
1276 }
1277
1278 fn check_generic_arg(&mut self, cx: &EarlyContext<'_>, arg: &ast::GenericArg) {
1279 if let ast::GenericArg::Const(ct) = arg {
1280 self.check_unused_delims_expr(
1281 cx,
1282 &ct.value,
1283 UnusedDelimsCtx::AnonConst,
1284 false,
1285 None,
1286 None,
1287 false,
1288 );
1289 }
1290 }
1291
1292 fn check_variant(&mut self, cx: &EarlyContext<'_>, v: &ast::Variant) {
1293 if let Some(anon_const) = &v.disr_expr {
1294 self.check_unused_delims_expr(
1295 cx,
1296 &anon_const.value,
1297 UnusedDelimsCtx::AnonConst,
1298 false,
1299 None,
1300 None,
1301 false,
1302 );
1303 }
1304 }
1305
1306 fn check_ty(&mut self, cx: &EarlyContext<'_>, ty: &ast::Ty) {
1307 match ty.kind {
1308 ast::TyKind::Array(_, ref len) => {
1309 self.check_unused_delims_expr(
1310 cx,
1311 &len.value,
1312 UnusedDelimsCtx::ArrayLenExpr,
1313 false,
1314 None,
1315 None,
1316 false,
1317 );
1318 }
1319
1320 _ => {}
1321 }
1322 }
1323
1324 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
1325 <Self as UnusedDelimLint>::check_item(self, cx, item)
1326 }
1327}
1328
1329#[doc =
r" The `unused_import_braces` lint catches unnecessary braces around an"]
#[doc = r" imported item."]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust,compile_fail"]
#[doc = r" #![deny(unused_import_braces)]"]
#[doc = r" use test::{A};"]
#[doc = r""]
#[doc = r" pub mod test {"]
#[doc = r" pub struct A;"]
#[doc = r" }"]
#[doc = r" # fn main() {}"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc =
r" If there is only a single item, then remove the braces (`use test::A;`"]
#[doc = r" for example)."]
#[doc = r""]
#[doc = r#" This lint is "allow" by default because it is only enforcing a"#]
#[doc = r" stylistic choice."]
static UNUSED_IMPORT_BRACES: &::rustc_lint_defs::Lint =
&::rustc_lint_defs::Lint {
name: "UNUSED_IMPORT_BRACES",
default_level: ::rustc_lint_defs::Allow,
desc: "unnecessary braces around an imported item",
..
};declare_lint! {
1330 UNUSED_IMPORT_BRACES,
1355 Allow,
1356 "unnecessary braces around an imported item"
1357}
1358
1359pub struct UnusedImportBraces;
#[automatically_derived]impl ::core::marker::Copy for UnusedImportBraces { }
#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for UnusedImportBraces {
}
#[automatically_derived]impl ::core::clone::Clone for UnusedImportBraces {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self { *self }
}
impl ::rustc_lint_defs::LintPass for UnusedImportBraces {
fn name(&self) -> &'static str { "UnusedImportBraces" }
fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[UNUSED_IMPORT_BRACES]))
}
}
impl UnusedImportBraces {
#[allow(unused)]
pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[UNUSED_IMPORT_BRACES]))
}
}declare_lint_pass!(UnusedImportBraces => [UNUSED_IMPORT_BRACES]);
1360
1361impl UnusedImportBraces {
1362 fn check_use_tree(&self, cx: &EarlyContext<'_>, use_tree: &ast::UseTree, item: &ast::Item) {
1363 if let ast::UseTreeKind::Nested { ref items, .. } = use_tree.kind {
1364 for tree in items {
1366 self.check_use_tree(cx, &tree.inner, item);
1367 }
1368
1369 let [tree] = items.as_slice() else { return };
1371
1372 let node_name = match tree.inner.kind {
1374 ast::UseTreeKind::Simple(rename) => {
1375 let orig_ident = tree.inner.prefix.segments.last().unwrap().ident;
1376 if orig_ident.name == kw::SelfLower {
1377 return;
1378 }
1379 rename.unwrap_or(orig_ident).name
1380 }
1381 ast::UseTreeKind::Glob(_) => sym::asterisk,
1382 ast::UseTreeKind::Nested { .. } => return,
1383 };
1384
1385 cx.emit_span_lint(
1386 UNUSED_IMPORT_BRACES,
1387 item.span,
1388 UnusedImportBracesDiag { node: node_name },
1389 );
1390 }
1391 }
1392}
1393
1394impl EarlyLintPass for UnusedImportBraces {
1395 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
1396 if let ast::ItemKind::Use(ref use_tree) = item.kind {
1397 self.check_use_tree(cx, use_tree, item);
1398 }
1399 }
1400}
1401
1402#[doc =
r" The `unused_allocation` lint detects unnecessary allocations that can"]
#[doc = r" be eliminated."]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust"]
#[doc = r" fn main() {"]
#[doc = r" let a = Box::new([1, 2, 3]).len();"]
#[doc = r" }"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc =
r" When a `box` expression is immediately coerced to a reference, then"]
#[doc =
r" the allocation is unnecessary, and a reference (using `&` or `&mut`)"]
#[doc = r" should be used instead to avoid the allocation."]
pub(super) static UNUSED_ALLOCATION: &::rustc_lint_defs::Lint =
&::rustc_lint_defs::Lint {
name: "UNUSED_ALLOCATION",
default_level: ::rustc_lint_defs::Warn,
desc: "detects unnecessary allocations that can be eliminated",
..
};declare_lint! {
1403 pub(super) UNUSED_ALLOCATION,
1422 Warn,
1423 "detects unnecessary allocations that can be eliminated"
1424}
1425
1426pub struct UnusedAllocation;
#[automatically_derived]impl ::core::marker::Copy for UnusedAllocation { }
#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for UnusedAllocation {
}
#[automatically_derived]impl ::core::clone::Clone for UnusedAllocation {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self { *self }
}
impl ::rustc_lint_defs::LintPass for UnusedAllocation {
fn name(&self) -> &'static str { "UnusedAllocation" }
fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[UNUSED_ALLOCATION]))
}
}
impl UnusedAllocation {
#[allow(unused)]
pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[UNUSED_ALLOCATION]))
}
}declare_lint_pass!(UnusedAllocation => [UNUSED_ALLOCATION]);
1427
1428impl<'tcx> LateLintPass<'tcx> for UnusedAllocation {
1429 fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &hir::Expr<'_>) {
1430 match e.kind {
1431 hir::ExprKind::Call(path_expr, [_])
1432 if let hir::ExprKind::Path(qpath) = &path_expr.kind
1433 && let Some(did) = cx.qpath_res(qpath, path_expr.hir_id).opt_def_id()
1434 && cx.tcx.is_diagnostic_item(sym::box_new, did) => {}
1435 _ => return,
1436 }
1437
1438 for adj in cx.typeck_results().expr_adjustments(e) {
1439 if let adjustment::Adjust::Borrow(adjustment::AutoBorrow::Ref(m)) = adj.kind {
1440 if let ty::Ref(_, inner_ty, _) = adj.target.kind()
1441 && inner_ty.is_box()
1442 {
1443 continue;
1445 }
1446 match m {
1447 adjustment::AutoBorrowMutability::Not => {
1448 cx.emit_span_lint(UNUSED_ALLOCATION, e.span, UnusedAllocationDiag);
1449 }
1450 adjustment::AutoBorrowMutability::Mut { .. } => {
1451 cx.emit_span_lint(UNUSED_ALLOCATION, e.span, UnusedAllocationMutDiag);
1452 }
1453 };
1454 }
1455 }
1456 }
1457}