1#![feature(box_patterns)]
2#![feature(if_let_guard)]
3#![feature(macro_metavar_expr)]
4#![feature(never_type)]
5#![feature(rustc_private)]
6#![feature(assert_matches)]
7#![feature(unwrap_infallible)]
8#![cfg_attr(bootstrap, feature(array_windows))]
9#![recursion_limit = "512"]
10#![allow(
11 clippy::missing_errors_doc,
12 clippy::missing_panics_doc,
13 clippy::must_use_candidate,
14 rustc::diagnostic_outside_of_impl,
15 rustc::untranslatable_diagnostic
16)]
17#![warn(
18 trivial_casts,
19 trivial_numeric_casts,
20 rust_2018_idioms,
21 unused_lifetimes,
22 unused_qualifications,
23 rustc::internal
24)]
25
26extern crate rustc_abi;
29extern crate rustc_ast;
30extern crate rustc_attr_parsing;
31extern crate rustc_const_eval;
32extern crate rustc_data_structures;
33#[expect(
34 unused_extern_crates,
35 reason = "The `rustc_driver` crate seems to be required in order to use the `rust_ast` crate."
36)]
37extern crate rustc_driver;
38extern crate rustc_errors;
39extern crate rustc_hir;
40extern crate rustc_hir_analysis;
41extern crate rustc_hir_typeck;
42extern crate rustc_index;
43extern crate rustc_infer;
44extern crate rustc_lexer;
45extern crate rustc_lint;
46extern crate rustc_middle;
47extern crate rustc_mir_dataflow;
48extern crate rustc_session;
49extern crate rustc_span;
50extern crate rustc_trait_selection;
51
52pub mod ast_utils;
53#[deny(missing_docs)]
54pub mod attrs;
55mod check_proc_macro;
56pub mod comparisons;
57pub mod consts;
58pub mod diagnostics;
59pub mod eager_or_lazy;
60pub mod higher;
61mod hir_utils;
62pub mod macros;
63pub mod mir;
64pub mod msrvs;
65pub mod numeric_literal;
66pub mod paths;
67pub mod qualify_min_const_fn;
68pub mod res;
69pub mod source;
70pub mod str_utils;
71pub mod sugg;
72pub mod sym;
73pub mod ty;
74pub mod usage;
75pub mod visitors;
76
77pub use self::attrs::*;
78pub use self::check_proc_macro::{is_from_proc_macro, is_span_if, is_span_match};
79pub use self::hir_utils::{
80 HirEqInterExpr, SpanlessEq, SpanlessHash, both, count_eq, eq_expr_value, has_ambiguous_literal_in_expr, hash_expr,
81 hash_stmt, is_bool, over,
82};
83
84use core::mem;
85use core::ops::ControlFlow;
86use std::collections::hash_map::Entry;
87use std::iter::{once, repeat_n, zip};
88use std::sync::{Mutex, MutexGuard, OnceLock};
89
90use itertools::Itertools;
91use rustc_abi::Integer;
92use rustc_ast::ast::{self, LitKind, RangeLimits};
93use rustc_ast::join_path_syms;
94use rustc_data_structures::fx::FxHashMap;
95use rustc_data_structures::indexmap;
96use rustc_data_structures::packed::Pu128;
97use rustc_data_structures::unhash::UnindexMap;
98use rustc_hir::LangItem::{OptionNone, OptionSome, ResultErr, ResultOk};
99use rustc_hir::attrs::AttributeKind;
100use rustc_hir::def::{DefKind, Res};
101use rustc_hir::def_id::{DefId, LocalDefId, LocalModDefId};
102use rustc_hir::definitions::{DefPath, DefPathData};
103use rustc_hir::hir_id::{HirIdMap, HirIdSet};
104use rustc_hir::intravisit::{Visitor, walk_expr};
105use rustc_hir::{
106 self as hir, Arm, BindingMode, Block, BlockCheckMode, Body, ByRef, Closure, ConstArgKind, CoroutineDesugaring,
107 CoroutineKind, CoroutineSource, Destination, Expr, ExprField, ExprKind, FnDecl, FnRetTy, GenericArg, GenericArgs,
108 HirId, Impl, ImplItem, ImplItemKind, Item, ItemKind, LangItem, LetStmt, MatchSource, Mutability, Node, OwnerId,
109 OwnerNode, Param, Pat, PatExpr, PatExprKind, PatKind, Path, PathSegment, QPath, Stmt, StmtKind, TraitFn, TraitItem,
110 TraitItemKind, TraitRef, TyKind, UnOp, def, find_attr,
111};
112use rustc_lexer::{FrontmatterAllowed, TokenKind, tokenize};
113use rustc_lint::{LateContext, Level, Lint, LintContext};
114use rustc_middle::hir::nested_filter;
115use rustc_middle::hir::place::PlaceBase;
116use rustc_middle::lint::LevelAndSource;
117use rustc_middle::mir::{AggregateKind, Operand, RETURN_PLACE, Rvalue, StatementKind, TerminatorKind};
118use rustc_middle::ty::adjustment::{Adjust, Adjustment, AutoBorrow, PointerCoercion};
119use rustc_middle::ty::layout::IntegerExt;
120use rustc_middle::ty::{
121 self as rustc_ty, Binder, BorrowKind, ClosureKind, EarlyBinder, GenericArgKind, GenericArgsRef, IntTy, Ty, TyCtxt,
122 TypeFlags, TypeVisitableExt, UintTy, UpvarCapture,
123};
124use rustc_hir::attrs::CfgEntry;
125use rustc_span::hygiene::{ExpnKind, MacroKind};
126use rustc_span::source_map::SourceMap;
127use rustc_span::symbol::{Ident, Symbol, kw};
128use rustc_span::{InnerSpan, Span};
129use source::{SpanRangeExt, walk_span_to_context};
130use visitors::{Visitable, for_each_unconsumed_temporary};
131
132use crate::ast_utils::unordered_over;
133use crate::consts::{ConstEvalCtxt, Constant};
134use crate::higher::Range;
135use crate::msrvs::Msrv;
136use crate::res::{MaybeDef, MaybeQPath, MaybeResPath};
137use crate::ty::{adt_and_variant_of_res, can_partially_move_ty, expr_sig, is_copy, is_recursively_primitive_type};
138use crate::visitors::for_each_expr_without_closures;
139
140pub const VEC_METHODS_SHADOWING_SLICE_METHODS: [Symbol; 3] = [sym::as_ptr, sym::is_empty, sym::len];
142
143#[macro_export]
144macro_rules! extract_msrv_attr {
145 () => {
146 fn check_attributes(&mut self, cx: &rustc_lint::EarlyContext<'_>, attrs: &[rustc_ast::ast::Attribute]) {
147 let sess = rustc_lint::LintContext::sess(cx);
148 self.msrv.check_attributes(sess, attrs);
149 }
150
151 fn check_attributes_post(&mut self, cx: &rustc_lint::EarlyContext<'_>, attrs: &[rustc_ast::ast::Attribute]) {
152 let sess = rustc_lint::LintContext::sess(cx);
153 self.msrv.check_attributes_post(sess, attrs);
154 }
155 };
156}
157
158pub fn expr_or_init<'a, 'b, 'tcx: 'b>(cx: &LateContext<'tcx>, mut expr: &'a Expr<'b>) -> &'a Expr<'b> {
181 while let Some(init) = expr
182 .res_local_id()
183 .and_then(|id| find_binding_init(cx, id))
184 .filter(|init| cx.typeck_results().expr_adjustments(init).is_empty())
185 {
186 expr = init;
187 }
188 expr
189}
190
191pub fn find_binding_init<'tcx>(cx: &LateContext<'tcx>, hir_id: HirId) -> Option<&'tcx Expr<'tcx>> {
200 if let Node::Pat(pat) = cx.tcx.hir_node(hir_id)
201 && matches!(pat.kind, PatKind::Binding(BindingMode::NONE, ..))
202 && let Node::LetStmt(local) = cx.tcx.parent_hir_node(hir_id)
203 {
204 return local.init;
205 }
206 None
207}
208
209pub fn local_is_initialized(cx: &LateContext<'_>, local: HirId) -> bool {
213 for (_, node) in cx.tcx.hir_parent_iter(local) {
214 match node {
215 Node::Pat(..) | Node::PatField(..) => {},
216 Node::LetStmt(let_stmt) => return let_stmt.init.is_some(),
217 _ => return true,
218 }
219 }
220
221 false
222}
223
224pub fn is_in_const_context(cx: &LateContext<'_>) -> bool {
235 debug_assert!(cx.enclosing_body.is_some(), "`LateContext` has no enclosing body");
236 cx.enclosing_body.is_some_and(|id| {
237 cx.tcx
238 .hir_body_const_context(cx.tcx.hir_body_owner_def_id(id))
239 .is_some()
240 })
241}
242
243pub fn is_inside_always_const_context(tcx: TyCtxt<'_>, hir_id: HirId) -> bool {
250 use rustc_hir::ConstContext::{Const, ConstFn, Static};
251 let Some(ctx) = tcx.hir_body_const_context(tcx.hir_enclosing_body_owner(hir_id)) else {
252 return false;
253 };
254 match ctx {
255 ConstFn => false,
256 Static(_) | Const { inline: _ } => true,
257 }
258}
259
260pub fn is_enum_variant_ctor(
262 cx: &LateContext<'_>,
263 enum_item: Symbol,
264 variant_name: Symbol,
265 ctor_call_id: DefId,
266) -> bool {
267 let Some(enum_def_id) = cx.tcx.get_diagnostic_item(enum_item) else {
268 return false;
269 };
270
271 let variants = cx.tcx.adt_def(enum_def_id).variants().iter();
272 variants
273 .filter(|variant| variant.name == variant_name)
274 .filter_map(|variant| variant.ctor.as_ref())
275 .any(|(_, ctor_def_id)| *ctor_def_id == ctor_call_id)
276}
277
278pub fn is_diagnostic_item_or_ctor(cx: &LateContext<'_>, did: DefId, item: Symbol) -> bool {
280 let did = match cx.tcx.def_kind(did) {
281 DefKind::Ctor(..) => cx.tcx.parent(did),
282 DefKind::Variant => match cx.tcx.opt_parent(did) {
284 Some(did) if matches!(cx.tcx.def_kind(did), DefKind::Variant) => did,
285 _ => did,
286 },
287 _ => did,
288 };
289
290 cx.tcx.is_diagnostic_item(item, did)
291}
292
293pub fn is_lang_item_or_ctor(cx: &LateContext<'_>, did: DefId, item: LangItem) -> bool {
295 let did = match cx.tcx.def_kind(did) {
296 DefKind::Ctor(..) => cx.tcx.parent(did),
297 DefKind::Variant => match cx.tcx.opt_parent(did) {
299 Some(did) if matches!(cx.tcx.def_kind(did), DefKind::Variant) => did,
300 _ => did,
301 },
302 _ => did,
303 };
304
305 cx.tcx.lang_items().get(item) == Some(did)
306}
307
308pub fn is_none_expr(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
310 expr.res(cx).ctor_parent(cx).is_lang_item(cx, OptionNone)
311}
312
313pub fn as_some_expr<'tcx>(cx: &LateContext<'_>, expr: &'tcx Expr<'tcx>) -> Option<&'tcx Expr<'tcx>> {
315 if let ExprKind::Call(e, [arg]) = expr.kind
316 && e.res(cx).ctor_parent(cx).is_lang_item(cx, OptionSome)
317 {
318 Some(arg)
319 } else {
320 None
321 }
322}
323
324pub fn is_unit_expr(expr: &Expr<'_>) -> bool {
326 matches!(
327 expr.kind,
328 ExprKind::Block(
329 Block {
330 stmts: [],
331 expr: None,
332 ..
333 },
334 _
335 ) | ExprKind::Tup([])
336 )
337}
338
339pub fn is_wild(pat: &Pat<'_>) -> bool {
341 matches!(pat.kind, PatKind::Wild)
342}
343
344pub fn as_some_pattern<'a, 'hir>(cx: &LateContext<'_>, pat: &'a Pat<'hir>) -> Option<&'a [Pat<'hir>]> {
351 if let PatKind::TupleStruct(ref qpath, inner, _) = pat.kind
352 && cx
353 .qpath_res(qpath, pat.hir_id)
354 .ctor_parent(cx)
355 .is_lang_item(cx, OptionSome)
356 {
357 Some(inner)
358 } else {
359 None
360 }
361}
362
363pub fn is_none_pattern(cx: &LateContext<'_>, pat: &Pat<'_>) -> bool {
365 matches!(pat.kind,
366 PatKind::Expr(PatExpr { kind: PatExprKind::Path(qpath), .. })
367 if cx.qpath_res(qpath, pat.hir_id).ctor_parent(cx).is_lang_item(cx, OptionNone))
368}
369
370pub fn is_none_arm(cx: &LateContext<'_>, arm: &Arm<'_>) -> bool {
372 is_none_pattern(cx, arm.pat)
373 && matches!(
374 peel_blocks(arm.body).kind,
375 ExprKind::Path(qpath)
376 if cx.qpath_res(&qpath, arm.body.hir_id).ctor_parent(cx).is_lang_item(cx, OptionNone)
377 )
378}
379
380pub fn is_ty_alias(qpath: &QPath<'_>) -> bool {
382 match *qpath {
383 QPath::Resolved(_, path) => matches!(path.res, Res::Def(DefKind::TyAlias | DefKind::AssocTy, ..)),
384 QPath::TypeRelative(ty, _) if let TyKind::Path(qpath) = ty.kind => is_ty_alias(&qpath),
385 QPath::TypeRelative(..) => false,
386 }
387}
388
389pub fn is_def_id_trait_method(cx: &LateContext<'_>, def_id: LocalDefId) -> bool {
391 if let Node::Item(item) = cx.tcx.parent_hir_node(cx.tcx.local_def_id_to_hir_id(def_id))
392 && let ItemKind::Impl(imp) = item.kind
393 {
394 imp.of_trait.is_some()
395 } else {
396 false
397 }
398}
399
400pub fn last_path_segment<'tcx>(path: &QPath<'tcx>) -> &'tcx PathSegment<'tcx> {
401 match *path {
402 QPath::Resolved(_, path) => path.segments.last().expect("A path must have at least one segment"),
403 QPath::TypeRelative(_, seg) => seg,
404 }
405}
406
407pub fn qpath_generic_tys<'tcx>(qpath: &QPath<'tcx>) -> impl Iterator<Item = &'tcx hir::Ty<'tcx>> {
408 last_path_segment(qpath)
409 .args
410 .map_or(&[][..], |a| a.args)
411 .iter()
412 .filter_map(|a| match a {
413 GenericArg::Type(ty) => Some(ty.as_unambig_ty()),
414 _ => None,
415 })
416}
417
418pub fn path_to_local_with_projections(expr: &Expr<'_>) -> Option<HirId> {
423 match expr.kind {
424 ExprKind::Field(recv, _) | ExprKind::Index(recv, _, _) => path_to_local_with_projections(recv),
425 ExprKind::Path(QPath::Resolved(
426 _,
427 Path {
428 res: Res::Local(local), ..
429 },
430 )) => Some(*local),
431 _ => None,
432 }
433}
434
435pub fn trait_ref_of_method<'tcx>(cx: &LateContext<'tcx>, owner: OwnerId) -> Option<&'tcx TraitRef<'tcx>> {
451 if let Node::Item(item) = cx.tcx.hir_node(cx.tcx.hir_owner_parent(owner))
452 && let ItemKind::Impl(impl_) = &item.kind
453 && let Some(of_trait) = impl_.of_trait
454 {
455 return Some(&of_trait.trait_ref);
456 }
457 None
458}
459
460fn projection_stack<'a, 'hir>(mut e: &'a Expr<'hir>) -> (Vec<&'a Expr<'hir>>, &'a Expr<'hir>) {
468 let mut result = vec![];
469 let root = loop {
470 match e.kind {
471 ExprKind::Index(ep, _, _) | ExprKind::Field(ep, _) => {
472 result.push(e);
473 e = ep;
474 },
475 _ => break e,
476 }
477 };
478 result.reverse();
479 (result, root)
480}
481
482pub fn expr_custom_deref_adjustment(cx: &LateContext<'_>, e: &Expr<'_>) -> Option<Mutability> {
484 cx.typeck_results()
485 .expr_adjustments(e)
486 .iter()
487 .find_map(|a| match a.kind {
488 Adjust::Deref(Some(d)) => Some(Some(d.mutbl)),
489 Adjust::Deref(None) => None,
490 _ => Some(None),
491 })
492 .and_then(|x| x)
493}
494
495pub fn can_mut_borrow_both(cx: &LateContext<'_>, e1: &Expr<'_>, e2: &Expr<'_>) -> bool {
498 let (s1, r1) = projection_stack(e1);
499 let (s2, r2) = projection_stack(e2);
500 if !eq_expr_value(cx, r1, r2) {
501 return true;
502 }
503 if expr_custom_deref_adjustment(cx, r1).is_some() || expr_custom_deref_adjustment(cx, r2).is_some() {
504 return false;
505 }
506
507 for (x1, x2) in zip(&s1, &s2) {
508 if expr_custom_deref_adjustment(cx, x1).is_some() || expr_custom_deref_adjustment(cx, x2).is_some() {
509 return false;
510 }
511
512 match (&x1.kind, &x2.kind) {
513 (ExprKind::Field(_, i1), ExprKind::Field(_, i2)) => {
514 if i1 != i2 {
515 return true;
516 }
517 },
518 (ExprKind::Index(_, i1, _), ExprKind::Index(_, i2, _)) => {
519 if !eq_expr_value(cx, i1, i2) {
520 return false;
521 }
522 },
523 _ => return false,
524 }
525 }
526 false
527}
528
529fn is_default_equivalent_ctor(cx: &LateContext<'_>, def_id: DefId, path: &QPath<'_>) -> bool {
532 let std_types_symbols = &[
533 sym::Vec,
534 sym::VecDeque,
535 sym::LinkedList,
536 sym::HashMap,
537 sym::BTreeMap,
538 sym::HashSet,
539 sym::BTreeSet,
540 sym::BinaryHeap,
541 ];
542
543 if let QPath::TypeRelative(_, method) = path
544 && method.ident.name == sym::new
545 && let Some(impl_did) = cx.tcx.impl_of_assoc(def_id)
546 && let Some(adt) = cx.tcx.type_of(impl_did).instantiate_identity().ty_adt_def()
547 {
548 return Some(adt.did()) == cx.tcx.lang_items().string()
549 || (cx.tcx.get_diagnostic_name(adt.did())).is_some_and(|adt_name| std_types_symbols.contains(&adt_name));
550 }
551 false
552}
553
554pub fn is_default_equivalent_call(
556 cx: &LateContext<'_>,
557 repl_func: &Expr<'_>,
558 whole_call_expr: Option<&Expr<'_>>,
559) -> bool {
560 if let ExprKind::Path(ref repl_func_qpath) = repl_func.kind
561 && let Some(repl_def) = cx.qpath_res(repl_func_qpath, repl_func.hir_id).opt_def(cx)
562 && (repl_def.assoc_fn_parent(cx).is_diag_item(cx, sym::Default)
563 || is_default_equivalent_ctor(cx, repl_def.1, repl_func_qpath))
564 {
565 return true;
566 }
567
568 let Some(e) = whole_call_expr else { return false };
571 let Some(default_fn_def_id) = cx.tcx.get_diagnostic_item(sym::default_fn) else {
572 return false;
573 };
574 let Some(ty) = cx.tcx.typeck(e.hir_id.owner.def_id).expr_ty_adjusted_opt(e) else {
575 return false;
576 };
577 let args = rustc_ty::GenericArgs::for_item(cx.tcx, default_fn_def_id, |param, _| {
578 if let rustc_ty::GenericParamDefKind::Lifetime = param.kind {
579 cx.tcx.lifetimes.re_erased.into()
580 } else if param.index == 0 && param.name == kw::SelfUpper {
581 ty.into()
582 } else {
583 param.to_error(cx.tcx)
584 }
585 });
586 let instance = rustc_ty::Instance::try_resolve(cx.tcx, cx.typing_env(), default_fn_def_id, args);
587
588 let Ok(Some(instance)) = instance else { return false };
589 if let rustc_ty::InstanceKind::Item(def) = instance.def
590 && !cx.tcx.is_mir_available(def)
591 {
592 return false;
593 }
594 let ExprKind::Path(ref repl_func_qpath) = repl_func.kind else {
595 return false;
596 };
597 let Some(repl_def_id) = cx.qpath_res(repl_func_qpath, repl_func.hir_id).opt_def_id() else {
598 return false;
599 };
600
601 let body = cx.tcx.instance_mir(instance.def);
607 for block_data in body.basic_blocks.iter() {
608 if block_data.statements.len() == 1
609 && let StatementKind::Assign(assign) = &block_data.statements[0].kind
610 && assign.0.local == RETURN_PLACE
611 && let Rvalue::Aggregate(kind, _places) = &assign.1
612 && let AggregateKind::Adt(did, variant_index, _, _, _) = &**kind
613 && let def = cx.tcx.adt_def(did)
614 && let variant = &def.variant(*variant_index)
615 && variant.fields.is_empty()
616 && let Some((_, did)) = variant.ctor
617 && did == repl_def_id
618 {
619 return true;
620 } else if block_data.statements.is_empty()
621 && let Some(term) = &block_data.terminator
622 {
623 match &term.kind {
624 TerminatorKind::Call {
625 func: Operand::Constant(c),
626 ..
627 } if let rustc_ty::FnDef(did, _args) = c.ty().kind()
628 && *did == repl_def_id =>
629 {
630 return true;
631 },
632 TerminatorKind::TailCall {
633 func: Operand::Constant(c),
634 ..
635 } if let rustc_ty::FnDef(did, _args) = c.ty().kind()
636 && *did == repl_def_id =>
637 {
638 return true;
639 },
640 _ => {},
641 }
642 }
643 }
644 false
645}
646
647pub fn is_default_equivalent(cx: &LateContext<'_>, e: &Expr<'_>) -> bool {
651 match &e.kind {
652 ExprKind::Lit(lit) => match lit.node {
653 LitKind::Bool(false) | LitKind::Int(Pu128(0), _) => true,
654 LitKind::Str(s, _) => s.is_empty(),
655 _ => false,
656 },
657 ExprKind::Tup(items) | ExprKind::Array(items) => items.iter().all(|x| is_default_equivalent(cx, x)),
658 ExprKind::Repeat(x, len) => {
659 if let ConstArgKind::Anon(anon_const) = len.kind
660 && let ExprKind::Lit(const_lit) = cx.tcx.hir_body(anon_const.body).value.kind
661 && let LitKind::Int(v, _) = const_lit.node
662 && v <= 32
663 && is_default_equivalent(cx, x)
664 {
665 true
666 } else {
667 false
668 }
669 },
670 ExprKind::Call(repl_func, []) => is_default_equivalent_call(cx, repl_func, Some(e)),
671 ExprKind::Call(from_func, [arg]) => is_default_equivalent_from(cx, from_func, arg),
672 ExprKind::Path(qpath) => cx
673 .qpath_res(qpath, e.hir_id)
674 .ctor_parent(cx)
675 .is_lang_item(cx, OptionNone),
676 ExprKind::AddrOf(rustc_hir::BorrowKind::Ref, _, expr) => matches!(expr.kind, ExprKind::Array([])),
677 ExprKind::Block(Block { stmts: [], expr, .. }, _) => expr.is_some_and(|e| is_default_equivalent(cx, e)),
678 _ => false,
679 }
680}
681
682fn is_default_equivalent_from(cx: &LateContext<'_>, from_func: &Expr<'_>, arg: &Expr<'_>) -> bool {
683 if let ExprKind::Path(QPath::TypeRelative(ty, seg)) = from_func.kind
684 && seg.ident.name == sym::from
685 {
686 match arg.kind {
687 ExprKind::Lit(hir::Lit {
688 node: LitKind::Str(sym, _),
689 ..
690 }) => return sym.is_empty() && ty.basic_res().is_lang_item(cx, LangItem::String),
691 ExprKind::Array([]) => return ty.basic_res().is_diag_item(cx, sym::Vec),
692 ExprKind::Repeat(_, len) => {
693 if let ConstArgKind::Anon(anon_const) = len.kind
694 && let ExprKind::Lit(const_lit) = cx.tcx.hir_body(anon_const.body).value.kind
695 && let LitKind::Int(v, _) = const_lit.node
696 {
697 return v == 0 && ty.basic_res().is_diag_item(cx, sym::Vec);
698 }
699 },
700 _ => (),
701 }
702 }
703 false
704}
705
706pub fn can_move_expr_to_closure_no_visit<'tcx>(
738 cx: &LateContext<'tcx>,
739 expr: &'tcx Expr<'_>,
740 loop_ids: &[HirId],
741 ignore_locals: &HirIdSet,
742) -> bool {
743 match expr.kind {
744 ExprKind::Break(Destination { target_id: Ok(id), .. }, _)
745 | ExprKind::Continue(Destination { target_id: Ok(id), .. })
746 if loop_ids.contains(&id) =>
747 {
748 true
749 },
750 ExprKind::Break(..)
751 | ExprKind::Continue(_)
752 | ExprKind::Ret(_)
753 | ExprKind::Yield(..)
754 | ExprKind::InlineAsm(_) => false,
755 ExprKind::Field(
758 &Expr {
759 hir_id,
760 kind:
761 ExprKind::Path(QPath::Resolved(
762 _,
763 Path {
764 res: Res::Local(local_id),
765 ..
766 },
767 )),
768 ..
769 },
770 _,
771 ) if !ignore_locals.contains(local_id) && can_partially_move_ty(cx, cx.typeck_results().node_type(hir_id)) => {
772 false
774 },
775 _ => true,
776 }
777}
778
779#[derive(Debug, Clone, Copy, PartialEq, Eq)]
781pub enum CaptureKind {
782 Value,
783 Use,
784 Ref(Mutability),
785}
786impl CaptureKind {
787 pub fn is_imm_ref(self) -> bool {
788 self == Self::Ref(Mutability::Not)
789 }
790}
791impl std::ops::BitOr for CaptureKind {
792 type Output = Self;
793 fn bitor(self, rhs: Self) -> Self::Output {
794 match (self, rhs) {
795 (CaptureKind::Value, _) | (_, CaptureKind::Value) => CaptureKind::Value,
796 (CaptureKind::Use, _) | (_, CaptureKind::Use) => CaptureKind::Use,
797 (CaptureKind::Ref(Mutability::Mut), CaptureKind::Ref(_))
798 | (CaptureKind::Ref(_), CaptureKind::Ref(Mutability::Mut)) => CaptureKind::Ref(Mutability::Mut),
799 (CaptureKind::Ref(Mutability::Not), CaptureKind::Ref(Mutability::Not)) => CaptureKind::Ref(Mutability::Not),
800 }
801 }
802}
803impl std::ops::BitOrAssign for CaptureKind {
804 fn bitor_assign(&mut self, rhs: Self) {
805 *self = *self | rhs;
806 }
807}
808
809pub fn capture_local_usage(cx: &LateContext<'_>, e: &Expr<'_>) -> CaptureKind {
815 fn pat_capture_kind(cx: &LateContext<'_>, pat: &Pat<'_>) -> CaptureKind {
816 let mut capture = CaptureKind::Ref(Mutability::Not);
817 pat.each_binding_or_first(&mut |_, id, span, _| match cx
818 .typeck_results()
819 .extract_binding_mode(cx.sess(), id, span)
820 .0
821 {
822 ByRef::No if !is_copy(cx, cx.typeck_results().node_type(id)) => {
823 capture = CaptureKind::Value;
824 },
825 ByRef::Yes(_, Mutability::Mut) if capture != CaptureKind::Value => {
826 capture = CaptureKind::Ref(Mutability::Mut);
827 },
828 _ => (),
829 });
830 capture
831 }
832
833 debug_assert!(matches!(
834 e.kind,
835 ExprKind::Path(QPath::Resolved(None, Path { res: Res::Local(_), .. }))
836 ));
837
838 let mut child_id = e.hir_id;
839 let mut capture = CaptureKind::Value;
840 let mut capture_expr_ty = e;
841
842 for (parent_id, parent) in cx.tcx.hir_parent_iter(e.hir_id) {
843 if let [
844 Adjustment {
845 kind: Adjust::Deref(_) | Adjust::Borrow(AutoBorrow::Ref(..)),
846 target,
847 },
848 ref adjust @ ..,
849 ] = *cx
850 .typeck_results()
851 .adjustments()
852 .get(child_id)
853 .map_or(&[][..], |x| &**x)
854 && let rustc_ty::RawPtr(_, mutability) | rustc_ty::Ref(_, _, mutability) =
855 *adjust.last().map_or(target, |a| a.target).kind()
856 {
857 return CaptureKind::Ref(mutability);
858 }
859
860 match parent {
861 Node::Expr(e) => match e.kind {
862 ExprKind::AddrOf(_, mutability, _) => return CaptureKind::Ref(mutability),
863 ExprKind::Index(..) | ExprKind::Unary(UnOp::Deref, _) => capture = CaptureKind::Ref(Mutability::Not),
864 ExprKind::Assign(lhs, ..) | ExprKind::AssignOp(_, lhs, _) if lhs.hir_id == child_id => {
865 return CaptureKind::Ref(Mutability::Mut);
866 },
867 ExprKind::Field(..) => {
868 if capture == CaptureKind::Value {
869 capture_expr_ty = e;
870 }
871 },
872 ExprKind::Let(let_expr) => {
873 let mutability = match pat_capture_kind(cx, let_expr.pat) {
874 CaptureKind::Value | CaptureKind::Use => Mutability::Not,
875 CaptureKind::Ref(m) => m,
876 };
877 return CaptureKind::Ref(mutability);
878 },
879 ExprKind::Match(_, arms, _) => {
880 let mut mutability = Mutability::Not;
881 for capture in arms.iter().map(|arm| pat_capture_kind(cx, arm.pat)) {
882 match capture {
883 CaptureKind::Value | CaptureKind::Use => break,
884 CaptureKind::Ref(Mutability::Mut) => mutability = Mutability::Mut,
885 CaptureKind::Ref(Mutability::Not) => (),
886 }
887 }
888 return CaptureKind::Ref(mutability);
889 },
890 _ => break,
891 },
892 Node::LetStmt(l) => match pat_capture_kind(cx, l.pat) {
893 CaptureKind::Value | CaptureKind::Use => break,
894 capture @ CaptureKind::Ref(_) => return capture,
895 },
896 _ => break,
897 }
898
899 child_id = parent_id;
900 }
901
902 if capture == CaptureKind::Value && is_copy(cx, cx.typeck_results().expr_ty(capture_expr_ty)) {
903 CaptureKind::Ref(Mutability::Not)
905 } else {
906 capture
907 }
908}
909
910pub fn can_move_expr_to_closure<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> Option<HirIdMap<CaptureKind>> {
913 struct V<'cx, 'tcx> {
914 cx: &'cx LateContext<'tcx>,
915 loops: Vec<HirId>,
917 locals: HirIdSet,
919 allow_closure: bool,
921 captures: HirIdMap<CaptureKind>,
924 }
925 impl<'tcx> Visitor<'tcx> for V<'_, 'tcx> {
926 fn visit_expr(&mut self, e: &'tcx Expr<'_>) {
927 if !self.allow_closure {
928 return;
929 }
930
931 match e.kind {
932 ExprKind::Path(QPath::Resolved(None, &Path { res: Res::Local(l), .. })) => {
933 if !self.locals.contains(&l) {
934 let cap = capture_local_usage(self.cx, e);
935 self.captures.entry(l).and_modify(|e| *e |= cap).or_insert(cap);
936 }
937 },
938 ExprKind::Closure(closure) => {
939 for capture in self.cx.typeck_results().closure_min_captures_flattened(closure.def_id) {
940 let local_id = match capture.place.base {
941 PlaceBase::Local(id) => id,
942 PlaceBase::Upvar(var) => var.var_path.hir_id,
943 _ => continue,
944 };
945 if !self.locals.contains(&local_id) {
946 let capture = match capture.info.capture_kind {
947 UpvarCapture::ByValue => CaptureKind::Value,
948 UpvarCapture::ByUse => CaptureKind::Use,
949 UpvarCapture::ByRef(kind) => match kind {
950 BorrowKind::Immutable => CaptureKind::Ref(Mutability::Not),
951 BorrowKind::UniqueImmutable | BorrowKind::Mutable => {
952 CaptureKind::Ref(Mutability::Mut)
953 },
954 },
955 };
956 self.captures
957 .entry(local_id)
958 .and_modify(|e| *e |= capture)
959 .or_insert(capture);
960 }
961 }
962 },
963 ExprKind::Loop(b, ..) => {
964 self.loops.push(e.hir_id);
965 self.visit_block(b);
966 self.loops.pop();
967 },
968 _ => {
969 self.allow_closure &= can_move_expr_to_closure_no_visit(self.cx, e, &self.loops, &self.locals);
970 walk_expr(self, e);
971 },
972 }
973 }
974
975 fn visit_pat(&mut self, p: &'tcx Pat<'tcx>) {
976 p.each_binding_or_first(&mut |_, id, _, _| {
977 self.locals.insert(id);
978 });
979 }
980 }
981
982 let mut v = V {
983 cx,
984 loops: Vec::new(),
985 locals: HirIdSet::default(),
986 allow_closure: true,
987 captures: HirIdMap::default(),
988 };
989 v.visit_expr(expr);
990 v.allow_closure.then_some(v.captures)
991}
992
993pub type MethodArguments<'tcx> = Vec<(&'tcx Expr<'tcx>, &'tcx [Expr<'tcx>])>;
995
996pub fn method_calls<'tcx>(expr: &'tcx Expr<'tcx>, max_depth: usize) -> (Vec<Symbol>, MethodArguments<'tcx>, Vec<Span>) {
999 let mut method_names = Vec::with_capacity(max_depth);
1000 let mut arg_lists = Vec::with_capacity(max_depth);
1001 let mut spans = Vec::with_capacity(max_depth);
1002
1003 let mut current = expr;
1004 for _ in 0..max_depth {
1005 if let ExprKind::MethodCall(path, receiver, args, _) = ¤t.kind {
1006 if receiver.span.from_expansion() || args.iter().any(|e| e.span.from_expansion()) {
1007 break;
1008 }
1009 method_names.push(path.ident.name);
1010 arg_lists.push((*receiver, &**args));
1011 spans.push(path.ident.span);
1012 current = receiver;
1013 } else {
1014 break;
1015 }
1016 }
1017
1018 (method_names, arg_lists, spans)
1019}
1020
1021pub fn method_chain_args<'a>(expr: &'a Expr<'_>, methods: &[Symbol]) -> Option<Vec<(&'a Expr<'a>, &'a [Expr<'a>])>> {
1028 let mut current = expr;
1029 let mut matched = Vec::with_capacity(methods.len());
1030 for method_name in methods.iter().rev() {
1031 if let ExprKind::MethodCall(path, receiver, args, _) = current.kind {
1033 if path.ident.name == *method_name {
1034 if receiver.span.from_expansion() || args.iter().any(|e| e.span.from_expansion()) {
1035 return None;
1036 }
1037 matched.push((receiver, args)); current = receiver; } else {
1040 return None;
1041 }
1042 } else {
1043 return None;
1044 }
1045 }
1046 matched.reverse();
1048 Some(matched)
1049}
1050
1051pub fn is_entrypoint_fn(cx: &LateContext<'_>, def_id: DefId) -> bool {
1053 cx.tcx
1054 .entry_fn(())
1055 .is_some_and(|(entry_fn_def_id, _)| def_id == entry_fn_def_id)
1056}
1057
1058pub fn is_in_panic_handler(cx: &LateContext<'_>, e: &Expr<'_>) -> bool {
1060 let parent = cx.tcx.hir_get_parent_item(e.hir_id);
1061 Some(parent.to_def_id()) == cx.tcx.lang_items().panic_impl()
1062}
1063
1064pub fn parent_item_name(cx: &LateContext<'_>, expr: &Expr<'_>) -> Option<Symbol> {
1066 let parent_id = cx.tcx.hir_get_parent_item(expr.hir_id).def_id;
1067 match cx.tcx.hir_node_by_def_id(parent_id) {
1068 Node::Item(item) => item.kind.ident().map(|ident| ident.name),
1069 Node::TraitItem(TraitItem { ident, .. }) | Node::ImplItem(ImplItem { ident, .. }) => Some(ident.name),
1070 _ => None,
1071 }
1072}
1073
1074pub struct ContainsName<'a, 'tcx> {
1075 pub cx: &'a LateContext<'tcx>,
1076 pub name: Symbol,
1077}
1078
1079impl<'tcx> Visitor<'tcx> for ContainsName<'_, 'tcx> {
1080 type Result = ControlFlow<()>;
1081 type NestedFilter = nested_filter::OnlyBodies;
1082
1083 fn visit_name(&mut self, name: Symbol) -> Self::Result {
1084 if self.name == name {
1085 ControlFlow::Break(())
1086 } else {
1087 ControlFlow::Continue(())
1088 }
1089 }
1090
1091 fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
1092 self.cx.tcx
1093 }
1094}
1095
1096pub fn contains_name<'tcx>(name: Symbol, expr: &'tcx Expr<'_>, cx: &LateContext<'tcx>) -> bool {
1098 let mut cn = ContainsName { cx, name };
1099 cn.visit_expr(expr).is_break()
1100}
1101
1102pub fn contains_return<'tcx>(expr: impl Visitable<'tcx>) -> bool {
1104 for_each_expr_without_closures(expr, |e| {
1105 if matches!(e.kind, ExprKind::Ret(..)) {
1106 ControlFlow::Break(())
1107 } else {
1108 ControlFlow::Continue(())
1109 }
1110 })
1111 .is_some()
1112}
1113
1114pub fn get_parent_expr<'tcx>(cx: &LateContext<'tcx>, e: &Expr<'_>) -> Option<&'tcx Expr<'tcx>> {
1116 get_parent_expr_for_hir(cx, e.hir_id)
1117}
1118
1119pub fn get_parent_expr_for_hir<'tcx>(cx: &LateContext<'tcx>, hir_id: HirId) -> Option<&'tcx Expr<'tcx>> {
1122 match cx.tcx.parent_hir_node(hir_id) {
1123 Node::Expr(parent) => Some(parent),
1124 _ => None,
1125 }
1126}
1127
1128pub fn get_enclosing_block<'tcx>(cx: &LateContext<'tcx>, hir_id: HirId) -> Option<&'tcx Block<'tcx>> {
1130 let enclosing_node = cx
1131 .tcx
1132 .hir_get_enclosing_scope(hir_id)
1133 .map(|enclosing_id| cx.tcx.hir_node(enclosing_id));
1134 enclosing_node.and_then(|node| match node {
1135 Node::Block(block) => Some(block),
1136 Node::Item(&Item {
1137 kind: ItemKind::Fn { body: eid, .. },
1138 ..
1139 })
1140 | Node::ImplItem(&ImplItem {
1141 kind: ImplItemKind::Fn(_, eid),
1142 ..
1143 })
1144 | Node::TraitItem(&TraitItem {
1145 kind: TraitItemKind::Fn(_, TraitFn::Provided(eid)),
1146 ..
1147 }) => match cx.tcx.hir_body(eid).value.kind {
1148 ExprKind::Block(block, _) => Some(block),
1149 _ => None,
1150 },
1151 _ => None,
1152 })
1153}
1154
1155pub fn get_enclosing_loop_or_multi_call_closure<'tcx>(
1157 cx: &LateContext<'tcx>,
1158 expr: &Expr<'_>,
1159) -> Option<&'tcx Expr<'tcx>> {
1160 for (_, node) in cx.tcx.hir_parent_iter(expr.hir_id) {
1161 match node {
1162 Node::Expr(e) => match e.kind {
1163 ExprKind::Closure { .. }
1164 if let rustc_ty::Closure(_, subs) = cx.typeck_results().expr_ty(e).kind()
1165 && subs.as_closure().kind() == ClosureKind::FnOnce => {},
1166
1167 ExprKind::Closure { .. } | ExprKind::Loop(..) => return Some(e),
1169 _ => (),
1170 },
1171 Node::Stmt(_) | Node::Block(_) | Node::LetStmt(_) | Node::Arm(_) | Node::ExprField(_) => (),
1172 _ => break,
1173 }
1174 }
1175 None
1176}
1177
1178pub fn get_parent_as_impl(tcx: TyCtxt<'_>, id: HirId) -> Option<&Impl<'_>> {
1180 match tcx.hir_parent_iter(id).next() {
1181 Some((
1182 _,
1183 Node::Item(Item {
1184 kind: ItemKind::Impl(imp),
1185 ..
1186 }),
1187 )) => Some(imp),
1188 _ => None,
1189 }
1190}
1191
1192pub fn peel_blocks<'a>(mut expr: &'a Expr<'a>) -> &'a Expr<'a> {
1203 while let ExprKind::Block(
1204 Block {
1205 stmts: [],
1206 expr: Some(inner),
1207 rules: BlockCheckMode::DefaultBlock,
1208 ..
1209 },
1210 _,
1211 ) = expr.kind
1212 {
1213 expr = inner;
1214 }
1215 expr
1216}
1217
1218pub fn peel_blocks_with_stmt<'a>(mut expr: &'a Expr<'a>) -> &'a Expr<'a> {
1229 while let ExprKind::Block(
1230 Block {
1231 stmts: [],
1232 expr: Some(inner),
1233 rules: BlockCheckMode::DefaultBlock,
1234 ..
1235 }
1236 | Block {
1237 stmts:
1238 [
1239 Stmt {
1240 kind: StmtKind::Expr(inner) | StmtKind::Semi(inner),
1241 ..
1242 },
1243 ],
1244 expr: None,
1245 rules: BlockCheckMode::DefaultBlock,
1246 ..
1247 },
1248 _,
1249 ) = expr.kind
1250 {
1251 expr = inner;
1252 }
1253 expr
1254}
1255
1256pub fn is_else_clause(tcx: TyCtxt<'_>, expr: &Expr<'_>) -> bool {
1258 let mut iter = tcx.hir_parent_iter(expr.hir_id);
1259 match iter.next() {
1260 Some((
1261 _,
1262 Node::Expr(Expr {
1263 kind: ExprKind::If(_, _, Some(else_expr)),
1264 ..
1265 }),
1266 )) => else_expr.hir_id == expr.hir_id,
1267 _ => false,
1268 }
1269}
1270
1271pub fn is_inside_let_else(tcx: TyCtxt<'_>, expr: &Expr<'_>) -> bool {
1274 let mut child_id = expr.hir_id;
1275 for (parent_id, node) in tcx.hir_parent_iter(child_id) {
1276 if let Node::LetStmt(LetStmt {
1277 init: Some(init),
1278 els: Some(els),
1279 ..
1280 }) = node
1281 && (init.hir_id == child_id || els.hir_id == child_id)
1282 {
1283 return true;
1284 }
1285
1286 child_id = parent_id;
1287 }
1288
1289 false
1290}
1291
1292pub fn is_else_clause_in_let_else(tcx: TyCtxt<'_>, expr: &Expr<'_>) -> bool {
1294 let mut child_id = expr.hir_id;
1295 for (parent_id, node) in tcx.hir_parent_iter(child_id) {
1296 if let Node::LetStmt(LetStmt { els: Some(els), .. }) = node
1297 && els.hir_id == child_id
1298 {
1299 return true;
1300 }
1301
1302 child_id = parent_id;
1303 }
1304
1305 false
1306}
1307
1308pub fn is_range_full(cx: &LateContext<'_>, expr: &Expr<'_>, container_path: Option<&Path<'_>>) -> bool {
1323 let ty = cx.typeck_results().expr_ty(expr);
1324 if let Some(Range { start, end, limits, .. }) = Range::hir(cx, expr) {
1325 let start_is_none_or_min = start.is_none_or(|start| {
1326 if let rustc_ty::Adt(_, subst) = ty.kind()
1327 && let bnd_ty = subst.type_at(0)
1328 && let Some(start_const) = ConstEvalCtxt::new(cx).eval(start)
1329 {
1330 start_const.is_numeric_min(cx.tcx, bnd_ty)
1331 } else {
1332 false
1333 }
1334 });
1335 let end_is_none_or_max = end.is_none_or(|end| match limits {
1336 RangeLimits::Closed => {
1337 if let rustc_ty::Adt(_, subst) = ty.kind()
1338 && let bnd_ty = subst.type_at(0)
1339 && let Some(end_const) = ConstEvalCtxt::new(cx).eval(end)
1340 {
1341 end_const.is_numeric_max(cx.tcx, bnd_ty)
1342 } else {
1343 false
1344 }
1345 },
1346 RangeLimits::HalfOpen => {
1347 if let Some(container_path) = container_path
1348 && let ExprKind::MethodCall(name, self_arg, [], _) = end.kind
1349 && name.ident.name == sym::len
1350 && let ExprKind::Path(QPath::Resolved(None, path)) = self_arg.kind
1351 {
1352 container_path.res == path.res
1353 } else {
1354 false
1355 }
1356 },
1357 });
1358 return start_is_none_or_min && end_is_none_or_max;
1359 }
1360 false
1361}
1362
1363pub fn is_integer_const(cx: &LateContext<'_>, e: &Expr<'_>, value: u128) -> bool {
1366 if is_integer_literal(e, value) {
1367 return true;
1368 }
1369 let enclosing_body = cx.tcx.hir_enclosing_body_owner(e.hir_id);
1370 if let Some(Constant::Int(v)) =
1371 ConstEvalCtxt::with_env(cx.tcx, cx.typing_env(), cx.tcx.typeck(enclosing_body)).eval(e)
1372 {
1373 return value == v;
1374 }
1375 false
1376}
1377
1378pub fn is_integer_literal(expr: &Expr<'_>, value: u128) -> bool {
1380 if let ExprKind::Lit(spanned) = expr.kind
1382 && let LitKind::Int(v, _) = spanned.node
1383 {
1384 return v == value;
1385 }
1386 false
1387}
1388
1389pub fn is_float_literal(expr: &Expr<'_>, value: f64) -> bool {
1391 if let ExprKind::Lit(spanned) = expr.kind
1392 && let LitKind::Float(v, _) = spanned.node
1393 {
1394 v.as_str().parse() == Ok(value)
1395 } else {
1396 false
1397 }
1398}
1399
1400pub fn is_adjusted(cx: &LateContext<'_>, e: &Expr<'_>) -> bool {
1408 cx.typeck_results().adjustments().get(e.hir_id).is_some()
1409}
1410
1411#[must_use]
1415pub fn is_expn_of(mut span: Span, name: Symbol) -> Option<Span> {
1416 loop {
1417 if span.from_expansion() {
1418 let data = span.ctxt().outer_expn_data();
1419 let new_span = data.call_site;
1420
1421 if let ExpnKind::Macro(MacroKind::Bang, mac_name) = data.kind
1422 && mac_name == name
1423 {
1424 return Some(new_span);
1425 }
1426
1427 span = new_span;
1428 } else {
1429 return None;
1430 }
1431 }
1432}
1433
1434#[must_use]
1445pub fn is_direct_expn_of(span: Span, name: Symbol) -> Option<Span> {
1446 if span.from_expansion() {
1447 let data = span.ctxt().outer_expn_data();
1448 let new_span = data.call_site;
1449
1450 if let ExpnKind::Macro(MacroKind::Bang, mac_name) = data.kind
1451 && mac_name == name
1452 {
1453 return Some(new_span);
1454 }
1455 }
1456
1457 None
1458}
1459
1460pub fn return_ty<'tcx>(cx: &LateContext<'tcx>, fn_def_id: OwnerId) -> Ty<'tcx> {
1462 let ret_ty = cx.tcx.fn_sig(fn_def_id).instantiate_identity().output();
1463 cx.tcx.instantiate_bound_regions_with_erased(ret_ty)
1464}
1465
1466pub fn nth_arg<'tcx>(cx: &LateContext<'tcx>, fn_def_id: OwnerId, nth: usize) -> Ty<'tcx> {
1468 let arg = cx.tcx.fn_sig(fn_def_id).instantiate_identity().input(nth);
1469 cx.tcx.instantiate_bound_regions_with_erased(arg)
1470}
1471
1472pub fn is_ctor_or_promotable_const_function(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
1474 if let ExprKind::Call(fun, _) = expr.kind
1475 && let ExprKind::Path(ref qp) = fun.kind
1476 {
1477 let res = cx.qpath_res(qp, fun.hir_id);
1478 return match res {
1479 Res::Def(DefKind::Variant | DefKind::Ctor(..), ..) => true,
1480 Res::Def(_, def_id) => cx.tcx.is_promotable_const_fn(def_id),
1481 _ => false,
1482 };
1483 }
1484 false
1485}
1486
1487pub fn is_refutable(cx: &LateContext<'_>, pat: &Pat<'_>) -> bool {
1490 fn is_qpath_refutable(cx: &LateContext<'_>, qpath: &QPath<'_>, id: HirId) -> bool {
1491 !matches!(
1492 cx.qpath_res(qpath, id),
1493 Res::Def(DefKind::Struct, ..) | Res::Def(DefKind::Ctor(def::CtorOf::Struct, _), _)
1494 )
1495 }
1496
1497 fn are_refutable<'a, I: IntoIterator<Item = &'a Pat<'a>>>(cx: &LateContext<'_>, i: I) -> bool {
1498 i.into_iter().any(|pat| is_refutable(cx, pat))
1499 }
1500
1501 match pat.kind {
1502 PatKind::Missing => unreachable!(),
1503 PatKind::Wild | PatKind::Never => false, PatKind::Binding(_, _, _, pat) => pat.is_some_and(|pat| is_refutable(cx, pat)),
1505 PatKind::Box(pat) | PatKind::Ref(pat, _, _) => is_refutable(cx, pat),
1506 PatKind::Expr(PatExpr {
1507 kind: PatExprKind::Path(qpath),
1508 hir_id,
1509 ..
1510 }) => is_qpath_refutable(cx, qpath, *hir_id),
1511 PatKind::Or(pats) => {
1512 are_refutable(cx, pats)
1514 },
1515 PatKind::Tuple(pats, _) => are_refutable(cx, pats),
1516 PatKind::Struct(ref qpath, fields, _) => {
1517 is_qpath_refutable(cx, qpath, pat.hir_id) || are_refutable(cx, fields.iter().map(|field| field.pat))
1518 },
1519 PatKind::TupleStruct(ref qpath, pats, _) => {
1520 is_qpath_refutable(cx, qpath, pat.hir_id) || are_refutable(cx, pats)
1521 },
1522 PatKind::Slice(head, middle, tail) => {
1523 match &cx.typeck_results().node_type(pat.hir_id).kind() {
1524 rustc_ty::Slice(..) => {
1525 !head.is_empty() || middle.is_none() || !tail.is_empty()
1527 },
1528 rustc_ty::Array(..) => are_refutable(cx, head.iter().chain(middle).chain(tail.iter())),
1529 _ => {
1530 true
1532 },
1533 }
1534 },
1535 PatKind::Expr(..) | PatKind::Range(..) | PatKind::Err(_) | PatKind::Deref(_) | PatKind::Guard(..) => true,
1536 }
1537}
1538
1539pub fn recurse_or_patterns<'tcx, F: FnMut(&'tcx Pat<'tcx>)>(pat: &'tcx Pat<'tcx>, mut f: F) {
1542 if let PatKind::Or(pats) = pat.kind {
1543 pats.iter().for_each(f);
1544 } else {
1545 f(pat);
1546 }
1547}
1548
1549pub fn is_self(slf: &Param<'_>) -> bool {
1550 if let PatKind::Binding(.., name, _) = slf.pat.kind {
1551 name.name == kw::SelfLower
1552 } else {
1553 false
1554 }
1555}
1556
1557pub fn is_self_ty(slf: &hir::Ty<'_>) -> bool {
1558 if let TyKind::Path(QPath::Resolved(None, path)) = slf.kind
1559 && let Res::SelfTyParam { .. } | Res::SelfTyAlias { .. } = path.res
1560 {
1561 return true;
1562 }
1563 false
1564}
1565
1566pub fn iter_input_pats<'tcx>(decl: &FnDecl<'_>, body: &'tcx Body<'_>) -> impl Iterator<Item = &'tcx Param<'tcx>> {
1567 (0..decl.inputs.len()).map(move |i| &body.params[i])
1568}
1569
1570pub fn is_try<'tcx>(cx: &LateContext<'_>, expr: &'tcx Expr<'tcx>) -> Option<&'tcx Expr<'tcx>> {
1573 fn is_ok(cx: &LateContext<'_>, arm: &Arm<'_>) -> bool {
1574 if let PatKind::TupleStruct(ref path, pat, ddpos) = arm.pat.kind
1575 && ddpos.as_opt_usize().is_none()
1576 && cx
1577 .qpath_res(path, arm.pat.hir_id)
1578 .ctor_parent(cx)
1579 .is_lang_item(cx, ResultOk)
1580 && let PatKind::Binding(_, hir_id, _, None) = pat[0].kind
1581 && arm.body.res_local_id() == Some(hir_id)
1582 {
1583 return true;
1584 }
1585 false
1586 }
1587
1588 fn is_err(cx: &LateContext<'_>, arm: &Arm<'_>) -> bool {
1589 if let PatKind::TupleStruct(ref path, _, _) = arm.pat.kind {
1590 cx.qpath_res(path, arm.pat.hir_id)
1591 .ctor_parent(cx)
1592 .is_lang_item(cx, ResultErr)
1593 } else {
1594 false
1595 }
1596 }
1597
1598 if let ExprKind::Match(_, arms, ref source) = expr.kind {
1599 if let MatchSource::TryDesugar(_) = *source {
1601 return Some(expr);
1602 }
1603
1604 if arms.len() == 2
1605 && arms[0].guard.is_none()
1606 && arms[1].guard.is_none()
1607 && ((is_ok(cx, &arms[0]) && is_err(cx, &arms[1])) || (is_ok(cx, &arms[1]) && is_err(cx, &arms[0])))
1608 {
1609 return Some(expr);
1610 }
1611 }
1612
1613 None
1614}
1615
1616pub fn fulfill_or_allowed(cx: &LateContext<'_>, lint: &'static Lint, ids: impl IntoIterator<Item = HirId>) -> bool {
1626 let mut suppress_lint = false;
1627
1628 for id in ids {
1629 let LevelAndSource { level, lint_id, .. } = cx.tcx.lint_level_at_node(lint, id);
1630 if let Some(expectation) = lint_id {
1631 cx.fulfill_expectation(expectation);
1632 }
1633
1634 match level {
1635 Level::Allow | Level::Expect => suppress_lint = true,
1636 Level::Warn | Level::ForceWarn | Level::Deny | Level::Forbid => {},
1637 }
1638 }
1639
1640 suppress_lint
1641}
1642
1643pub fn is_lint_allowed(cx: &LateContext<'_>, lint: &'static Lint, id: HirId) -> bool {
1651 cx.tcx.lint_level_at_node(lint, id).level == Level::Allow
1652}
1653
1654pub fn strip_pat_refs<'hir>(mut pat: &'hir Pat<'hir>) -> &'hir Pat<'hir> {
1655 while let PatKind::Ref(subpat, _, _) = pat.kind {
1656 pat = subpat;
1657 }
1658 pat
1659}
1660
1661pub fn int_bits(tcx: TyCtxt<'_>, ity: IntTy) -> u64 {
1662 Integer::from_int_ty(&tcx, ity).size().bits()
1663}
1664
1665#[expect(clippy::cast_possible_wrap)]
1666pub fn sext(tcx: TyCtxt<'_>, u: u128, ity: IntTy) -> i128 {
1668 let amt = 128 - int_bits(tcx, ity);
1669 ((u as i128) << amt) >> amt
1670}
1671
1672#[expect(clippy::cast_sign_loss)]
1673pub fn unsext(tcx: TyCtxt<'_>, u: i128, ity: IntTy) -> u128 {
1675 let amt = 128 - int_bits(tcx, ity);
1676 ((u as u128) << amt) >> amt
1677}
1678
1679pub fn clip(tcx: TyCtxt<'_>, u: u128, ity: UintTy) -> u128 {
1681 let bits = Integer::from_uint_ty(&tcx, ity).size().bits();
1682 let amt = 128 - bits;
1683 (u << amt) >> amt
1684}
1685
1686pub fn has_attr(attrs: &[hir::Attribute], symbol: Symbol) -> bool {
1687 attrs.iter().any(|attr| attr.has_name(symbol))
1688}
1689
1690pub fn has_repr_attr(cx: &LateContext<'_>, hir_id: HirId) -> bool {
1691 find_attr!(cx.tcx.hir_attrs(hir_id), AttributeKind::Repr { .. })
1692}
1693
1694pub fn any_parent_has_attr(tcx: TyCtxt<'_>, node: HirId, symbol: Symbol) -> bool {
1695 let mut prev_enclosing_node = None;
1696 let mut enclosing_node = node;
1697 while Some(enclosing_node) != prev_enclosing_node {
1698 if has_attr(tcx.hir_attrs(enclosing_node), symbol) {
1699 return true;
1700 }
1701 prev_enclosing_node = Some(enclosing_node);
1702 enclosing_node = tcx.hir_get_parent_item(enclosing_node).into();
1703 }
1704
1705 false
1706}
1707
1708pub fn in_automatically_derived(tcx: TyCtxt<'_>, id: HirId) -> bool {
1711 tcx.hir_parent_owner_iter(id)
1712 .filter(|(_, node)| matches!(node, OwnerNode::Item(item) if matches!(item.kind, ItemKind::Impl(_))))
1713 .any(|(id, _)| {
1714 find_attr!(
1715 tcx.hir_attrs(tcx.local_def_id_to_hir_id(id.def_id)),
1716 AttributeKind::AutomaticallyDerived(..)
1717 )
1718 })
1719}
1720
1721pub fn match_libc_symbol(cx: &LateContext<'_>, did: DefId, name: Symbol) -> bool {
1723 cx.tcx.crate_name(did.krate) == sym::libc && cx.tcx.def_path_str(did).ends_with(name.as_str())
1726}
1727
1728pub fn if_sequence<'tcx>(mut expr: &'tcx Expr<'tcx>) -> (Vec<&'tcx Expr<'tcx>>, Vec<&'tcx Block<'tcx>>) {
1733 let mut conds = Vec::new();
1734 let mut blocks: Vec<&Block<'_>> = Vec::new();
1735
1736 while let Some(higher::IfOrIfLet { cond, then, r#else }) = higher::IfOrIfLet::hir(expr) {
1737 conds.push(cond);
1738 if let ExprKind::Block(block, _) = then.kind {
1739 blocks.push(block);
1740 } else {
1741 panic!("ExprKind::If node is not an ExprKind::Block");
1742 }
1743
1744 if let Some(else_expr) = r#else {
1745 expr = else_expr;
1746 } else {
1747 break;
1748 }
1749 }
1750
1751 if !blocks.is_empty()
1753 && let ExprKind::Block(block, _) = expr.kind
1754 {
1755 blocks.push(block);
1756 }
1757
1758 (conds, blocks)
1759}
1760
1761pub fn get_async_closure_expr<'tcx>(tcx: TyCtxt<'tcx>, expr: &Expr<'_>) -> Option<&'tcx Expr<'tcx>> {
1763 if let ExprKind::Closure(&Closure {
1764 body,
1765 kind: hir::ClosureKind::Coroutine(CoroutineKind::Desugared(CoroutineDesugaring::Async, _)),
1766 ..
1767 }) = expr.kind
1768 && let ExprKind::Block(
1769 Block {
1770 expr:
1771 Some(Expr {
1772 kind: ExprKind::DropTemps(inner_expr),
1773 ..
1774 }),
1775 ..
1776 },
1777 _,
1778 ) = tcx.hir_body(body).value.kind
1779 {
1780 Some(inner_expr)
1781 } else {
1782 None
1783 }
1784}
1785
1786pub fn get_async_fn_body<'tcx>(tcx: TyCtxt<'tcx>, body: &Body<'_>) -> Option<&'tcx Expr<'tcx>> {
1788 get_async_closure_expr(tcx, body.value)
1789}
1790
1791pub fn is_must_use_func_call(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
1793 let did = match expr.kind {
1794 ExprKind::Call(path, _) => {
1795 if let ExprKind::Path(ref qpath) = path.kind
1796 && let Res::Def(_, did) = cx.qpath_res(qpath, path.hir_id)
1797 {
1798 Some(did)
1799 } else {
1800 None
1801 }
1802 },
1803 ExprKind::MethodCall(..) => cx.typeck_results().type_dependent_def_id(expr.hir_id),
1804 _ => None,
1805 };
1806
1807 did.is_some_and(|did| find_attr!(cx.tcx.get_all_attrs(did), AttributeKind::MustUse { .. }))
1808}
1809
1810fn is_body_identity_function(cx: &LateContext<'_>, func: &Body<'_>) -> bool {
1822 let [param] = func.params else {
1823 return false;
1824 };
1825
1826 let mut expr = func.value;
1827 loop {
1828 match expr.kind {
1829 ExprKind::Block(
1830 &Block {
1831 stmts: [],
1832 expr: Some(e),
1833 ..
1834 },
1835 _,
1836 )
1837 | ExprKind::Ret(Some(e)) => expr = e,
1838 ExprKind::Block(
1839 &Block {
1840 stmts: [stmt],
1841 expr: None,
1842 ..
1843 },
1844 _,
1845 ) => {
1846 if let StmtKind::Semi(e) | StmtKind::Expr(e) = stmt.kind
1847 && let ExprKind::Ret(Some(ret_val)) = e.kind
1848 {
1849 expr = ret_val;
1850 } else {
1851 return false;
1852 }
1853 },
1854 _ => return is_expr_identity_of_pat(cx, param.pat, expr, true),
1855 }
1856 }
1857}
1858
1859pub fn is_expr_identity_of_pat(cx: &LateContext<'_>, pat: &Pat<'_>, expr: &Expr<'_>, by_hir: bool) -> bool {
1869 if cx
1870 .typeck_results()
1871 .pat_binding_modes()
1872 .get(pat.hir_id)
1873 .is_some_and(|mode| matches!(mode.0, ByRef::Yes(..)))
1874 {
1875 return false;
1879 }
1880
1881 let qpath_res = |qpath, hir| cx.typeck_results().qpath_res(qpath, hir);
1883
1884 match (pat.kind, expr.kind) {
1885 (PatKind::Binding(_, id, _, _), _) if by_hir => {
1886 expr.res_local_id() == Some(id) && cx.typeck_results().expr_adjustments(expr).is_empty()
1887 },
1888 (PatKind::Binding(_, _, ident, _), ExprKind::Path(QPath::Resolved(_, path))) => {
1889 matches!(path.segments, [ segment] if segment.ident.name == ident.name)
1890 },
1891 (PatKind::Tuple(pats, dotdot), ExprKind::Tup(tup))
1892 if dotdot.as_opt_usize().is_none() && pats.len() == tup.len() =>
1893 {
1894 over(pats, tup, |pat, expr| is_expr_identity_of_pat(cx, pat, expr, by_hir))
1895 },
1896 (PatKind::Slice(before, None, after), ExprKind::Array(arr)) if before.len() + after.len() == arr.len() => {
1897 zip(before.iter().chain(after), arr).all(|(pat, expr)| is_expr_identity_of_pat(cx, pat, expr, by_hir))
1898 },
1899 (PatKind::TupleStruct(pat_ident, field_pats, dotdot), ExprKind::Call(ident, fields))
1900 if dotdot.as_opt_usize().is_none() && field_pats.len() == fields.len() =>
1901 {
1902 if let ExprKind::Path(ident) = &ident.kind
1904 && qpath_res(&pat_ident, pat.hir_id) == qpath_res(ident, expr.hir_id)
1905 && over(field_pats, fields, |pat, expr| is_expr_identity_of_pat(cx, pat, expr,by_hir))
1907 {
1908 true
1909 } else {
1910 false
1911 }
1912 },
1913 (PatKind::Struct(pat_ident, field_pats, None), ExprKind::Struct(ident, fields, hir::StructTailExpr::None))
1914 if field_pats.len() == fields.len() =>
1915 {
1916 qpath_res(&pat_ident, pat.hir_id) == qpath_res(ident, expr.hir_id)
1918 && unordered_over(field_pats, fields, |field_pat, field| {
1920 field_pat.ident == field.ident && is_expr_identity_of_pat(cx, field_pat.pat, field.expr, by_hir)
1921 })
1922 },
1923 _ => false,
1924 }
1925}
1926
1927pub fn is_expr_untyped_identity_function(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
1932 match expr.kind {
1933 ExprKind::Closure(&Closure { body, fn_decl, .. })
1934 if fn_decl.inputs.iter().all(|ty| matches!(ty.kind, TyKind::Infer(()))) =>
1935 {
1936 is_body_identity_function(cx, cx.tcx.hir_body(body))
1937 },
1938 ExprKind::Path(QPath::Resolved(_, path))
1939 if path.segments.iter().all(|seg| seg.infer_args)
1940 && let Some(did) = path.res.opt_def_id() =>
1941 {
1942 cx.tcx.is_diagnostic_item(sym::convert_identity, did)
1943 },
1944 _ => false,
1945 }
1946}
1947
1948pub fn is_expr_identity_function(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
1957 match expr.kind {
1958 ExprKind::Closure(&Closure { body, .. }) => is_body_identity_function(cx, cx.tcx.hir_body(body)),
1959 _ => expr.basic_res().is_diag_item(cx, sym::convert_identity),
1960 }
1961}
1962
1963pub fn get_expr_use_or_unification_node<'tcx>(tcx: TyCtxt<'tcx>, expr: &Expr<'_>) -> Option<(Node<'tcx>, HirId)> {
1966 let mut child_id = expr.hir_id;
1967 let mut iter = tcx.hir_parent_iter(child_id);
1968 loop {
1969 match iter.next() {
1970 None => break None,
1971 Some((id, Node::Block(_))) => child_id = id,
1972 Some((id, Node::Arm(arm))) if arm.body.hir_id == child_id => child_id = id,
1973 Some((_, Node::Expr(expr))) => match expr.kind {
1974 ExprKind::Match(_, [arm], _) if arm.hir_id == child_id => child_id = expr.hir_id,
1975 ExprKind::Block(..) | ExprKind::DropTemps(_) => child_id = expr.hir_id,
1976 ExprKind::If(_, then_expr, None) if then_expr.hir_id == child_id => break None,
1977 _ => break Some((Node::Expr(expr), child_id)),
1978 },
1979 Some((_, node)) => break Some((node, child_id)),
1980 }
1981 }
1982}
1983
1984pub fn is_expr_used_or_unified(tcx: TyCtxt<'_>, expr: &Expr<'_>) -> bool {
1986 !matches!(
1987 get_expr_use_or_unification_node(tcx, expr),
1988 None | Some((
1989 Node::Stmt(Stmt {
1990 kind: StmtKind::Expr(_)
1991 | StmtKind::Semi(_)
1992 | StmtKind::Let(LetStmt {
1993 pat: Pat {
1994 kind: PatKind::Wild,
1995 ..
1996 },
1997 ..
1998 }),
1999 ..
2000 }),
2001 _
2002 ))
2003 )
2004}
2005
2006pub fn is_expr_final_block_expr(tcx: TyCtxt<'_>, expr: &Expr<'_>) -> bool {
2008 matches!(tcx.parent_hir_node(expr.hir_id), Node::Block(..))
2009}
2010
2011pub fn is_expr_temporary_value(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
2015 !expr.is_place_expr(|base| {
2016 cx.typeck_results()
2017 .adjustments()
2018 .get(base.hir_id)
2019 .is_some_and(|x| x.iter().any(|adj| matches!(adj.kind, Adjust::Deref(_))))
2020 })
2021}
2022
2023pub fn std_or_core(cx: &LateContext<'_>) -> Option<&'static str> {
2024 if !is_no_std_crate(cx) {
2025 Some("std")
2026 } else if !is_no_core_crate(cx) {
2027 Some("core")
2028 } else {
2029 None
2030 }
2031}
2032
2033pub fn is_no_std_crate(cx: &LateContext<'_>) -> bool {
2034 find_attr!(cx.tcx.hir_attrs(hir::CRATE_HIR_ID), AttributeKind::NoStd(..))
2035}
2036
2037pub fn is_no_core_crate(cx: &LateContext<'_>) -> bool {
2038 find_attr!(cx.tcx.hir_attrs(hir::CRATE_HIR_ID), AttributeKind::NoCore(..))
2039}
2040
2041pub fn is_trait_impl_item(cx: &LateContext<'_>, hir_id: HirId) -> bool {
2051 if let Node::Item(item) = cx.tcx.parent_hir_node(hir_id) {
2052 matches!(item.kind, ItemKind::Impl(Impl { of_trait: Some(_), .. }))
2053 } else {
2054 false
2055 }
2056}
2057
2058pub fn fn_has_unsatisfiable_preds(cx: &LateContext<'_>, did: DefId) -> bool {
2068 use rustc_trait_selection::traits;
2069 let predicates = cx
2070 .tcx
2071 .predicates_of(did)
2072 .predicates
2073 .iter()
2074 .filter_map(|(p, _)| if p.is_global() { Some(*p) } else { None });
2075 traits::impossible_predicates(cx.tcx, traits::elaborate(cx.tcx, predicates).collect::<Vec<_>>())
2076}
2077
2078pub fn fn_def_id(cx: &LateContext<'_>, expr: &Expr<'_>) -> Option<DefId> {
2080 fn_def_id_with_node_args(cx, expr).map(|(did, _)| did)
2081}
2082
2083pub fn fn_def_id_with_node_args<'tcx>(
2086 cx: &LateContext<'tcx>,
2087 expr: &Expr<'_>,
2088) -> Option<(DefId, GenericArgsRef<'tcx>)> {
2089 let typeck = cx.typeck_results();
2090 match &expr.kind {
2091 ExprKind::MethodCall(..) => Some((
2092 typeck.type_dependent_def_id(expr.hir_id)?,
2093 typeck.node_args(expr.hir_id),
2094 )),
2095 ExprKind::Call(
2096 Expr {
2097 kind: ExprKind::Path(qpath),
2098 hir_id: path_hir_id,
2099 ..
2100 },
2101 ..,
2102 ) => {
2103 if let Res::Def(DefKind::Fn | DefKind::Ctor(..) | DefKind::AssocFn, id) =
2106 typeck.qpath_res(qpath, *path_hir_id)
2107 {
2108 Some((id, typeck.node_args(*path_hir_id)))
2109 } else {
2110 None
2111 }
2112 },
2113 _ => None,
2114 }
2115}
2116
2117pub fn is_slice_of_primitives(cx: &LateContext<'_>, expr: &Expr<'_>) -> Option<String> {
2122 let expr_type = cx.typeck_results().expr_ty_adjusted(expr);
2123 let expr_kind = expr_type.kind();
2124 let is_primitive = match expr_kind {
2125 rustc_ty::Slice(element_type) => is_recursively_primitive_type(*element_type),
2126 rustc_ty::Ref(_, inner_ty, _) if matches!(inner_ty.kind(), &rustc_ty::Slice(_)) => {
2127 if let rustc_ty::Slice(element_type) = inner_ty.kind() {
2128 is_recursively_primitive_type(*element_type)
2129 } else {
2130 unreachable!()
2131 }
2132 },
2133 _ => false,
2134 };
2135
2136 if is_primitive {
2137 match expr_type.peel_refs().walk().nth(1).unwrap().expect_ty().kind() {
2140 rustc_ty::Slice(..) => return Some("slice".into()),
2141 rustc_ty::Array(..) => return Some("array".into()),
2142 rustc_ty::Tuple(..) => return Some("tuple".into()),
2143 _ => {
2144 let refs_peeled = expr_type.peel_refs();
2147 return Some(refs_peeled.walk().last().unwrap().to_string());
2148 },
2149 }
2150 }
2151 None
2152}
2153
2154pub fn search_same<T, Hash, Eq>(exprs: &[T], mut hash: Hash, mut eq: Eq) -> Vec<Vec<&T>>
2162where
2163 Hash: FnMut(&T) -> u64,
2164 Eq: FnMut(&T, &T) -> bool,
2165{
2166 match exprs {
2167 [a, b] if eq(a, b) => return vec![vec![a, b]],
2168 _ if exprs.len() <= 2 => return vec![],
2169 _ => {},
2170 }
2171
2172 let mut buckets: UnindexMap<u64, Vec<Vec<&T>>> = UnindexMap::default();
2173
2174 for expr in exprs {
2175 match buckets.entry(hash(expr)) {
2176 indexmap::map::Entry::Occupied(mut o) => {
2177 let bucket = o.get_mut();
2178 match bucket.iter_mut().find(|group| eq(expr, group[0])) {
2179 Some(group) => group.push(expr),
2180 None => bucket.push(vec![expr]),
2181 }
2182 },
2183 indexmap::map::Entry::Vacant(v) => {
2184 v.insert(vec![vec![expr]]);
2185 },
2186 }
2187 }
2188
2189 buckets
2190 .into_values()
2191 .flatten()
2192 .filter(|group| group.len() > 1)
2193 .collect()
2194}
2195
2196pub fn peel_hir_pat_refs<'a>(pat: &'a Pat<'a>) -> (&'a Pat<'a>, usize) {
2199 fn peel<'a>(pat: &'a Pat<'a>, count: usize) -> (&'a Pat<'a>, usize) {
2200 if let PatKind::Ref(pat, _, _) = pat.kind {
2201 peel(pat, count + 1)
2202 } else {
2203 (pat, count)
2204 }
2205 }
2206 peel(pat, 0)
2207}
2208
2209pub fn peel_hir_expr_while<'tcx>(
2211 mut expr: &'tcx Expr<'tcx>,
2212 mut f: impl FnMut(&'tcx Expr<'tcx>) -> Option<&'tcx Expr<'tcx>>,
2213) -> &'tcx Expr<'tcx> {
2214 while let Some(e) = f(expr) {
2215 expr = e;
2216 }
2217 expr
2218}
2219
2220pub fn peel_n_hir_expr_refs<'a>(expr: &'a Expr<'a>, count: usize) -> (&'a Expr<'a>, usize) {
2223 let mut remaining = count;
2224 let e = peel_hir_expr_while(expr, |e| match e.kind {
2225 ExprKind::AddrOf(ast::BorrowKind::Ref, _, e) if remaining != 0 => {
2226 remaining -= 1;
2227 Some(e)
2228 },
2229 _ => None,
2230 });
2231 (e, count - remaining)
2232}
2233
2234pub fn peel_hir_expr_unary<'a>(expr: &'a Expr<'a>) -> (&'a Expr<'a>, usize) {
2237 let mut count: usize = 0;
2238 let mut curr_expr = expr;
2239 while let ExprKind::Unary(_, local_expr) = curr_expr.kind {
2240 count = count.wrapping_add(1);
2241 curr_expr = local_expr;
2242 }
2243 (curr_expr, count)
2244}
2245
2246pub fn peel_hir_expr_refs<'a>(expr: &'a Expr<'a>) -> (&'a Expr<'a>, usize) {
2249 let mut count = 0;
2250 let e = peel_hir_expr_while(expr, |e| match e.kind {
2251 ExprKind::AddrOf(ast::BorrowKind::Ref, _, e) => {
2252 count += 1;
2253 Some(e)
2254 },
2255 _ => None,
2256 });
2257 (e, count)
2258}
2259
2260pub fn peel_hir_ty_refs<'a>(mut ty: &'a hir::Ty<'a>) -> (&'a hir::Ty<'a>, usize) {
2263 let mut count = 0;
2264 loop {
2265 match &ty.kind {
2266 TyKind::Ref(_, ref_ty) => {
2267 ty = ref_ty.ty;
2268 count += 1;
2269 },
2270 _ => break (ty, count),
2271 }
2272 }
2273}
2274
2275pub fn peel_hir_ty_refs_and_ptrs<'tcx>(ty: &'tcx hir::Ty<'tcx>) -> &'tcx hir::Ty<'tcx> {
2277 match &ty.kind {
2278 TyKind::Ptr(mut_ty) | TyKind::Ref(_, mut_ty) => peel_hir_ty_refs_and_ptrs(mut_ty.ty),
2279 _ => ty,
2280 }
2281}
2282
2283pub fn peel_ref_operators<'hir>(cx: &LateContext<'_>, mut expr: &'hir Expr<'hir>) -> &'hir Expr<'hir> {
2286 loop {
2287 match expr.kind {
2288 ExprKind::AddrOf(_, _, e) => expr = e,
2289 ExprKind::Unary(UnOp::Deref, e) if cx.typeck_results().expr_ty(e).is_ref() => expr = e,
2290 _ => break,
2291 }
2292 }
2293 expr
2294}
2295
2296pub fn get_ref_operators<'hir>(cx: &LateContext<'_>, expr: &'hir Expr<'hir>) -> Vec<&'hir Expr<'hir>> {
2299 let mut operators = Vec::new();
2300 peel_hir_expr_while(expr, |expr| match expr.kind {
2301 ExprKind::AddrOf(_, _, e) => {
2302 operators.push(expr);
2303 Some(e)
2304 },
2305 ExprKind::Unary(UnOp::Deref, e) if cx.typeck_results().expr_ty(e).is_ref() => {
2306 operators.push(expr);
2307 Some(e)
2308 },
2309 _ => None,
2310 });
2311 operators
2312}
2313
2314pub fn is_hir_ty_cfg_dependant(cx: &LateContext<'_>, ty: &hir::Ty<'_>) -> bool {
2315 if let TyKind::Path(QPath::Resolved(_, path)) = ty.kind
2316 && let Res::Def(_, def_id) = path.res
2317 {
2318 return cx.tcx.has_attr(def_id, sym::cfg) || cx.tcx.has_attr(def_id, sym::cfg_attr);
2319 }
2320 false
2321}
2322
2323static TEST_ITEM_NAMES_CACHE: OnceLock<Mutex<FxHashMap<LocalModDefId, Vec<Symbol>>>> = OnceLock::new();
2324
2325fn with_test_item_names(tcx: TyCtxt<'_>, module: LocalModDefId, f: impl FnOnce(&[Symbol]) -> bool) -> bool {
2328 let cache = TEST_ITEM_NAMES_CACHE.get_or_init(|| Mutex::new(FxHashMap::default()));
2329 let mut map: MutexGuard<'_, FxHashMap<LocalModDefId, Vec<Symbol>>> = cache.lock().unwrap();
2330 let value = map.entry(module);
2331 match value {
2332 Entry::Occupied(entry) => f(entry.get()),
2333 Entry::Vacant(entry) => {
2334 let mut names = Vec::new();
2335 for id in tcx.hir_module_free_items(module) {
2336 if matches!(tcx.def_kind(id.owner_id), DefKind::Const)
2337 && let item = tcx.hir_item(id)
2338 && let ItemKind::Const(ident, _generics, ty, _body) = item.kind
2339 && let TyKind::Path(QPath::Resolved(_, path)) = ty.kind
2340 && let Res::Def(DefKind::Struct, _) = path.res
2342 {
2343 let has_test_marker = tcx
2344 .hir_attrs(item.hir_id())
2345 .iter()
2346 .any(|a| a.has_name(sym::rustc_test_marker));
2347 if has_test_marker {
2348 names.push(ident.name);
2349 }
2350 }
2351 }
2352 names.sort_unstable();
2353 f(entry.insert(names))
2354 },
2355 }
2356}
2357
2358pub fn is_in_test_function(tcx: TyCtxt<'_>, id: HirId) -> bool {
2362 with_test_item_names(tcx, tcx.parent_module(id), |names| {
2363 let node = tcx.hir_node(id);
2364 once((id, node))
2365 .chain(tcx.hir_parent_iter(id))
2366 .any(|(_id, node)| {
2369 if let Node::Item(item) = node
2370 && let ItemKind::Fn { ident, .. } = item.kind
2371 {
2372 return names.binary_search(&ident.name).is_ok();
2375 }
2376 false
2377 })
2378 })
2379}
2380
2381pub fn is_test_function(tcx: TyCtxt<'_>, fn_def_id: LocalDefId) -> bool {
2388 let id = tcx.local_def_id_to_hir_id(fn_def_id);
2389 if let Node::Item(item) = tcx.hir_node(id)
2390 && let ItemKind::Fn { ident, .. } = item.kind
2391 {
2392 with_test_item_names(tcx, tcx.parent_module(id), |names| {
2393 names.binary_search(&ident.name).is_ok()
2394 })
2395 } else {
2396 false
2397 }
2398}
2399
2400pub fn is_cfg_test(tcx: TyCtxt<'_>, id: HirId) -> bool {
2405 if let Some(cfgs) = find_attr!(tcx.hir_attrs(id), AttributeKind::CfgTrace(cfgs) => cfgs)
2406 && cfgs.iter().any(|(cfg, _)| { matches!(cfg, CfgEntry::NameValue { name: sym::test, ..})}) {
2407 true
2408 } else {
2409 false
2410 }
2411}
2412
2413pub fn is_in_cfg_test(tcx: TyCtxt<'_>, id: HirId) -> bool {
2415 tcx.hir_parent_id_iter(id).any(|parent_id| is_cfg_test(tcx, parent_id))
2416}
2417
2418pub fn is_in_test(tcx: TyCtxt<'_>, hir_id: HirId) -> bool {
2420 is_in_test_function(tcx, hir_id) || is_in_cfg_test(tcx, hir_id)
2421}
2422
2423pub fn inherits_cfg(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
2425 find_attr!(tcx.get_all_attrs(def_id), AttributeKind::CfgTrace(..))
2426 || find_attr!(tcx
2427 .hir_parent_iter(tcx.local_def_id_to_hir_id(def_id))
2428 .flat_map(|(parent_id, _)| tcx.hir_attrs(parent_id)), AttributeKind::CfgTrace(..))
2429}
2430
2431pub fn walk_to_expr_usage<'tcx, T>(
2442 cx: &LateContext<'tcx>,
2443 e: &Expr<'tcx>,
2444 mut f: impl FnMut(HirId, Node<'tcx>, HirId) -> ControlFlow<T>,
2445) -> Option<ControlFlow<T, (Node<'tcx>, HirId)>> {
2446 let mut iter = cx.tcx.hir_parent_iter(e.hir_id);
2447 let mut child_id = e.hir_id;
2448
2449 while let Some((parent_id, parent)) = iter.next() {
2450 if let ControlFlow::Break(x) = f(parent_id, parent, child_id) {
2451 return Some(ControlFlow::Break(x));
2452 }
2453 let parent_expr = match parent {
2454 Node::Expr(e) => e,
2455 Node::Block(Block { expr: Some(body), .. }) | Node::Arm(Arm { body, .. }) if body.hir_id == child_id => {
2456 child_id = parent_id;
2457 continue;
2458 },
2459 Node::Arm(a) if a.body.hir_id == child_id => {
2460 child_id = parent_id;
2461 continue;
2462 },
2463 _ => return Some(ControlFlow::Continue((parent, child_id))),
2464 };
2465 match parent_expr.kind {
2466 ExprKind::If(child, ..) | ExprKind::Match(child, ..) if child.hir_id != child_id => child_id = parent_id,
2467 ExprKind::Break(Destination { target_id: Ok(id), .. }, _) => {
2468 child_id = id;
2469 iter = cx.tcx.hir_parent_iter(id);
2470 },
2471 ExprKind::Block(..) | ExprKind::DropTemps(_) => child_id = parent_id,
2472 _ => return Some(ControlFlow::Continue((parent, child_id))),
2473 }
2474 }
2475 debug_assert!(false, "no parent node found for `{child_id:?}`");
2476 None
2477}
2478
2479#[derive(Clone, Copy)]
2481pub enum DefinedTy<'tcx> {
2482 Hir(&'tcx hir::Ty<'tcx>),
2484 Mir {
2492 def_site_def_id: Option<DefId>,
2493 ty: Binder<'tcx, Ty<'tcx>>,
2494 },
2495}
2496
2497pub struct ExprUseCtxt<'tcx> {
2499 pub node: Node<'tcx>,
2501 pub child_id: HirId,
2503 pub adjustments: &'tcx [Adjustment<'tcx>],
2505 pub is_ty_unified: bool,
2507 pub moved_before_use: bool,
2509 pub same_ctxt: bool,
2511}
2512impl<'tcx> ExprUseCtxt<'tcx> {
2513 pub fn use_node(&self, cx: &LateContext<'tcx>) -> ExprUseNode<'tcx> {
2514 match self.node {
2515 Node::LetStmt(l) => ExprUseNode::LetStmt(l),
2516 Node::ExprField(field) => ExprUseNode::Field(field),
2517
2518 Node::Item(&Item {
2519 kind: ItemKind::Static(..) | ItemKind::Const(..),
2520 owner_id,
2521 ..
2522 })
2523 | Node::TraitItem(&TraitItem {
2524 kind: TraitItemKind::Const(..),
2525 owner_id,
2526 ..
2527 })
2528 | Node::ImplItem(&ImplItem {
2529 kind: ImplItemKind::Const(..),
2530 owner_id,
2531 ..
2532 }) => ExprUseNode::ConstStatic(owner_id),
2533
2534 Node::Item(&Item {
2535 kind: ItemKind::Fn { .. },
2536 owner_id,
2537 ..
2538 })
2539 | Node::TraitItem(&TraitItem {
2540 kind: TraitItemKind::Fn(..),
2541 owner_id,
2542 ..
2543 })
2544 | Node::ImplItem(&ImplItem {
2545 kind: ImplItemKind::Fn(..),
2546 owner_id,
2547 ..
2548 }) => ExprUseNode::Return(owner_id),
2549
2550 Node::Expr(use_expr) => match use_expr.kind {
2551 ExprKind::Ret(_) => ExprUseNode::Return(OwnerId {
2552 def_id: cx.tcx.hir_body_owner_def_id(cx.enclosing_body.unwrap()),
2553 }),
2554
2555 ExprKind::Closure(closure) => ExprUseNode::Return(OwnerId { def_id: closure.def_id }),
2556 ExprKind::Call(func, args) => match args.iter().position(|arg| arg.hir_id == self.child_id) {
2557 Some(i) => ExprUseNode::FnArg(func, i),
2558 None => ExprUseNode::Callee,
2559 },
2560 ExprKind::MethodCall(name, _, args, _) => ExprUseNode::MethodArg(
2561 use_expr.hir_id,
2562 name.args,
2563 args.iter()
2564 .position(|arg| arg.hir_id == self.child_id)
2565 .map_or(0, |i| i + 1),
2566 ),
2567 ExprKind::Field(_, name) => ExprUseNode::FieldAccess(name),
2568 ExprKind::AddrOf(kind, mutbl, _) => ExprUseNode::AddrOf(kind, mutbl),
2569 _ => ExprUseNode::Other,
2570 },
2571 _ => ExprUseNode::Other,
2572 }
2573 }
2574}
2575
2576pub enum ExprUseNode<'tcx> {
2578 LetStmt(&'tcx LetStmt<'tcx>),
2580 ConstStatic(OwnerId),
2582 Return(OwnerId),
2584 Field(&'tcx ExprField<'tcx>),
2586 FnArg(&'tcx Expr<'tcx>, usize),
2588 MethodArg(HirId, Option<&'tcx GenericArgs<'tcx>>, usize),
2590 Callee,
2592 FieldAccess(Ident),
2594 AddrOf(ast::BorrowKind, Mutability),
2596 Other,
2597}
2598impl<'tcx> ExprUseNode<'tcx> {
2599 pub fn is_return(&self) -> bool {
2601 matches!(self, Self::Return(_))
2602 }
2603
2604 pub fn is_recv(&self) -> bool {
2606 matches!(self, Self::MethodArg(_, _, 0))
2607 }
2608
2609 pub fn defined_ty(&self, cx: &LateContext<'tcx>) -> Option<DefinedTy<'tcx>> {
2611 match *self {
2612 Self::LetStmt(LetStmt { ty: Some(ty), .. }) => Some(DefinedTy::Hir(ty)),
2613 Self::ConstStatic(id) => Some(DefinedTy::Mir {
2614 def_site_def_id: Some(id.def_id.to_def_id()),
2615 ty: Binder::dummy(cx.tcx.type_of(id).instantiate_identity()),
2616 }),
2617 Self::Return(id) => {
2618 if let Node::Expr(Expr {
2619 kind: ExprKind::Closure(c),
2620 ..
2621 }) = cx.tcx.hir_node_by_def_id(id.def_id)
2622 {
2623 match c.fn_decl.output {
2624 FnRetTy::DefaultReturn(_) => None,
2625 FnRetTy::Return(ty) => Some(DefinedTy::Hir(ty)),
2626 }
2627 } else {
2628 let ty = cx.tcx.fn_sig(id).instantiate_identity().output();
2629 Some(DefinedTy::Mir {
2630 def_site_def_id: Some(id.def_id.to_def_id()),
2631 ty,
2632 })
2633 }
2634 },
2635 Self::Field(field) => match get_parent_expr_for_hir(cx, field.hir_id) {
2636 Some(Expr {
2637 hir_id,
2638 kind: ExprKind::Struct(path, ..),
2639 ..
2640 }) => adt_and_variant_of_res(cx, cx.qpath_res(path, *hir_id))
2641 .and_then(|(adt, variant)| {
2642 variant
2643 .fields
2644 .iter()
2645 .find(|f| f.name == field.ident.name)
2646 .map(|f| (adt, f))
2647 })
2648 .map(|(adt, field_def)| DefinedTy::Mir {
2649 def_site_def_id: Some(adt.did()),
2650 ty: Binder::dummy(cx.tcx.type_of(field_def.did).instantiate_identity()),
2651 }),
2652 _ => None,
2653 },
2654 Self::FnArg(callee, i) => {
2655 let sig = expr_sig(cx, callee)?;
2656 let (hir_ty, ty) = sig.input_with_hir(i)?;
2657 Some(match hir_ty {
2658 Some(hir_ty) => DefinedTy::Hir(hir_ty),
2659 None => DefinedTy::Mir {
2660 def_site_def_id: sig.predicates_id(),
2661 ty,
2662 },
2663 })
2664 },
2665 Self::MethodArg(id, _, i) => {
2666 let id = cx.typeck_results().type_dependent_def_id(id)?;
2667 let sig = cx.tcx.fn_sig(id).skip_binder();
2668 Some(DefinedTy::Mir {
2669 def_site_def_id: Some(id),
2670 ty: sig.input(i),
2671 })
2672 },
2673 Self::LetStmt(_) | Self::FieldAccess(..) | Self::Callee | Self::Other | Self::AddrOf(..) => None,
2674 }
2675 }
2676}
2677
2678pub fn expr_use_ctxt<'tcx>(cx: &LateContext<'tcx>, e: &Expr<'tcx>) -> ExprUseCtxt<'tcx> {
2680 let mut adjustments = [].as_slice();
2681 let mut is_ty_unified = false;
2682 let mut moved_before_use = false;
2683 let mut same_ctxt = true;
2684 let ctxt = e.span.ctxt();
2685 let node = walk_to_expr_usage(cx, e, &mut |parent_id, parent, child_id| -> ControlFlow<!> {
2686 if adjustments.is_empty()
2687 && let Node::Expr(e) = cx.tcx.hir_node(child_id)
2688 {
2689 adjustments = cx.typeck_results().expr_adjustments(e);
2690 }
2691 same_ctxt &= cx.tcx.hir_span(parent_id).ctxt() == ctxt;
2692 if let Node::Expr(e) = parent {
2693 match e.kind {
2694 ExprKind::If(e, _, _) | ExprKind::Match(e, _, _) if e.hir_id != child_id => {
2695 is_ty_unified = true;
2696 moved_before_use = true;
2697 },
2698 ExprKind::Block(_, Some(_)) | ExprKind::Break(..) => {
2699 is_ty_unified = true;
2700 moved_before_use = true;
2701 },
2702 ExprKind::Block(..) => moved_before_use = true,
2703 _ => {},
2704 }
2705 }
2706 ControlFlow::Continue(())
2707 });
2708 match node {
2709 Some(ControlFlow::Continue((node, child_id))) => ExprUseCtxt {
2710 node,
2711 child_id,
2712 adjustments,
2713 is_ty_unified,
2714 moved_before_use,
2715 same_ctxt,
2716 },
2717 None => ExprUseCtxt {
2718 node: Node::Crate(cx.tcx.hir_root_module()),
2719 child_id: HirId::INVALID,
2720 adjustments: &[],
2721 is_ty_unified: true,
2722 moved_before_use: true,
2723 same_ctxt: false,
2724 },
2725 }
2726}
2727
2728pub fn tokenize_with_text(s: &str) -> impl Iterator<Item = (TokenKind, &str, InnerSpan)> {
2730 let mut pos = 0;
2731 tokenize(s, FrontmatterAllowed::No).map(move |t| {
2732 let end = pos + t.len;
2733 let range = pos as usize..end as usize;
2734 let inner = InnerSpan::new(range.start, range.end);
2735 pos = end;
2736 (t.kind, s.get(range).unwrap_or_default(), inner)
2737 })
2738}
2739
2740pub fn span_contains_comment(sm: &SourceMap, span: Span) -> bool {
2743 let Ok(snippet) = sm.span_to_snippet(span) else {
2744 return false;
2745 };
2746 return tokenize(&snippet, FrontmatterAllowed::No).any(|token| {
2747 matches!(
2748 token.kind,
2749 TokenKind::BlockComment { .. } | TokenKind::LineComment { .. }
2750 )
2751 });
2752}
2753
2754pub fn span_contains_non_whitespace(cx: &impl source::HasSession, span: Span, skip_comments: bool) -> bool {
2759 matches!(span.get_source_text(cx), Some(snippet) if tokenize_with_text(&snippet).any(|(token, _, _)|
2760 match token {
2761 TokenKind::Whitespace => false,
2762 TokenKind::BlockComment { .. } | TokenKind::LineComment { .. } => !skip_comments,
2763 _ => true,
2764 }
2765 ))
2766}
2767pub fn span_extract_comment(sm: &SourceMap, span: Span) -> String {
2771 span_extract_comments(sm, span).join("\n")
2772}
2773
2774pub fn span_extract_comments(sm: &SourceMap, span: Span) -> Vec<String> {
2778 let snippet = sm.span_to_snippet(span).unwrap_or_default();
2779 tokenize_with_text(&snippet)
2780 .filter(|(t, ..)| matches!(t, TokenKind::BlockComment { .. } | TokenKind::LineComment { .. }))
2781 .map(|(_, s, _)| s.to_string())
2782 .collect::<Vec<_>>()
2783}
2784
2785pub fn span_find_starting_semi(sm: &SourceMap, span: Span) -> Span {
2786 sm.span_take_while(span, |&ch| ch == ' ' || ch == ';')
2787}
2788
2789pub fn pat_and_expr_can_be_question_mark<'a, 'hir>(
2814 cx: &LateContext<'_>,
2815 pat: &'a Pat<'hir>,
2816 else_body: &Expr<'_>,
2817) -> Option<&'a Pat<'hir>> {
2818 if let Some([inner_pat]) = as_some_pattern(cx, pat)
2819 && !is_refutable(cx, inner_pat)
2820 && let else_body = peel_blocks(else_body)
2821 && let ExprKind::Ret(Some(ret_val)) = else_body.kind
2822 && let ExprKind::Path(ret_path) = ret_val.kind
2823 && cx
2824 .qpath_res(&ret_path, ret_val.hir_id)
2825 .ctor_parent(cx)
2826 .is_lang_item(cx, OptionNone)
2827 {
2828 Some(inner_pat)
2829 } else {
2830 None
2831 }
2832}
2833
2834macro_rules! op_utils {
2835 ($($name:ident $assign:ident)*) => {
2836 pub static BINOP_TRAITS: &[LangItem] = &[$(LangItem::$name,)*];
2838
2839 pub static OP_ASSIGN_TRAITS: &[LangItem] = &[$(LangItem::$assign,)*];
2841
2842 pub fn binop_traits(kind: hir::BinOpKind) -> Option<(LangItem, LangItem)> {
2844 match kind {
2845 $(hir::BinOpKind::$name => Some((LangItem::$name, LangItem::$assign)),)*
2846 _ => None,
2847 }
2848 }
2849 };
2850}
2851
2852op_utils! {
2853 Add AddAssign
2854 Sub SubAssign
2855 Mul MulAssign
2856 Div DivAssign
2857 Rem RemAssign
2858 BitXor BitXorAssign
2859 BitAnd BitAndAssign
2860 BitOr BitOrAssign
2861 Shl ShlAssign
2862 Shr ShrAssign
2863}
2864
2865pub fn pat_is_wild<'tcx>(cx: &LateContext<'tcx>, pat: &'tcx PatKind<'_>, body: impl Visitable<'tcx>) -> bool {
2868 match *pat {
2869 PatKind::Wild => true,
2870 PatKind::Binding(_, id, ident, None) if ident.as_str().starts_with('_') => {
2871 !visitors::is_local_used(cx, body, id)
2872 },
2873 _ => false,
2874 }
2875}
2876
2877#[derive(Clone, Copy)]
2878pub enum RequiresSemi {
2879 Yes,
2880 No,
2881}
2882impl RequiresSemi {
2883 pub fn requires_semi(self) -> bool {
2884 matches!(self, Self::Yes)
2885 }
2886}
2887
2888#[expect(clippy::too_many_lines)]
2891pub fn is_never_expr<'tcx>(cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) -> Option<RequiresSemi> {
2892 struct BreakTarget {
2893 id: HirId,
2894 unused: bool,
2895 }
2896
2897 struct V<'cx, 'tcx> {
2898 cx: &'cx LateContext<'tcx>,
2899 break_targets: Vec<BreakTarget>,
2900 break_targets_for_result_ty: u32,
2901 in_final_expr: bool,
2902 requires_semi: bool,
2903 is_never: bool,
2904 }
2905
2906 impl V<'_, '_> {
2907 fn push_break_target(&mut self, id: HirId) {
2908 self.break_targets.push(BreakTarget { id, unused: true });
2909 self.break_targets_for_result_ty += u32::from(self.in_final_expr);
2910 }
2911 }
2912
2913 impl<'tcx> Visitor<'tcx> for V<'_, 'tcx> {
2914 fn visit_expr(&mut self, e: &'tcx Expr<'_>) {
2915 if self.is_never && self.break_targets.is_empty() {
2932 if self.in_final_expr && !self.requires_semi {
2933 match e.kind {
2936 ExprKind::DropTemps(e) => self.visit_expr(e),
2937 ExprKind::If(_, then, Some(else_)) => {
2938 self.visit_expr(then);
2939 self.visit_expr(else_);
2940 },
2941 ExprKind::Match(_, arms, _) => {
2942 for arm in arms {
2943 self.visit_expr(arm.body);
2944 }
2945 },
2946 ExprKind::Loop(b, ..) => {
2947 self.push_break_target(e.hir_id);
2948 self.in_final_expr = false;
2949 self.visit_block(b);
2950 self.break_targets.pop();
2951 },
2952 ExprKind::Block(b, _) => {
2953 if b.targeted_by_break {
2954 self.push_break_target(b.hir_id);
2955 self.visit_block(b);
2956 self.break_targets.pop();
2957 } else {
2958 self.visit_block(b);
2959 }
2960 },
2961 _ => {
2962 self.requires_semi = !self.cx.typeck_results().expr_ty(e).is_never();
2963 },
2964 }
2965 }
2966 return;
2967 }
2968 match e.kind {
2969 ExprKind::DropTemps(e) => self.visit_expr(e),
2970 ExprKind::Ret(None) | ExprKind::Continue(_) => self.is_never = true,
2971 ExprKind::Ret(Some(e)) | ExprKind::Become(e) => {
2972 self.in_final_expr = false;
2973 self.visit_expr(e);
2974 self.is_never = true;
2975 },
2976 ExprKind::Break(dest, e) => {
2977 if let Some(e) = e {
2978 self.in_final_expr = false;
2979 self.visit_expr(e);
2980 }
2981 if let Ok(id) = dest.target_id
2982 && let Some((i, target)) = self
2983 .break_targets
2984 .iter_mut()
2985 .enumerate()
2986 .find(|(_, target)| target.id == id)
2987 {
2988 target.unused &= self.is_never;
2989 if i < self.break_targets_for_result_ty as usize {
2990 self.requires_semi = true;
2991 }
2992 }
2993 self.is_never = true;
2994 },
2995 ExprKind::If(cond, then, else_) => {
2996 let in_final_expr = mem::replace(&mut self.in_final_expr, false);
2997 self.visit_expr(cond);
2998 self.in_final_expr = in_final_expr;
2999
3000 if self.is_never {
3001 self.visit_expr(then);
3002 if let Some(else_) = else_ {
3003 self.visit_expr(else_);
3004 }
3005 } else {
3006 self.visit_expr(then);
3007 let is_never = mem::replace(&mut self.is_never, false);
3008 if let Some(else_) = else_ {
3009 self.visit_expr(else_);
3010 self.is_never &= is_never;
3011 }
3012 }
3013 },
3014 ExprKind::Match(scrutinee, arms, _) => {
3015 let in_final_expr = mem::replace(&mut self.in_final_expr, false);
3016 self.visit_expr(scrutinee);
3017 self.in_final_expr = in_final_expr;
3018
3019 if self.is_never {
3020 for arm in arms {
3021 self.visit_arm(arm);
3022 }
3023 } else {
3024 let mut is_never = true;
3025 for arm in arms {
3026 self.is_never = false;
3027 if let Some(guard) = arm.guard {
3028 let in_final_expr = mem::replace(&mut self.in_final_expr, false);
3029 self.visit_expr(guard);
3030 self.in_final_expr = in_final_expr;
3031 self.is_never = false;
3033 }
3034 self.visit_expr(arm.body);
3035 is_never &= self.is_never;
3036 }
3037 self.is_never = is_never;
3038 }
3039 },
3040 ExprKind::Loop(b, _, _, _) => {
3041 self.push_break_target(e.hir_id);
3042 self.in_final_expr = false;
3043 self.visit_block(b);
3044 self.is_never = self.break_targets.pop().unwrap().unused;
3045 },
3046 ExprKind::Block(b, _) => {
3047 if b.targeted_by_break {
3048 self.push_break_target(b.hir_id);
3049 self.visit_block(b);
3050 self.is_never &= self.break_targets.pop().unwrap().unused;
3051 } else {
3052 self.visit_block(b);
3053 }
3054 },
3055 _ => {
3056 self.in_final_expr = false;
3057 walk_expr(self, e);
3058 self.is_never |= self.cx.typeck_results().expr_ty(e).is_never();
3059 },
3060 }
3061 }
3062
3063 fn visit_block(&mut self, b: &'tcx Block<'_>) {
3064 let in_final_expr = mem::replace(&mut self.in_final_expr, false);
3065 for s in b.stmts {
3066 self.visit_stmt(s);
3067 }
3068 self.in_final_expr = in_final_expr;
3069 if let Some(e) = b.expr {
3070 self.visit_expr(e);
3071 }
3072 }
3073
3074 fn visit_local(&mut self, l: &'tcx LetStmt<'_>) {
3075 if let Some(e) = l.init {
3076 self.visit_expr(e);
3077 }
3078 if let Some(else_) = l.els {
3079 let is_never = self.is_never;
3080 self.visit_block(else_);
3081 self.is_never = is_never;
3082 }
3083 }
3084
3085 fn visit_arm(&mut self, arm: &Arm<'tcx>) {
3086 if let Some(guard) = arm.guard {
3087 let in_final_expr = mem::replace(&mut self.in_final_expr, false);
3088 self.visit_expr(guard);
3089 self.in_final_expr = in_final_expr;
3090 }
3091 self.visit_expr(arm.body);
3092 }
3093 }
3094
3095 if cx.typeck_results().expr_ty(e).is_never() {
3096 Some(RequiresSemi::No)
3097 } else if let ExprKind::Block(b, _) = e.kind
3098 && !b.targeted_by_break
3099 && b.expr.is_none()
3100 {
3101 None
3103 } else {
3104 let mut v = V {
3105 cx,
3106 break_targets: Vec::new(),
3107 break_targets_for_result_ty: 0,
3108 in_final_expr: true,
3109 requires_semi: false,
3110 is_never: false,
3111 };
3112 v.visit_expr(e);
3113 v.is_never
3114 .then_some(if v.requires_semi && matches!(e.kind, ExprKind::Block(..)) {
3115 RequiresSemi::Yes
3116 } else {
3117 RequiresSemi::No
3118 })
3119 }
3120}
3121
3122pub fn get_path_from_caller_to_method_type<'tcx>(
3128 tcx: TyCtxt<'tcx>,
3129 from: LocalDefId,
3130 method: DefId,
3131 args: GenericArgsRef<'tcx>,
3132) -> String {
3133 let assoc_item = tcx.associated_item(method);
3134 let def_id = assoc_item.container_id(tcx);
3135 match assoc_item.container {
3136 rustc_ty::AssocContainer::Trait => get_path_to_callee(tcx, from, def_id),
3137 rustc_ty::AssocContainer::InherentImpl | rustc_ty::AssocContainer::TraitImpl(_) => {
3138 let ty = tcx.type_of(def_id).instantiate_identity();
3139 get_path_to_ty(tcx, from, ty, args)
3140 },
3141 }
3142}
3143
3144fn get_path_to_ty<'tcx>(tcx: TyCtxt<'tcx>, from: LocalDefId, ty: Ty<'tcx>, args: GenericArgsRef<'tcx>) -> String {
3145 match ty.kind() {
3146 rustc_ty::Adt(adt, _) => get_path_to_callee(tcx, from, adt.did()),
3147 rustc_ty::Array(..)
3149 | rustc_ty::Dynamic(..)
3150 | rustc_ty::Never
3151 | rustc_ty::RawPtr(_, _)
3152 | rustc_ty::Ref(..)
3153 | rustc_ty::Slice(_)
3154 | rustc_ty::Tuple(_) => format!("<{}>", EarlyBinder::bind(ty).instantiate(tcx, args)),
3155 _ => ty.to_string(),
3156 }
3157}
3158
3159fn get_path_to_callee(tcx: TyCtxt<'_>, from: LocalDefId, callee: DefId) -> String {
3161 if callee.is_local() {
3163 let callee_path = tcx.def_path(callee);
3164 let caller_path = tcx.def_path(from.to_def_id());
3165 maybe_get_relative_path(&caller_path, &callee_path, 2)
3166 } else {
3167 tcx.def_path_str(callee)
3168 }
3169}
3170
3171fn maybe_get_relative_path(from: &DefPath, to: &DefPath, max_super: usize) -> String {
3184 use itertools::EitherOrBoth::{Both, Left, Right};
3185
3186 let unique_parts = to
3188 .data
3189 .iter()
3190 .zip_longest(from.data.iter())
3191 .skip_while(|el| matches!(el, Both(l, r) if l == r))
3192 .map(|el| match el {
3193 Both(l, r) => Both(l.data, r.data),
3194 Left(l) => Left(l.data),
3195 Right(r) => Right(r.data),
3196 });
3197
3198 let mut go_up_by = 0;
3200 let mut path = Vec::new();
3201 for el in unique_parts {
3202 match el {
3203 Both(l, r) => {
3204 if let DefPathData::TypeNs(sym) = l {
3214 path.push(sym);
3215 }
3216 if let DefPathData::TypeNs(_) = r {
3217 go_up_by += 1;
3218 }
3219 },
3220 Left(DefPathData::TypeNs(sym)) => path.push(sym),
3225 Right(DefPathData::TypeNs(_)) => go_up_by += 1,
3230 _ => {},
3231 }
3232 }
3233
3234 if go_up_by > max_super {
3235 join_path_syms(once(kw::Crate).chain(to.data.iter().filter_map(|el| {
3237 if let DefPathData::TypeNs(sym) = el.data {
3238 Some(sym)
3239 } else {
3240 None
3241 }
3242 })))
3243 } else {
3244 join_path_syms(repeat_n(kw::Super, go_up_by).chain(path))
3245 }
3246}
3247
3248pub fn is_parent_stmt(cx: &LateContext<'_>, id: HirId) -> bool {
3251 matches!(
3252 cx.tcx.parent_hir_node(id),
3253 Node::Stmt(..) | Node::Block(Block { stmts: [], .. })
3254 )
3255}
3256
3257pub fn is_block_like(expr: &Expr<'_>) -> bool {
3260 matches!(
3261 expr.kind,
3262 ExprKind::Block(..) | ExprKind::ConstBlock(..) | ExprKind::If(..) | ExprKind::Loop(..) | ExprKind::Match(..)
3263 )
3264}
3265
3266pub fn binary_expr_needs_parentheses(expr: &Expr<'_>) -> bool {
3268 fn contains_block(expr: &Expr<'_>, is_operand: bool) -> bool {
3269 match expr.kind {
3270 ExprKind::Binary(_, lhs, _) | ExprKind::Cast(lhs, _) => contains_block(lhs, true),
3271 _ if is_block_like(expr) => is_operand,
3272 _ => false,
3273 }
3274 }
3275
3276 contains_block(expr, false)
3277}
3278
3279pub fn is_receiver_of_method_call(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
3281 if let Some(parent_expr) = get_parent_expr(cx, expr)
3282 && let ExprKind::MethodCall(_, receiver, ..) = parent_expr.kind
3283 && receiver.hir_id == expr.hir_id
3284 {
3285 return true;
3286 }
3287 false
3288}
3289
3290pub fn leaks_droppable_temporary_with_limited_lifetime<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> bool {
3293 for_each_unconsumed_temporary(cx, expr, |temporary_ty| {
3294 if temporary_ty.has_significant_drop(cx.tcx, cx.typing_env())
3295 && temporary_ty
3296 .walk()
3297 .any(|arg| matches!(arg.kind(), GenericArgKind::Lifetime(re) if !re.is_static()))
3298 {
3299 ControlFlow::Break(())
3300 } else {
3301 ControlFlow::Continue(())
3302 }
3303 })
3304 .is_break()
3305}
3306
3307pub fn expr_requires_coercion<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'tcx>) -> bool {
3318 let expr_ty_is_adjusted = cx
3319 .typeck_results()
3320 .expr_adjustments(expr)
3321 .iter()
3322 .any(|adj| !matches!(adj.kind, Adjust::NeverToAny));
3324 if expr_ty_is_adjusted {
3325 return true;
3326 }
3327
3328 match expr.kind {
3331 ExprKind::Call(_, args) | ExprKind::MethodCall(_, _, args, _) if let Some(def_id) = fn_def_id(cx, expr) => {
3332 let fn_sig = cx.tcx.fn_sig(def_id).instantiate_identity();
3333
3334 if !fn_sig.output().skip_binder().has_type_flags(TypeFlags::HAS_TY_PARAM) {
3335 return false;
3336 }
3337
3338 let self_arg_count = usize::from(matches!(expr.kind, ExprKind::MethodCall(..)));
3339 let mut args_with_ty_param = {
3340 fn_sig
3341 .inputs()
3342 .skip_binder()
3343 .iter()
3344 .skip(self_arg_count)
3345 .zip(args)
3346 .filter_map(|(arg_ty, arg)| {
3347 if arg_ty.has_type_flags(TypeFlags::HAS_TY_PARAM) {
3348 Some(arg)
3349 } else {
3350 None
3351 }
3352 })
3353 };
3354 args_with_ty_param.any(|arg| expr_requires_coercion(cx, arg))
3355 },
3356 ExprKind::Struct(qpath, _, _) => {
3358 let res = cx.typeck_results().qpath_res(qpath, expr.hir_id);
3359 if let Some((_, v_def)) = adt_and_variant_of_res(cx, res) {
3360 let rustc_ty::Adt(_, generic_args) = cx.typeck_results().expr_ty_adjusted(expr).kind() else {
3361 return true;
3363 };
3364 v_def
3365 .fields
3366 .iter()
3367 .any(|field| field.ty(cx.tcx, generic_args).has_type_flags(TypeFlags::HAS_TY_PARAM))
3368 } else {
3369 false
3370 }
3371 },
3372 ExprKind::Block(
3374 &Block {
3375 expr: Some(ret_expr), ..
3376 },
3377 _,
3378 )
3379 | ExprKind::Ret(Some(ret_expr)) => expr_requires_coercion(cx, ret_expr),
3380
3381 ExprKind::Array(elems) | ExprKind::Tup(elems) => elems.iter().any(|elem| expr_requires_coercion(cx, elem)),
3383 ExprKind::Repeat(rep_elem, _) => expr_requires_coercion(cx, rep_elem),
3385 ExprKind::If(_, then, maybe_else) => {
3387 expr_requires_coercion(cx, then) || maybe_else.is_some_and(|e| expr_requires_coercion(cx, e))
3388 },
3389 ExprKind::Match(_, arms, _) => arms
3390 .iter()
3391 .map(|arm| arm.body)
3392 .any(|body| expr_requires_coercion(cx, body)),
3393 _ => false,
3394 }
3395}
3396
3397pub fn is_mutable(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
3400 if let Some(hir_id) = expr.res_local_id()
3401 && let Node::Pat(pat) = cx.tcx.hir_node(hir_id)
3402 {
3403 matches!(pat.kind, PatKind::Binding(BindingMode::MUT, ..))
3404 } else if let ExprKind::Path(p) = &expr.kind
3405 && let Some(mutability) = cx
3406 .qpath_res(p, expr.hir_id)
3407 .opt_def_id()
3408 .and_then(|id| cx.tcx.static_mutability(id))
3409 {
3410 mutability == Mutability::Mut
3411 } else if let ExprKind::Field(parent, _) = expr.kind {
3412 is_mutable(cx, parent)
3413 } else {
3414 true
3415 }
3416}
3417
3418pub fn peel_hir_ty_options<'tcx>(cx: &LateContext<'tcx>, mut hir_ty: &'tcx hir::Ty<'tcx>) -> &'tcx hir::Ty<'tcx> {
3421 let Some(option_def_id) = cx.tcx.get_diagnostic_item(sym::Option) else {
3422 return hir_ty;
3423 };
3424 while let TyKind::Path(QPath::Resolved(None, path)) = hir_ty.kind
3425 && let Some(segment) = path.segments.last()
3426 && segment.ident.name == sym::Option
3427 && let Res::Def(DefKind::Enum, def_id) = segment.res
3428 && def_id == option_def_id
3429 && let [GenericArg::Type(arg_ty)] = segment.args().args
3430 {
3431 hir_ty = arg_ty.as_unambig_ty();
3432 }
3433 hir_ty
3434}
3435
3436pub fn desugar_await<'tcx>(expr: &'tcx Expr<'_>) -> Option<&'tcx Expr<'tcx>> {
3439 if let ExprKind::Match(match_value, _, MatchSource::AwaitDesugar) = expr.kind
3440 && let ExprKind::Call(_, [into_future_arg]) = match_value.kind
3441 && let ctxt = expr.span.ctxt()
3442 && for_each_expr_without_closures(into_future_arg, |e| {
3443 walk_span_to_context(e.span, ctxt).map_or(ControlFlow::Break(()), |_| ControlFlow::Continue(()))
3444 })
3445 .is_none()
3446 {
3447 Some(into_future_arg)
3448 } else {
3449 None
3450 }
3451}
3452
3453pub fn is_expr_default<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> bool {
3455 if let ExprKind::Call(fn_expr, []) = &expr.kind
3456 && let ExprKind::Path(qpath) = &fn_expr.kind
3457 && let Res::Def(_, def_id) = cx.qpath_res(qpath, fn_expr.hir_id)
3458 {
3459 cx.tcx.is_diagnostic_item(sym::default_fn, def_id)
3460 } else {
3461 false
3462 }
3463}
3464
3465pub fn potential_return_of_enclosing_body(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
3482 let enclosing_body_owner = cx
3483 .tcx
3484 .local_def_id_to_hir_id(cx.tcx.hir_enclosing_body_owner(expr.hir_id));
3485 let mut prev_id = expr.hir_id;
3486 let mut skip_until_id = None;
3487 for (hir_id, node) in cx.tcx.hir_parent_iter(expr.hir_id) {
3488 if hir_id == enclosing_body_owner {
3489 return true;
3490 }
3491 if let Some(id) = skip_until_id {
3492 prev_id = hir_id;
3493 if id == hir_id {
3494 skip_until_id = None;
3495 }
3496 continue;
3497 }
3498 match node {
3499 Node::Block(Block { expr, .. }) if expr.is_some_and(|expr| expr.hir_id == prev_id) => {},
3500 Node::Arm(arm) if arm.body.hir_id == prev_id => {},
3501 Node::Expr(expr) => match expr.kind {
3502 ExprKind::Ret(_) => return true,
3503 ExprKind::If(_, then, opt_else)
3504 if then.hir_id == prev_id || opt_else.is_some_and(|els| els.hir_id == prev_id) => {},
3505 ExprKind::Match(_, arms, _) if arms.iter().any(|arm| arm.hir_id == prev_id) => {},
3506 ExprKind::Block(block, _) if block.hir_id == prev_id => {},
3507 ExprKind::Break(
3508 Destination {
3509 target_id: Ok(target_id),
3510 ..
3511 },
3512 _,
3513 ) => skip_until_id = Some(target_id),
3514 _ => break,
3515 },
3516 _ => break,
3517 }
3518 prev_id = hir_id;
3519 }
3520
3521 false
3524}
3525
3526pub fn expr_adjustment_requires_coercion(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
3529 cx.typeck_results().expr_adjustments(expr).iter().any(|adj| {
3530 matches!(
3531 adj.kind,
3532 Adjust::Deref(Some(_)) | Adjust::Pointer(PointerCoercion::Unsize) | Adjust::NeverToAny
3533 )
3534 })
3535}
3536
3537pub fn is_expr_async_block(expr: &Expr<'_>) -> bool {
3539 matches!(
3540 expr.kind,
3541 ExprKind::Closure(Closure {
3542 kind: hir::ClosureKind::Coroutine(CoroutineKind::Desugared(
3543 CoroutineDesugaring::Async,
3544 CoroutineSource::Block
3545 )),
3546 ..
3547 })
3548 )
3549}
3550
3551pub fn can_use_if_let_chains(cx: &LateContext<'_>, msrv: Msrv) -> bool {
3553 cx.tcx.sess.edition().at_least_rust_2024() && msrv.meets(cx, msrvs::LET_CHAINS)
3554}