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) -> PathStatements { *self }
}
impl ::rustc_lint_defs::LintPass for PathStatements {
fn name(&self) -> &'static str { "PathStatements" }
fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[PATH_STATEMENTS]))
}
}
impl PathStatements {
#[allow(unused)]
pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[PATH_STATEMENTS]))
}
}declare_lint_pass!(PathStatements => [PATH_STATEMENTS]);
41
42impl<'tcx> LateLintPass<'tcx> for PathStatements {
43 fn check_stmt(&mut self, cx: &LateContext<'_>, s: &hir::Stmt<'_>) {
44 if let hir::StmtKind::Semi(expr) = s.kind
45 && let hir::ExprKind::Path(_) = expr.kind
46 {
47 let ty = cx.typeck_results().expr_ty(expr);
48 if ty.needs_drop(cx.tcx, cx.typing_env()) {
49 let sub = if let Ok(snippet) = cx.sess().source_map().span_to_snippet(expr.span) {
50 PathStatementDropSub::Suggestion { span: s.span, snippet }
51 } else {
52 PathStatementDropSub::Help { span: s.span }
53 };
54 cx.emit_span_lint(PATH_STATEMENTS, s.span, PathStatementDrop { sub })
55 } else {
56 cx.emit_span_lint(PATH_STATEMENTS, s.span, PathStatementNoEffect);
57 }
58 }
59 }
60}
61
62#[derive(#[automatically_derived]
impl ::core::marker::Copy for UnusedDelimsCtx { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for UnusedDelimsCtx { }
#[automatically_derived]
impl ::core::clone::Clone for UnusedDelimsCtx {
#[inline]
fn clone(&self) -> UnusedDelimsCtx { *self }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for UnusedDelimsCtx {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
UnusedDelimsCtx::FunctionArg => "FunctionArg",
UnusedDelimsCtx::MethodArg => "MethodArg",
UnusedDelimsCtx::AssignedValue => "AssignedValue",
UnusedDelimsCtx::AssignedValueLetElse =>
"AssignedValueLetElse",
UnusedDelimsCtx::IfCond => "IfCond",
UnusedDelimsCtx::WhileCond => "WhileCond",
UnusedDelimsCtx::ForIterExpr => "ForIterExpr",
UnusedDelimsCtx::MatchScrutineeExpr => "MatchScrutineeExpr",
UnusedDelimsCtx::ReturnValue => "ReturnValue",
UnusedDelimsCtx::BlockRetValue => "BlockRetValue",
UnusedDelimsCtx::BreakValue => "BreakValue",
UnusedDelimsCtx::LetScrutineeExpr => "LetScrutineeExpr",
UnusedDelimsCtx::ArrayLenExpr => "ArrayLenExpr",
UnusedDelimsCtx::AnonConst => "AnonConst",
UnusedDelimsCtx::MatchArmExpr => "MatchArmExpr",
UnusedDelimsCtx::IndexExpr => "IndexExpr",
UnusedDelimsCtx::ClosureBody => "ClosureBody",
})
}
}Debug, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for UnusedDelimsCtx { }
#[automatically_derived]
impl ::core::cmp::PartialEq for UnusedDelimsCtx {
#[inline]
fn eq(&self, other: &UnusedDelimsCtx) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for UnusedDelimsCtx {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {}
}Eq)]
63enum UnusedDelimsCtx {
64 FunctionArg,
65 MethodArg,
66 AssignedValue,
67 AssignedValueLetElse,
68 IfCond,
69 WhileCond,
70 ForIterExpr,
71 MatchScrutineeExpr,
72 ReturnValue,
73 BlockRetValue,
74 BreakValue,
75 LetScrutineeExpr,
76 ArrayLenExpr,
77 AnonConst,
78 MatchArmExpr,
79 IndexExpr,
80 ClosureBody,
81}
82
83impl From<UnusedDelimsCtx> for &'static str {
84 fn from(ctx: UnusedDelimsCtx) -> &'static str {
85 match ctx {
86 UnusedDelimsCtx::FunctionArg => "function argument",
87 UnusedDelimsCtx::MethodArg => "method argument",
88 UnusedDelimsCtx::AssignedValue | UnusedDelimsCtx::AssignedValueLetElse => {
89 "assigned value"
90 }
91 UnusedDelimsCtx::IfCond => "`if` condition",
92 UnusedDelimsCtx::WhileCond => "`while` condition",
93 UnusedDelimsCtx::ForIterExpr => "`for` iterator expression",
94 UnusedDelimsCtx::MatchScrutineeExpr => "`match` scrutinee expression",
95 UnusedDelimsCtx::ReturnValue => "`return` value",
96 UnusedDelimsCtx::BlockRetValue => "block return value",
97 UnusedDelimsCtx::BreakValue => "`break` value",
98 UnusedDelimsCtx::LetScrutineeExpr => "`let` scrutinee expression",
99 UnusedDelimsCtx::ArrayLenExpr | UnusedDelimsCtx::AnonConst => "const expression",
100 UnusedDelimsCtx::MatchArmExpr => "match arm expression",
101 UnusedDelimsCtx::IndexExpr => "index expression",
102 UnusedDelimsCtx::ClosureBody => "closure body",
103 }
104 }
105}
106
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 DirectConstArg(_) => 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() -> UnusedParens {
UnusedParens {
with_self_ty_parens: ::core::default::Default::default(),
parens_in_cast_in_lt: ::core::default::Default::default(),
in_no_bounds_pos: ::core::default::Default::default(),
}
}
}Default)]
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 cast_followed_by_lt(&self, expr: &ast::Expr) -> Option<ast::NodeId> {
787 if let ExprKind::Binary(op, lhs, _rhs) = &expr.kind
788 && (op.node == ast::BinOpKind::Lt || op.node == ast::BinOpKind::Shl)
789 {
790 let mut cur = lhs;
791 while let ExprKind::Binary(_, _, rhs) = &cur.kind {
792 cur = rhs;
793 }
794
795 if let ExprKind::Cast(_, ty) = &cur.kind
796 && let ast::TyKind::Paren(_) = &ty.kind
797 {
798 return Some(ty.id);
799 }
800 }
801 None
802 }
803}
804
805impl EarlyLintPass for UnusedParens {
806 #[inline]
807 fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
808 if let Some(ty_id) = self.cast_followed_by_lt(e) {
809 self.parens_in_cast_in_lt.push(ty_id);
810 }
811
812 match e.kind {
813 ExprKind::Let(ref pat, _, _, _) | ExprKind::ForLoop(ForLoop { ref pat, .. }) => {
814 self.check_unused_parens_pat(cx, pat, false, false, (true, true));
815 }
816 ExprKind::If(ref cond, ref block, ref else_)
820 if #[allow(non_exhaustive_omitted_patterns)] match cond.peel_parens().kind {
ExprKind::Let(..) => true,
_ => false,
}matches!(cond.peel_parens().kind, ExprKind::Let(..)) =>
821 {
822 self.check_unused_delims_expr(
823 cx,
824 cond.peel_parens(),
825 UnusedDelimsCtx::LetScrutineeExpr,
826 true,
827 None,
828 None,
829 true,
830 );
831 for stmt in &block.stmts {
832 <Self as UnusedDelimLint>::check_stmt(self, cx, stmt);
833 }
834 if let Some(e) = else_ {
835 <Self as UnusedDelimLint>::check_expr(self, cx, e);
836 }
837 return;
838 }
839 ExprKind::Match(ref _expr, ref arm, _) => {
840 for a in arm {
841 if let Some(body) = &a.body {
842 self.check_unused_delims_expr(
843 cx,
844 body,
845 UnusedDelimsCtx::MatchArmExpr,
846 false,
847 None,
848 None,
849 true,
850 );
851 }
852 }
853 }
854 _ => {}
855 }
856
857 <Self as UnusedDelimLint>::check_expr(self, cx, e)
858 }
859
860 fn check_expr_post(&mut self, _cx: &EarlyContext<'_>, e: &ast::Expr) {
861 if let Some(ty_id) = self.cast_followed_by_lt(e) {
862 let id = self
863 .parens_in_cast_in_lt
864 .pop()
865 .expect("check_expr and check_expr_post must balance");
866 {
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!(
867 id, ty_id,
868 "check_expr, check_ty, and check_expr_post are called, in that order, by the visitor"
869 );
870 }
871 }
872
873 fn check_pat(&mut self, cx: &EarlyContext<'_>, p: &ast::Pat) {
874 use ast::PatKind::*;
875 use ast::{Mutability, Pinnedness};
876 let keep_space = (false, false);
877 match &p.kind {
878 Paren(_) => {}
880 Missing
882 | Wild
883 | Never
884 | Rest
885 | Expr(..)
886 | MacCall(..)
887 | Range(..)
888 | Ident(.., None)
889 | Path(..)
890 | Err(_) => {}
891 TupleStruct(_, _, ps) | Tuple(ps) | Slice(ps) | Or(ps) => {
893 for p in ps {
894 self.check_unused_parens_pat(cx, p, false, false, keep_space);
895 }
896 }
897 Struct(_, _, fps, _) => {
898 for f in fps {
899 self.check_unused_parens_pat(cx, &f.pat, false, false, keep_space);
900 }
901 }
902 Ident(.., Some(p)) | Deref(p) | Guard(p, _) => {
904 self.check_unused_parens_pat(cx, p, true, false, keep_space)
905 }
906 Ref(p, pinned, m)
912 if *pinned != Pinnedness::Pinned
913 || cx.builder.features().pin_ergonomics() =>
915 {
916 self.check_unused_parens_pat(
917 cx,
918 p,
919 true,
920 *pinned == Pinnedness::Not && *m == Mutability::Not,
921 keep_space,
922 );
923 }
924 Ref(..) => {}
925 }
926 }
927
928 fn check_stmt(&mut self, cx: &EarlyContext<'_>, s: &ast::Stmt) {
929 if let StmtKind::Let(ref local) = s.kind {
930 self.check_unused_parens_pat(cx, &local.pat, true, false, (true, false));
931 }
932
933 <Self as UnusedDelimLint>::check_stmt(self, cx, s)
934 }
935
936 fn check_param(&mut self, cx: &EarlyContext<'_>, param: &ast::Param) {
937 self.check_unused_parens_pat(cx, ¶m.pat, true, false, (false, false));
938 }
939
940 fn check_arm(&mut self, cx: &EarlyContext<'_>, arm: &ast::Arm) {
941 self.check_unused_parens_pat(cx, &arm.pat, false, false, (false, false));
942 }
943
944 fn check_ty(&mut self, cx: &EarlyContext<'_>, ty: &ast::Ty) {
945 if let ast::TyKind::Paren(_) = ty.kind
946 && Some(&ty.id) == self.parens_in_cast_in_lt.last()
947 {
948 return;
949 }
950 match &ty.kind {
951 ast::TyKind::Array(_, len) => {
952 self.check_unused_delims_expr(
953 cx,
954 &len.value,
955 UnusedDelimsCtx::ArrayLenExpr,
956 false,
957 None,
958 None,
959 false,
960 );
961 }
962 ast::TyKind::Paren(r) => {
963 let unused_parens = match &r.kind {
964 ast::TyKind::ImplTrait(_, bounds) | ast::TyKind::TraitObject(bounds, _) => {
965 match self.in_no_bounds_pos.get(&ty.id) {
966 Some(NoBoundsException::None) => false,
967 Some(NoBoundsException::OneBound) => bounds.len() <= 1,
968 None => true,
969 }
970 }
971 ast::TyKind::FnPtr(b) => {
972 !self.with_self_ty_parens || b.generic_params.is_empty()
973 }
974 _ => true,
975 };
976
977 if unused_parens {
978 let spans = (!ty.span.from_expansion())
979 .then(|| {
980 r.span
981 .find_ancestor_inside(ty.span)
982 .map(|r| (ty.span.with_hi(r.lo()), ty.span.with_lo(r.hi())))
983 })
984 .flatten();
985
986 self.emit_unused_delims(cx, ty.span, spans, "type", (false, false), false);
987 }
988
989 self.with_self_ty_parens = false;
990 }
991 ast::TyKind::Ref(_, mut_ty) | ast::TyKind::Ptr(mut_ty) => {
992 let own_constraint = self.in_no_bounds_pos.get(&ty.id);
995 let constraint = match own_constraint {
996 Some(NoBoundsException::None) => NoBoundsException::None,
997 Some(NoBoundsException::OneBound) => NoBoundsException::OneBound,
998 None => NoBoundsException::OneBound,
999 };
1000 self.in_no_bounds_pos.insert(mut_ty.ty.id, constraint);
1001 }
1002 ast::TyKind::TraitObject(bounds, _) | ast::TyKind::ImplTrait(_, bounds) => {
1003 for i in 0..bounds.len() {
1004 let is_last = i == bounds.len() - 1;
1005
1006 if let ast::GenericBound::Trait(poly_trait_ref) = &bounds[i] {
1007 let fn_with_explicit_ret_ty = if let [.., segment] =
1008 &*poly_trait_ref.trait_ref.path.segments
1009 && let Some(args) = segment.args.as_ref()
1010 && let ast::GenericArgs::Parenthesized(paren_args) = &**args
1011 && let ast::FnRetTy::Ty(ret_ty) = &paren_args.output
1012 {
1013 self.in_no_bounds_pos.insert(
1014 ret_ty.id,
1015 if is_last {
1016 NoBoundsException::OneBound
1017 } else {
1018 NoBoundsException::None
1019 },
1020 );
1021
1022 true
1023 } else {
1024 false
1025 };
1026
1027 let dyn2015_exception = cx.sess().psess.edition == Edition2015
1032 && #[allow(non_exhaustive_omitted_patterns)] match ty.kind {
ast::TyKind::TraitObject(..) => true,
_ => false,
}matches!(ty.kind, ast::TyKind::TraitObject(..))
1033 && i == 0
1034 && poly_trait_ref
1035 .trait_ref
1036 .path
1037 .segments
1038 .first()
1039 .map(|s| s.ident.name == kw::PathRoot)
1040 .unwrap_or(false);
1041
1042 if let ast::Parens::Yes = poly_trait_ref.parens
1043 && (is_last || !fn_with_explicit_ret_ty)
1044 && !dyn2015_exception
1045 {
1046 let s = poly_trait_ref.span;
1047 if !s.from_expansion()
1051 && let Ok(snippet) = cx.sess().source_map().span_to_snippet(s)
1052 && snippet.starts_with('(')
1053 && snippet.ends_with(')')
1054 {
1055 let spans = Some((
1056 s.with_hi(s.lo() + rustc_span::BytePos(1)),
1057 s.with_lo(s.hi() - rustc_span::BytePos(1)),
1058 ));
1059
1060 self.emit_unused_delims(
1061 cx,
1062 poly_trait_ref.span,
1063 spans,
1064 "type",
1065 (false, false),
1066 false,
1067 );
1068 }
1069 }
1070 }
1071 }
1072 }
1073 _ => {}
1074 }
1075 }
1076
1077 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
1078 <Self as UnusedDelimLint>::check_item(self, cx, item)
1079 }
1080
1081 fn check_item_post(&mut self, _: &EarlyContext<'_>, _: &rustc_ast::Item) {
1082 self.in_no_bounds_pos.clear();
1083 }
1084
1085 fn check_where_predicate(&mut self, _: &EarlyContext<'_>, pred: &ast::WherePredicate) {
1086 use rustc_ast::{WhereBoundPredicate, WherePredicateKind};
1087 if let WherePredicateKind::BoundPredicate(WhereBoundPredicate {
1088 bounded_ty,
1089 bound_generic_params,
1090 ..
1091 }) = &pred.kind
1092 && let ast::TyKind::Paren(_) = &bounded_ty.kind
1093 && bound_generic_params.is_empty()
1094 {
1095 self.with_self_ty_parens = true;
1096 }
1097 }
1098
1099 fn check_where_predicate_post(&mut self, _: &EarlyContext<'_>, _: &ast::WherePredicate) {
1100 if !!self.with_self_ty_parens {
::core::panicking::panic("assertion failed: !self.with_self_ty_parens")
};assert!(!self.with_self_ty_parens);
1101 }
1102}
1103
1104#[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! {
1105 pub(super) UNUSED_BRACES,
1123 Warn,
1124 "unnecessary braces around an expression"
1125}
1126
1127pub struct UnusedBraces;
#[automatically_derived]
impl ::core::marker::Copy for UnusedBraces { }
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for UnusedBraces { }
#[automatically_derived]
impl ::core::clone::Clone for UnusedBraces {
#[inline]
fn clone(&self) -> UnusedBraces { *self }
}
impl ::rustc_lint_defs::LintPass for UnusedBraces {
fn name(&self) -> &'static str { "UnusedBraces" }
fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[UNUSED_BRACES]))
}
}
impl UnusedBraces {
#[allow(unused)]
pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[UNUSED_BRACES]))
}
}declare_lint_pass!(UnusedBraces => [UNUSED_BRACES]);
1128
1129impl UnusedDelimLint for UnusedBraces {
1130 const DELIM_STR: &'static str = "braces";
1131
1132 const LINT_EXPR_IN_PATTERN_MATCHING_CTX: bool = false;
1133
1134 fn lint(&self) -> &'static Lint {
1135 UNUSED_BRACES
1136 }
1137
1138 fn check_unused_delims_expr(
1139 &self,
1140 cx: &EarlyContext<'_>,
1141 value: &ast::Expr,
1142 ctx: UnusedDelimsCtx,
1143 followed_by_block: bool,
1144 left_pos: Option<BytePos>,
1145 right_pos: Option<BytePos>,
1146 is_kw: bool,
1147 ) {
1148 match value.kind {
1149 ast::ExprKind::Block(ref inner, None)
1150 if inner.rules == ast::BlockCheckMode::Default =>
1151 {
1152 if let [stmt] = inner.stmts.as_slice()
1177 && let ast::StmtKind::Expr(ref expr) = stmt.kind
1178 && !Self::is_expr_delims_necessary(expr, ctx, followed_by_block)
1179 && !(ctx == UnusedDelimsCtx::ForIterExpr
1182 && value.span.edition().at_least_rust_2024())
1183 && !Self::needs_arg_block_to_preserve_temporaries(ctx, value, expr)
1184 && (ctx != UnusedDelimsCtx::AnonConst
1185 || (#[allow(non_exhaustive_omitted_patterns)] match expr.kind {
ast::ExprKind::Lit(_) => true,
_ => false,
}matches!(expr.kind, ast::ExprKind::Lit(_))
1186 && !expr.span.from_expansion()))
1187 && ctx != UnusedDelimsCtx::ClosureBody
1188 && !cx.sess().source_map().is_multiline(value.span)
1189 && value.attrs.is_empty()
1190 && !value.span.from_expansion()
1191 && !inner.span.from_expansion()
1192 {
1193 self.emit_unused_delims_expr(cx, value, ctx, left_pos, right_pos, is_kw)
1194 }
1195 }
1196 ast::ExprKind::Let(_, ref expr, _, _) => {
1197 self.check_unused_delims_expr(
1198 cx,
1199 expr,
1200 UnusedDelimsCtx::LetScrutineeExpr,
1201 followed_by_block,
1202 None,
1203 None,
1204 false,
1205 );
1206 }
1207 _ => {}
1208 }
1209 }
1210}
1211
1212impl EarlyLintPass for UnusedBraces {
1213 fn check_stmt(&mut self, cx: &EarlyContext<'_>, s: &ast::Stmt) {
1214 <Self as UnusedDelimLint>::check_stmt(self, cx, s)
1215 }
1216
1217 #[inline]
1218 fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
1219 <Self as UnusedDelimLint>::check_expr(self, cx, e);
1220
1221 if let ExprKind::Repeat(_, ref anon_const) = e.kind {
1222 self.check_unused_delims_expr(
1223 cx,
1224 &anon_const.value,
1225 UnusedDelimsCtx::AnonConst,
1226 false,
1227 None,
1228 None,
1229 false,
1230 );
1231 }
1232 }
1233
1234 fn check_generic_arg(&mut self, cx: &EarlyContext<'_>, arg: &ast::GenericArg) {
1235 if let ast::GenericArg::Const(ct) = arg {
1236 self.check_unused_delims_expr(
1237 cx,
1238 &ct.value,
1239 UnusedDelimsCtx::AnonConst,
1240 false,
1241 None,
1242 None,
1243 false,
1244 );
1245 }
1246 }
1247
1248 fn check_variant(&mut self, cx: &EarlyContext<'_>, v: &ast::Variant) {
1249 if let Some(anon_const) = &v.disr_expr {
1250 self.check_unused_delims_expr(
1251 cx,
1252 &anon_const.value,
1253 UnusedDelimsCtx::AnonConst,
1254 false,
1255 None,
1256 None,
1257 false,
1258 );
1259 }
1260 }
1261
1262 fn check_ty(&mut self, cx: &EarlyContext<'_>, ty: &ast::Ty) {
1263 match ty.kind {
1264 ast::TyKind::Array(_, ref len) => {
1265 self.check_unused_delims_expr(
1266 cx,
1267 &len.value,
1268 UnusedDelimsCtx::ArrayLenExpr,
1269 false,
1270 None,
1271 None,
1272 false,
1273 );
1274 }
1275
1276 _ => {}
1277 }
1278 }
1279
1280 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
1281 <Self as UnusedDelimLint>::check_item(self, cx, item)
1282 }
1283}
1284
1285#[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! {
1286 UNUSED_IMPORT_BRACES,
1311 Allow,
1312 "unnecessary braces around an imported item"
1313}
1314
1315pub struct UnusedImportBraces;
#[automatically_derived]
impl ::core::marker::Copy for UnusedImportBraces { }
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for UnusedImportBraces { }
#[automatically_derived]
impl ::core::clone::Clone for UnusedImportBraces {
#[inline]
fn clone(&self) -> UnusedImportBraces { *self }
}
impl ::rustc_lint_defs::LintPass for UnusedImportBraces {
fn name(&self) -> &'static str { "UnusedImportBraces" }
fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[UNUSED_IMPORT_BRACES]))
}
}
impl UnusedImportBraces {
#[allow(unused)]
pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[UNUSED_IMPORT_BRACES]))
}
}declare_lint_pass!(UnusedImportBraces => [UNUSED_IMPORT_BRACES]);
1316
1317impl UnusedImportBraces {
1318 fn check_use_tree(&self, cx: &EarlyContext<'_>, use_tree: &ast::UseTree, item: &ast::Item) {
1319 if let ast::UseTreeKind::Nested { ref items, .. } = use_tree.kind {
1320 for (tree, _) in items {
1322 self.check_use_tree(cx, tree, item);
1323 }
1324
1325 let [(tree, _)] = items.as_slice() else { return };
1327
1328 let node_name = match tree.kind {
1330 ast::UseTreeKind::Simple(rename) => {
1331 let orig_ident = tree.prefix.segments.last().unwrap().ident;
1332 if orig_ident.name == kw::SelfLower {
1333 return;
1334 }
1335 rename.unwrap_or(orig_ident).name
1336 }
1337 ast::UseTreeKind::Glob(_) => sym::asterisk,
1338 ast::UseTreeKind::Nested { .. } => return,
1339 };
1340
1341 cx.emit_span_lint(
1342 UNUSED_IMPORT_BRACES,
1343 item.span,
1344 UnusedImportBracesDiag { node: node_name },
1345 );
1346 }
1347 }
1348}
1349
1350impl EarlyLintPass for UnusedImportBraces {
1351 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
1352 if let ast::ItemKind::Use(ref use_tree) = item.kind {
1353 self.check_use_tree(cx, use_tree, item);
1354 }
1355 }
1356}
1357
1358#[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! {
1359 pub(super) UNUSED_ALLOCATION,
1378 Warn,
1379 "detects unnecessary allocations that can be eliminated"
1380}
1381
1382pub struct UnusedAllocation;
#[automatically_derived]
impl ::core::marker::Copy for UnusedAllocation { }
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for UnusedAllocation { }
#[automatically_derived]
impl ::core::clone::Clone for UnusedAllocation {
#[inline]
fn clone(&self) -> UnusedAllocation { *self }
}
impl ::rustc_lint_defs::LintPass for UnusedAllocation {
fn name(&self) -> &'static str { "UnusedAllocation" }
fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[UNUSED_ALLOCATION]))
}
}
impl UnusedAllocation {
#[allow(unused)]
pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[UNUSED_ALLOCATION]))
}
}declare_lint_pass!(UnusedAllocation => [UNUSED_ALLOCATION]);
1383
1384impl<'tcx> LateLintPass<'tcx> for UnusedAllocation {
1385 fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &hir::Expr<'_>) {
1386 match e.kind {
1387 hir::ExprKind::Call(path_expr, [_])
1388 if let hir::ExprKind::Path(qpath) = &path_expr.kind
1389 && let Some(did) = cx.qpath_res(qpath, path_expr.hir_id).opt_def_id()
1390 && cx.tcx.is_diagnostic_item(sym::box_new, did) => {}
1391 _ => return,
1392 }
1393
1394 for adj in cx.typeck_results().expr_adjustments(e) {
1395 if let adjustment::Adjust::Borrow(adjustment::AutoBorrow::Ref(m)) = adj.kind {
1396 if let ty::Ref(_, inner_ty, _) = adj.target.kind()
1397 && inner_ty.is_box()
1398 {
1399 continue;
1401 }
1402 match m {
1403 adjustment::AutoBorrowMutability::Not => {
1404 cx.emit_span_lint(UNUSED_ALLOCATION, e.span, UnusedAllocationDiag);
1405 }
1406 adjustment::AutoBorrowMutability::Mut { .. } => {
1407 cx.emit_span_lint(UNUSED_ALLOCATION, e.span, UnusedAllocationMutDiag);
1408 }
1409 };
1410 }
1411 }
1412 }
1413}