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",
is_externally_loaded: false,
..::rustc_lint_defs::Lint::default_fields_for_macro()
};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]
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]
fn clone(&self) -> Self { *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::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 primary_span = if let Some((lo, hi)) = spans {
395 if hi.is_empty() {
396 return;
398 }
399 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])
400 } else {
401 MultiSpan::from(value_span)
402 };
403 let suggestion = spans.map(|(lo, hi)| {
404 let sm = cx.sess().source_map();
405 let lo_replace = if (keep_space.0 || is_kw)
406 && let Ok(snip) = sm.span_to_prev_source(lo)
407 && !snip.ends_with(' ')
408 {
409 " "
410 } else if let Ok(snip) = sm.span_to_prev_source(value_span)
411 && snip.ends_with(|c: char| c.is_alphanumeric())
412 {
413 " "
414 } else {
415 ""
416 };
417
418 let hi_replace = if keep_space.1
419 && let Ok(snip) = sm.span_to_next_source(hi)
420 && !snip.starts_with(' ')
421 {
422 " "
423 } else if let Ok(snip) = sm.span_to_next_source(value_span)
424 && snip.starts_with(|c: char| c.is_alphanumeric())
425 {
426 " "
427 } else {
428 ""
429 };
430 UnusedDelimSuggestion {
431 start_span: lo,
432 start_replace: lo_replace,
433 end_span: hi,
434 end_replace: hi_replace,
435 delim: Self::DELIM_STR,
436 }
437 });
438 cx.emit_span_lint(
439 self.lint(),
440 primary_span,
441 UnusedDelim { delim: Self::DELIM_STR, item: msg, suggestion },
442 );
443 }
444
445 fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
446 use rustc_ast::ExprKind::*;
447 let (value, ctx, followed_by_block, left_pos, right_pos, is_kw) = match e.kind {
448 If(ref cond, ref block, _)
450 if !#[allow(non_exhaustive_omitted_patterns)] match cond.kind {
Let(..) => true,
_ => false,
}matches!(cond.kind, Let(..)) || Self::LINT_EXPR_IN_PATTERN_MATCHING_CTX =>
451 {
452 let left = e.span.lo() + rustc_span::BytePos(2);
453 let right = block.span.lo();
454 (cond, UnusedDelimsCtx::IfCond, true, Some(left), Some(right), true)
455 }
456
457 While(ref cond, ref block, ..)
459 if !#[allow(non_exhaustive_omitted_patterns)] match cond.kind {
Let(..) => true,
_ => false,
}matches!(cond.kind, Let(..)) || Self::LINT_EXPR_IN_PATTERN_MATCHING_CTX =>
460 {
461 let left = e.span.lo() + rustc_span::BytePos(5);
462 let right = block.span.lo();
463 (cond, UnusedDelimsCtx::WhileCond, true, Some(left), Some(right), true)
464 }
465
466 ForLoop(ast::ForLoop { ref iter, ref body, .. }) => {
467 (iter, UnusedDelimsCtx::ForIterExpr, true, None, Some(body.span.lo()), true)
468 }
469
470 Match(ref head, _, ast::MatchKind::Prefix)
471 if Self::LINT_EXPR_IN_PATTERN_MATCHING_CTX =>
472 {
473 let left = e.span.lo() + rustc_span::BytePos(5);
474 (head, UnusedDelimsCtx::MatchScrutineeExpr, true, Some(left), None, true)
475 }
476
477 Ret(Some(ref value)) => {
478 let left = e.span.lo() + rustc_span::BytePos(3);
479 (value, UnusedDelimsCtx::ReturnValue, false, Some(left), None, true)
480 }
481
482 Break(label, Some(ref value)) => {
483 if label.is_some()
487 && #[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)
488 if matches!(inner.kind, ast::ExprKind::Block(..)))
489 {
490 return;
491 }
492 (value, UnusedDelimsCtx::BreakValue, false, None, None, true)
493 }
494
495 Index(_, ref value, _) => (value, UnusedDelimsCtx::IndexExpr, false, None, None, false),
496
497 Assign(_, ref value, _) | AssignOp(.., ref value) => {
498 (value, UnusedDelimsCtx::AssignedValue, false, None, None, false)
499 }
500 ref call_or_other => {
502 let (args_to_check, ctx, callee_from_expansion) = match *call_or_other {
503 Call(ref callee, ref args) => {
504 (&args[..], UnusedDelimsCtx::FunctionArg, callee.span.from_expansion())
505 }
506 MethodCall(ref call) => (
507 &call.args[..],
508 UnusedDelimsCtx::MethodArg,
509 call.seg.ident.span.from_expansion(),
510 ),
511 Closure(ref closure)
512 if #[allow(non_exhaustive_omitted_patterns)] match closure.fn_decl.output {
FnRetTy::Default(_) => true,
_ => false,
}matches!(closure.fn_decl.output, FnRetTy::Default(_)) =>
513 {
514 (&[closure.body.clone()][..], UnusedDelimsCtx::ClosureBody, false)
515 }
516 _ => {
518 return;
519 }
520 };
521 if e.span.ctxt().outer_expn_data().call_site.from_expansion() {
526 return;
527 }
528 for arg in args_to_check {
529 if callee_from_expansion && Self::block_wraps_expanded_expr(arg) {
532 continue;
533 }
534 self.check_unused_delims_expr(cx, arg, ctx, false, None, None, false);
535 }
536 return;
537 }
538 };
539 self.check_unused_delims_expr(
540 cx,
541 value,
542 ctx,
543 followed_by_block,
544 left_pos,
545 right_pos,
546 is_kw,
547 );
548 }
549
550 fn check_stmt(&mut self, cx: &EarlyContext<'_>, s: &ast::Stmt) {
551 match s.kind {
552 StmtKind::Let(ref local) if Self::LINT_EXPR_IN_PATTERN_MATCHING_CTX => {
553 if let Some((init, els)) = local.kind.init_else_opt() {
554 if els.is_some()
555 && let ExprKind::Paren(paren) = &init.kind
556 && !init.span.eq_ctxt(paren.span)
557 {
558 return;
569 }
570 let ctx = match els {
571 None => UnusedDelimsCtx::AssignedValue,
572 Some(_) => UnusedDelimsCtx::AssignedValueLetElse,
573 };
574 self.check_unused_delims_expr(cx, init, ctx, false, None, None, false);
575 }
576 }
577 StmtKind::Expr(ref expr) => {
578 self.check_unused_delims_expr(
579 cx,
580 expr,
581 UnusedDelimsCtx::BlockRetValue,
582 false,
583 None,
584 None,
585 false,
586 );
587 }
588 _ => {}
589 }
590 }
591
592 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
593 use ast::ItemKind::*;
594
595 let expr = if let Const(ast::ConstItem { body: Some(expr), .. }) = &item.kind {
596 expr
597 } else if let Static(ast::StaticItem { expr: Some(expr), .. }) = &item.kind {
598 expr
599 } else {
600 return;
601 };
602 self.check_unused_delims_expr(
603 cx,
604 expr,
605 UnusedDelimsCtx::AssignedValue,
606 false,
607 None,
608 None,
609 false,
610 );
611 }
612
613 fn block_wraps_expanded_expr(value: &ast::Expr) -> bool {
615 if let ast::ExprKind::Block(ref block, None) = value.kind
616 && block.rules == ast::BlockCheckMode::Default
617 && !value.span.from_expansion()
618 && let [stmt] = block.stmts.as_slice()
619 && let ast::StmtKind::Expr(ref expr) = stmt.kind
620 {
621 expr.span.from_expansion()
622 } else {
623 false
624 }
625 }
626}
627
628#[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! {
629 pub(super) UNUSED_PARENS,
645 Warn,
646 "`if`, `match`, `while` and `return` do not need parentheses"
647}
648
649#[derive(#[automatically_derived]
impl ::core::default::Default for UnusedParens {
#[inline]
fn default() -> Self {
Self {
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)]
650pub(crate) struct UnusedParens {
651 with_self_ty_parens: bool,
652 parens_in_cast_in_lt: Vec<ast::NodeId>,
655 in_no_bounds_pos: FxHashMap<ast::NodeId, NoBoundsException>,
658}
659
660enum NoBoundsException {
675 None,
677 OneBound,
680}
681
682impl ::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]);
683
684impl UnusedDelimLint for UnusedParens {
685 const DELIM_STR: &'static str = "parentheses";
686
687 const LINT_EXPR_IN_PATTERN_MATCHING_CTX: bool = true;
688
689 fn lint(&self) -> &'static Lint {
690 UNUSED_PARENS
691 }
692
693 fn check_unused_delims_expr(
694 &self,
695 cx: &EarlyContext<'_>,
696 value: &ast::Expr,
697 ctx: UnusedDelimsCtx,
698 followed_by_block: bool,
699 left_pos: Option<BytePos>,
700 right_pos: Option<BytePos>,
701 is_kw: bool,
702 ) {
703 match value.kind {
704 ast::ExprKind::Paren(ref inner) => {
705 if !Self::is_expr_delims_necessary(inner, ctx, followed_by_block)
706 && value.attrs.is_empty()
707 && !value.span.from_expansion()
708 && (ctx != UnusedDelimsCtx::LetScrutineeExpr
709 || !#[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(
710 rustc_span::Spanned { node, .. },
711 _,
712 _,
713 ) if node.is_lazy()))
714 && !((ctx == UnusedDelimsCtx::ReturnValue
715 || ctx == UnusedDelimsCtx::BreakValue)
716 && #[allow(non_exhaustive_omitted_patterns)] match inner.kind {
ast::ExprKind::Assign(_, _, _) => true,
_ => false,
}matches!(inner.kind, ast::ExprKind::Assign(_, _, _)))
717 {
718 self.emit_unused_delims_expr(cx, value, ctx, left_pos, right_pos, is_kw)
719 }
720 }
721 ast::ExprKind::Let(_, ref expr, _, _) => {
722 self.check_unused_delims_expr(
723 cx,
724 expr,
725 UnusedDelimsCtx::LetScrutineeExpr,
726 followed_by_block,
727 None,
728 None,
729 false,
730 );
731 }
732 _ => {}
733 }
734 }
735}
736
737impl UnusedParens {
738 fn check_unused_parens_pat(
739 &self,
740 cx: &EarlyContext<'_>,
741 value: &ast::Pat,
742 avoid_or: bool,
743 avoid_mut: bool,
744 keep_space: (bool, bool),
745 ) {
746 use ast::{BindingMode, ByRef, Mutability, PatKind, Pinnedness};
747
748 if let PatKind::Paren(inner) = &value.kind {
749 match inner.kind {
750 PatKind::Range(..) => return,
755 PatKind::Guard(..) => return,
757 PatKind::Or(..) if avoid_or => return,
759 PatKind::Ident(BindingMode(_, Mutability::Mut), ..) if avoid_mut => {
762 return;
763 }
764 PatKind::Ref(_, Pinnedness::Pinned, _)
765 | PatKind::Ident(BindingMode(ByRef::Yes(Pinnedness::Pinned, _), _), ..)
766 if !cx.builder.features().pin_ergonomics() =>
768 {
769 return;
770 }
771 _ => {}
773 }
774 let spans = if !value.span.from_expansion() {
775 inner
776 .span
777 .find_ancestor_inside(value.span)
778 .map(|inner| (value.span.with_hi(inner.lo()), value.span.with_lo(inner.hi())))
779 } else {
780 None
781 };
782 self.emit_unused_delims(cx, value.span, spans, "pattern", keep_space, false);
783 }
784 }
785
786 fn pat_is_macro_arg(pat_span: Span, parent_span: Span) -> bool {
791 !pat_span.eq_ctxt(parent_span)
792 }
793
794 fn cast_followed_by_lt(&self, expr: &ast::Expr) -> Option<ast::NodeId> {
795 if let ExprKind::Binary(op, lhs, _rhs) = &expr.kind
796 && (op.node == ast::BinOpKind::Lt || op.node == ast::BinOpKind::Shl)
797 {
798 let mut cur = lhs;
799 while let ExprKind::Binary(_, _, rhs) = &cur.kind {
800 cur = rhs;
801 }
802
803 if let ExprKind::Cast(_, ty) = &cur.kind
804 && let ast::TyKind::Paren(_) = &ty.kind
805 {
806 return Some(ty.id);
807 }
808 }
809 None
810 }
811}
812
813impl EarlyLintPass for UnusedParens {
814 #[inline]
815 fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
816 if let Some(ty_id) = self.cast_followed_by_lt(e) {
817 self.parens_in_cast_in_lt.push(ty_id);
818 }
819
820 match e.kind {
821 ExprKind::Let(ref pat, _, _, _) | ExprKind::ForLoop(ForLoop { ref pat, .. }) => {
822 let avoid_or = Self::pat_is_macro_arg(pat.span, e.span);
823 self.check_unused_parens_pat(cx, pat, avoid_or, false, (true, true));
824 }
825 ExprKind::If(ref cond, ref block, ref else_)
829 if #[allow(non_exhaustive_omitted_patterns)] match cond.peel_parens().kind {
ExprKind::Let(..) => true,
_ => false,
}matches!(cond.peel_parens().kind, ExprKind::Let(..)) =>
830 {
831 self.check_unused_delims_expr(
832 cx,
833 cond.peel_parens(),
834 UnusedDelimsCtx::LetScrutineeExpr,
835 true,
836 None,
837 None,
838 true,
839 );
840 for stmt in &block.stmts {
841 <Self as UnusedDelimLint>::check_stmt(self, cx, stmt);
842 }
843 if let Some(e) = else_ {
844 <Self as UnusedDelimLint>::check_expr(self, cx, e);
845 }
846 return;
847 }
848 ExprKind::Match(ref _expr, ref arm, _) => {
849 for a in arm {
850 if let Some(body) = &a.body {
851 self.check_unused_delims_expr(
852 cx,
853 body,
854 UnusedDelimsCtx::MatchArmExpr,
855 false,
856 None,
857 None,
858 true,
859 );
860 }
861 }
862 }
863 _ => {}
864 }
865
866 <Self as UnusedDelimLint>::check_expr(self, cx, e)
867 }
868
869 fn check_expr_post(&mut self, _cx: &EarlyContext<'_>, e: &ast::Expr) {
870 if let Some(ty_id) = self.cast_followed_by_lt(e) {
871 let id = self
872 .parens_in_cast_in_lt
873 .pop()
874 .expect("check_expr and check_expr_post must balance");
875 {
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!(
876 id, ty_id,
877 "check_expr, check_ty, and check_expr_post are called, in that order, by the visitor"
878 );
879 }
880 }
881
882 fn check_pat(&mut self, cx: &EarlyContext<'_>, p: &ast::Pat) {
883 use ast::PatKind::*;
884 use ast::{Mutability, Pinnedness};
885 let keep_space = (false, false);
886 match &p.kind {
887 Paren(_) => {}
889 Missing
891 | Wild
892 | Never
893 | Rest
894 | Expr(..)
895 | MacCall(..)
896 | Range(..)
897 | Ident(.., None)
898 | Path(..)
899 | Err(_) => {}
900 TupleStruct(_, _, ps) | Tuple(ps) | Slice(ps) | Or(ps) => {
902 for sub in ps {
903 let avoid_or = Self::pat_is_macro_arg(sub.span, p.span);
904 self.check_unused_parens_pat(cx, sub, avoid_or, false, keep_space);
905 }
906 }
907 Struct(_, _, fps, _) => {
908 for f in fps {
909 let avoid_or = Self::pat_is_macro_arg(f.pat.span, p.span);
910 self.check_unused_parens_pat(cx, &f.pat, avoid_or, false, keep_space);
911 }
912 }
913 Ident(.., Some(p)) | Deref(p) | Guard(p, _) => {
915 self.check_unused_parens_pat(cx, p, true, false, keep_space)
916 }
917 Ref(p, pinned, m)
923 if *pinned != Pinnedness::Pinned
924 || cx.builder.features().pin_ergonomics() =>
926 {
927 self.check_unused_parens_pat(
928 cx,
929 p,
930 true,
931 *pinned == Pinnedness::Not && *m == Mutability::Not,
932 keep_space,
933 );
934 }
935 Ref(..) => {}
936 }
937 }
938
939 fn check_stmt(&mut self, cx: &EarlyContext<'_>, s: &ast::Stmt) {
940 if let StmtKind::Let(ref local) = s.kind {
941 self.check_unused_parens_pat(cx, &local.pat, true, false, (true, false));
942 }
943
944 <Self as UnusedDelimLint>::check_stmt(self, cx, s)
945 }
946
947 fn check_param(&mut self, cx: &EarlyContext<'_>, param: &ast::Param) {
948 self.check_unused_parens_pat(cx, ¶m.pat, true, false, (false, false));
949 }
950
951 fn check_arm(&mut self, cx: &EarlyContext<'_>, arm: &ast::Arm) {
952 let avoid_or = Self::pat_is_macro_arg(arm.pat.span, arm.span);
953 self.check_unused_parens_pat(cx, &arm.pat, avoid_or, false, (false, false));
954 }
955
956 fn check_ty(&mut self, cx: &EarlyContext<'_>, ty: &ast::Ty) {
957 if let ast::TyKind::Paren(_) = ty.kind
958 && Some(&ty.id) == self.parens_in_cast_in_lt.last()
959 {
960 return;
961 }
962 match &ty.kind {
963 ast::TyKind::Array(_, len) => {
964 self.check_unused_delims_expr(
965 cx,
966 &len.value,
967 UnusedDelimsCtx::ArrayLenExpr,
968 false,
969 None,
970 None,
971 false,
972 );
973 }
974 ast::TyKind::Paren(r) => {
975 let unused_parens = match &r.kind {
976 ast::TyKind::ImplTrait(_, bounds) | ast::TyKind::TraitObject(bounds, _) => {
977 match self.in_no_bounds_pos.get(&ty.id) {
978 Some(NoBoundsException::None) => false,
979 Some(NoBoundsException::OneBound) => bounds.len() <= 1,
980 None => true,
981 }
982 }
983 ast::TyKind::FnPtr(b) => {
984 !self.with_self_ty_parens || b.generic_params.is_empty()
985 }
986 _ => true,
987 };
988
989 if unused_parens {
990 let spans = (!ty.span.from_expansion())
991 .then(|| {
992 r.span
993 .find_ancestor_inside(ty.span)
994 .map(|r| (ty.span.with_hi(r.lo()), ty.span.with_lo(r.hi())))
995 })
996 .flatten();
997
998 self.emit_unused_delims(cx, ty.span, spans, "type", (false, false), false);
999 }
1000
1001 self.with_self_ty_parens = false;
1002 }
1003 ast::TyKind::Ref(_, inner_ty, _) | ast::TyKind::Ptr(inner_ty, _) => {
1004 let own_constraint = self.in_no_bounds_pos.get(&ty.id);
1007 let constraint = match own_constraint {
1008 Some(NoBoundsException::None) => NoBoundsException::None,
1009 Some(NoBoundsException::OneBound) => NoBoundsException::OneBound,
1010 None => NoBoundsException::OneBound,
1011 };
1012 self.in_no_bounds_pos.insert(inner_ty.id, constraint);
1013 }
1014 ast::TyKind::TraitObject(bounds, _) | ast::TyKind::ImplTrait(_, bounds) => {
1015 for i in 0..bounds.len() {
1016 let is_last = i == bounds.len() - 1;
1017
1018 if let ast::GenericBound::Trait(poly_trait_ref) = &bounds[i] {
1019 let fn_with_explicit_ret_ty = if let [.., segment] =
1020 &*poly_trait_ref.trait_ref.path.segments
1021 && let Some(args) = segment.args.as_ref()
1022 && let ast::GenericArgs::Parenthesized(paren_args) = &**args
1023 && let ast::FnRetTy::Ty(ret_ty) = &paren_args.output
1024 {
1025 self.in_no_bounds_pos.insert(
1026 ret_ty.id,
1027 if is_last {
1028 NoBoundsException::OneBound
1029 } else {
1030 NoBoundsException::None
1031 },
1032 );
1033
1034 true
1035 } else {
1036 false
1037 };
1038
1039 let dyn2015_exception = cx.sess().psess.edition == Edition2015
1044 && #[allow(non_exhaustive_omitted_patterns)] match ty.kind {
ast::TyKind::TraitObject(..) => true,
_ => false,
}matches!(ty.kind, ast::TyKind::TraitObject(..))
1045 && i == 0
1046 && poly_trait_ref
1047 .trait_ref
1048 .path
1049 .segments
1050 .first()
1051 .map(|s| s.ident.name == kw::PathRoot)
1052 .unwrap_or(false);
1053
1054 if let ast::Parens::Yes = poly_trait_ref.parens
1055 && (is_last || !fn_with_explicit_ret_ty)
1056 && !dyn2015_exception
1057 {
1058 let s = poly_trait_ref.span;
1059 if !s.from_expansion()
1063 && let Ok(snippet) = cx.sess().source_map().span_to_snippet(s)
1064 && snippet.starts_with('(')
1065 && snippet.ends_with(')')
1066 {
1067 let spans = Some((
1068 s.with_hi(s.lo() + rustc_span::BytePos(1)),
1069 s.with_lo(s.hi() - rustc_span::BytePos(1)),
1070 ));
1071
1072 self.emit_unused_delims(
1073 cx,
1074 poly_trait_ref.span,
1075 spans,
1076 "type",
1077 (false, false),
1078 false,
1079 );
1080 }
1081 }
1082 }
1083 }
1084 }
1085 _ => {}
1086 }
1087 }
1088
1089 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
1090 <Self as UnusedDelimLint>::check_item(self, cx, item)
1091 }
1092
1093 fn check_item_post(&mut self, _: &EarlyContext<'_>, _: &rustc_ast::Item) {
1094 self.in_no_bounds_pos.clear();
1095 }
1096
1097 fn check_where_predicate(&mut self, _: &EarlyContext<'_>, pred: &ast::WherePredicate) {
1098 use rustc_ast::{WhereBoundPredicate, WherePredicateKind};
1099 if let WherePredicateKind::BoundPredicate(WhereBoundPredicate {
1100 bounded_ty,
1101 bound_generic_params,
1102 ..
1103 }) = &pred.kind
1104 && let ast::TyKind::Paren(_) = &bounded_ty.kind
1105 && bound_generic_params.is_empty()
1106 {
1107 self.with_self_ty_parens = true;
1108 }
1109 }
1110
1111 fn check_where_predicate_post(&mut self, _: &EarlyContext<'_>, _: &ast::WherePredicate) {
1112 if !!self.with_self_ty_parens {
::core::panicking::panic("assertion failed: !self.with_self_ty_parens")
};assert!(!self.with_self_ty_parens);
1113 }
1114}
1115
1116#[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! {
1117 pub(super) UNUSED_BRACES,
1135 Warn,
1136 "unnecessary braces around an expression"
1137}
1138
1139pub 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) -> 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]);
1140
1141impl UnusedDelimLint for UnusedBraces {
1142 const DELIM_STR: &'static str = "braces";
1143
1144 const LINT_EXPR_IN_PATTERN_MATCHING_CTX: bool = false;
1145
1146 fn lint(&self) -> &'static Lint {
1147 UNUSED_BRACES
1148 }
1149
1150 fn check_unused_delims_expr(
1151 &self,
1152 cx: &EarlyContext<'_>,
1153 value: &ast::Expr,
1154 ctx: UnusedDelimsCtx,
1155 followed_by_block: bool,
1156 left_pos: Option<BytePos>,
1157 right_pos: Option<BytePos>,
1158 is_kw: bool,
1159 ) {
1160 match value.kind {
1161 ast::ExprKind::Block(ref inner, None)
1162 if inner.rules == ast::BlockCheckMode::Default =>
1163 {
1164 if let [stmt] = inner.stmts.as_slice()
1189 && let ast::StmtKind::Expr(ref expr) = stmt.kind
1190 && !Self::is_expr_delims_necessary(expr, ctx, followed_by_block)
1191 && !(ctx == UnusedDelimsCtx::ForIterExpr
1194 && value.span.edition().at_least_rust_2024())
1195 && !Self::needs_arg_block_to_preserve_temporaries(ctx, value, expr)
1196 && (ctx != UnusedDelimsCtx::AnonConst
1197 || (#[allow(non_exhaustive_omitted_patterns)] match expr.kind {
ast::ExprKind::Lit(_) => true,
_ => false,
}matches!(expr.kind, ast::ExprKind::Lit(_))
1198 && !expr.span.from_expansion()))
1199 && ctx != UnusedDelimsCtx::ClosureBody
1200 && !cx.sess().source_map().is_multiline(value.span)
1201 && value.attrs.is_empty()
1202 && !value.span.from_expansion()
1203 && !inner.span.from_expansion()
1204 {
1205 self.emit_unused_delims_expr(cx, value, ctx, left_pos, right_pos, is_kw)
1206 }
1207 }
1208 ast::ExprKind::Let(_, ref expr, _, _) => {
1209 self.check_unused_delims_expr(
1210 cx,
1211 expr,
1212 UnusedDelimsCtx::LetScrutineeExpr,
1213 followed_by_block,
1214 None,
1215 None,
1216 false,
1217 );
1218 }
1219 _ => {}
1220 }
1221 }
1222}
1223
1224impl EarlyLintPass for UnusedBraces {
1225 fn check_stmt(&mut self, cx: &EarlyContext<'_>, s: &ast::Stmt) {
1226 <Self as UnusedDelimLint>::check_stmt(self, cx, s)
1227 }
1228
1229 #[inline]
1230 fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
1231 <Self as UnusedDelimLint>::check_expr(self, cx, e);
1232
1233 if let ExprKind::Repeat(_, ref anon_const) = e.kind {
1234 self.check_unused_delims_expr(
1235 cx,
1236 &anon_const.value,
1237 UnusedDelimsCtx::AnonConst,
1238 false,
1239 None,
1240 None,
1241 false,
1242 );
1243 }
1244 }
1245
1246 fn check_generic_arg(&mut self, cx: &EarlyContext<'_>, arg: &ast::GenericArg) {
1247 if let ast::GenericArg::Const(ct) = arg {
1248 self.check_unused_delims_expr(
1249 cx,
1250 &ct.value,
1251 UnusedDelimsCtx::AnonConst,
1252 false,
1253 None,
1254 None,
1255 false,
1256 );
1257 }
1258 }
1259
1260 fn check_variant(&mut self, cx: &EarlyContext<'_>, v: &ast::Variant) {
1261 if let Some(anon_const) = &v.disr_expr {
1262 self.check_unused_delims_expr(
1263 cx,
1264 &anon_const.value,
1265 UnusedDelimsCtx::AnonConst,
1266 false,
1267 None,
1268 None,
1269 false,
1270 );
1271 }
1272 }
1273
1274 fn check_ty(&mut self, cx: &EarlyContext<'_>, ty: &ast::Ty) {
1275 match ty.kind {
1276 ast::TyKind::Array(_, ref len) => {
1277 self.check_unused_delims_expr(
1278 cx,
1279 &len.value,
1280 UnusedDelimsCtx::ArrayLenExpr,
1281 false,
1282 None,
1283 None,
1284 false,
1285 );
1286 }
1287
1288 _ => {}
1289 }
1290 }
1291
1292 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
1293 <Self as UnusedDelimLint>::check_item(self, cx, item)
1294 }
1295}
1296
1297#[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! {
1298 UNUSED_IMPORT_BRACES,
1323 Allow,
1324 "unnecessary braces around an imported item"
1325}
1326
1327pub 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) -> 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]);
1328
1329impl UnusedImportBraces {
1330 fn check_use_tree(&self, cx: &EarlyContext<'_>, use_tree: &ast::UseTree, item: &ast::Item) {
1331 if let ast::UseTreeKind::Nested { ref items, .. } = use_tree.kind {
1332 for tree in items {
1334 self.check_use_tree(cx, &tree.inner, item);
1335 }
1336
1337 let [tree] = items.as_slice() else { return };
1339
1340 let node_name = match tree.inner.kind {
1342 ast::UseTreeKind::Simple(rename) => {
1343 let orig_ident = tree.inner.prefix.segments.last().unwrap().ident;
1344 if orig_ident.name == kw::SelfLower {
1345 return;
1346 }
1347 rename.unwrap_or(orig_ident).name
1348 }
1349 ast::UseTreeKind::Glob(_) => sym::asterisk,
1350 ast::UseTreeKind::Nested { .. } => return,
1351 };
1352
1353 cx.emit_span_lint(
1354 UNUSED_IMPORT_BRACES,
1355 item.span,
1356 UnusedImportBracesDiag { node: node_name },
1357 );
1358 }
1359 }
1360}
1361
1362impl EarlyLintPass for UnusedImportBraces {
1363 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
1364 if let ast::ItemKind::Use(ref use_tree) = item.kind {
1365 self.check_use_tree(cx, use_tree, item);
1366 }
1367 }
1368}
1369
1370#[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! {
1371 pub(super) UNUSED_ALLOCATION,
1390 Warn,
1391 "detects unnecessary allocations that can be eliminated"
1392}
1393
1394pub 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) -> 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]);
1395
1396impl<'tcx> LateLintPass<'tcx> for UnusedAllocation {
1397 fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &hir::Expr<'_>) {
1398 match e.kind {
1399 hir::ExprKind::Call(path_expr, [_])
1400 if let hir::ExprKind::Path(qpath) = &path_expr.kind
1401 && let Some(did) = cx.qpath_res(qpath, path_expr.hir_id).opt_def_id()
1402 && cx.tcx.is_diagnostic_item(sym::box_new, did) => {}
1403 _ => return,
1404 }
1405
1406 for adj in cx.typeck_results().expr_adjustments(e) {
1407 if let adjustment::Adjust::Borrow(adjustment::AutoBorrow::Ref(m)) = adj.kind {
1408 if let ty::Ref(_, inner_ty, _) = adj.target.kind()
1409 && inner_ty.is_box()
1410 {
1411 continue;
1413 }
1414 match m {
1415 adjustment::AutoBorrowMutability::Not => {
1416 cx.emit_span_lint(UNUSED_ALLOCATION, e.span, UnusedAllocationDiag);
1417 }
1418 adjustment::AutoBorrowMutability::Mut { .. } => {
1419 cx.emit_span_lint(UNUSED_ALLOCATION, e.span, UnusedAllocationMutDiag);
1420 }
1421 };
1422 }
1423 }
1424 }
1425}