Skip to main content

clippy_utils/
lib.rs

1#![feature(deref_patterns)]
2#![feature(macro_metavar_expr)]
3#![feature(rustc_private)]
4#![recursion_limit = "512"]
5#![expect(clippy::missing_errors_doc, clippy::missing_panics_doc, clippy::must_use_candidate)]
6#![warn(
7    rust_2018_idioms,
8    trivial_casts,
9    trivial_numeric_casts,
10    unused_lifetimes,
11    unused_qualifications,
12    rustc::internal
13)]
14
15// FIXME: switch to something more ergonomic here, once available.
16// (Currently there is no way to opt into sysroot crates without `extern crate`.)
17extern crate rustc_abi;
18extern crate rustc_ast;
19extern crate rustc_attr_ir;
20extern crate rustc_attr_parsing;
21extern crate rustc_const_eval;
22extern crate rustc_data_structures;
23#[expect(
24    unused_extern_crates,
25    reason = "The `rustc_driver` crate seems to be required in order to use the `rust_ast` crate."
26)]
27extern crate rustc_driver;
28extern crate rustc_errors;
29extern crate rustc_hir;
30extern crate rustc_hir_analysis;
31extern crate rustc_hir_typeck;
32extern crate rustc_index;
33extern crate rustc_infer;
34extern crate rustc_lexer;
35extern crate rustc_lint;
36extern crate rustc_middle;
37extern crate rustc_mir_dataflow;
38extern crate rustc_session;
39extern crate rustc_span;
40extern crate rustc_trait_selection;
41
42pub mod ast_utils;
43#[deny(missing_docs)]
44pub mod attrs;
45mod check_proc_macro;
46pub mod comparisons;
47pub mod consts;
48pub mod diagnostics;
49pub mod eager_or_lazy;
50pub mod higher;
51mod hir_utils;
52pub mod macros;
53pub mod mir;
54pub mod msrvs;
55pub mod numeric_literal;
56pub mod paths;
57pub mod qualify_min_const_fn;
58pub mod res;
59pub mod source;
60pub mod str_utils;
61pub mod sugg;
62pub mod sym;
63pub mod ty;
64pub mod usage;
65pub mod visitors;
66
67pub use self::attrs::*;
68pub use self::check_proc_macro::{is_from_proc_macro, is_span_if, is_span_match};
69pub use self::hir_utils::{
70    HirEqInterExpr, SpanlessEq, SpanlessHash, both, count_eq, eq_expr_value, has_ambiguous_literal_in_expr, hash_expr,
71    hash_stmt, is_bool, over,
72};
73
74use core::mem;
75use core::ops::ControlFlow;
76use std::collections::hash_map::Entry;
77use std::iter::{once, repeat_n, zip};
78use std::sync::{Mutex, OnceLock};
79
80use itertools::Itertools as _;
81use rustc_abi::Integer;
82use rustc_ast::ast::{self, LitKind, RangeLimits};
83use rustc_ast::{LitIntType, join_path_syms};
84use rustc_attr_ir::lang_items::LangItem;
85use rustc_attr_ir::lang_items::LangItem::{OptionNone, OptionSome, ResultErr, ResultOk};
86use rustc_attr_ir::{CfgEntry, find_attr};
87use rustc_data_structures::fx::FxHashMap;
88use rustc_data_structures::indexmap;
89use rustc_data_structures::packed::Pu128;
90use rustc_data_structures::unhash::UnindexMap;
91use rustc_hir::def::{DefKind, Res};
92use rustc_hir::def_id::{DefId, LocalDefId, LocalModId};
93use rustc_hir::definitions::{DefPath, DefPathData};
94use rustc_hir::intravisit::{Visitor, walk_expr};
95use rustc_hir::{
96    self as hir, AnonConst, Arm, BindingMode, Block, BlockCheckMode, Body, ByRef, CRATE_HIR_ID, Closure, ConstArg,
97    ConstArgKind, CoroutineDesugaring, CoroutineKind, CoroutineSource, Destination, Expr, ExprField, ExprKind,
98    FieldDef, FnDecl, FnRetTy, GenericArg, GenericArgs, HirId, HirIdMap, HirIdSet, Impl, ImplItem, ImplItemKind, Item,
99    ItemKind, LetStmt, MatchSource, Mutability, Node, OwnerId, OwnerNode, Param, Pat, PatExpr, PatExprKind, PatKind,
100    Path, PathSegment, QPath, Stmt, StmtKind, TraitFn, TraitItem, TraitItemKind, TraitRef, TyKind, UnOp, Variant, def,
101};
102use rustc_lexer::{FrontmatterAllowed, TokenKind, tokenize};
103use rustc_lint::{LateContext, Level, Lint, LintContext as _};
104use rustc_middle::hir::nested_filter;
105use rustc_middle::hir::place::PlaceBase;
106use rustc_middle::mir::{AggregateKind, Operand, RETURN_PLACE, Rvalue, StatementKind, TerminatorKind};
107use rustc_middle::ty::adjustment::{Adjust, Adjustment, AutoBorrow, DerefAdjustKind, PointerCoercion};
108use rustc_middle::ty::layout::IntegerExt as _;
109use rustc_middle::ty::{
110    self as rustc_ty, Binder, BorrowKind, ClosureKind, EarlyBinder, GenericArgKind, IntTy, Ty, TyCtxt, TypeFlags,
111    TypeVisitableExt as _, TypeckResults, UintTy, UpvarCapture,
112};
113use rustc_session::config::Input;
114use rustc_span::hygiene::{ExpnKind, MacroKind};
115use rustc_span::source_map::SourceMap;
116use rustc_span::symbol::{Ident, Symbol, kw};
117use rustc_span::{InnerSpan, Span, SyntaxContext};
118use source::{SpanExt as _, walk_span_to_context};
119use visitors::{Visitable, for_each_unconsumed_temporary};
120
121use crate::ast_utils::unordered_over;
122use crate::higher::Range;
123use crate::msrvs::Msrv;
124use crate::res::{MaybeDef as _, MaybeResPath as _};
125use crate::source::HasSourceMap;
126use crate::ty::{adt_and_variant_of_res, can_partially_move_ty, expr_sig, is_copy, is_recursively_primitive_type};
127use crate::visitors::for_each_expr_without_closures;
128
129/// Methods on `Vec` that also exists on slices.
130pub const VEC_METHODS_SHADOWING_SLICE_METHODS: [Symbol; 3] = [sym::as_ptr, sym::is_empty, sym::len];
131
132#[macro_export]
133macro_rules! extract_msrv_attr {
134    () => {
135        fn check_attributes(&mut self, cx: &rustc_lint::EarlyContext<'_>, attrs: &[rustc_ast::ast::Attribute]) {
136            let sess = rustc_lint::LintContext::sess(cx);
137            self.msrv.check_attributes(attrs);
138        }
139
140        fn check_attributes_post(&mut self, cx: &rustc_lint::EarlyContext<'_>, attrs: &[rustc_ast::ast::Attribute]) {
141            let sess = rustc_lint::LintContext::sess(cx);
142            self.msrv.check_attributes_post(attrs);
143        }
144    };
145}
146
147/// If the given expression is a local binding, find the initializer expression.
148/// If that initializer expression is another local binding, find its initializer again.
149///
150/// This process repeats as long as possible (but usually no more than once). Initializer
151/// expressions with adjustments are ignored. If this is not desired, use [`find_binding_init`]
152/// instead.
153///
154/// Examples:
155/// ```no_run
156/// let abc = 1;
157/// //        ^ output
158/// let def = abc;
159/// dbg!(def);
160/// //   ^^^ input
161///
162/// // or...
163/// let abc = 1;
164/// let def = abc + 2;
165/// //        ^^^^^^^ output
166/// dbg!(def);
167/// //   ^^^ input
168/// ```
169pub fn expr_or_init<'a, 'b, 'tcx: 'b>(cx: &LateContext<'tcx>, mut expr: &'a Expr<'b>) -> &'a Expr<'b> {
170    while let Some(init) = expr
171        .res_local_id()
172        .and_then(|id| find_binding_init(cx, id))
173        .filter(|init| cx.typeck_results().expr_adjustments(init).is_empty())
174    {
175        expr = init;
176    }
177    expr
178}
179
180/// Finds the initializer expression for a local binding. Returns `None` if the binding is mutable.
181///
182/// By only considering immutable bindings, we guarantee that the returned expression represents the
183/// value of the binding wherever it is referenced.
184///
185/// Example: For `let x = 1`, if the `HirId` of `x` is provided, the `Expr` `1` is returned.
186/// Note: If you have an expression that references a binding `x`, use `path_to_local` to get the
187/// canonical binding `HirId`.
188pub fn find_binding_init<'tcx>(cx: &LateContext<'tcx>, hir_id: HirId) -> Option<&'tcx Expr<'tcx>> {
189    if let Node::Pat(pat) = cx.tcx.hir_node(hir_id)
190        && matches!(pat.kind, PatKind::Binding(BindingMode::NONE, ..))
191        && let Node::LetStmt(local) = cx.tcx.parent_hir_node(hir_id)
192    {
193        return local.init;
194    }
195    None
196}
197
198/// Checks if the given local has an initializer or is from something other than a `let` statement
199///
200/// e.g. returns true for `x` in `fn f(x: usize) { .. }` and `let x = 1;` but false for `let x;`
201pub fn local_is_initialized(cx: &LateContext<'_>, local: HirId) -> bool {
202    for (_, node) in cx.tcx.hir_parent_iter(local) {
203        match node {
204            Node::Pat(..) | Node::PatField(..) => {},
205            Node::LetStmt(let_stmt) => return let_stmt.init.is_some(),
206            _ => return true,
207        }
208    }
209
210    false
211}
212
213/// Checks if we are currently in a const context (e.g. `const fn`, `static`/`const` initializer).
214///
215/// The current context is determined based on the current body which is set before calling a lint's
216/// entry point (any function on `LateLintPass`). If you need to check in a different context use
217/// `tcx.hir_is_inside_const_context(_)`.
218///
219/// Do not call this unless the `LateContext` has an enclosing body. For release build this case
220/// will safely return `false`, but debug builds will ICE. Note that `check_expr`, `check_block`,
221/// `check_pat` and a few other entry points will always have an enclosing body. Some entry points
222/// like `check_path` or `check_ty` may or may not have one.
223pub fn is_in_const_context(cx: &LateContext<'_>) -> bool {
224    debug_assert!(cx.enclosing_body.is_some(), "`LateContext` has no enclosing body");
225    cx.enclosing_body.is_some_and(|id| {
226        cx.tcx
227            .hir_body_const_context(cx.tcx.hir_body_owner_def_id(id))
228            .is_some()
229    })
230}
231
232/// Returns `true` if the given `HirId` is inside an always constant context.
233///
234/// This context includes:
235///  * const/static items
236///  * const blocks (or inline consts)
237///  * associated constants
238pub fn is_inside_always_const_context(tcx: TyCtxt<'_>, hir_id: HirId) -> bool {
239    use rustc_hir::ConstContext::{Const, ConstFn, Static};
240    let Some(ctx) = tcx.hir_body_const_context(tcx.hir_enclosing_body_owner(hir_id)) else {
241        return false;
242    };
243    match ctx {
244        ConstFn => false,
245        Static(_)
246        | Const {
247            allow_const_fn_promotion: _,
248        } => true,
249    }
250}
251
252/// Checks if `{ctor_call_id}(...)` is `{enum_item}::{variant_name}(...)`.
253pub fn is_enum_variant_ctor(
254    cx: &LateContext<'_>,
255    enum_item: Symbol,
256    variant_name: Symbol,
257    ctor_call_id: DefId,
258) -> bool {
259    let Some(enum_def_id) = cx.tcx.get_diagnostic_item(enum_item) else {
260        return false;
261    };
262
263    let variants = cx.tcx.adt_def(enum_def_id).variants().iter();
264    variants
265        .filter(|variant| variant.name == variant_name)
266        .filter_map(|variant| variant.ctor.as_ref())
267        .any(|(_, ctor_def_id)| *ctor_def_id == ctor_call_id)
268}
269
270/// Checks if the `DefId` matches the given diagnostic item or it's constructor.
271pub fn is_diagnostic_item_or_ctor(cx: &LateContext<'_>, did: DefId, item: Symbol) -> bool {
272    let did = match cx.tcx.def_kind(did) {
273        DefKind::Ctor(..) => cx.tcx.parent(did),
274        // Constructors for types in external crates seem to have `DefKind::Variant`
275        DefKind::Variant => match cx.tcx.opt_parent(did) {
276            Some(did) if matches!(cx.tcx.def_kind(did), DefKind::Variant) => did,
277            _ => did,
278        },
279        _ => did,
280    };
281
282    cx.tcx.is_diagnostic_item(item, did)
283}
284
285/// Checks if the `DefId` matches the given `LangItem` or it's constructor.
286pub fn is_lang_item_or_ctor(cx: &LateContext<'_>, did: DefId, item: LangItem) -> bool {
287    let did = match cx.tcx.def_kind(did) {
288        DefKind::Ctor(..) => cx.tcx.parent(did),
289        // Constructors for types in external crates seem to have `DefKind::Variant`
290        DefKind::Variant => match cx.tcx.opt_parent(did) {
291            Some(did) if matches!(cx.tcx.def_kind(did), DefKind::Variant) => did,
292            _ => did,
293        },
294        _ => did,
295    };
296
297    cx.tcx.lang_items().get(item) == Some(did)
298}
299
300/// Checks is `expr` is `None`
301pub fn is_none_expr(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
302    expr.basic_res().ctor_parent(cx).is_lang_item(cx, OptionNone)
303}
304
305/// If `expr` is `Some(inner)`, returns `inner`
306pub fn as_some_expr<'tcx>(cx: &LateContext<'_>, expr: &'tcx Expr<'tcx>) -> Option<&'tcx Expr<'tcx>> {
307    if let ExprKind::Call(e, [arg]) = expr.kind
308        && e.basic_res().ctor_parent(cx).is_lang_item(cx, OptionSome)
309    {
310        Some(arg)
311    } else {
312        None
313    }
314}
315
316/// Check if the given `Expr` is an empty block (i.e. `{}`) or not.
317pub fn is_empty_block(expr: &Expr<'_>) -> bool {
318    matches!(
319        expr.kind,
320        ExprKind::Block(
321            Block {
322                stmts: [],
323                expr: None,
324                ..
325            },
326            _,
327        )
328    )
329}
330
331/// Checks if `expr` is an empty block or an empty tuple.
332pub fn is_unit_expr(expr: &Expr<'_>) -> bool {
333    matches!(
334        expr.kind,
335        ExprKind::Block(
336            Block {
337                stmts: [],
338                expr: None,
339                ..
340            },
341            _
342        ) | ExprKind::Tup([])
343    )
344}
345
346/// Checks if given pattern is a wildcard (`_`)
347pub fn is_wild(pat: &Pat<'_>) -> bool {
348    matches!(pat.kind, PatKind::Wild)
349}
350
351/// If `pat` is:
352/// - `Some(inner)`, returns `inner`
353///    - it will _usually_ contain just one element, but could have two, given patterns like `Some(inner, ..)` or
354///      `Some(.., inner)`
355/// - `Some`, returns `[]`
356/// - otherwise, returns `None`
357pub fn as_some_pattern<'a, 'hir>(cx: &LateContext<'_>, pat: &'a Pat<'hir>) -> Option<&'a [Pat<'hir>]> {
358    if let PatKind::TupleStruct(ref qpath, inner, _) = pat.kind
359        && cx
360            .qpath_res(qpath, pat.hir_id)
361            .ctor_parent(cx)
362            .is_lang_item(cx, OptionSome)
363    {
364        Some(inner)
365    } else {
366        None
367    }
368}
369
370/// Checks if the `pat` is `None`.
371pub fn is_none_pattern(cx: &LateContext<'_>, pat: &Pat<'_>) -> bool {
372    matches!(pat.kind,
373        PatKind::Expr(PatExpr { kind: PatExprKind::Path(qpath), .. })
374            if cx.qpath_res(qpath, pat.hir_id).ctor_parent(cx).is_lang_item(cx, OptionNone))
375}
376
377/// Checks if `arm` has the form `None => None`.
378pub fn is_none_arm(cx: &LateContext<'_>, arm: &Arm<'_>) -> bool {
379    is_none_pattern(cx, arm.pat)
380        && matches!(
381            peel_blocks(arm.body).kind,
382            ExprKind::Path(qpath)
383            if cx.qpath_res(&qpath, arm.body.hir_id).ctor_parent(cx).is_lang_item(cx, OptionNone)
384        )
385}
386
387/// Checks if the given `QPath` belongs to a type alias.
388pub fn is_ty_alias(qpath: &QPath<'_>) -> bool {
389    match *qpath {
390        QPath::Resolved(_, path) => matches!(path.res, Res::Def(DefKind::TyAlias | DefKind::AssocTy, ..)),
391        QPath::TypeRelative(ty, _) if let TyKind::Path(qpath) = ty.kind => is_ty_alias(&qpath),
392        QPath::TypeRelative(..) => false,
393    }
394}
395
396/// Checks if the given `Ty` is either an `impl Future` or async coroutine.
397pub fn ty_is_future<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
398    let Some(future_trait) = cx.tcx.lang_items().future_trait() else {
399        return false;
400    };
401
402    match *ty.kind() {
403        rustc_ty::Alias(_, alias) => {
404            if let rustc_ty::AliasTy {
405                kind: rustc_ty::Opaque { def_id },
406                args,
407                ..
408            } = alias
409                && let preds = cx.tcx.explicit_item_self_bounds(def_id)
410                && preds
411                    .iter_instantiated_copied(cx.tcx, args)
412                    .map(rustc_ty::Unnormalized::skip_normalization)
413                    .filter_map(|(p, _)| p.as_trait_clause())
414                    .any(|trait_pred| trait_pred.skip_binder().trait_ref.def_id == future_trait)
415            {
416                true
417            } else {
418                false
419            }
420        },
421        rustc_ty::Coroutine(def_id, _) | rustc_ty::CoroutineWitness(def_id, _) => cx.tcx.coroutine_is_async(def_id),
422        _ => false,
423    }
424}
425
426/// Checks if the `def_id` belongs to a function that is part of a trait impl.
427pub fn is_def_id_trait_method(cx: &LateContext<'_>, def_id: LocalDefId) -> bool {
428    if let Node::Item(item) = cx.tcx.parent_hir_node(cx.tcx.local_def_id_to_hir_id(def_id))
429        && let ItemKind::Impl(imp) = item.kind
430    {
431        imp.of_trait.is_some()
432    } else {
433        false
434    }
435}
436
437pub fn last_path_segment<'tcx>(path: &QPath<'tcx>) -> &'tcx PathSegment<'tcx> {
438    match *path {
439        QPath::Resolved(_, path) => path.segments.last().expect("A path must have at least one segment"),
440        QPath::TypeRelative(_, seg) => seg,
441    }
442}
443
444pub fn qpath_generic_tys<'tcx>(qpath: &QPath<'tcx>) -> impl Iterator<Item = &'tcx hir::Ty<'tcx>> {
445    last_path_segment(qpath)
446        .args
447        .map_or(&[][..], |a| a.args)
448        .iter()
449        .filter_map(|a| match a {
450            GenericArg::Type(ty) => Some(ty.as_unambig_ty()),
451            _ => None,
452        })
453}
454
455/// If the expression is a path to a local (with optional projections),
456/// returns the canonical `HirId` of the local.
457///
458/// For example, `x.field[0].field2` would return the `HirId` of `x`.
459pub fn path_to_local_with_projections(expr: &Expr<'_>) -> Option<HirId> {
460    match expr.kind {
461        ExprKind::Field(recv, _) | ExprKind::Index(recv, _, _) => path_to_local_with_projections(recv),
462        ExprKind::Path(QPath::Resolved(
463            _,
464            Path {
465                res: Res::Local(local), ..
466            },
467        )) => Some(*local),
468        _ => None,
469    }
470}
471
472/// Gets the `hir::TraitRef` of the trait the given method is implemented for.
473///
474/// Use this if you want to find the `TraitRef` of the `Add` trait in this example:
475///
476/// ```no_run
477/// struct Point(isize, isize);
478///
479/// impl std::ops::Add for Point {
480///     type Output = Self;
481///
482///     fn add(self, other: Self) -> Self {
483///         Point(0, 0)
484///     }
485/// }
486/// ```
487pub fn trait_ref_of_method<'tcx>(cx: &LateContext<'tcx>, owner: OwnerId) -> Option<&'tcx TraitRef<'tcx>> {
488    if let Node::Item(item) = cx.tcx.hir_node(cx.tcx.hir_owner_parent(owner))
489        && let ItemKind::Impl(impl_) = &item.kind
490        && let Some(of_trait) = impl_.of_trait
491    {
492        return Some(&of_trait.trait_ref);
493    }
494    None
495}
496
497/// This method will return tuple of projection stack and root of the expression,
498/// used in `can_mut_borrow_both`.
499///
500/// For example, if `e` represents the `v[0].a.b[x]`
501/// this method will return a tuple, composed of a `Vec`
502/// containing the `Expr`s for `v[0], v[0].a, v[0].a.b, v[0].a.b[x]`
503/// and an `Expr` for root of them, `v`
504fn projection_stack<'a, 'hir>(
505    mut e: &'a Expr<'hir>,
506    ctxt: SyntaxContext,
507) -> Option<(Vec<&'a Expr<'hir>>, &'a Expr<'hir>)> {
508    let mut result = vec![];
509    let root = loop {
510        match e.kind {
511            ExprKind::Index(ep, _, _) | ExprKind::Field(ep, _) if e.span.ctxt() == ctxt => {
512                result.push(e);
513                e = ep;
514            },
515            ExprKind::Index(..) | ExprKind::Field(..) => return None,
516            _ => break e,
517        }
518    };
519    result.reverse();
520    Some((result, root))
521}
522
523/// Gets the mutability of the custom deref adjustment, if any.
524pub fn expr_custom_deref_adjustment(cx: &LateContext<'_>, e: &Expr<'_>) -> Option<Mutability> {
525    cx.typeck_results()
526        .expr_adjustments(e)
527        .iter()
528        .find_map(|a| match a.kind {
529            Adjust::Deref(DerefAdjustKind::Overloaded(d)) => Some(Some(d.mutbl)),
530            Adjust::Deref(DerefAdjustKind::Builtin) => None,
531            _ => Some(None),
532        })
533        .and_then(|x| x)
534}
535
536/// Checks if two expressions can be mutably borrowed simultaneously
537/// and they aren't dependent on borrowing same thing twice
538pub fn can_mut_borrow_both(cx: &LateContext<'_>, ctxt: SyntaxContext, e1: &Expr<'_>, e2: &Expr<'_>) -> bool {
539    let Some((s1, r1)) = projection_stack(e1, ctxt) else {
540        return false;
541    };
542    let Some((s2, r2)) = projection_stack(e2, ctxt) else {
543        return false;
544    };
545    if !eq_expr_value(cx, ctxt, r1, r2) {
546        return true;
547    }
548    if expr_custom_deref_adjustment(cx, r1).is_some() || expr_custom_deref_adjustment(cx, r2).is_some() {
549        return false;
550    }
551
552    for (x1, x2) in zip(&s1, &s2) {
553        if expr_custom_deref_adjustment(cx, x1).is_some() || expr_custom_deref_adjustment(cx, x2).is_some() {
554            return false;
555        }
556
557        match (&x1.kind, &x2.kind) {
558            (ExprKind::Field(_, i1), ExprKind::Field(_, i2)) => {
559                if i1 != i2 {
560                    return true;
561                }
562            },
563            _ => return false,
564        }
565    }
566    false
567}
568
569/// Returns true if the `def_id` associated with the `path` is recognized as a "default-equivalent"
570/// constructor from the std library
571fn is_default_equivalent_ctor(cx: &LateContext<'_>, def_id: DefId, path: &QPath<'_>) -> bool {
572    let std_types_symbols = &[
573        sym::Vec,
574        sym::VecDeque,
575        sym::LinkedList,
576        sym::HashMap,
577        sym::BTreeMap,
578        sym::HashSet,
579        sym::BTreeSet,
580        sym::BinaryHeap,
581    ];
582
583    if let QPath::TypeRelative(_, method) = path
584        && method.ident.name == sym::new
585        && let Some(impl_did) = cx.tcx.impl_of_assoc(def_id)
586        && let Some(adt) = cx
587            .tcx
588            .type_of(impl_did)
589            .instantiate_identity()
590            .skip_norm_wip()
591            .ty_adt_def()
592    {
593        return Some(adt.did()) == cx.tcx.lang_items().string()
594            || (cx.tcx.get_diagnostic_name(adt.did())).is_some_and(|adt_name| std_types_symbols.contains(&adt_name));
595    }
596    false
597}
598
599/// Returns true if the expr is equal to `Default::default` when evaluated.
600pub fn is_default_equivalent_call(
601    cx: &LateContext<'_>,
602    repl_func: &Expr<'_>,
603    whole_call_expr: Option<&Expr<'_>>,
604) -> bool {
605    if let ExprKind::Path(ref repl_func_qpath) = repl_func.kind
606        && let Some(repl_def) = cx.qpath_res(repl_func_qpath, repl_func.hir_id).opt_def(cx)
607        && (repl_def.assoc_fn_parent(cx).is_diag_item(cx, sym::Default)
608            || is_default_equivalent_ctor(cx, repl_def.1, repl_func_qpath))
609    {
610        return true;
611    }
612
613    // Get the type of the whole method call expression, find the exact method definition, look at
614    // its body and check if it is similar to the corresponding `Default::default()` body.
615    let Some(e) = whole_call_expr else { return false };
616    let Some(default_fn_def_id) = cx.tcx.get_diagnostic_item(sym::default_fn) else {
617        return false;
618    };
619    let Some(ty) = cx.tcx.typeck(e.hir_id.owner.def_id).expr_ty_adjusted_opt(e) else {
620        return false;
621    };
622    let args = rustc_ty::GenericArgs::for_item(cx.tcx, default_fn_def_id, |param, _| {
623        if let rustc_ty::GenericParamDefKind::Lifetime = param.kind {
624            cx.tcx.lifetimes.re_erased.into()
625        } else if param.index == 0 && param.name == kw::SelfUpper {
626            ty.into()
627        } else {
628            param.to_error(cx.tcx)
629        }
630    });
631    let instance = rustc_ty::Instance::try_resolve(cx.tcx, cx.typing_env(), default_fn_def_id, args);
632
633    let Ok(Some(instance)) = instance else { return false };
634    if let rustc_ty::InstanceKind::Item(def) = instance.def
635        && !cx.tcx.is_mir_available(def)
636    {
637        return false;
638    }
639    let ExprKind::Path(ref repl_func_qpath) = repl_func.kind else {
640        return false;
641    };
642    let Some(repl_def_id) = cx.qpath_res(repl_func_qpath, repl_func.hir_id).opt_def_id() else {
643        return false;
644    };
645
646    // Get the MIR Body for the `<Ty as Default>::default()` function.
647    // If it is a value or call (either fn or ctor), we compare its `DefId` against the one for the
648    // resolution of the expression we had in the path. This lets us identify, for example, that
649    // the body of `<Vec<T> as Default>::default()` is a `Vec::new()`, and the field was being
650    // initialized to `Vec::new()` as well.
651    let body = cx.tcx.instance_mir(instance.def);
652    for block_data in body.basic_blocks.iter() {
653        if block_data.statements.len() == 1
654            && let StatementKind::Assign(assign) = &block_data.statements[0].kind
655            && assign.0.local == RETURN_PLACE
656            && let Rvalue::Aggregate(kind, _places) = &assign.1
657            && let AggregateKind::Adt(did, variant_index, _, _, _) = **kind
658            && let def = cx.tcx.adt_def(did)
659            && let variant = &def.variant(variant_index)
660            && variant.fields.is_empty()
661            && let Some((_, did)) = variant.ctor
662            && did == repl_def_id
663        {
664            return true;
665        } else if block_data.statements.is_empty()
666            && let Some(term) = &block_data.terminator
667        {
668            match &term.kind {
669                TerminatorKind::Call {
670                    func: Operand::Constant(c),
671                    ..
672                } if let rustc_ty::FnDef(did, _args) = c.ty().kind()
673                    && *did == repl_def_id =>
674                {
675                    return true;
676                },
677                TerminatorKind::TailCall {
678                    func: Operand::Constant(c),
679                    ..
680                } if let rustc_ty::FnDef(did, _args) = c.ty().kind()
681                    && *did == repl_def_id =>
682                {
683                    return true;
684                },
685                _ => {},
686            }
687        }
688    }
689    false
690}
691
692/// Returns true if the expr is equal to `Default::default()` of its type when evaluated.
693///
694/// It doesn't cover all cases, like struct literals, but it is a close approximation.
695pub fn is_default_equivalent(cx: &LateContext<'_>, e: &Expr<'_>) -> bool {
696    match &e.kind {
697        ExprKind::Lit(lit) => match lit.node {
698            LitKind::Bool(false) | LitKind::Int(Pu128(0), _) => true,
699            LitKind::Str(s, _) => s.is_empty(),
700            _ => false,
701        },
702        ExprKind::Tup(items) | ExprKind::Array(items) => items.iter().all(|x| is_default_equivalent(cx, x)),
703        ExprKind::Repeat(x, len) => {
704            if let ConstArgKind::Anon(anon_const) = len.kind
705                && let ExprKind::Lit(const_lit) = cx.tcx.hir_body(anon_const.body).value.kind
706                && let LitKind::Int(v, _) = const_lit.node
707                && v <= 32
708                && is_default_equivalent(cx, x)
709            {
710                true
711            } else {
712                false
713            }
714        },
715        ExprKind::Call(repl_func, []) => is_default_equivalent_call(cx, repl_func, Some(e)),
716        ExprKind::Call(from_func, [arg]) => is_default_equivalent_from(cx, from_func, arg),
717        ExprKind::Path(qpath) => cx
718            .qpath_res(qpath, e.hir_id)
719            .ctor_parent(cx)
720            .is_lang_item(cx, OptionNone),
721        ExprKind::AddrOf(rustc_hir::BorrowKind::Ref, _, expr) => matches!(expr.kind, ExprKind::Array([])),
722        ExprKind::Block(Block { stmts: [], expr, .. }, _) => expr.is_some_and(|e| is_default_equivalent(cx, e)),
723        _ => false,
724    }
725}
726
727fn is_default_equivalent_from(cx: &LateContext<'_>, from_func: &Expr<'_>, arg: &Expr<'_>) -> bool {
728    if let ExprKind::Path(QPath::TypeRelative(ty, seg)) = from_func.kind
729        && seg.ident.name == sym::from
730    {
731        match arg.kind {
732            ExprKind::Lit(hir::Lit {
733                node: LitKind::Str(sym, _),
734                ..
735            }) => return sym.is_empty() && ty.basic_res().is_lang_item(cx, LangItem::String),
736            ExprKind::Array([]) => return ty.basic_res().is_diag_item(cx, sym::Vec),
737            ExprKind::Repeat(_, len) => {
738                if let ConstArgKind::Anon(anon_const) = len.kind
739                    && let ExprKind::Lit(const_lit) = cx.tcx.hir_body(anon_const.body).value.kind
740                    && let LitKind::Int(v, _) = const_lit.node
741                {
742                    return v == 0 && ty.basic_res().is_diag_item(cx, sym::Vec);
743                }
744            },
745            _ => (),
746        }
747    }
748    false
749}
750
751/// Checks if the top level expression can be moved into a closure as is.
752/// Currently checks for:
753/// * Break/Continue outside the given loop HIR ids.
754/// * Yield/Return statements.
755/// * Inline assembly.
756/// * Usages of a field of a local where the type of the local can be partially moved.
757///
758/// For example, given the following function:
759///
760/// ```no_run
761/// fn f<'a>(iter: &mut impl Iterator<Item = (usize, &'a mut String)>) {
762///     for item in iter {
763///         let s = item.1;
764///         if item.0 > 10 {
765///             continue;
766///         } else {
767///             s.clear();
768///         }
769///     }
770/// }
771/// ```
772///
773/// When called on the expression `item.0` this will return false unless the local `item` is in the
774/// `ignore_locals` set. The type `(usize, &mut String)` can have the second element moved, so it
775/// isn't always safe to move into a closure when only a single field is needed.
776///
777/// When called on the `continue` expression this will return false unless the outer loop expression
778/// is in the `loop_ids` set.
779///
780/// Note that this check is not recursive, so passing the `if` expression will always return true
781/// even though sub-expressions might return false.
782pub fn can_move_expr_to_closure_no_visit<'tcx>(
783    cx: &LateContext<'tcx>,
784    expr: &'tcx Expr<'_>,
785    loop_ids: &[HirId],
786    ignore_locals: &HirIdSet,
787) -> bool {
788    match expr.kind {
789        ExprKind::Break(Destination { target_id: Ok(id), .. }, _)
790        | ExprKind::Continue(Destination { target_id: Ok(id), .. })
791            if loop_ids.contains(&id) =>
792        {
793            true
794        },
795        ExprKind::Break(..)
796        | ExprKind::Continue(_)
797        | ExprKind::Ret(_)
798        | ExprKind::Yield(..)
799        | ExprKind::InlineAsm(_) => false,
800        // Accessing a field of a local value can only be done if the type isn't
801        // partially moved.
802        ExprKind::Field(
803            &Expr {
804                hir_id,
805                kind:
806                    ExprKind::Path(QPath::Resolved(
807                        _,
808                        Path {
809                            res: Res::Local(local_id),
810                            ..
811                        },
812                    )),
813                ..
814            },
815            _,
816        ) if !ignore_locals.contains(local_id) && can_partially_move_ty(cx, cx.typeck_results().node_type(hir_id)) => {
817            // TODO: check if the local has been partially moved. Assume it has for now.
818            false
819        },
820        _ => true,
821    }
822}
823
824/// How a local is captured by a closure
825#[derive(Debug, Clone, Copy, PartialEq, Eq)]
826pub enum CaptureKind {
827    Value,
828    Use,
829    Ref(Mutability),
830}
831impl CaptureKind {
832    pub fn is_imm_ref(self) -> bool {
833        self == Self::Ref(Mutability::Not)
834    }
835}
836impl std::ops::BitOr for CaptureKind {
837    type Output = Self;
838    fn bitor(self, rhs: Self) -> Self::Output {
839        match (self, rhs) {
840            (CaptureKind::Value, _) | (_, CaptureKind::Value) => CaptureKind::Value,
841            (CaptureKind::Use, _) | (_, CaptureKind::Use) => CaptureKind::Use,
842            (CaptureKind::Ref(Mutability::Mut), CaptureKind::Ref(_))
843            | (CaptureKind::Ref(_), CaptureKind::Ref(Mutability::Mut)) => CaptureKind::Ref(Mutability::Mut),
844            (CaptureKind::Ref(Mutability::Not), CaptureKind::Ref(Mutability::Not)) => CaptureKind::Ref(Mutability::Not),
845        }
846    }
847}
848impl std::ops::BitOrAssign for CaptureKind {
849    fn bitor_assign(&mut self, rhs: Self) {
850        *self = *self | rhs;
851    }
852}
853
854/// Given an expression referencing a local, determines how it would be captured in a closure.
855///
856/// Note as this will walk up to parent expressions until the capture can be determined it should
857/// only be used while making a closure somewhere a value is consumed. e.g. a block, match arm, or
858/// function argument (other than a receiver).
859pub fn capture_local_usage(cx: &LateContext<'_>, e: &Expr<'_>) -> CaptureKind {
860    fn pat_capture_kind(cx: &LateContext<'_>, pat: &Pat<'_>) -> CaptureKind {
861        let mut capture = CaptureKind::Ref(Mutability::Not);
862        pat.each_binding_or_first(&mut |_, id, span, _| match cx
863            .typeck_results()
864            .extract_binding_mode(cx.sess(), id, span)
865            .0
866        {
867            ByRef::No if !is_copy(cx, cx.typeck_results().node_type(id)) => {
868                capture = CaptureKind::Value;
869            },
870            ByRef::Yes(_, Mutability::Mut) if capture != CaptureKind::Value => {
871                capture = CaptureKind::Ref(Mutability::Mut);
872            },
873            _ => (),
874        });
875        capture
876    }
877
878    debug_assert!(matches!(
879        e.kind,
880        ExprKind::Path(QPath::Resolved(None, Path { res: Res::Local(_), .. }))
881    ));
882
883    let mut capture = CaptureKind::Value;
884    let mut capture_expr_ty = e;
885
886    for (parent, child_id) in hir_parent_with_src_iter(cx.tcx, e.hir_id) {
887        if let [
888            Adjustment {
889                kind: Adjust::Deref(_) | Adjust::Borrow(AutoBorrow::Ref(..)),
890                target,
891            },
892            ref adjust @ ..,
893        ] = *cx
894            .typeck_results()
895            .adjustments()
896            .get(child_id)
897            .map_or(&[][..], |x| &**x)
898            && let rustc_ty::RawPtr(_, mutability) | rustc_ty::Ref(_, _, mutability) =
899                *adjust.last().map_or(target, |a| a.target).kind()
900        {
901            return CaptureKind::Ref(mutability);
902        }
903
904        match parent {
905            Node::Expr(e) => match e.kind {
906                ExprKind::AddrOf(_, mutability, _) => return CaptureKind::Ref(mutability),
907                ExprKind::Index(..) | ExprKind::Unary(UnOp::Deref, _) => capture = CaptureKind::Ref(Mutability::Not),
908                ExprKind::Assign(lhs, ..) | ExprKind::AssignOp(_, lhs, _) if lhs.hir_id == child_id => {
909                    return CaptureKind::Ref(Mutability::Mut);
910                },
911                ExprKind::Field(..) => {
912                    if capture == CaptureKind::Value {
913                        capture_expr_ty = e;
914                    }
915                },
916                ExprKind::Let(let_expr) => {
917                    let mutability = match pat_capture_kind(cx, let_expr.pat) {
918                        CaptureKind::Value | CaptureKind::Use => Mutability::Not,
919                        CaptureKind::Ref(m) => m,
920                    };
921                    return CaptureKind::Ref(mutability);
922                },
923                ExprKind::Match(_, arms, _) => {
924                    let mut mutability = Mutability::Not;
925                    for capture in arms.iter().map(|arm| pat_capture_kind(cx, arm.pat)) {
926                        match capture {
927                            CaptureKind::Value | CaptureKind::Use => break,
928                            CaptureKind::Ref(Mutability::Mut) => mutability = Mutability::Mut,
929                            CaptureKind::Ref(Mutability::Not) => (),
930                        }
931                    }
932                    return CaptureKind::Ref(mutability);
933                },
934                _ => break,
935            },
936            Node::LetStmt(l) => match pat_capture_kind(cx, l.pat) {
937                CaptureKind::Value | CaptureKind::Use => break,
938                capture @ CaptureKind::Ref(_) => return capture,
939            },
940            _ => break,
941        }
942    }
943
944    if capture == CaptureKind::Value && is_copy(cx, cx.typeck_results().expr_ty(capture_expr_ty)) {
945        // Copy types are never automatically captured by value.
946        CaptureKind::Ref(Mutability::Not)
947    } else {
948        capture
949    }
950}
951
952/// Checks if the expression can be moved into a closure as is. This will return a list of captures
953/// if so, otherwise, `None`.
954pub fn can_move_expr_to_closure<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> Option<HirIdMap<CaptureKind>> {
955    struct V<'cx, 'tcx> {
956        cx: &'cx LateContext<'tcx>,
957        // Stack of potential break targets contained in the expression.
958        loops: Vec<HirId>,
959        /// Local variables created in the expression. These don't need to be captured.
960        locals: HirIdSet,
961        /// Whether this expression can be turned into a closure.
962        allow_closure: bool,
963        /// Locals which need to be captured, and whether they need to be by value, reference, or
964        /// mutable reference.
965        captures: HirIdMap<CaptureKind>,
966    }
967    impl<'tcx> Visitor<'tcx> for V<'_, 'tcx> {
968        fn visit_expr(&mut self, e: &'tcx Expr<'_>) {
969            if !self.allow_closure {
970                return;
971            }
972
973            match e.kind {
974                ExprKind::Path(QPath::Resolved(None, &Path { res: Res::Local(l), .. })) => {
975                    if !self.locals.contains(&l) {
976                        let cap = capture_local_usage(self.cx, e);
977                        self.captures.entry(l).and_modify(|e| *e |= cap).or_insert(cap);
978                    }
979                },
980                ExprKind::Closure(closure) => {
981                    for capture in self.cx.typeck_results().closure_min_captures_flattened(closure.def_id) {
982                        let local_id = match capture.place.base {
983                            PlaceBase::Local(id) => id,
984                            PlaceBase::Upvar(var) => var.var_path.hir_id,
985                            _ => continue,
986                        };
987                        if !self.locals.contains(&local_id) {
988                            let capture = match capture.info.capture_kind {
989                                UpvarCapture::ByValue => CaptureKind::Value,
990                                UpvarCapture::ByUse => CaptureKind::Use,
991                                UpvarCapture::ByRef(kind) => match kind {
992                                    BorrowKind::Immutable => CaptureKind::Ref(Mutability::Not),
993                                    BorrowKind::UniqueImmutable | BorrowKind::Mutable => {
994                                        CaptureKind::Ref(Mutability::Mut)
995                                    },
996                                },
997                            };
998                            self.captures
999                                .entry(local_id)
1000                                .and_modify(|e| *e |= capture)
1001                                .or_insert(capture);
1002                        }
1003                    }
1004                },
1005                ExprKind::Loop(b, ..) => {
1006                    self.loops.push(e.hir_id);
1007                    self.visit_block(b);
1008                    self.loops.pop();
1009                },
1010                _ => {
1011                    self.allow_closure &= can_move_expr_to_closure_no_visit(self.cx, e, &self.loops, &self.locals);
1012                    walk_expr(self, e);
1013                },
1014            }
1015        }
1016
1017        fn visit_pat(&mut self, p: &'tcx Pat<'tcx>) {
1018            p.each_binding_or_first(&mut |_, id, _, _| {
1019                self.locals.insert(id);
1020            });
1021        }
1022    }
1023
1024    let mut v = V {
1025        cx,
1026        loops: Vec::new(),
1027        locals: HirIdSet::default(),
1028        allow_closure: true,
1029        captures: HirIdMap::default(),
1030    };
1031    v.visit_expr(expr);
1032    v.allow_closure.then_some(v.captures)
1033}
1034
1035/// Arguments of a method: the receiver and all the additional arguments.
1036pub type MethodArguments<'tcx> = Vec<(&'tcx Expr<'tcx>, &'tcx [Expr<'tcx>])>;
1037
1038/// Returns the method names and argument list of nested method call expressions that make up
1039/// `expr`. method/span lists are sorted with the most recent call first.
1040pub fn method_calls<'tcx>(expr: &'tcx Expr<'tcx>, max_depth: usize) -> (Vec<Symbol>, MethodArguments<'tcx>, Vec<Span>) {
1041    let mut method_names = Vec::with_capacity(max_depth);
1042    let mut arg_lists = Vec::with_capacity(max_depth);
1043    let mut spans = Vec::with_capacity(max_depth);
1044
1045    let mut current = expr;
1046    for _ in 0..max_depth {
1047        if let ExprKind::MethodCall(path, receiver, args, _) = &current.kind {
1048            if receiver.span.from_expansion() || args.iter().any(|e| e.span.from_expansion()) {
1049                break;
1050            }
1051            method_names.push(path.ident.name);
1052            arg_lists.push((*receiver, &**args));
1053            spans.push(path.ident.span);
1054            current = receiver;
1055        } else {
1056            break;
1057        }
1058    }
1059
1060    (method_names, arg_lists, spans)
1061}
1062
1063/// Matches an `Expr` against a chain of methods, and return the matched `Expr`s.
1064///
1065/// For example, if `expr` represents the `.baz()` in `foo.bar().baz()`,
1066/// `method_chain_args(expr, &[sym::bar, sym::baz])` will return a `Vec`
1067/// containing the `Expr`s for
1068/// `.bar()` and `.baz()`
1069pub fn method_chain_args<'a>(expr: &'a Expr<'_>, methods: &[Symbol]) -> Option<Vec<(&'a Expr<'a>, &'a [Expr<'a>])>> {
1070    let mut current = expr;
1071    let mut matched = Vec::with_capacity(methods.len());
1072    for method_name in methods.iter().rev() {
1073        // method chains are stored last -> first
1074        if let ExprKind::MethodCall(path, receiver, args, _) = current.kind {
1075            if path.ident.name == *method_name {
1076                if receiver.span.from_expansion() || args.iter().any(|e| e.span.from_expansion()) {
1077                    return None;
1078                }
1079                matched.push((receiver, args)); // build up `matched` backwards
1080                current = receiver; // go to parent expression
1081            } else {
1082                return None;
1083            }
1084        } else {
1085            return None;
1086        }
1087    }
1088    // Reverse `matched` so that it is in the same order as `methods`.
1089    matched.reverse();
1090    Some(matched)
1091}
1092
1093/// Returns `true` if the provided `def_id` is an entrypoint to a program.
1094pub fn is_entrypoint_fn(cx: &LateContext<'_>, def_id: DefId) -> bool {
1095    cx.tcx
1096        .entry_fn(())
1097        .is_some_and(|(entry_fn_def_id, _)| def_id == entry_fn_def_id)
1098}
1099
1100/// Returns `true` if the expression is in the program's `#[panic_handler]`.
1101pub fn is_in_panic_handler(cx: &LateContext<'_>, e: &Expr<'_>) -> bool {
1102    let parent = cx.tcx.hir_get_parent_item(e.hir_id);
1103    Some(parent.to_def_id()) == cx.tcx.lang_items().panic_impl()
1104}
1105
1106/// Gets the name of the item the expression is in, if available.
1107pub fn parent_item_name(cx: &LateContext<'_>, expr: &Expr<'_>) -> Option<Symbol> {
1108    let parent_id = cx.tcx.hir_get_parent_item(expr.hir_id).def_id;
1109    match cx.tcx.hir_node_by_def_id(parent_id) {
1110        Node::Item(item) => item.kind.ident().map(|ident| ident.name),
1111        Node::TraitItem(TraitItem { ident, .. }) | Node::ImplItem(ImplItem { ident, .. }) => Some(ident.name),
1112        _ => None,
1113    }
1114}
1115
1116pub struct ContainsName<'a, 'tcx> {
1117    pub cx: &'a LateContext<'tcx>,
1118    pub name: Symbol,
1119}
1120
1121impl<'tcx> Visitor<'tcx> for ContainsName<'_, 'tcx> {
1122    type Result = ControlFlow<()>;
1123    type NestedFilter = nested_filter::OnlyBodies;
1124
1125    fn visit_name(&mut self, name: Symbol) -> Self::Result {
1126        if self.name == name {
1127            ControlFlow::Break(())
1128        } else {
1129            ControlFlow::Continue(())
1130        }
1131    }
1132
1133    fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
1134        self.cx.tcx
1135    }
1136}
1137
1138/// Checks if an `Expr` contains a certain name.
1139pub fn contains_name<'tcx>(name: Symbol, expr: &'tcx Expr<'_>, cx: &LateContext<'tcx>) -> bool {
1140    let mut cn = ContainsName { cx, name };
1141    cn.visit_expr(expr).is_break()
1142}
1143
1144/// Returns `true` if `expr` contains a return expression
1145pub fn contains_return<'tcx>(expr: impl Visitable<'tcx>) -> bool {
1146    for_each_expr_without_closures(expr, |e| {
1147        if matches!(e.kind, ExprKind::Ret(..)) {
1148            ControlFlow::Break(())
1149        } else {
1150            ControlFlow::Continue(())
1151        }
1152    })
1153    .is_some()
1154}
1155
1156/// Gets the parent expression, if any –- this is useful to constrain a lint.
1157pub fn get_parent_expr<'tcx>(cx: &LateContext<'tcx>, e: &Expr<'_>) -> Option<&'tcx Expr<'tcx>> {
1158    get_parent_expr_for_hir(cx, e.hir_id)
1159}
1160
1161/// This retrieves the parent for the given `HirId` if it's an expression. This is useful for
1162/// constraint lints
1163pub fn get_parent_expr_for_hir<'tcx>(cx: &LateContext<'tcx>, hir_id: HirId) -> Option<&'tcx Expr<'tcx>> {
1164    match cx.tcx.parent_hir_node(hir_id) {
1165        Node::Expr(parent) => Some(parent),
1166        _ => None,
1167    }
1168}
1169
1170/// Gets the enclosing block, if any.
1171pub fn get_enclosing_block<'tcx>(cx: &LateContext<'tcx>, hir_id: HirId) -> Option<&'tcx Block<'tcx>> {
1172    let enclosing_node = cx
1173        .tcx
1174        .hir_get_enclosing_scope(hir_id)
1175        .map(|enclosing_id| cx.tcx.hir_node(enclosing_id));
1176    enclosing_node.and_then(|node| match node {
1177        Node::Block(block) => Some(block),
1178        Node::Item(&Item {
1179            kind: ItemKind::Fn { body: eid, .. },
1180            ..
1181        })
1182        | Node::ImplItem(&ImplItem {
1183            kind: ImplItemKind::Fn(_, eid),
1184            ..
1185        })
1186        | Node::TraitItem(&TraitItem {
1187            kind: TraitItemKind::Fn(_, TraitFn::Provided(eid)),
1188            ..
1189        }) => match cx.tcx.hir_body(eid).value.kind {
1190            ExprKind::Block(block, _) => Some(block),
1191            _ => None,
1192        },
1193        _ => None,
1194    })
1195}
1196
1197/// Returns the [`Closure`] enclosing `hir_id`, if any.
1198pub fn get_enclosing_closure<'tcx>(cx: &LateContext<'tcx>, hir_id: HirId) -> Option<&'tcx Closure<'tcx>> {
1199    cx.tcx.hir_parent_iter(hir_id).find_map(|(_, node)| {
1200        if let Node::Expr(expr) = node
1201            && let ExprKind::Closure(closure) = expr.kind
1202        {
1203            Some(closure)
1204        } else {
1205            None
1206        }
1207    })
1208}
1209
1210/// Checks whether a local identified by `local_id` is captured as an upvar by the given `closure`.
1211pub fn is_upvar_in_closure(cx: &LateContext<'_>, closure: &Closure<'_>, local_id: HirId) -> bool {
1212    cx.typeck_results()
1213        .closure_min_captures
1214        .get(&closure.def_id)
1215        .is_some_and(|x| x.contains_key(&local_id))
1216}
1217
1218/// Gets the loop or closure enclosing the given expression, if any.
1219pub fn get_enclosing_loop_or_multi_call_closure<'tcx>(
1220    cx: &LateContext<'tcx>,
1221    expr: &Expr<'_>,
1222) -> Option<&'tcx Expr<'tcx>> {
1223    for (_, node) in cx.tcx.hir_parent_iter(expr.hir_id) {
1224        match node {
1225            Node::Expr(e) => match e.kind {
1226                ExprKind::Closure { .. }
1227                    if let rustc_ty::Closure(_, subs) = cx.typeck_results().expr_ty(e).kind()
1228                        && subs.as_closure().kind() == ClosureKind::FnOnce => {},
1229
1230                // Note: A closure's kind is determined by how it's used, not it's captures.
1231                ExprKind::Closure { .. } | ExprKind::Loop(..) => return Some(e),
1232                _ => (),
1233            },
1234            Node::Stmt(_) | Node::Block(_) | Node::LetStmt(_) | Node::Arm(_) | Node::ExprField(_) => (),
1235            _ => break,
1236        }
1237    }
1238    None
1239}
1240
1241/// Gets the parent node if it's an impl block.
1242pub fn get_parent_as_impl(tcx: TyCtxt<'_>, id: HirId) -> Option<&Impl<'_>> {
1243    match tcx.hir_parent_iter(id).next() {
1244        Some((
1245            _,
1246            Node::Item(Item {
1247                kind: ItemKind::Impl(imp),
1248                ..
1249            }),
1250        )) => Some(imp),
1251        _ => None,
1252    }
1253}
1254
1255/// Removes blocks around an expression, only if the block contains just one expression
1256/// and no statements. Unsafe blocks are not removed.
1257///
1258/// Examples:
1259///  * `{}`               -> `{}`
1260///  * `{ x }`            -> `x`
1261///  * `{{ x }}`          -> `x`
1262///  * `{ x; }`           -> `{ x; }`
1263///  * `{ x; y }`         -> `{ x; y }`
1264///  * `{ unsafe { x } }` -> `unsafe { x }`
1265pub fn peel_blocks<'a>(mut expr: &'a Expr<'a>) -> &'a Expr<'a> {
1266    while let ExprKind::Block(
1267        Block {
1268            stmts: [],
1269            expr: Some(inner),
1270            rules: BlockCheckMode::DefaultBlock,
1271            ..
1272        },
1273        _,
1274    ) = expr.kind
1275    {
1276        expr = inner;
1277    }
1278    expr
1279}
1280
1281/// Removes blocks around an expression, only if the block contains just one expression
1282/// or just one expression statement with a semicolon. Unsafe blocks are not removed.
1283///
1284/// Examples:
1285///  * `{}`               -> `{}`
1286///  * `{ x }`            -> `x`
1287///  * `{ x; }`           -> `x`
1288///  * `{{ x; }}`         -> `x`
1289///  * `{ x; y }`         -> `{ x; y }`
1290///  * `{ unsafe { x } }` -> `unsafe { x }`
1291pub fn peel_blocks_with_stmt<'a>(mut expr: &'a Expr<'a>) -> &'a Expr<'a> {
1292    while let ExprKind::Block(
1293        Block {
1294            stmts: [],
1295            expr: Some(inner),
1296            rules: BlockCheckMode::DefaultBlock,
1297            ..
1298        }
1299        | Block {
1300            stmts:
1301                [
1302                    Stmt {
1303                        kind: StmtKind::Expr(inner) | StmtKind::Semi(inner),
1304                        ..
1305                    },
1306                ],
1307            expr: None,
1308            rules: BlockCheckMode::DefaultBlock,
1309            ..
1310        },
1311        _,
1312    ) = expr.kind
1313    {
1314        expr = inner;
1315    }
1316    expr
1317}
1318
1319/// Checks if the given expression is the else clause of either an `if` or `if let` expression.
1320pub fn is_else_clause(tcx: TyCtxt<'_>, expr: &Expr<'_>) -> bool {
1321    let mut iter = tcx.hir_parent_iter(expr.hir_id);
1322    match iter.next() {
1323        Some((
1324            _,
1325            Node::Expr(Expr {
1326                kind: ExprKind::If(_, _, Some(else_expr)),
1327                ..
1328            }),
1329        )) => else_expr.hir_id == expr.hir_id,
1330        _ => false,
1331    }
1332}
1333
1334/// Checks if the given expression is a part of `let else`
1335/// returns `true` for both the `init` and the `else` part
1336pub fn is_inside_let_else(tcx: TyCtxt<'_>, expr: &Expr<'_>) -> bool {
1337    hir_parent_with_src_iter(tcx, expr.hir_id).any(|(node, child_id)| {
1338        matches!(
1339            node,
1340            Node::LetStmt(LetStmt {
1341                init: Some(init),
1342                els: Some(els),
1343                ..
1344            })
1345            if init.hir_id == child_id || els.hir_id == child_id
1346        )
1347    })
1348}
1349
1350/// Checks if the given expression is the else clause of a `let else` expression
1351pub fn is_else_clause_in_let_else(tcx: TyCtxt<'_>, expr: &Expr<'_>) -> bool {
1352    hir_parent_with_src_iter(tcx, expr.hir_id).any(|(node, child_id)| {
1353        matches!(
1354            node,
1355            Node::LetStmt(LetStmt { els: Some(els), .. })
1356            if els.hir_id == child_id
1357        )
1358    })
1359}
1360
1361/// Checks whether the given `Expr` is a range over the entire container.
1362pub fn is_full_collection_range(cx: &LateContext<'_>, container: Option<HirId>, expr: &Expr<'_>) -> bool {
1363    if let Some(Range { start, end, ty, .. }) = Range::hir(cx, expr) {
1364        start.is_none_or(|start| is_integer_literal(start, 0))
1365            && end.is_none_or(|end| {
1366                if ty.limits() == RangeLimits::HalfOpen
1367                    && let Some(container) = container
1368                    && let ExprKind::MethodCall(seg, recv, [], _) = end.kind
1369                {
1370                    seg.ident.name == sym::len && recv.res_local_id() == Some(container)
1371                } else {
1372                    false
1373                }
1374            })
1375    } else {
1376        false
1377    }
1378}
1379
1380/// Checks whether the given expression is a constant literal of the given value.
1381pub fn is_integer_literal(expr: &Expr<'_>, value: u128) -> bool {
1382    if let ExprKind::Lit(spanned) = expr.kind
1383        && let LitKind::Int(v, _) = spanned.node
1384    {
1385        return v == value;
1386    }
1387    false
1388}
1389
1390/// Checks whether the given expression is an untyped integer literal.
1391pub fn is_integer_literal_untyped(expr: &Expr<'_>) -> bool {
1392    if let ExprKind::Lit(spanned) = expr.kind
1393        && let LitKind::Int(_, suffix) = spanned.node
1394    {
1395        return suffix == LitIntType::Unsuffixed;
1396    }
1397
1398    false
1399}
1400
1401/// Checks whether the given expression is a constant literal of the given value.
1402pub fn is_float_literal(expr: &Expr<'_>, value: f64) -> bool {
1403    if let ExprKind::Lit(spanned) = expr.kind
1404        && let LitKind::Float(v, _) = spanned.node
1405    {
1406        v.as_str().parse() == Ok(value)
1407    } else {
1408        false
1409    }
1410}
1411
1412/// Returns `true` if the given `Expr` has been coerced before.
1413///
1414/// Examples of coercions can be found in the Nomicon at
1415/// <https://doc.rust-lang.org/nomicon/coercions.html>.
1416///
1417/// See `rustc_middle::ty::adjustment::Adjustment` and `rustc_hir_analysis::check::coercion` for
1418/// more information on adjustments and coercions.
1419pub fn is_adjusted(cx: &LateContext<'_>, e: &Expr<'_>) -> bool {
1420    cx.typeck_results().adjustments().get(e.hir_id).is_some()
1421}
1422
1423/// Returns the pre-expansion span if this comes from an expansion of the
1424/// macro `name`.
1425/// See also [`is_direct_expn_of`].
1426#[must_use]
1427pub fn is_expn_of(mut span: Span, name: Symbol) -> Option<Span> {
1428    loop {
1429        if span.from_expansion() {
1430            let data = span.ctxt().outer_expn_data();
1431            let new_span = data.call_site;
1432
1433            if let ExpnKind::Macro(MacroKind::Bang, mac_name) = data.kind
1434                && mac_name == name
1435            {
1436                return Some(new_span);
1437            }
1438
1439            span = new_span;
1440        } else {
1441            return None;
1442        }
1443    }
1444}
1445
1446/// Returns the pre-expansion span if the span directly comes from an expansion
1447/// of the macro `name`.
1448/// The difference with [`is_expn_of`] is that in
1449/// ```no_run
1450/// # macro_rules! foo { ($name:tt!$args:tt) => { $name!$args } }
1451/// # macro_rules! bar { ($e:expr) => { $e } }
1452/// foo!(bar!(42));
1453/// ```
1454/// `42` is considered expanded from `foo!` and `bar!` by `is_expn_of` but only
1455/// from `bar!` by `is_direct_expn_of`.
1456#[must_use]
1457pub fn is_direct_expn_of(span: Span, name: Symbol) -> Option<Span> {
1458    if span.from_expansion() {
1459        let data = span.ctxt().outer_expn_data();
1460        let new_span = data.call_site;
1461
1462        if let ExpnKind::Macro(MacroKind::Bang, mac_name) = data.kind
1463            && mac_name == name
1464        {
1465            return Some(new_span);
1466        }
1467    }
1468
1469    None
1470}
1471
1472/// Convenience function to get the return type of a function.
1473pub fn return_ty<'tcx>(cx: &LateContext<'tcx>, fn_def_id: OwnerId) -> Ty<'tcx> {
1474    let ret_ty = cx.tcx.fn_sig(fn_def_id).instantiate_identity().skip_norm_wip().output();
1475    cx.tcx.instantiate_bound_regions_with_erased(ret_ty)
1476}
1477
1478/// Convenience function to get the nth argument type of a function.
1479pub fn nth_arg<'tcx>(cx: &LateContext<'tcx>, fn_def_id: OwnerId, nth: usize) -> Ty<'tcx> {
1480    let arg = cx
1481        .tcx
1482        .fn_sig(fn_def_id)
1483        .instantiate_identity()
1484        .skip_norm_wip()
1485        .input(nth);
1486    cx.tcx.instantiate_bound_regions_with_erased(arg)
1487}
1488
1489/// Checks if an expression is constructing a tuple-like enum variant or struct
1490pub fn is_ctor_or_promotable_const_function(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
1491    if let ExprKind::Call(fun, _) = expr.kind
1492        && let ExprKind::Path(ref qp) = fun.kind
1493    {
1494        let res = cx.qpath_res(qp, fun.hir_id);
1495        return match res {
1496            Res::Def(DefKind::Variant | DefKind::Ctor(..), ..) => true,
1497            Res::Def(_, def_id) => cx.tcx.is_promotable_const_fn(def_id),
1498            _ => false,
1499        };
1500    }
1501    false
1502}
1503
1504/// Returns `true` if a pattern is refutable.
1505// TODO: should be implemented using rustc/mir_build/thir machinery
1506pub fn is_refutable(cx: &LateContext<'_>, pat: &Pat<'_>) -> bool {
1507    fn is_qpath_refutable(cx: &LateContext<'_>, qpath: &QPath<'_>, id: HirId) -> bool {
1508        !matches!(
1509            cx.qpath_res(qpath, id),
1510            Res::Def(DefKind::Struct, ..) | Res::Def(DefKind::Ctor(def::CtorOf::Struct, _), _)
1511        )
1512    }
1513
1514    fn are_refutable<'a, I: IntoIterator<Item = &'a Pat<'a>>>(cx: &LateContext<'_>, i: I) -> bool {
1515        i.into_iter().any(|pat| is_refutable(cx, pat))
1516    }
1517
1518    match pat.kind {
1519        PatKind::Missing => unreachable!(),
1520        PatKind::Wild | PatKind::Never => false, // If `!` typechecked then the type is empty, so not refutable.
1521        PatKind::Binding(_, _, _, pat) => pat.is_some_and(|pat| is_refutable(cx, pat)),
1522        PatKind::Ref(pat, _, _) => is_refutable(cx, pat),
1523        PatKind::Expr(PatExpr {
1524            kind: PatExprKind::Path(qpath),
1525            hir_id,
1526            ..
1527        }) => is_qpath_refutable(cx, qpath, *hir_id),
1528        PatKind::Or(pats) => {
1529            // TODO: should be the honest check, that pats is exhaustive set
1530            are_refutable(cx, pats)
1531        },
1532        PatKind::Tuple(pats, _) => are_refutable(cx, pats),
1533        PatKind::Struct(ref qpath, fields, _) => {
1534            is_qpath_refutable(cx, qpath, pat.hir_id) || are_refutable(cx, fields.iter().map(|field| field.pat))
1535        },
1536        PatKind::TupleStruct(ref qpath, pats, _) => {
1537            is_qpath_refutable(cx, qpath, pat.hir_id) || are_refutable(cx, pats)
1538        },
1539        PatKind::Slice(head, middle, tail) => {
1540            match &cx.typeck_results().node_type(pat.hir_id).kind() {
1541                rustc_ty::Slice(..) => {
1542                    // [..] is the only irrefutable slice pattern.
1543                    !head.is_empty() || middle.is_none() || !tail.is_empty()
1544                },
1545                rustc_ty::Array(..) => are_refutable(cx, head.iter().chain(middle).chain(tail.iter())),
1546                _ => {
1547                    // unreachable!()
1548                    true
1549                },
1550            }
1551        },
1552        PatKind::Expr(..) | PatKind::Range(..) | PatKind::Err(_) | PatKind::Deref(_) | PatKind::Guard(..) => true,
1553    }
1554}
1555
1556/// If the pattern is an `or` pattern, call the function once for each sub pattern. Otherwise, call
1557/// the function once on the given pattern.
1558pub fn recurse_or_patterns<'tcx, F: FnMut(&'tcx Pat<'tcx>)>(pat: &'tcx Pat<'tcx>, mut f: F) {
1559    if let PatKind::Or(pats) = pat.kind {
1560        pats.iter().for_each(f);
1561    } else {
1562        f(pat);
1563    }
1564}
1565
1566pub fn is_self(slf: &Param<'_>) -> bool {
1567    if let PatKind::Binding(.., name, _) = slf.pat.kind {
1568        name.name == kw::SelfLower
1569    } else {
1570        false
1571    }
1572}
1573
1574pub fn is_self_ty(slf: &hir::Ty<'_>) -> bool {
1575    if let TyKind::Path(QPath::Resolved(None, path)) = slf.kind
1576        && let Res::SelfTyParam { .. } | Res::SelfTyAlias { .. } = path.res
1577    {
1578        return true;
1579    }
1580    false
1581}
1582
1583pub fn iter_input_pats<'tcx>(decl: &FnDecl<'_>, body: &'tcx Body<'_>) -> impl Iterator<Item = &'tcx Param<'tcx>> {
1584    (0..decl.inputs.len()).map(move |i| &body.params[i])
1585}
1586
1587/// Checks if a given expression is a match expression expanded from the `?`
1588/// operator or the `try` macro.
1589pub fn is_try<'tcx>(cx: &LateContext<'_>, expr: &'tcx Expr<'tcx>) -> Option<&'tcx Expr<'tcx>> {
1590    fn is_ok(cx: &LateContext<'_>, arm: &Arm<'_>) -> bool {
1591        if let PatKind::TupleStruct(ref path, pat, ddpos) = arm.pat.kind
1592            && ddpos.as_opt_usize().is_none()
1593            && cx
1594                .qpath_res(path, arm.pat.hir_id)
1595                .ctor_parent(cx)
1596                .is_lang_item(cx, ResultOk)
1597            && let PatKind::Binding(_, hir_id, _, None) = pat[0].kind
1598            && arm.body.res_local_id() == Some(hir_id)
1599        {
1600            return true;
1601        }
1602        false
1603    }
1604
1605    fn is_err(cx: &LateContext<'_>, arm: &Arm<'_>) -> bool {
1606        if let PatKind::TupleStruct(ref path, _, _) = arm.pat.kind {
1607            cx.qpath_res(path, arm.pat.hir_id)
1608                .ctor_parent(cx)
1609                .is_lang_item(cx, ResultErr)
1610        } else {
1611            false
1612        }
1613    }
1614
1615    if let ExprKind::Match(_, arms, ref source) = expr.kind {
1616        // desugared from a `?` operator
1617        if let MatchSource::TryDesugar(_) = *source {
1618            return Some(expr);
1619        }
1620
1621        if arms.len() == 2
1622            && arms[0].guard.is_none()
1623            && arms[1].guard.is_none()
1624            && ((is_ok(cx, &arms[0]) && is_err(cx, &arms[1])) || (is_ok(cx, &arms[1]) && is_err(cx, &arms[0])))
1625        {
1626            return Some(expr);
1627        }
1628    }
1629
1630    None
1631}
1632
1633/// Returns `true` if the lint is `#[allow]`ed or `#[expect]`ed at any of the `ids`, fulfilling all
1634/// of the expectations in `ids`
1635///
1636/// This should only be used when the lint would otherwise be emitted, for a way to check if a lint
1637/// is allowed early to skip work see [`is_lint_allowed`]
1638///
1639/// To emit at a lint at a different context than the one current see
1640/// [`span_lint_hir`](diagnostics::span_lint_hir) or
1641/// [`span_lint_hir_and_then`](diagnostics::span_lint_hir_and_then)
1642pub fn fulfill_or_allowed(cx: &LateContext<'_>, lint: &'static Lint, ids: impl IntoIterator<Item = HirId>) -> bool {
1643    let mut suppress_lint = false;
1644
1645    for id in ids {
1646        let level_spec = cx.tcx.lint_level_spec_at_node(lint, id);
1647        if let Some(expectation) = level_spec.lint_id() {
1648            cx.fulfill_expectation(expectation);
1649        }
1650
1651        match level_spec.level() {
1652            Level::Allow | Level::Expect => suppress_lint = true,
1653            Level::Warn | Level::ForceWarn | Level::Deny | Level::Forbid => {},
1654        }
1655    }
1656
1657    suppress_lint
1658}
1659
1660/// Returns `true` if the lint is allowed in the current context. This is useful for
1661/// skipping long running code when it's unnecessary
1662///
1663/// This function should check the lint level for the same node, that the lint will
1664/// be emitted at. If the information is buffered to be emitted at a later point, please
1665/// make sure to use `span_lint_hir` functions to emit the lint. This ensures that
1666/// expectations at the checked nodes will be fulfilled.
1667pub fn is_lint_allowed(cx: &LateContext<'_>, lint: &'static Lint, id: HirId) -> bool {
1668    cx.tcx.lint_level_spec_at_node(lint, id).is_allow()
1669}
1670
1671pub fn strip_pat_refs<'hir>(mut pat: &'hir Pat<'hir>) -> &'hir Pat<'hir> {
1672    while let PatKind::Ref(subpat, _, _) = pat.kind {
1673        pat = subpat;
1674    }
1675    pat
1676}
1677
1678pub fn int_bits(tcx: TyCtxt<'_>, ity: IntTy) -> u64 {
1679    Integer::from_int_ty(&tcx, ity).size().bits()
1680}
1681
1682#[expect(clippy::cast_possible_wrap)]
1683/// Turn a constant int byte representation into an i128
1684pub fn sext(tcx: TyCtxt<'_>, u: u128, ity: IntTy) -> i128 {
1685    let amt = 128 - int_bits(tcx, ity);
1686    ((u as i128) << amt) >> amt
1687}
1688
1689#[expect(clippy::cast_sign_loss)]
1690/// clip unused bytes
1691pub fn unsext(tcx: TyCtxt<'_>, u: i128, ity: IntTy) -> u128 {
1692    let amt = 128 - int_bits(tcx, ity);
1693    ((u as u128) << amt) >> amt
1694}
1695
1696/// clip unused bytes
1697pub fn clip(tcx: TyCtxt<'_>, u: u128, ity: UintTy) -> u128 {
1698    let bits = Integer::from_uint_ty(&tcx, ity).size().bits();
1699    let amt = 128 - bits;
1700    (u << amt) >> amt
1701}
1702
1703pub fn has_repr_attr(cx: &LateContext<'_>, hir_id: HirId) -> bool {
1704    find_attr!(cx.tcx, hir_id, Repr { .. })
1705}
1706
1707/// Checks if the given HIR node is inside an `impl` block with the `automatically_derived`
1708/// attribute.
1709pub fn in_automatically_derived(tcx: TyCtxt<'_>, id: HirId) -> bool {
1710    tcx.hir_parent_owner_iter(id)
1711        .filter(|(_, node)| matches!(node, OwnerNode::Item(item) if matches!(item.kind, ItemKind::Impl(_))))
1712        .any(|(id, _)| find_attr!(tcx, id.def_id, AutomaticallyDerived))
1713}
1714
1715/// Functions marked with these attributes must have an exact signature.
1716pub fn requires_exact_signature(attrs: &[rustc_attr_ir::Attribute]) -> bool {
1717    find_attr!(attrs, ProcMacro | ProcMacroAttribute | ProcMacroDerive { .. })
1718}
1719
1720/// Checks if the given `DefId` matches the `libc` item.
1721pub fn match_libc_symbol(cx: &LateContext<'_>, did: DefId, name: Symbol) -> bool {
1722    // libc is meant to be used as a flat list of names, but they're all actually defined in
1723    // different modules based on the target platform. Ignore everything but crate name and the
1724    // item name.
1725    cx.tcx.crate_name(did.krate) == sym::libc && cx.tcx.def_path_str(did).ends_with(name.as_str())
1726}
1727
1728/// Returns the list of condition expressions and the list of blocks in a
1729/// sequence of `if/else`.
1730/// E.g., this returns `([a, b], [c, d, e])` for the expression
1731/// `if a { c } else if b { d } else { e }`.
1732pub 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    // final `else {..}`
1752    if !blocks.is_empty()
1753        && let ExprKind::Block(block, _) = expr.kind
1754    {
1755        blocks.push(block);
1756    }
1757
1758    (conds, blocks)
1759}
1760
1761/// Peels away all the compiler generated code surrounding the body of an async closure.
1762pub 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
1786/// Peels away all the compiler generated code surrounding the body of an async function,
1787pub 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
1791// check if expr is calling method or function with #[must_use] attribute
1792pub 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, did, MustUse { .. }))
1808}
1809
1810/// Checks if a function's body represents the identity function. Looks for bodies of the form:
1811/// * `|x| x`
1812/// * `|x| return x`
1813/// * `|x| { return x }`
1814/// * `|x| { return x; }`
1815/// * `|(x, y)| (x, y)`
1816/// * `|[x, y]| [x, y]`
1817/// * `|Foo(bar, baz)| Foo(bar, baz)`
1818/// * `|Foo { bar, baz }| Foo { bar, baz }`
1819/// * `|x| { let y = x; ...; let z = y; z }`
1820/// * `|x| { let y = x; ...; let z = y; return z }`
1821///
1822/// Consider calling [`is_expr_untyped_identity_function`] or [`is_expr_identity_function`] instead.
1823fn is_body_identity_function<'hir>(cx: &LateContext<'_>, func: &Body<'hir>) -> bool {
1824    let [param] = func.params else {
1825        return false;
1826    };
1827
1828    let mut param_pat = param.pat;
1829
1830    // Given a sequence of `Stmt`s of the form `let p = e` where `e` is an expr identical to the
1831    // current `param_pat`, advance the current `param_pat` to `p`.
1832    //
1833    // Note: This is similar to `clippy_utils::get_last_chain_binding_hir_id`, but it works
1834    // directly over a `Pattern` rather than a `HirId`. And it checks for compatibility via
1835    // `is_expr_identity_of_pat` rather than `HirId` equality
1836    let mut advance_param_pat_over_stmts = |stmts: &[Stmt<'hir>]| {
1837        for stmt in stmts {
1838            if let StmtKind::Let(local) = stmt.kind
1839                && let Some(init) = local.init
1840                && is_expr_identity_of_pat(cx, param_pat, init, true)
1841            {
1842                param_pat = local.pat;
1843            } else {
1844                return false;
1845            }
1846        }
1847
1848        true
1849    };
1850
1851    let mut expr = func.value;
1852    loop {
1853        match expr.kind {
1854            ExprKind::Block(
1855                &Block {
1856                    stmts: [],
1857                    expr: Some(e),
1858                    ..
1859                },
1860                _,
1861            )
1862            | ExprKind::Ret(Some(e)) => expr = e,
1863            ExprKind::Block(
1864                &Block {
1865                    stmts: [stmt],
1866                    expr: None,
1867                    ..
1868                },
1869                _,
1870            ) => {
1871                if let StmtKind::Semi(e) | StmtKind::Expr(e) = stmt.kind
1872                    && let ExprKind::Ret(Some(ret_val)) = e.kind
1873                {
1874                    expr = ret_val;
1875                } else {
1876                    return false;
1877                }
1878            },
1879            ExprKind::Block(
1880                &Block {
1881                    stmts, expr: Some(e), ..
1882                },
1883                _,
1884            ) => {
1885                if !advance_param_pat_over_stmts(stmts) {
1886                    return false;
1887                }
1888
1889                expr = e;
1890            },
1891            ExprKind::Block(&Block { stmts, expr: None, .. }, _) => {
1892                if let Some((last_stmt, stmts)) = stmts.split_last()
1893                    && advance_param_pat_over_stmts(stmts)
1894                    && let StmtKind::Semi(e) | StmtKind::Expr(e) = last_stmt.kind
1895                    && let ExprKind::Ret(Some(ret_val)) = e.kind
1896                {
1897                    expr = ret_val;
1898                } else {
1899                    return false;
1900                }
1901            },
1902            _ => return is_expr_identity_of_pat(cx, param_pat, expr, true),
1903        }
1904    }
1905}
1906
1907/// Checks if the given expression is an identity representation of the given pattern:
1908/// * `x` is the identity representation of `x`
1909/// * `(x, y)` is the identity representation of `(x, y)`
1910/// * `[x, y]` is the identity representation of `[x, y]`
1911/// * `Foo(bar, baz)` is the identity representation of `Foo(bar, baz)`
1912/// * `Foo { bar, baz }` is the identity representation of `Foo { bar, baz }`
1913///
1914/// Note that `by_hir` is used to determine bindings are checked by their `HirId` or by their name.
1915/// This can be useful when checking patterns in `let` bindings or `match` arms.
1916pub fn is_expr_identity_of_pat(cx: &LateContext<'_>, pat: &Pat<'_>, expr: &Expr<'_>, by_hir: bool) -> bool {
1917    if cx
1918        .typeck_results()
1919        .pat_binding_modes()
1920        .get(pat.hir_id)
1921        .is_some_and(|mode| matches!(mode.0, ByRef::Yes(..)))
1922    {
1923        // If the parameter is `(x, y)` of type `&(T, T)`, or `[x, y]` of type `&[T; 2]`, then
1924        // due to match ergonomics, the inner patterns become references. Don't consider this
1925        // the identity function as that changes types.
1926        return false;
1927    }
1928
1929    // NOTE: we're inside a (function) body, so this won't ICE
1930    let qpath_res = |qpath, hir| cx.typeck_results().qpath_res(qpath, hir);
1931
1932    match (pat.kind, expr.kind) {
1933        (PatKind::Binding(_, id, _, _), _) if by_hir => {
1934            expr.res_local_id() == Some(id) && cx.typeck_results().expr_adjustments(expr).is_empty()
1935        },
1936        (PatKind::Binding(_, _, ident, _), ExprKind::Path(QPath::Resolved(_, path))) => {
1937            matches!(path.segments, [ segment] if segment.ident.name == ident.name)
1938        },
1939        (PatKind::Tuple(pats, dotdot), ExprKind::Tup(tup))
1940            if dotdot.as_opt_usize().is_none() && pats.len() == tup.len() =>
1941        {
1942            over(pats, tup, |pat, expr| is_expr_identity_of_pat(cx, pat, expr, by_hir))
1943        },
1944        (PatKind::Slice(before, None, after), ExprKind::Array(arr)) if before.len() + after.len() == arr.len() => {
1945            zip(before.iter().chain(after), arr).all(|(pat, expr)| is_expr_identity_of_pat(cx, pat, expr, by_hir))
1946        },
1947        (PatKind::TupleStruct(pat_ident, field_pats, dotdot), ExprKind::Call(ident, fields))
1948            if dotdot.as_opt_usize().is_none() && field_pats.len() == fields.len() =>
1949        {
1950            // check ident
1951            if let ExprKind::Path(ident) = &ident.kind
1952                && qpath_res(&pat_ident, pat.hir_id) == qpath_res(ident, expr.hir_id)
1953                // check fields
1954                && over(field_pats, fields, |pat, expr| is_expr_identity_of_pat(cx, pat, expr,by_hir))
1955            {
1956                true
1957            } else {
1958                false
1959            }
1960        },
1961        (PatKind::Struct(pat_ident, field_pats, None), ExprKind::Struct(ident, fields, hir::StructTailExpr::None))
1962            if field_pats.len() == fields.len() =>
1963        {
1964            // check ident
1965            qpath_res(&pat_ident, pat.hir_id) == qpath_res(ident, expr.hir_id)
1966                // check fields
1967                && unordered_over(field_pats, fields, |field_pat, field| {
1968                    field_pat.ident == field.ident && is_expr_identity_of_pat(cx, field_pat.pat, field.expr, by_hir)
1969                })
1970        },
1971        _ => false,
1972    }
1973}
1974
1975/// This is the same as [`is_expr_identity_function`], but does not consider closures
1976/// with type annotations for its bindings (or similar) as identity functions:
1977/// * `|x: u8| x`
1978/// * `std::convert::identity::<u8>`
1979pub fn is_expr_untyped_identity_function(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
1980    match expr.kind {
1981        ExprKind::Closure(&Closure { body, fn_decl, .. })
1982            if fn_decl.inputs.iter().all(|ty| matches!(ty.kind, TyKind::Infer(()))) =>
1983        {
1984            is_body_identity_function(cx, cx.tcx.hir_body(body))
1985        },
1986        ExprKind::Path(QPath::Resolved(_, path))
1987            if path.segments.iter().all(|seg| seg.infer_args)
1988                && let Some(did) = path.res.opt_def_id() =>
1989        {
1990            cx.tcx.is_diagnostic_item(sym::convert_identity, did)
1991        },
1992        _ => false,
1993    }
1994}
1995
1996/// Checks if an expression represents the identity function
1997/// Only examines closures and `std::convert::identity`
1998///
1999/// NOTE: If you want to use this function to find out if a closure is unnecessary, you likely want
2000/// to call [`is_expr_untyped_identity_function`] instead, which makes sure that the closure doesn't
2001/// have type annotations. This is important because removing a closure with bindings can
2002/// remove type information that helped type inference before, which can then lead to compile
2003/// errors.
2004pub fn is_expr_identity_function(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
2005    match expr.kind {
2006        ExprKind::Closure(&Closure { body, .. }) => is_body_identity_function(cx, cx.tcx.hir_body(body)),
2007        _ => expr.basic_res().is_diag_item(cx, sym::convert_identity),
2008    }
2009}
2010
2011/// Gets the node where an expression is either used, or it's type is unified with another branch.
2012/// Returns both the node and the `HirId` of the closest child node.
2013pub fn get_expr_use_or_unification_node<'tcx>(tcx: TyCtxt<'tcx>, expr: &Expr<'_>) -> Option<(Node<'tcx>, HirId)> {
2014    for (node, child_id) in hir_parent_with_src_iter(tcx, expr.hir_id) {
2015        match node {
2016            Node::Block(_) => {},
2017            Node::Arm(arm) if arm.body.hir_id == child_id => {},
2018            Node::Expr(expr) => match expr.kind {
2019                ExprKind::Block(..) | ExprKind::DropTemps(_) => {},
2020                ExprKind::Match(_, [arm], _) if arm.hir_id == child_id => {},
2021                ExprKind::If(_, then_expr, None) if then_expr.hir_id == child_id => return None,
2022                _ => return Some((Node::Expr(expr), child_id)),
2023            },
2024            node => return Some((node, child_id)),
2025        }
2026    }
2027    None
2028}
2029
2030/// Checks if the result of an expression is used, or it's type is unified with another branch.
2031pub fn is_expr_used_or_unified(tcx: TyCtxt<'_>, expr: &Expr<'_>) -> bool {
2032    !matches!(
2033        get_expr_use_or_unification_node(tcx, expr),
2034        None | Some((
2035            Node::Stmt(Stmt {
2036                kind: StmtKind::Expr(_)
2037                    | StmtKind::Semi(_)
2038                    | StmtKind::Let(LetStmt {
2039                        pat: Pat {
2040                            kind: PatKind::Wild,
2041                            ..
2042                        },
2043                        ..
2044                    }),
2045                ..
2046            }),
2047            _
2048        ))
2049    )
2050}
2051
2052/// Checks if the expression is the final expression returned from a block.
2053pub fn is_expr_final_block_expr(tcx: TyCtxt<'_>, expr: &Expr<'_>) -> bool {
2054    matches!(tcx.parent_hir_node(expr.hir_id), Node::Block(..))
2055}
2056
2057/// Checks if the expression is a temporary value.
2058// This logic is the same as the one used in rustc's `check_named_place_expr function`.
2059// https://github.com/rust-lang/rust/blob/3ed2a10d173d6c2e0232776af338ca7d080b1cd4/compiler/rustc_hir_typeck/src/expr.rs#L482-L499
2060pub fn is_expr_temporary_value(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
2061    !expr.is_place_expr(|base| {
2062        cx.typeck_results()
2063            .adjustments()
2064            .get(base.hir_id)
2065            .is_some_and(|x| x.iter().any(|adj| matches!(adj.kind, Adjust::Deref(_))))
2066    })
2067}
2068
2069pub fn is_no_std_crate(cx: &LateContext<'_>) -> bool {
2070    find_attr!(cx.tcx, crate, NoStd)
2071}
2072
2073pub fn is_no_core_crate(cx: &LateContext<'_>) -> bool {
2074    find_attr!(cx.tcx, crate, NoCore)
2075}
2076
2077/// Check if parent of a hir node is a trait implementation block.
2078/// For example, `f` in
2079/// ```no_run
2080/// # struct S;
2081/// # trait Trait { fn f(); }
2082/// impl Trait for S {
2083///     fn f() {}
2084/// }
2085/// ```
2086pub fn is_trait_impl_item(cx: &LateContext<'_>, hir_id: HirId) -> bool {
2087    if let Node::Item(item) = cx.tcx.parent_hir_node(hir_id) {
2088        matches!(item.kind, ItemKind::Impl(Impl { of_trait: Some(_), .. }))
2089    } else {
2090        false
2091    }
2092}
2093
2094/// Check if it's even possible to satisfy the `where` clause for the item.
2095///
2096/// `trivial_bounds` feature allows functions with unsatisfiable bounds, for example:
2097///
2098/// ```ignore
2099/// fn foo() where i32: Iterator {
2100///     for _ in 2i32 {}
2101/// }
2102/// ```
2103pub fn fn_has_unsatisfiable_clauses(cx: &LateContext<'_>, did: DefId) -> bool {
2104    use rustc_trait_selection::traits;
2105    let clauses = cx
2106        .tcx
2107        .clauses_of(did)
2108        .clauses
2109        .iter()
2110        .filter_map(|(p, _)| if p.is_global() { Some(*p) } else { None });
2111    traits::impossible_clauses(cx.tcx, traits::elaborate(cx.tcx, clauses).collect::<Vec<_>>())
2112}
2113
2114/// Returns the `DefId` of the callee if the given expression is a function or method call.
2115pub fn fn_def_id(cx: &LateContext<'_>, expr: &Expr<'_>) -> Option<DefId> {
2116    fn_def_id_with_node_args(cx, expr).map(|(did, _)| did)
2117}
2118
2119/// Returns the `DefId` of the callee if the given expression is a function or method call,
2120/// as well as its node args.
2121pub fn fn_def_id_with_node_args<'tcx>(
2122    cx: &LateContext<'tcx>,
2123    expr: &Expr<'_>,
2124) -> Option<(DefId, rustc_ty::GenericArgs<'tcx>)> {
2125    let typeck = cx.typeck_results();
2126    match &expr.kind {
2127        ExprKind::MethodCall(..) => Some((
2128            typeck.type_dependent_def_id(expr.hir_id)?,
2129            typeck.node_args(expr.hir_id),
2130        )),
2131        ExprKind::Call(
2132            Expr {
2133                kind: ExprKind::Path(qpath),
2134                hir_id: path_hir_id,
2135                ..
2136            },
2137            ..,
2138        ) => {
2139            // Only return Fn-like DefIds, not the DefIds of statics/consts/etc that contain or
2140            // deref to fn pointers, dyn Fn, impl Fn - #8850
2141            if let Res::Def(DefKind::Fn | DefKind::Ctor(..) | DefKind::AssocFn, id) =
2142                typeck.qpath_res(qpath, *path_hir_id)
2143            {
2144                Some((id, typeck.node_args(*path_hir_id)))
2145            } else {
2146                None
2147            }
2148        },
2149        _ => None,
2150    }
2151}
2152
2153/// Returns `Option<String>` where String is a textual representation of the type encapsulated in
2154/// the slice iff the given expression is a slice of primitives.
2155///
2156/// (As defined in the `is_recursively_primitive_type` function.) Returns `None` otherwise.
2157pub fn is_slice_of_primitives(cx: &LateContext<'_>, expr: &Expr<'_>) -> Option<String> {
2158    let expr_type = cx.typeck_results().expr_ty_adjusted(expr);
2159    let expr_kind = expr_type.kind();
2160    let is_primitive = match expr_kind {
2161        rustc_ty::Slice(element_type) => is_recursively_primitive_type(*element_type),
2162        rustc_ty::Ref(_, inner_ty, _) if matches!(inner_ty.kind(), &rustc_ty::Slice(_)) => {
2163            if let rustc_ty::Slice(element_type) = inner_ty.kind() {
2164                is_recursively_primitive_type(*element_type)
2165            } else {
2166                unreachable!()
2167            }
2168        },
2169        _ => false,
2170    };
2171
2172    if is_primitive {
2173        // if we have wrappers like Array, Slice or Tuple, print these
2174        // and get the type enclosed in the slice ref
2175        match expr_type.peel_refs().walk().nth(1).unwrap().expect_ty().kind() {
2176            rustc_ty::Slice(..) => return Some("slice".into()),
2177            rustc_ty::Array(..) => return Some("array".into()),
2178            rustc_ty::Tuple(..) => return Some("tuple".into()),
2179            _ => {
2180                // is_recursively_primitive_type() should have taken care
2181                // of the rest and we can rely on the type that is found
2182                let refs_peeled = expr_type.peel_refs();
2183                return Some(refs_peeled.walk().last().unwrap().to_string());
2184            },
2185        }
2186    }
2187    None
2188}
2189
2190/// Returns a list of groups where elements in each group are equal according to `eq`
2191///
2192/// - Within each group the elements are sorted by the order they appear in `exprs`
2193/// - The groups themselves are sorted by their first element's appearence in `exprs`
2194///
2195/// Given functions `eq` and `hash` such that `eq(a, b) == true`
2196/// implies `hash(a) == hash(b)`
2197pub fn search_same<T, Hash, Eq>(exprs: &[T], mut hash: Hash, mut eq: Eq) -> Vec<Vec<&T>>
2198where
2199    Hash: FnMut(&T) -> u64,
2200    Eq: FnMut(&T, &T) -> bool,
2201{
2202    match exprs {
2203        [a, b] if eq(a, b) => return vec![vec![a, b]],
2204        _ if exprs.len() <= 2 => return vec![],
2205        _ => {},
2206    }
2207
2208    let mut buckets: UnindexMap<u64, Vec<Vec<&T>>> = UnindexMap::default();
2209
2210    for expr in exprs {
2211        match buckets.entry(hash(expr)) {
2212            indexmap::map::Entry::Occupied(mut o) => {
2213                let bucket = o.get_mut();
2214                match bucket.iter_mut().find(|group| eq(expr, group[0])) {
2215                    Some(group) => group.push(expr),
2216                    None => bucket.push(vec![expr]),
2217                }
2218            },
2219            indexmap::map::Entry::Vacant(v) => {
2220                v.insert(vec![vec![expr]]);
2221            },
2222        }
2223    }
2224
2225    buckets
2226        .into_values()
2227        .flatten()
2228        .filter(|group| group.len() > 1)
2229        .collect()
2230}
2231
2232/// Peels off all references on the pattern. Returns the underlying pattern and the number of
2233/// references removed.
2234pub fn peel_hir_pat_refs<'a>(pat: &'a Pat<'a>) -> (&'a Pat<'a>, usize) {
2235    fn peel<'a>(pat: &'a Pat<'a>, count: usize) -> (&'a Pat<'a>, usize) {
2236        if let PatKind::Ref(pat, _, _) = pat.kind {
2237            peel(pat, count + 1)
2238        } else {
2239            (pat, count)
2240        }
2241    }
2242    peel(pat, 0)
2243}
2244
2245/// Peels of expressions while the given closure returns `Some`.
2246pub fn peel_hir_expr_while<'tcx>(
2247    mut expr: &'tcx Expr<'tcx>,
2248    mut f: impl FnMut(&'tcx Expr<'tcx>) -> Option<&'tcx Expr<'tcx>>,
2249) -> &'tcx Expr<'tcx> {
2250    while let Some(e) = f(expr) {
2251        expr = e;
2252    }
2253    expr
2254}
2255
2256/// Peels off up to the given number of references on the expression. Returns the underlying
2257/// expression and the number of references removed.
2258pub fn peel_n_hir_expr_refs<'a>(expr: &'a Expr<'a>, count: usize) -> (&'a Expr<'a>, usize) {
2259    let mut remaining = count;
2260    let e = peel_hir_expr_while(expr, |e| match e.kind {
2261        ExprKind::AddrOf(ast::BorrowKind::Ref, _, e) if remaining != 0 => {
2262            remaining -= 1;
2263            Some(e)
2264        },
2265        _ => None,
2266    });
2267    (e, count - remaining)
2268}
2269
2270/// Peels off all unary operators of an expression. Returns the underlying expression and the number
2271/// of operators removed.
2272pub fn peel_hir_expr_unary<'a>(expr: &'a Expr<'a>) -> (&'a Expr<'a>, usize) {
2273    let mut count: usize = 0;
2274    let mut curr_expr = expr;
2275    while let ExprKind::Unary(_, local_expr) = curr_expr.kind {
2276        count = count.wrapping_add(1);
2277        curr_expr = local_expr;
2278    }
2279    (curr_expr, count)
2280}
2281
2282/// Peels off all references on the expression. Returns the underlying expression and the number of
2283/// references removed.
2284pub fn peel_hir_expr_refs<'a>(expr: &'a Expr<'a>) -> (&'a Expr<'a>, usize) {
2285    let mut count = 0;
2286    let e = peel_hir_expr_while(expr, |e| match e.kind {
2287        ExprKind::AddrOf(ast::BorrowKind::Ref, _, e) => {
2288            count += 1;
2289            Some(e)
2290        },
2291        _ => None,
2292    });
2293    (e, count)
2294}
2295
2296/// Peels off all references on the type. Returns the underlying type and the number of references
2297/// removed.
2298pub fn peel_hir_ty_refs<'a>(mut ty: &'a hir::Ty<'a>) -> (&'a hir::Ty<'a>, usize) {
2299    let mut count = 0;
2300    loop {
2301        match &ty.kind {
2302            TyKind::Ref(_, inner_ty, _) => {
2303                ty = inner_ty;
2304                count += 1;
2305            },
2306            _ => break (ty, count),
2307        }
2308    }
2309}
2310
2311/// Returns the base type for HIR references and pointers.
2312pub fn peel_hir_ty_refs_and_ptrs<'tcx>(ty: &'tcx hir::Ty<'tcx>) -> &'tcx hir::Ty<'tcx> {
2313    match &ty.kind {
2314        TyKind::Ptr(inner_ty, _) | TyKind::Ref(_, inner_ty, _) => peel_hir_ty_refs_and_ptrs(inner_ty),
2315        _ => ty,
2316    }
2317}
2318
2319/// Removes `AddrOf` operators (`&`) or deref operators (`*`), but only if a reference type is
2320/// dereferenced. An overloaded deref such as `Vec` to slice would not be removed.
2321pub fn peel_ref_operators<'hir>(cx: &LateContext<'_>, mut expr: &'hir Expr<'hir>) -> &'hir Expr<'hir> {
2322    loop {
2323        match expr.kind {
2324            ExprKind::AddrOf(_, _, e) => expr = e,
2325            ExprKind::Unary(UnOp::Deref, e) if cx.typeck_results().expr_ty(e).is_ref() => expr = e,
2326            _ => break,
2327        }
2328    }
2329    expr
2330}
2331
2332/// Returns a `Vec` of `Expr`s containing `AddrOf` operators (`&`) or deref operators (`*`) of a
2333/// given expression.
2334pub fn get_ref_operators<'hir>(cx: &LateContext<'_>, expr: &'hir Expr<'hir>) -> Vec<&'hir Expr<'hir>> {
2335    let mut operators = Vec::new();
2336    peel_hir_expr_while(expr, |expr| match expr.kind {
2337        ExprKind::AddrOf(_, _, e) => {
2338            operators.push(expr);
2339            Some(e)
2340        },
2341        ExprKind::Unary(UnOp::Deref, e) if cx.typeck_results().expr_ty(e).is_ref() => {
2342            operators.push(expr);
2343            Some(e)
2344        },
2345        _ => None,
2346    });
2347    operators
2348}
2349
2350pub fn is_hir_ty_cfg_dependant(cx: &LateContext<'_>, ty: &hir::Ty<'_>) -> bool {
2351    if let TyKind::Path(QPath::Resolved(_, path)) = ty.kind
2352        && let Res::Def(_, def_id) = path.res
2353    {
2354        return find_attr!(cx.tcx, def_id, CfgTrace(..) | CfgAttrTrace(..));
2355    }
2356    false
2357}
2358
2359static TEST_ITEM_NAMES_CACHE: OnceLock<Mutex<FxHashMap<LocalModId, Vec<Symbol>>>> = OnceLock::new();
2360
2361/// Returns the names of the test items in the given module.
2362/// The names are sorted using the default `Symbol` ordering.
2363fn test_item_names(tcx: TyCtxt<'_>, module: LocalModId) -> Vec<Symbol> {
2364    let cache = TEST_ITEM_NAMES_CACHE.get_or_init(|| Mutex::new(FxHashMap::default()));
2365    let mut map = cache.lock().unwrap();
2366    match map.entry(module) {
2367        Entry::Occupied(entry) => entry.get().clone(),
2368        Entry::Vacant(entry) => {
2369            let mut names = Vec::new();
2370            for id in tcx.hir_module_free_items(module) {
2371                if matches!(tcx.def_kind(id.owner_id), DefKind::Static { .. })
2372                    && let item = tcx.hir_item(id)
2373                    && let ItemKind::Static(_mut, ident, ty, _body) = item.kind
2374                    && let TyKind::Path(QPath::Resolved(_, path)) = ty.kind
2375                    // We could also check for the type name `test::TestDescAndFn`
2376                    && let Res::Def(DefKind::Struct, _) = path.res
2377                    && find_attr!(tcx, item.hir_id(), RustcTestMarker(..))
2378                {
2379                    names.push(ident.name);
2380                }
2381            }
2382            names.sort_unstable();
2383            entry.insert(names).clone()
2384        },
2385    }
2386}
2387
2388/// Checks if the function containing the given `HirId` is a `#[test]` function
2389///
2390/// Note: Add `//@compile-flags: --test` to UI tests with a `#[test]` function
2391pub fn is_in_test_function(tcx: TyCtxt<'_>, id: HirId) -> bool {
2392    let names = test_item_names(tcx, tcx.parent_module(id));
2393    // Without `--test` there are no test items, so the parent walk can never match.
2394    if names.is_empty() {
2395        return false;
2396    }
2397    once((id, tcx.hir_node(id)))
2398        .chain(tcx.hir_parent_iter(id))
2399        // Since you can nest functions we need to collect all until we leave
2400        // function scope
2401        .any(|(_id, node)| {
2402            if let Node::Item(item) = node
2403                && let ItemKind::Fn { ident, .. } = item.kind
2404            {
2405                // Note that we have sorted the item names in the visitor,
2406                // so the binary_search gets the same as `contains`, but faster.
2407                return names.binary_search(&ident.name).is_ok();
2408            }
2409            false
2410        })
2411}
2412
2413/// Checks if `fn_def_id` has a `#[test]` attribute applied
2414///
2415/// This only checks directly applied attributes. To see if a node has a parent function marked with
2416/// `#[test]` use [`is_in_test_function`].
2417///
2418/// Note: Add `//@compile-flags: --test` to UI tests with a `#[test]` function
2419pub fn is_test_function(tcx: TyCtxt<'_>, fn_def_id: LocalDefId) -> bool {
2420    let id = tcx.local_def_id_to_hir_id(fn_def_id);
2421    if let Node::Item(item) = tcx.hir_node(id)
2422        && let ItemKind::Fn { ident, .. } = item.kind
2423    {
2424        test_item_names(tcx, tcx.parent_module(id))
2425            .binary_search(&ident.name)
2426            .is_ok()
2427    } else {
2428        false
2429    }
2430}
2431
2432/// Checks if `id` has a `#[cfg(test)]` attribute applied
2433///
2434/// This only checks directly applied attributes, to see if a node is inside a `#[cfg(test)]` parent
2435/// use [`is_in_cfg_test`]
2436pub fn is_cfg_test(tcx: TyCtxt<'_>, id: HirId) -> bool {
2437    if let Some(cfgs) = find_attr!(tcx, id, CfgTrace(cfgs) => cfgs)
2438        && cfgs
2439            .iter()
2440            .any(|(cfg, _)| matches!(cfg, CfgEntry::NameValue { name: sym::test, .. }))
2441    {
2442        true
2443    } else {
2444        false
2445    }
2446}
2447
2448/// Checks if any parent node of `HirId` has `#[cfg(test)]` attribute applied
2449pub fn is_in_cfg_test(tcx: TyCtxt<'_>, id: HirId) -> bool {
2450    tcx.hir_parent_id_iter(id).any(|parent_id| is_cfg_test(tcx, parent_id))
2451}
2452
2453/// Checks if the node is in a `#[test]` function or has any parent node marked `#[cfg(test)]`
2454pub fn is_in_test(tcx: TyCtxt<'_>, hir_id: HirId) -> bool {
2455    is_in_test_function(tcx, hir_id) || is_in_cfg_test(tcx, hir_id) || is_in_integration_test_file(tcx)
2456}
2457
2458/// Check if the node is in an integration test file (i.e. under `tests/`).
2459fn is_in_integration_test_file(tcx: TyCtxt<'_>) -> bool {
2460    if let Input::File(ref path) = tcx.sess.io.input
2461        && !tcx.sess.opts.unstable_opts.ui_testing
2462    {
2463        path.starts_with("tests")
2464    } else {
2465        false
2466    }
2467}
2468
2469/// Checks if the item of any of its parents has `#[cfg(...)]` attribute applied.
2470pub fn inherits_cfg(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
2471    find_attr!(tcx, def_id, CfgTrace(..))
2472        || find_attr!(
2473            tcx.hir_parent_id_iter(tcx.local_def_id_to_hir_id(def_id))
2474                .flat_map(|parent_id| tcx.hir_attrs(parent_id)),
2475            CfgTrace(..)
2476        )
2477}
2478
2479/// A type definition as it would be viewed from within a function.
2480#[derive(Clone, Copy)]
2481pub enum DefinedTy<'tcx> {
2482    // Used for locals and closures defined within the function.
2483    Hir(&'tcx hir::Ty<'tcx>),
2484    /// Used for function signatures, and constant and static values. The type is
2485    /// in the context of its definition site. We also track the `def_id` of its
2486    /// definition site.
2487    ///
2488    /// WARNING: As the `ty` is in the scope of the definition, not of the function
2489    /// using it, you must be very careful with how you use it. Using it in the wrong
2490    /// scope easily results in ICEs.
2491    Mir {
2492        def_site_def_id: Option<DefId>,
2493        ty: Binder<'tcx, Ty<'tcx>>,
2494    },
2495}
2496
2497/// The location that recives the value of an expression.
2498pub struct ExprUseSite<'tcx> {
2499    /// The parent node which consumes the value.
2500    pub node: Node<'tcx>,
2501    /// The ID of the immediate child of the use node.
2502    pub child_id: HirId,
2503    /// Any adjustments applied to the type.
2504    pub adjustments: &'tcx [Adjustment<'tcx>],
2505    /// Whether the type must unify with another code path.
2506    pub is_ty_unified: bool,
2507    /// Whether the value will be moved before it's used.
2508    pub moved_before_use: bool,
2509    /// Whether the use site has the same `SyntaxContext` as the value.
2510    pub same_ctxt: bool,
2511}
2512impl<'tcx> ExprUseSite<'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
2576/// The node which consumes a value.
2577pub enum ExprUseNode<'tcx> {
2578    /// Assignment to, or initializer for, a local
2579    LetStmt(&'tcx LetStmt<'tcx>),
2580    /// Initializer for a const or static item.
2581    ConstStatic(OwnerId),
2582    /// Implicit or explicit return from a function.
2583    Return(OwnerId),
2584    /// Initialization of a struct field.
2585    Field(&'tcx ExprField<'tcx>),
2586    /// An argument to a function.
2587    FnArg(&'tcx Expr<'tcx>, usize),
2588    /// An argument to a method.
2589    MethodArg(HirId, Option<&'tcx GenericArgs<'tcx>>, usize),
2590    /// The callee of a function call.
2591    Callee,
2592    /// Access of a field.
2593    FieldAccess(Ident),
2594    /// Borrow expression.
2595    AddrOf(ast::BorrowKind, Mutability),
2596    Other,
2597}
2598impl<'tcx> ExprUseNode<'tcx> {
2599    /// Checks if the value is returned from the function.
2600    pub fn is_return(&self) -> bool {
2601        matches!(self, Self::Return(_))
2602    }
2603
2604    /// Checks if the value is used as a method call receiver.
2605    pub fn is_recv(&self) -> bool {
2606        matches!(self, Self::MethodArg(_, _, 0))
2607    }
2608
2609    /// Gets the needed type as it's defined without any type inference.
2610    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().skip_norm_wip()),
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().skip_norm_wip().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().skip_norm_wip()),
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
2678struct ReplacingFilterMap<I, F>(I, F);
2679impl<I, F, U> Iterator for ReplacingFilterMap<I, F>
2680where
2681    I: Iterator,
2682    F: FnMut(&mut I, I::Item) -> Option<U>,
2683{
2684    type Item = U;
2685    fn next(&mut self) -> Option<U> {
2686        while let Some(x) = self.0.next() {
2687            if let Some(x) = (self.1)(&mut self.0, x) {
2688                return Some(x);
2689            }
2690        }
2691        None
2692    }
2693}
2694
2695/// Returns an iterator which walks successive value using parent nodes skipping any node
2696/// which simply moves a value.
2697#[expect(clippy::too_many_lines)]
2698pub fn expr_use_sites<'tcx>(
2699    tcx: TyCtxt<'tcx>,
2700    typeck: &'tcx TypeckResults<'tcx>,
2701    mut ctxt: SyntaxContext,
2702    e: &'tcx Expr<'tcx>,
2703) -> impl Iterator<Item = ExprUseSite<'tcx>> {
2704    let mut adjustments: &[_] = typeck.expr_adjustments(e);
2705    let mut is_ty_unified = false;
2706    let mut moved_before_use = false;
2707    let mut same_ctxt = true;
2708    ReplacingFilterMap(
2709        hir_parent_with_src_iter(tcx, e.hir_id),
2710        move |iter: &mut _, (parent, child_id)| {
2711            let parent_ctxt;
2712            let mut parent_adjustments: &[_] = &[];
2713            match parent {
2714                Node::Expr(parent_expr) => {
2715                    parent_ctxt = parent_expr.span.ctxt();
2716                    same_ctxt &= parent_ctxt == ctxt;
2717                    parent_adjustments = typeck.expr_adjustments(parent_expr);
2718                    match parent_expr.kind {
2719                        ExprKind::Match(scrutinee, arms, _) if scrutinee.hir_id != child_id => {
2720                            is_ty_unified |= arms.len() != 1;
2721                            moved_before_use = true;
2722                            if adjustments.is_empty() {
2723                                adjustments = parent_adjustments;
2724                            }
2725                            return None;
2726                        },
2727                        ExprKind::If(cond, _, else_) if cond.hir_id != child_id => {
2728                            is_ty_unified |= else_.is_some();
2729                            moved_before_use = true;
2730                            if adjustments.is_empty() {
2731                                adjustments = parent_adjustments;
2732                            }
2733                            return None;
2734                        },
2735                        ExprKind::Break(Destination { target_id: Ok(id), .. }, _) => {
2736                            is_ty_unified = true;
2737                            moved_before_use = true;
2738                            *iter = hir_parent_with_src_iter(tcx, id);
2739                            if adjustments.is_empty() {
2740                                adjustments = parent_adjustments;
2741                            }
2742                            return None;
2743                        },
2744                        ExprKind::Block(b, _) => {
2745                            is_ty_unified |= b.targeted_by_break;
2746                            moved_before_use = true;
2747                            if adjustments.is_empty() {
2748                                adjustments = parent_adjustments;
2749                            }
2750                            return None;
2751                        },
2752                        ExprKind::DropTemps(_) | ExprKind::Type(..) => {
2753                            if adjustments.is_empty() {
2754                                adjustments = parent_adjustments;
2755                            }
2756                            return None;
2757                        },
2758                        _ => {},
2759                    }
2760                },
2761                Node::Arm(arm) => {
2762                    parent_ctxt = arm.span.ctxt();
2763                    same_ctxt &= parent_ctxt == ctxt;
2764                    if arm.body.hir_id == child_id {
2765                        return None;
2766                    }
2767                },
2768                Node::Block(b) => {
2769                    same_ctxt &= b.span.ctxt() == ctxt;
2770                    return None;
2771                },
2772                Node::ConstBlock(_) => parent_ctxt = ctxt,
2773                Node::ExprField(&ExprField { span, .. }) => {
2774                    parent_ctxt = span.ctxt();
2775                    same_ctxt &= parent_ctxt == ctxt;
2776                },
2777                Node::AnonConst(&AnonConst { span, .. })
2778                | Node::ConstArg(&ConstArg { span, .. })
2779                | Node::Field(&FieldDef { span, .. })
2780                | Node::ImplItem(&ImplItem { span, .. })
2781                | Node::Item(&Item { span, .. })
2782                | Node::LetStmt(&LetStmt { span, .. })
2783                | Node::Stmt(&Stmt { span, .. })
2784                | Node::TraitItem(&TraitItem { span, .. })
2785                | Node::Variant(&Variant { span, .. }) => {
2786                    parent_ctxt = span.ctxt();
2787                    same_ctxt &= parent_ctxt == ctxt;
2788                    *iter = hir_parent_with_src_iter(tcx, CRATE_HIR_ID);
2789                },
2790                Node::AssocItemConstraint(_)
2791                | Node::ConstArgExprField(_)
2792                | Node::Crate(_)
2793                | Node::Ctor(_)
2794                | Node::Err(_)
2795                | Node::ForeignItem(_)
2796                | Node::GenericParam(_)
2797                | Node::Infer(_)
2798                | Node::Lifetime(_)
2799                | Node::OpaqueTy(_)
2800                | Node::Param(_)
2801                | Node::Pat(_)
2802                | Node::PatExpr(_)
2803                | Node::PatField(_)
2804                | Node::PathSegment(_)
2805                | Node::PreciseCapturingNonLifetimeArg(_)
2806                | Node::Synthetic
2807                | Node::TraitRef(_)
2808                | Node::Ty(_)
2809                | Node::TyPat(_)
2810                | Node::NestedUseTree(_)
2811                | Node::WherePredicate(_)
2812                | Node::TestBinderForall(_)
2813                | Node::TestBinderExists(_)
2814                | Node::TestBinderBoundTypeConstraint(_) => {
2815                    // This shouldn't be possible to hit; the inner iterator should have
2816                    // been moved to the end before we hit any of these nodes.
2817                    debug_assert!(false, "found {parent:?} which is after the final use node");
2818                    return None;
2819                },
2820            }
2821
2822            ctxt = parent_ctxt;
2823            Some(ExprUseSite {
2824                node: parent,
2825                child_id,
2826                adjustments: mem::replace(&mut adjustments, parent_adjustments),
2827                is_ty_unified: mem::replace(&mut is_ty_unified, false),
2828                moved_before_use: mem::replace(&mut moved_before_use, false),
2829                same_ctxt: mem::replace(&mut same_ctxt, true),
2830            })
2831        },
2832    )
2833}
2834
2835pub fn get_expr_use_site<'tcx>(
2836    tcx: TyCtxt<'tcx>,
2837    typeck: &'tcx TypeckResults<'tcx>,
2838    ctxt: SyntaxContext,
2839    e: &'tcx Expr<'tcx>,
2840) -> ExprUseSite<'tcx> {
2841    // The value in `unwrap_or` doesn't actually matter; an expression always
2842    // has a use site.
2843    expr_use_sites(tcx, typeck, ctxt, e).next().unwrap_or_else(|| {
2844        debug_assert!(false, "failed to find a use site for expr {e:?}");
2845        ExprUseSite {
2846            node: Node::Synthetic, // The crate root would also work.
2847            child_id: CRATE_HIR_ID,
2848            adjustments: &[],
2849            is_ty_unified: false,
2850            moved_before_use: false,
2851            same_ctxt: false,
2852        }
2853    })
2854}
2855
2856/// Tokenizes the input while keeping the text associated with each token.
2857pub fn tokenize_with_text(s: &str) -> impl Iterator<Item = (TokenKind, &str, InnerSpan)> {
2858    let mut pos = 0;
2859    tokenize(s, FrontmatterAllowed::No).map(move |t| {
2860        let end = pos + t.len;
2861        let range = pos as usize..end as usize;
2862        let inner = InnerSpan::new(range.start, range.end);
2863        pos = end;
2864        (t.kind, s.get(range).unwrap_or_default(), inner)
2865    })
2866}
2867
2868/// Checks whether a given span has any comment token
2869/// This checks for all types of comment: line "//", block "/**", doc "///" "//!"
2870pub fn span_contains_comment<'sm>(sm: impl HasSourceMap<'sm>, span: Span) -> bool {
2871    span.check_text(sm, |snippet| {
2872        tokenize(snippet, FrontmatterAllowed::No).any(|token| {
2873            matches!(
2874                token.kind,
2875                TokenKind::BlockComment { .. } | TokenKind::LineComment { .. }
2876            )
2877        })
2878    })
2879}
2880
2881/// Checks whether a given span has any significant token. A significant token is a non-whitespace
2882/// token, including comments unless `skip_comments` is set.
2883/// This is useful to determine if there are any actual code tokens in the span that are omitted in
2884/// the late pass, such as platform-specific code.
2885pub fn span_contains_non_whitespace<'sm>(sm: impl HasSourceMap<'sm>, span: Span, skip_comments: bool) -> bool {
2886    span.check_text(sm, |snippet| {
2887        tokenize_with_text(snippet).any(|(token, _, _)| match token {
2888            TokenKind::Whitespace => false,
2889            TokenKind::BlockComment { .. } | TokenKind::LineComment { .. } => !skip_comments,
2890            _ => true,
2891        })
2892    })
2893}
2894
2895/// Returns all the comments a given span contains
2896///
2897/// Comments are returned wrapped with their relevant delimiters
2898pub fn span_extract_comment<'sm>(sm: impl HasSourceMap<'sm>, span: Span) -> String {
2899    span_extract_comments(sm, span).join("\n")
2900}
2901
2902/// Returns all the comments a given span contains.
2903///
2904/// Comments are returned wrapped with their relevant delimiters.
2905pub fn span_extract_comments<'sm>(sm: impl HasSourceMap<'sm>, span: Span) -> Vec<String> {
2906    span.with_source_text(sm, |snippet| {
2907        tokenize_with_text(snippet)
2908            .filter(|(t, ..)| matches!(t, TokenKind::BlockComment { .. } | TokenKind::LineComment { .. }))
2909            .map(|(_, s, _)| s.to_string())
2910            .collect::<Vec<_>>()
2911    })
2912    .unwrap_or_default()
2913}
2914
2915pub fn span_find_starting_semi(sm: &SourceMap, span: Span) -> Span {
2916    sm.span_take_while(span, |&ch| ch == ' ' || ch == ';')
2917}
2918
2919/// Returns whether the given let pattern and else body can be turned into the `?` operator
2920///
2921/// For this example:
2922/// ```ignore
2923/// let FooBar { a, b } = if let Some(a) = ex { a } else { return None };
2924/// ```
2925/// We get as parameters:
2926/// ```ignore
2927/// pat: Some(a)
2928/// else_body: return None
2929/// ```
2930///
2931/// And for this example:
2932/// ```ignore
2933/// let Some(FooBar { a, b }) = ex else { return None };
2934/// ```
2935/// We get as parameters:
2936/// ```ignore
2937/// pat: Some(FooBar { a, b })
2938/// else_body: return None
2939/// ```
2940///
2941/// We output `Some(a)` in the first instance, and `Some(FooBar { a, b })` in the second, because
2942/// the `?` operator is applicable here. Callers have to check whether we are in a constant or not.
2943pub fn pat_and_expr_can_be_question_mark<'a, 'hir>(
2944    cx: &LateContext<'_>,
2945    pat: &'a Pat<'hir>,
2946    else_body: &Expr<'_>,
2947) -> Option<&'a Pat<'hir>> {
2948    if let Some([inner_pat]) = as_some_pattern(cx, pat)
2949        && !is_refutable(cx, inner_pat)
2950        && let else_body = peel_blocks(else_body)
2951        && let ExprKind::Ret(Some(ret_val)) = else_body.kind
2952        && let ExprKind::Path(ret_path) = ret_val.kind
2953        && cx
2954            .qpath_res(&ret_path, ret_val.hir_id)
2955            .ctor_parent(cx)
2956            .is_lang_item(cx, OptionNone)
2957    {
2958        Some(inner_pat)
2959    } else {
2960        None
2961    }
2962}
2963
2964macro_rules! op_utils {
2965    ($($name:ident $assign:ident)*) => {
2966        /// Binary operation traits like `LangItem::Add`
2967        pub static BINOP_TRAITS: &[LangItem] = &[$(LangItem::$name,)*];
2968
2969        /// Operator-Assign traits like `LangItem::AddAssign`
2970        pub static OP_ASSIGN_TRAITS: &[LangItem] = &[$(LangItem::$assign,)*];
2971
2972        /// Converts `BinOpKind::Add` to `(LangItem::Add, LangItem::AddAssign)`, for example
2973        pub fn binop_traits(kind: hir::BinOpKind) -> Option<(LangItem, LangItem)> {
2974            match kind {
2975                $(hir::BinOpKind::$name => Some((LangItem::$name, LangItem::$assign)),)*
2976                _ => None,
2977            }
2978        }
2979    };
2980}
2981
2982op_utils! {
2983    Add    AddAssign
2984    Sub    SubAssign
2985    Mul    MulAssign
2986    Div    DivAssign
2987    Rem    RemAssign
2988    BitXor BitXorAssign
2989    BitAnd BitAndAssign
2990    BitOr  BitOrAssign
2991    Shl    ShlAssign
2992    Shr    ShrAssign
2993}
2994
2995/// Returns `true` if the pattern is a `PatWild`, or is an ident prefixed with `_`
2996/// that is not locally used.
2997pub fn pat_is_wild<'tcx>(cx: &LateContext<'tcx>, pat: &'tcx PatKind<'_>, body: impl Visitable<'tcx>) -> bool {
2998    match *pat {
2999        PatKind::Wild => true,
3000        PatKind::Binding(_, id, ident, None) if ident.as_str().starts_with('_') => {
3001            !visitors::is_local_used(cx, body, id)
3002        },
3003        _ => false,
3004    }
3005}
3006
3007#[derive(Clone, Copy)]
3008pub enum RequiresSemi {
3009    Yes,
3010    No,
3011}
3012impl RequiresSemi {
3013    pub fn requires_semi(self) -> bool {
3014        matches!(self, Self::Yes)
3015    }
3016}
3017
3018/// Check if the expression return `!`, a type coerced from `!`, or could return `!` if the final
3019/// expression were turned into a statement.
3020#[expect(clippy::too_many_lines)]
3021pub fn is_never_expr<'tcx>(cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) -> Option<RequiresSemi> {
3022    struct BreakTarget {
3023        id: HirId,
3024        unused: bool,
3025    }
3026
3027    struct V<'cx, 'tcx> {
3028        cx: &'cx LateContext<'tcx>,
3029        break_targets: Vec<BreakTarget>,
3030        break_targets_for_result_ty: u32,
3031        in_final_expr: bool,
3032        requires_semi: bool,
3033        is_never: bool,
3034    }
3035
3036    impl V<'_, '_> {
3037        fn push_break_target(&mut self, id: HirId) {
3038            self.break_targets.push(BreakTarget { id, unused: true });
3039            self.break_targets_for_result_ty += u32::from(self.in_final_expr);
3040        }
3041    }
3042
3043    impl<'tcx> Visitor<'tcx> for V<'_, 'tcx> {
3044        fn visit_expr(&mut self, e: &'tcx Expr<'_>) {
3045            // Note: Part of the complexity here comes from the fact that
3046            // coercions are applied to the innermost expression.
3047            // e.g. In `let x: u32 = { break () };` the never-to-any coercion
3048            // is applied to the break expression. This means we can't just
3049            // check the block's type as it will be `u32` despite the fact
3050            // that the block always diverges.
3051
3052            // The rest of the complexity comes from checking blocks which
3053            // syntactically return a value, but will always diverge before
3054            // reaching that point.
3055            // e.g. In `let x = { foo(panic!()) };` the block's type will be the
3056            // return type of `foo` even though it will never actually run. This
3057            // can be trivially fixed by adding a semicolon after the call, but
3058            // we must first detect that a semicolon is needed to make that
3059            // suggestion.
3060
3061            if self.is_never && self.break_targets.is_empty() {
3062                if self.in_final_expr && !self.requires_semi {
3063                    // This expression won't ever run, but we still need to check
3064                    // if it can affect the type of the final expression.
3065                    match e.kind {
3066                        ExprKind::DropTemps(e) => self.visit_expr(e),
3067                        ExprKind::If(_, then, Some(else_)) => {
3068                            self.visit_expr(then);
3069                            self.visit_expr(else_);
3070                        },
3071                        ExprKind::Match(_, arms, _) => {
3072                            for arm in arms {
3073                                self.visit_expr(arm.body);
3074                            }
3075                        },
3076                        ExprKind::Loop(b, ..) => {
3077                            self.push_break_target(e.hir_id);
3078                            self.in_final_expr = false;
3079                            self.visit_block(b);
3080                            self.break_targets.pop();
3081                        },
3082                        ExprKind::Block(b, _) => {
3083                            if b.targeted_by_break {
3084                                self.push_break_target(b.hir_id);
3085                                self.visit_block(b);
3086                                self.break_targets.pop();
3087                            } else {
3088                                self.visit_block(b);
3089                            }
3090                        },
3091                        _ => {
3092                            self.requires_semi = !self.cx.typeck_results().expr_ty(e).is_never();
3093                        },
3094                    }
3095                }
3096                return;
3097            }
3098            match e.kind {
3099                ExprKind::DropTemps(e) => self.visit_expr(e),
3100                ExprKind::Ret(None) | ExprKind::Continue(_) => self.is_never = true,
3101                ExprKind::Ret(Some(e)) | ExprKind::Become(e) => {
3102                    self.in_final_expr = false;
3103                    self.visit_expr(e);
3104                    self.is_never = true;
3105                },
3106                ExprKind::Break(dest, e) => {
3107                    if let Some(e) = e {
3108                        self.in_final_expr = false;
3109                        self.visit_expr(e);
3110                    }
3111                    if let Ok(id) = dest.target_id
3112                        && let Some((i, target)) = self
3113                            .break_targets
3114                            .iter_mut()
3115                            .enumerate()
3116                            .find(|(_, target)| target.id == id)
3117                    {
3118                        target.unused &= self.is_never;
3119                        if i < self.break_targets_for_result_ty as usize {
3120                            self.requires_semi = true;
3121                        }
3122                    }
3123                    self.is_never = true;
3124                },
3125                ExprKind::If(cond, then, else_) => {
3126                    let in_final_expr = mem::replace(&mut self.in_final_expr, false);
3127                    self.visit_expr(cond);
3128                    self.in_final_expr = in_final_expr;
3129
3130                    if self.is_never {
3131                        self.visit_expr(then);
3132                        if let Some(else_) = else_ {
3133                            self.visit_expr(else_);
3134                        }
3135                    } else {
3136                        self.visit_expr(then);
3137                        let is_never = mem::replace(&mut self.is_never, false);
3138                        if let Some(else_) = else_ {
3139                            self.visit_expr(else_);
3140                            self.is_never &= is_never;
3141                        }
3142                    }
3143                },
3144                ExprKind::Match(scrutinee, arms, _) => {
3145                    let in_final_expr = mem::replace(&mut self.in_final_expr, false);
3146                    self.visit_expr(scrutinee);
3147                    self.in_final_expr = in_final_expr;
3148
3149                    if self.is_never {
3150                        for arm in arms {
3151                            self.visit_arm(arm);
3152                        }
3153                    } else {
3154                        let mut is_never = true;
3155                        for arm in arms {
3156                            self.is_never = false;
3157                            if let Some(guard) = arm.guard {
3158                                let in_final_expr = mem::replace(&mut self.in_final_expr, false);
3159                                self.visit_expr(guard);
3160                                self.in_final_expr = in_final_expr;
3161                                // The compiler doesn't consider diverging guards as causing the arm
3162                                // to diverge.
3163                                self.is_never = false;
3164                            }
3165                            self.visit_expr(arm.body);
3166                            is_never &= self.is_never;
3167                        }
3168                        self.is_never = is_never;
3169                    }
3170                },
3171                ExprKind::Loop(b, _, _, _) => {
3172                    self.push_break_target(e.hir_id);
3173                    self.in_final_expr = false;
3174                    self.visit_block(b);
3175                    self.is_never = self.break_targets.pop().unwrap().unused;
3176                },
3177                ExprKind::Block(b, _) => {
3178                    if b.targeted_by_break {
3179                        self.push_break_target(b.hir_id);
3180                        self.visit_block(b);
3181                        self.is_never &= self.break_targets.pop().unwrap().unused;
3182                    } else {
3183                        self.visit_block(b);
3184                    }
3185                },
3186                _ => {
3187                    self.in_final_expr = false;
3188                    walk_expr(self, e);
3189                    self.is_never |= self.cx.typeck_results().expr_ty(e).is_never();
3190                },
3191            }
3192        }
3193
3194        fn visit_block(&mut self, b: &'tcx Block<'_>) {
3195            let in_final_expr = mem::replace(&mut self.in_final_expr, false);
3196            for s in b.stmts {
3197                self.visit_stmt(s);
3198            }
3199            self.in_final_expr = in_final_expr;
3200            if let Some(e) = b.expr {
3201                self.visit_expr(e);
3202            }
3203        }
3204
3205        fn visit_local(&mut self, l: &'tcx LetStmt<'_>) {
3206            if let Some(e) = l.init {
3207                self.visit_expr(e);
3208            }
3209            if let Some(else_) = l.els {
3210                let is_never = self.is_never;
3211                self.visit_block(else_);
3212                self.is_never = is_never;
3213            }
3214        }
3215
3216        fn visit_arm(&mut self, arm: &Arm<'tcx>) {
3217            if let Some(guard) = arm.guard {
3218                let in_final_expr = mem::replace(&mut self.in_final_expr, false);
3219                self.visit_expr(guard);
3220                self.in_final_expr = in_final_expr;
3221            }
3222            self.visit_expr(arm.body);
3223        }
3224    }
3225
3226    if cx.typeck_results().expr_ty(e).is_never() {
3227        Some(RequiresSemi::No)
3228    } else if let ExprKind::Block(b, _) = e.kind
3229        && !b.targeted_by_break
3230        && b.expr.is_none()
3231    {
3232        // If a block diverges without a final expression then it's type is `!`.
3233        None
3234    } else {
3235        let mut v = V {
3236            cx,
3237            break_targets: Vec::new(),
3238            break_targets_for_result_ty: 0,
3239            in_final_expr: true,
3240            requires_semi: false,
3241            is_never: false,
3242        };
3243        v.visit_expr(e);
3244        v.is_never
3245            .then_some(if v.requires_semi && matches!(e.kind, ExprKind::Block(..)) {
3246                RequiresSemi::Yes
3247            } else {
3248                RequiresSemi::No
3249            })
3250    }
3251}
3252
3253/// Produces a path from a local caller to the type of the called method. Suitable for user
3254/// output/suggestions.
3255///
3256/// Returned path can be either absolute (for methods defined non-locally), or relative (for local
3257/// methods).
3258pub fn get_path_from_caller_to_method_type<'tcx>(
3259    tcx: TyCtxt<'tcx>,
3260    from: LocalDefId,
3261    method: DefId,
3262    args: rustc_ty::GenericArgs<'tcx>,
3263) -> String {
3264    let assoc_item = tcx.associated_item(method);
3265    let def_id = assoc_item.container_id(tcx);
3266    match assoc_item.container {
3267        rustc_ty::AssocContainer::Trait => get_path_to_callee(tcx, from, def_id),
3268        rustc_ty::AssocContainer::InherentImpl | rustc_ty::AssocContainer::TraitImpl(_) => {
3269            let ty = tcx.type_of(def_id).instantiate_identity().skip_norm_wip();
3270            get_path_to_ty(tcx, from, ty, args)
3271        },
3272    }
3273}
3274
3275fn get_path_to_ty<'tcx>(
3276    tcx: TyCtxt<'tcx>,
3277    from: LocalDefId,
3278    ty: Ty<'tcx>,
3279    args: rustc_ty::GenericArgs<'tcx>,
3280) -> String {
3281    match ty.kind() {
3282        rustc_ty::Adt(adt, _) => get_path_to_callee(tcx, from, adt.did()),
3283        // TODO these types need to be recursively resolved as well
3284        rustc_ty::Array(..)
3285        | rustc_ty::Dynamic(..)
3286        | rustc_ty::Never
3287        | rustc_ty::RawPtr(_, _)
3288        | rustc_ty::Ref(..)
3289        | rustc_ty::Slice(_)
3290        | rustc_ty::Tuple(_) => format!(
3291            "<{}>",
3292            EarlyBinder::bind(tcx, ty).instantiate(tcx, args).skip_norm_wip()
3293        ),
3294        _ => ty.to_string(),
3295    }
3296}
3297
3298/// Produce a path from some local caller to the callee. Suitable for user output/suggestions.
3299fn get_path_to_callee(tcx: TyCtxt<'_>, from: LocalDefId, callee: DefId) -> String {
3300    // only search for a relative path if the call is fully local
3301    if callee.is_local() {
3302        let callee_path = tcx.def_path(callee);
3303        let caller_path = tcx.def_path(from.to_def_id());
3304        maybe_get_relative_path(&caller_path, &callee_path, 2)
3305    } else {
3306        tcx.def_path_str(callee)
3307    }
3308}
3309
3310/// Tries to produce a relative path from `from` to `to`; if such a path would contain more than
3311/// `max_super` `super` items, produces an absolute path instead. Both `from` and `to` should be in
3312/// the local crate.
3313///
3314/// Suitable for user output/suggestions.
3315///
3316/// This ignores use items, and assumes that the target path is visible from the source
3317/// path (which _should_ be a reasonable assumption since we in order to be able to use an object of
3318/// certain type T, T is required to be visible).
3319///
3320/// TODO make use of `use` items. Maybe we should have something more sophisticated like
3321/// rust-analyzer does? <https://docs.rs/ra_ap_hir_def/0.0.169/src/ra_ap_hir_def/find_path.rs.html#19-27>
3322fn maybe_get_relative_path(from: &DefPath, to: &DefPath, max_super: usize) -> String {
3323    use itertools::EitherOrBoth::{Both, Left, Right};
3324
3325    // 1. skip the segments common for both paths (regardless of their type)
3326    let unique_parts = to
3327        .data
3328        .iter()
3329        .zip_longest(from.data.iter())
3330        .skip_while(|el| matches!(el, Both(l, r) if l == r))
3331        .map(|el| match el {
3332            Both(l, r) => Both(l.data, r.data),
3333            Left(l) => Left(l.data),
3334            Right(r) => Right(r.data),
3335        });
3336
3337    // 2. for the remaining segments, construct relative path using only mod names and `super`
3338    let mut go_up_by = 0;
3339    let mut path = Vec::new();
3340    for el in unique_parts {
3341        match el {
3342            Both(l, r) => {
3343                // consider:
3344                // a::b::sym:: ::    refers to
3345                // c::d::e  ::f::sym
3346                // result should be super::super::c::d::e::f
3347                //
3348                // alternatively:
3349                // a::b::c  ::d::sym refers to
3350                // e::f::sym:: ::
3351                // result should be super::super::super::super::e::f
3352                if let DefPathData::TypeNs(sym) = l {
3353                    path.push(sym);
3354                }
3355                if let DefPathData::TypeNs(_) = r {
3356                    go_up_by += 1;
3357                }
3358            },
3359            // consider:
3360            // a::b::sym:: ::    refers to
3361            // c::d::e  ::f::sym
3362            // when looking at `f`
3363            Left(DefPathData::TypeNs(sym)) => path.push(sym),
3364            // consider:
3365            // a::b::c  ::d::sym refers to
3366            // e::f::sym:: ::
3367            // when looking at `d`
3368            Right(DefPathData::TypeNs(_)) => go_up_by += 1,
3369            _ => {},
3370        }
3371    }
3372
3373    if go_up_by > max_super {
3374        // `super` chain would be too long, just use the absolute path instead
3375        join_path_syms(once(kw::Crate).chain(to.data.iter().filter_map(|el| {
3376            if let DefPathData::TypeNs(sym) = el.data {
3377                Some(sym)
3378            } else {
3379                None
3380            }
3381        })))
3382    } else if go_up_by == 0 && path.is_empty() {
3383        String::from("Self")
3384    } else {
3385        join_path_syms(repeat_n(kw::Super, go_up_by).chain(path))
3386    }
3387}
3388
3389/// Returns true if the specified `HirId` is the top-level expression of a statement or the only
3390/// expression in a block.
3391pub fn is_parent_stmt(cx: &LateContext<'_>, id: HirId) -> bool {
3392    matches!(
3393        cx.tcx.parent_hir_node(id),
3394        Node::Stmt(..) | Node::Block(Block { stmts: [], .. })
3395    )
3396}
3397
3398/// Returns true if the given `expr` is a block or resembled as a block,
3399/// such as `if`, `loop`, `match` expressions etc.
3400pub fn is_block_like(expr: &Expr<'_>) -> bool {
3401    matches!(
3402        expr.kind,
3403        ExprKind::Block(..) | ExprKind::ConstBlock(..) | ExprKind::If(..) | ExprKind::Loop(..) | ExprKind::Match(..)
3404    )
3405}
3406
3407/// Returns true if the given `expr` is binary expression that needs to be wrapped in parentheses.
3408pub fn binary_expr_needs_parentheses(expr: &Expr<'_>) -> bool {
3409    fn contains_block(expr: &Expr<'_>, is_operand: bool) -> bool {
3410        match expr.kind {
3411            ExprKind::Binary(_, lhs, _) | ExprKind::Cast(lhs, _) => contains_block(lhs, true),
3412            _ if is_block_like(expr) => is_operand,
3413            _ => false,
3414        }
3415    }
3416
3417    contains_block(expr, false)
3418}
3419
3420/// Returns true if the specified expression is in a receiver position.
3421pub fn is_receiver_of_method_call(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
3422    if let Some(parent_expr) = get_parent_expr(cx, expr)
3423        && let ExprKind::MethodCall(_, receiver, ..) = parent_expr.kind
3424        && receiver.hir_id == expr.hir_id
3425    {
3426        return true;
3427    }
3428    false
3429}
3430
3431/// Returns true if `expr` creates any temporary whose type references a non-static lifetime and has
3432/// a significant drop and does not consume it.
3433pub fn leaks_droppable_temporary_with_limited_lifetime<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> bool {
3434    for_each_unconsumed_temporary(cx, expr, |temporary_ty| {
3435        if temporary_ty.has_significant_drop(cx.tcx, cx.typing_env())
3436            && temporary_ty
3437                .walk()
3438                .any(|arg| matches!(arg.kind(), GenericArgKind::Lifetime(re) if !re.is_static()))
3439        {
3440            ControlFlow::Break(())
3441        } else {
3442            ControlFlow::Continue(())
3443        }
3444    })
3445    .is_break()
3446}
3447
3448/// Returns true if `expr` creates any temporary that has a significant drop and does not consume
3449/// it.
3450pub fn leaks_droppable_temporary<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> bool {
3451    for_each_unconsumed_temporary(cx, expr, |temporary_ty| {
3452        if temporary_ty.has_significant_drop(cx.tcx, cx.typing_env()) {
3453            ControlFlow::Break(())
3454        } else {
3455            ControlFlow::Continue(())
3456        }
3457    })
3458    .is_break()
3459}
3460
3461/// Returns true if the specified `expr` requires coercion,
3462/// meaning that it either has a coercion or propagates a coercion from one of its sub expressions.
3463///
3464/// Similar to [`is_adjusted`], this not only checks if an expression's type was adjusted,
3465/// but also going through extra steps to see if it fits the description of [coercion sites].
3466///
3467/// You should used this when you want to avoid suggesting replacing an expression that is currently
3468/// a coercion site or coercion propagating expression with one that is not.
3469///
3470/// [coercion sites]: https://doc.rust-lang.org/stable/reference/type-coercions.html#coercion-sites
3471pub fn expr_requires_coercion<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'tcx>) -> bool {
3472    let expr_ty_is_adjusted = cx
3473        .typeck_results()
3474        .expr_adjustments(expr)
3475        .iter()
3476        // ignore `NeverToAny` adjustments, such as `panic!` call.
3477        .any(|adj| !matches!(adj.kind, Adjust::NeverToAny));
3478    if expr_ty_is_adjusted {
3479        return true;
3480    }
3481
3482    // Identify coercion sites and recursively check if those sites
3483    // actually have type adjustments.
3484    match expr.kind {
3485        ExprKind::Call(_, args) | ExprKind::MethodCall(_, _, args, _) if let Some(def_id) = fn_def_id(cx, expr) => {
3486            let fn_sig = cx.tcx.fn_sig(def_id).instantiate_identity().skip_norm_wip();
3487
3488            if !fn_sig.output().skip_binder().has_type_flags(TypeFlags::HAS_TY_PARAM) {
3489                return false;
3490            }
3491
3492            let self_arg_count = usize::from(matches!(expr.kind, ExprKind::MethodCall(..)));
3493            let mut args_with_ty_param = {
3494                fn_sig
3495                    .inputs()
3496                    .skip_binder()
3497                    .iter()
3498                    .skip(self_arg_count)
3499                    .zip(args)
3500                    .filter_map(|(arg_ty, arg)| {
3501                        if arg_ty.has_type_flags(TypeFlags::HAS_TY_PARAM) {
3502                            Some(arg)
3503                        } else {
3504                            None
3505                        }
3506                    })
3507            };
3508            args_with_ty_param.any(|arg| expr_requires_coercion(cx, arg))
3509        },
3510        // Struct/union initialization.
3511        ExprKind::Struct(qpath, _, _) => {
3512            let res = cx.typeck_results().qpath_res(qpath, expr.hir_id);
3513            if let Some((_, v_def)) = adt_and_variant_of_res(cx, res) {
3514                let rustc_ty::Adt(_, generic_args) = cx.typeck_results().expr_ty_adjusted(expr).kind() else {
3515                    // This should never happen, but when it does, not linting is the better option.
3516                    return true;
3517                };
3518                v_def
3519                    .fields
3520                    .iter()
3521                    .any(|field| field.ty(cx.tcx, *generic_args).has_type_flags(TypeFlags::HAS_TY_PARAM))
3522            } else {
3523                false
3524            }
3525        },
3526        // Function results, including the final line of a block or a `return` expression.
3527        ExprKind::Block(
3528            &Block {
3529                expr: Some(ret_expr), ..
3530            },
3531            _,
3532        )
3533        | ExprKind::Ret(Some(ret_expr)) => expr_requires_coercion(cx, ret_expr),
3534
3535        // ===== Coercion-propagation expressions =====
3536        ExprKind::Array(elems) | ExprKind::Tup(elems) => elems.iter().any(|elem| expr_requires_coercion(cx, elem)),
3537        // Array but with repeating syntax.
3538        ExprKind::Repeat(rep_elem, _) => expr_requires_coercion(cx, rep_elem),
3539        // Others that may contain coercion sites.
3540        ExprKind::If(_, then, maybe_else) => {
3541            expr_requires_coercion(cx, then) || maybe_else.is_some_and(|e| expr_requires_coercion(cx, e))
3542        },
3543        ExprKind::Match(_, arms, _) => arms
3544            .iter()
3545            .map(|arm| arm.body)
3546            .any(|body| expr_requires_coercion(cx, body)),
3547        _ => false,
3548    }
3549}
3550
3551/// Returns `true` if `expr` designates a mutable static, a mutable local binding, or an expression
3552/// that can be owned.
3553pub fn is_mutable(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
3554    if let Some(hir_id) = expr.res_local_id()
3555        && let Node::Pat(pat) = cx.tcx.hir_node(hir_id)
3556    {
3557        matches!(pat.kind, PatKind::Binding(BindingMode::MUT, ..))
3558    } else if let ExprKind::Path(p) = &expr.kind
3559        && let Some(mutability) = cx
3560            .qpath_res(p, expr.hir_id)
3561            .opt_def_id()
3562            .and_then(|id| cx.tcx.static_mutability(id))
3563    {
3564        mutability == Mutability::Mut
3565    } else if let ExprKind::Field(parent, _) = expr.kind {
3566        is_mutable(cx, parent)
3567    } else {
3568        true
3569    }
3570}
3571
3572/// Peel `Option<…>` from `hir_ty` as long as the HIR name is `Option` and it corresponds to the
3573/// `core::Option<_>` type.
3574pub fn peel_hir_ty_options<'tcx>(cx: &LateContext<'tcx>, mut hir_ty: &'tcx hir::Ty<'tcx>) -> &'tcx hir::Ty<'tcx> {
3575    let Some(option_def_id) = cx.tcx.get_diagnostic_item(sym::Option) else {
3576        return hir_ty;
3577    };
3578    while let TyKind::Path(QPath::Resolved(None, path)) = hir_ty.kind
3579        && let Some(segment) = path.segments.last()
3580        && segment.ident.name == sym::Option
3581        && let Res::Def(DefKind::Enum, def_id) = segment.res
3582        && def_id == option_def_id
3583        && let [GenericArg::Type(arg_ty)] = segment.args().args
3584    {
3585        hir_ty = arg_ty.as_unambig_ty();
3586    }
3587    hir_ty
3588}
3589
3590/// If `expr` is a desugared `.await`, return the original expression if it does not come from a
3591/// macro expansion.
3592pub fn desugar_await<'tcx>(expr: &'tcx Expr<'_>) -> Option<&'tcx Expr<'tcx>> {
3593    if let ExprKind::Match(match_value, _, MatchSource::AwaitDesugar) = expr.kind
3594        && let ExprKind::Call(_, [into_future_arg]) = match_value.kind
3595        && let ctxt = expr.span.ctxt()
3596        && for_each_expr_without_closures(into_future_arg, |e| {
3597            walk_span_to_context(e.span, ctxt).map_or(ControlFlow::Break(()), |_| ControlFlow::Continue(()))
3598        })
3599        .is_none()
3600    {
3601        Some(into_future_arg)
3602    } else {
3603        None
3604    }
3605}
3606
3607/// Checks if the given expression is a call to `Default::default()`.
3608pub fn is_expr_default<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> bool {
3609    if let ExprKind::Call(fn_expr, []) = &expr.kind
3610        && let ExprKind::Path(qpath) = &fn_expr.kind
3611        && let Res::Def(_, def_id) = cx.qpath_res(qpath, fn_expr.hir_id)
3612    {
3613        cx.tcx.is_diagnostic_item(sym::default_fn, def_id)
3614    } else {
3615        false
3616    }
3617}
3618
3619/// Checks if `expr` may be directly used as the return value of its enclosing body.
3620/// The following cases are covered:
3621/// - `expr` as the last expression of the body, or of a block that can be used as the return value
3622/// - `return expr`
3623/// - then or else part of a `if` in return position
3624/// - arm body of a `match` in a return position
3625/// - `break expr` or `break 'label expr` if the loop or block being exited is used as a return value
3626///
3627/// Contrary to [`TyCtxt::hir_get_fn_id_for_return_block()`], if `expr` is part of a
3628/// larger expression, for example a field expression of a `struct`, it will not be
3629/// considered as matching the condition and will return `false`.
3630///
3631/// Also, even if `expr` is assigned to a variable which is later returned, this function
3632/// will still return `false` because `expr` is not used *directly* as the return value
3633/// as it goes through the intermediate variable.
3634pub fn potential_return_of_enclosing_body(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
3635    let enclosing_body_owner = cx
3636        .tcx
3637        .local_def_id_to_hir_id(cx.tcx.hir_enclosing_body_owner(expr.hir_id));
3638    let mut prev_id = expr.hir_id;
3639    let mut skip_until_id = None;
3640    for (hir_id, node) in cx.tcx.hir_parent_iter(expr.hir_id) {
3641        if hir_id == enclosing_body_owner {
3642            return true;
3643        }
3644        if let Some(id) = skip_until_id {
3645            prev_id = hir_id;
3646            if id == hir_id {
3647                skip_until_id = None;
3648            }
3649            continue;
3650        }
3651        match node {
3652            Node::Block(Block { expr, .. }) if expr.is_some_and(|expr| expr.hir_id == prev_id) => {},
3653            Node::Arm(arm) if arm.body.hir_id == prev_id => {},
3654            Node::Expr(expr) => match expr.kind {
3655                ExprKind::Ret(_) => return true,
3656                ExprKind::If(_, then, opt_else)
3657                    if then.hir_id == prev_id || opt_else.is_some_and(|els| els.hir_id == prev_id) => {},
3658                ExprKind::Match(_, arms, _) if arms.iter().any(|arm| arm.hir_id == prev_id) => {},
3659                ExprKind::Block(block, _) if block.hir_id == prev_id => {},
3660                ExprKind::Break(
3661                    Destination {
3662                        target_id: Ok(target_id),
3663                        ..
3664                    },
3665                    _,
3666                ) => skip_until_id = Some(target_id),
3667                _ => break,
3668            },
3669            _ => break,
3670        }
3671        prev_id = hir_id;
3672    }
3673
3674    // `expr` is used as part of "something" and is not returned directly from its
3675    // enclosing body.
3676    false
3677}
3678
3679/// Checks if the expression has adjustments that require coercion, for example: dereferencing with
3680/// overloaded deref, coercing pointers and `dyn` objects.
3681pub fn expr_adjustment_requires_coercion(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
3682    cx.typeck_results().expr_adjustments(expr).iter().any(|adj| {
3683        matches!(
3684            adj.kind,
3685            Adjust::Deref(DerefAdjustKind::Overloaded(_))
3686                | Adjust::Pointer(PointerCoercion::Unsize)
3687                | Adjust::NeverToAny
3688        )
3689    })
3690}
3691
3692/// Checks if the expression is an async block (i.e., `async { ... }`).
3693pub fn is_expr_async_block(expr: &Expr<'_>) -> bool {
3694    matches!(
3695        expr.kind,
3696        ExprKind::Closure(Closure {
3697            kind: hir::ClosureKind::Coroutine(CoroutineKind::Desugared(
3698                CoroutineDesugaring::Async,
3699                CoroutineSource::Block
3700            )),
3701            ..
3702        })
3703    )
3704}
3705
3706/// Checks if the chosen edition and `msrv` allows using `if let` chains.
3707pub fn can_use_if_let_chains(cx: &LateContext<'_>, msrv: Msrv) -> bool {
3708    cx.tcx.sess.edition().at_least_rust_2024() && msrv.meets(cx, msrvs::LET_CHAINS)
3709}
3710
3711/// Returns an iterator over successive parent nodes paired with the ID of the node which
3712/// immediatly preceeded them.
3713#[inline]
3714pub fn hir_parent_with_src_iter(tcx: TyCtxt<'_>, mut id: HirId) -> impl Iterator<Item = (Node<'_>, HirId)> {
3715    tcx.hir_parent_id_iter(id)
3716        .map(move |parent| (tcx.hir_node(parent), mem::replace(&mut id, parent)))
3717}