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
15extern 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
129pub 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
147pub 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
180pub 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
198pub 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
213pub 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
232pub 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
252pub 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
270pub 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 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
285pub 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 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
300pub fn is_none_expr(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
302 expr.basic_res().ctor_parent(cx).is_lang_item(cx, OptionNone)
303}
304
305pub 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
316pub 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
331pub 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
346pub fn is_wild(pat: &Pat<'_>) -> bool {
348 matches!(pat.kind, PatKind::Wild)
349}
350
351pub 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
370pub 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
377pub 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
387pub 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
396pub 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
426pub 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
455pub 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
472pub 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
497fn 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
523pub 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
536pub 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
569fn 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
599pub 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 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 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
692pub 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
751pub 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 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 false
819 },
820 _ => true,
821 }
822}
823
824#[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
854pub 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 CaptureKind::Ref(Mutability::Not)
947 } else {
948 capture
949 }
950}
951
952pub 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 loops: Vec<HirId>,
959 locals: HirIdSet,
961 allow_closure: bool,
963 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
1035pub type MethodArguments<'tcx> = Vec<(&'tcx Expr<'tcx>, &'tcx [Expr<'tcx>])>;
1037
1038pub 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, _) = ¤t.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
1063pub 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 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)); current = receiver; } else {
1082 return None;
1083 }
1084 } else {
1085 return None;
1086 }
1087 }
1088 matched.reverse();
1090 Some(matched)
1091}
1092
1093pub 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
1100pub 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
1106pub 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
1138pub 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
1144pub 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
1156pub 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
1161pub 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
1170pub 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
1197pub 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
1210pub 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
1218pub 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 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
1241pub 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
1255pub 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
1281pub 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
1319pub 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
1334pub 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
1350pub 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
1361pub 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
1380pub 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
1390pub 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
1401pub 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
1412pub fn is_adjusted(cx: &LateContext<'_>, e: &Expr<'_>) -> bool {
1420 cx.typeck_results().adjustments().get(e.hir_id).is_some()
1421}
1422
1423#[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#[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
1472pub 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
1478pub 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
1489pub 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
1504pub 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, 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 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 !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 true
1549 },
1550 }
1551 },
1552 PatKind::Expr(..) | PatKind::Range(..) | PatKind::Err(_) | PatKind::Deref(_) | PatKind::Guard(..) => true,
1553 }
1554}
1555
1556pub 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
1587pub 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 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
1633pub 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
1660pub 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)]
1683pub 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)]
1690pub 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
1696pub 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
1707pub 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
1715pub fn requires_exact_signature(attrs: &[rustc_attr_ir::Attribute]) -> bool {
1717 find_attr!(attrs, ProcMacro | ProcMacroAttribute | ProcMacroDerive { .. })
1718}
1719
1720pub fn match_libc_symbol(cx: &LateContext<'_>, did: DefId, name: Symbol) -> bool {
1722 cx.tcx.crate_name(did.krate) == sym::libc && cx.tcx.def_path_str(did).ends_with(name.as_str())
1726}
1727
1728pub fn if_sequence<'tcx>(mut expr: &'tcx Expr<'tcx>) -> (Vec<&'tcx Expr<'tcx>>, Vec<&'tcx Block<'tcx>>) {
1733 let mut conds = Vec::new();
1734 let mut blocks: Vec<&Block<'_>> = Vec::new();
1735
1736 while let Some(higher::IfOrIfLet { cond, then, r#else }) = higher::IfOrIfLet::hir(expr) {
1737 conds.push(cond);
1738 if let ExprKind::Block(block, _) = then.kind {
1739 blocks.push(block);
1740 } else {
1741 panic!("ExprKind::If node is not an ExprKind::Block");
1742 }
1743
1744 if let Some(else_expr) = r#else {
1745 expr = else_expr;
1746 } else {
1747 break;
1748 }
1749 }
1750
1751 if !blocks.is_empty()
1753 && let ExprKind::Block(block, _) = expr.kind
1754 {
1755 blocks.push(block);
1756 }
1757
1758 (conds, blocks)
1759}
1760
1761pub fn get_async_closure_expr<'tcx>(tcx: TyCtxt<'tcx>, expr: &Expr<'_>) -> Option<&'tcx Expr<'tcx>> {
1763 if let ExprKind::Closure(&Closure {
1764 body,
1765 kind: hir::ClosureKind::Coroutine(CoroutineKind::Desugared(CoroutineDesugaring::Async, _)),
1766 ..
1767 }) = expr.kind
1768 && let ExprKind::Block(
1769 Block {
1770 expr:
1771 Some(Expr {
1772 kind: ExprKind::DropTemps(inner_expr),
1773 ..
1774 }),
1775 ..
1776 },
1777 _,
1778 ) = tcx.hir_body(body).value.kind
1779 {
1780 Some(inner_expr)
1781 } else {
1782 None
1783 }
1784}
1785
1786pub fn get_async_fn_body<'tcx>(tcx: TyCtxt<'tcx>, body: &Body<'_>) -> Option<&'tcx Expr<'tcx>> {
1788 get_async_closure_expr(tcx, body.value)
1789}
1790
1791pub fn is_must_use_func_call(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
1793 let did = match expr.kind {
1794 ExprKind::Call(path, _) => {
1795 if let ExprKind::Path(ref qpath) = path.kind
1796 && let Res::Def(_, did) = cx.qpath_res(qpath, path.hir_id)
1797 {
1798 Some(did)
1799 } else {
1800 None
1801 }
1802 },
1803 ExprKind::MethodCall(..) => cx.typeck_results().type_dependent_def_id(expr.hir_id),
1804 _ => None,
1805 };
1806
1807 did.is_some_and(|did| find_attr!(cx.tcx, did, MustUse { .. }))
1808}
1809
1810fn 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 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
1907pub 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 return false;
1927 }
1928
1929 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 if let ExprKind::Path(ident) = &ident.kind
1952 && qpath_res(&pat_ident, pat.hir_id) == qpath_res(ident, expr.hir_id)
1953 && 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 qpath_res(&pat_ident, pat.hir_id) == qpath_res(ident, expr.hir_id)
1966 && 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
1975pub 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
1996pub 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
2011pub 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
2030pub 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
2052pub fn is_expr_final_block_expr(tcx: TyCtxt<'_>, expr: &Expr<'_>) -> bool {
2054 matches!(tcx.parent_hir_node(expr.hir_id), Node::Block(..))
2055}
2056
2057pub 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
2077pub 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
2094pub 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
2114pub fn fn_def_id(cx: &LateContext<'_>, expr: &Expr<'_>) -> Option<DefId> {
2116 fn_def_id_with_node_args(cx, expr).map(|(did, _)| did)
2117}
2118
2119pub 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 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
2153pub 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 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 let refs_peeled = expr_type.peel_refs();
2183 return Some(refs_peeled.walk().last().unwrap().to_string());
2184 },
2185 }
2186 }
2187 None
2188}
2189
2190pub 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
2232pub 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
2245pub 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
2256pub 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
2270pub 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
2282pub 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
2296pub 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
2311pub 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
2319pub 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
2332pub 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
2361fn 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 && 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
2388pub fn is_in_test_function(tcx: TyCtxt<'_>, id: HirId) -> bool {
2392 let names = test_item_names(tcx, tcx.parent_module(id));
2393 if names.is_empty() {
2395 return false;
2396 }
2397 once((id, tcx.hir_node(id)))
2398 .chain(tcx.hir_parent_iter(id))
2399 .any(|(_id, node)| {
2402 if let Node::Item(item) = node
2403 && let ItemKind::Fn { ident, .. } = item.kind
2404 {
2405 return names.binary_search(&ident.name).is_ok();
2408 }
2409 false
2410 })
2411}
2412
2413pub 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
2432pub 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
2448pub 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
2453pub 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
2458fn 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
2469pub 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#[derive(Clone, Copy)]
2481pub enum DefinedTy<'tcx> {
2482 Hir(&'tcx hir::Ty<'tcx>),
2484 Mir {
2492 def_site_def_id: Option<DefId>,
2493 ty: Binder<'tcx, Ty<'tcx>>,
2494 },
2495}
2496
2497pub struct ExprUseSite<'tcx> {
2499 pub node: Node<'tcx>,
2501 pub child_id: HirId,
2503 pub adjustments: &'tcx [Adjustment<'tcx>],
2505 pub is_ty_unified: bool,
2507 pub moved_before_use: bool,
2509 pub same_ctxt: bool,
2511}
2512impl<'tcx> 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
2576pub enum ExprUseNode<'tcx> {
2578 LetStmt(&'tcx LetStmt<'tcx>),
2580 ConstStatic(OwnerId),
2582 Return(OwnerId),
2584 Field(&'tcx ExprField<'tcx>),
2586 FnArg(&'tcx Expr<'tcx>, usize),
2588 MethodArg(HirId, Option<&'tcx GenericArgs<'tcx>>, usize),
2590 Callee,
2592 FieldAccess(Ident),
2594 AddrOf(ast::BorrowKind, Mutability),
2596 Other,
2597}
2598impl<'tcx> ExprUseNode<'tcx> {
2599 pub fn is_return(&self) -> bool {
2601 matches!(self, Self::Return(_))
2602 }
2603
2604 pub fn is_recv(&self) -> bool {
2606 matches!(self, Self::MethodArg(_, _, 0))
2607 }
2608
2609 pub fn defined_ty(&self, cx: &LateContext<'tcx>) -> Option<DefinedTy<'tcx>> {
2611 match *self {
2612 Self::LetStmt(LetStmt { ty: Some(ty), .. }) => Some(DefinedTy::Hir(ty)),
2613 Self::ConstStatic(id) => Some(DefinedTy::Mir {
2614 def_site_def_id: Some(id.def_id.to_def_id()),
2615 ty: Binder::dummy(cx.tcx.type_of(id).instantiate_identity().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#[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 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 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, 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
2856pub 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
2868pub 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
2881pub 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
2895pub fn span_extract_comment<'sm>(sm: impl HasSourceMap<'sm>, span: Span) -> String {
2899 span_extract_comments(sm, span).join("\n")
2900}
2901
2902pub 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
2919pub 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 pub static BINOP_TRAITS: &[LangItem] = &[$(LangItem::$name,)*];
2968
2969 pub static OP_ASSIGN_TRAITS: &[LangItem] = &[$(LangItem::$assign,)*];
2971
2972 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
2995pub 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#[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 if self.is_never && self.break_targets.is_empty() {
3062 if self.in_final_expr && !self.requires_semi {
3063 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 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 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
3253pub 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 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
3298fn get_path_to_callee(tcx: TyCtxt<'_>, from: LocalDefId, callee: DefId) -> String {
3300 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
3310fn maybe_get_relative_path(from: &DefPath, to: &DefPath, max_super: usize) -> String {
3323 use itertools::EitherOrBoth::{Both, Left, Right};
3324
3325 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 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 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 Left(DefPathData::TypeNs(sym)) => path.push(sym),
3364 Right(DefPathData::TypeNs(_)) => go_up_by += 1,
3369 _ => {},
3370 }
3371 }
3372
3373 if go_up_by > max_super {
3374 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
3389pub 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
3398pub 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
3407pub 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
3420pub 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
3431pub 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
3448pub 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
3461pub 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 .any(|adj| !matches!(adj.kind, Adjust::NeverToAny));
3478 if expr_ty_is_adjusted {
3479 return true;
3480 }
3481
3482 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 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 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 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 ExprKind::Array(elems) | ExprKind::Tup(elems) => elems.iter().any(|elem| expr_requires_coercion(cx, elem)),
3537 ExprKind::Repeat(rep_elem, _) => expr_requires_coercion(cx, rep_elem),
3539 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
3551pub 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
3572pub 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
3590pub 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
3607pub 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
3619pub 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 false
3677}
3678
3679pub 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
3692pub 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
3706pub 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#[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}