]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_utils/src/ty.rs
Auto merge of #102394 - dingxiangfei2009:issue-102317, r=oli-obk
[rust.git] / src / tools / clippy / clippy_utils / src / ty.rs
1 //! Util methods for [`rustc_middle::ty`]
2
3 #![allow(clippy::module_name_repetitions)]
4
5 use core::ops::ControlFlow;
6 use rustc_ast::ast::Mutability;
7 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
8 use rustc_hir as hir;
9 use rustc_hir::def::{CtorKind, CtorOf, DefKind, Res};
10 use rustc_hir::def_id::DefId;
11 use rustc_hir::{Expr, FnDecl, LangItem, TyKind, Unsafety};
12 use rustc_infer::infer::TyCtxtInferExt;
13 use rustc_lint::LateContext;
14 use rustc_middle::mir::interpret::{ConstValue, Scalar};
15 use rustc_middle::ty::{GenericArg, GenericArgKind};
16 use rustc_middle::ty::{
17     self, AdtDef, Binder, BoundRegion, DefIdTree, FnSig, IntTy, ParamEnv, Predicate, PredicateKind, ProjectionTy,
18     Region, RegionKind, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable, TypeVisitor, UintTy, VariantDef, VariantDiscr,
19 };
20 use rustc_span::symbol::Ident;
21 use rustc_span::{sym, Span, Symbol, DUMMY_SP};
22 use rustc_target::abi::{Size, VariantIdx};
23 use rustc_trait_selection::infer::InferCtxtExt;
24 use rustc_trait_selection::traits::query::normalize::AtExt;
25 use std::iter;
26
27 use crate::{match_def_path, path_res, paths};
28
29 // Checks if the given type implements copy.
30 pub fn is_copy<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
31     ty.is_copy_modulo_regions(cx.tcx.at(DUMMY_SP), cx.param_env)
32 }
33
34 /// This checks whether a given type is known to implement Debug.
35 pub fn has_debug_impl<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
36     cx.tcx
37         .get_diagnostic_item(sym::Debug)
38         .map_or(false, |debug| implements_trait(cx, ty, debug, &[]))
39 }
40
41 /// Checks whether a type can be partially moved.
42 pub fn can_partially_move_ty<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
43     if has_drop(cx, ty) || is_copy(cx, ty) {
44         return false;
45     }
46     match ty.kind() {
47         ty::Param(_) => false,
48         ty::Adt(def, subs) => def.all_fields().any(|f| !is_copy(cx, f.ty(cx.tcx, subs))),
49         _ => true,
50     }
51 }
52
53 /// Walks into `ty` and returns `true` if any inner type is an instance of the given adt
54 /// constructor.
55 pub fn contains_adt_constructor<'tcx>(ty: Ty<'tcx>, adt: AdtDef<'tcx>) -> bool {
56     ty.walk().any(|inner| match inner.unpack() {
57         GenericArgKind::Type(inner_ty) => inner_ty.ty_adt_def() == Some(adt),
58         GenericArgKind::Lifetime(_) | GenericArgKind::Const(_) => false,
59     })
60 }
61
62 /// Resolves `<T as Iterator>::Item` for `T`
63 /// Do not invoke without first verifying that the type implements `Iterator`
64 pub fn get_iterator_item_ty<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> Option<Ty<'tcx>> {
65     cx.tcx
66         .get_diagnostic_item(sym::Iterator)
67         .and_then(|iter_did| get_associated_type(cx, ty, iter_did, "Item"))
68 }
69
70 /// Returns the associated type `name` for `ty` as an implementation of `trait_id`.
71 /// Do not invoke without first verifying that the type implements the trait.
72 pub fn get_associated_type<'tcx>(
73     cx: &LateContext<'tcx>,
74     ty: Ty<'tcx>,
75     trait_id: DefId,
76     name: &str,
77 ) -> Option<Ty<'tcx>> {
78     cx.tcx
79         .associated_items(trait_id)
80         .find_by_name_and_kind(cx.tcx, Ident::from_str(name), ty::AssocKind::Type, trait_id)
81         .and_then(|assoc| {
82             let proj = cx.tcx.mk_projection(assoc.def_id, cx.tcx.mk_substs_trait(ty, &[]));
83             cx.tcx.try_normalize_erasing_regions(cx.param_env, proj).ok()
84         })
85 }
86
87 /// Get the diagnostic name of a type, e.g. `sym::HashMap`. To check if a type
88 /// implements a trait marked with a diagnostic item use [`implements_trait`].
89 ///
90 /// For a further exploitation what diagnostic items are see [diagnostic items] in
91 /// rustc-dev-guide.
92 ///
93 /// [Diagnostic Items]: https://rustc-dev-guide.rust-lang.org/diagnostics/diagnostic-items.html
94 pub fn get_type_diagnostic_name(cx: &LateContext<'_>, ty: Ty<'_>) -> Option<Symbol> {
95     match ty.kind() {
96         ty::Adt(adt, _) => cx.tcx.get_diagnostic_name(adt.did()),
97         _ => None,
98     }
99 }
100
101 /// Returns true if ty has `iter` or `iter_mut` methods
102 pub fn has_iter_method(cx: &LateContext<'_>, probably_ref_ty: Ty<'_>) -> Option<Symbol> {
103     // FIXME: instead of this hard-coded list, we should check if `<adt>::iter`
104     // exists and has the desired signature. Unfortunately FnCtxt is not exported
105     // so we can't use its `lookup_method` method.
106     let into_iter_collections: &[Symbol] = &[
107         sym::Vec,
108         sym::Option,
109         sym::Result,
110         sym::BTreeMap,
111         sym::BTreeSet,
112         sym::VecDeque,
113         sym::LinkedList,
114         sym::BinaryHeap,
115         sym::HashSet,
116         sym::HashMap,
117         sym::PathBuf,
118         sym::Path,
119         sym::Receiver,
120     ];
121
122     let ty_to_check = match probably_ref_ty.kind() {
123         ty::Ref(_, ty_to_check, _) => *ty_to_check,
124         _ => probably_ref_ty,
125     };
126
127     let def_id = match ty_to_check.kind() {
128         ty::Array(..) => return Some(sym::array),
129         ty::Slice(..) => return Some(sym::slice),
130         ty::Adt(adt, _) => adt.did(),
131         _ => return None,
132     };
133
134     for &name in into_iter_collections {
135         if cx.tcx.is_diagnostic_item(name, def_id) {
136             return Some(cx.tcx.item_name(def_id));
137         }
138     }
139     None
140 }
141
142 /// Checks whether a type implements a trait.
143 /// The function returns false in case the type contains an inference variable.
144 ///
145 /// See:
146 /// * [`get_trait_def_id`](super::get_trait_def_id) to get a trait [`DefId`].
147 /// * [Common tools for writing lints] for an example how to use this function and other options.
148 ///
149 /// [Common tools for writing lints]: https://github.com/rust-lang/rust-clippy/blob/master/book/src/development/common_tools_writing_lints.md#checking-if-a-type-implements-a-specific-trait
150 pub fn implements_trait<'tcx>(
151     cx: &LateContext<'tcx>,
152     ty: Ty<'tcx>,
153     trait_id: DefId,
154     ty_params: &[GenericArg<'tcx>],
155 ) -> bool {
156     implements_trait_with_env(cx.tcx, cx.param_env, ty, trait_id, ty_params)
157 }
158
159 /// Same as `implements_trait` but allows using a `ParamEnv` different from the lint context.
160 pub fn implements_trait_with_env<'tcx>(
161     tcx: TyCtxt<'tcx>,
162     param_env: ParamEnv<'tcx>,
163     ty: Ty<'tcx>,
164     trait_id: DefId,
165     ty_params: &[GenericArg<'tcx>],
166 ) -> bool {
167     // Clippy shouldn't have infer types
168     assert!(!ty.needs_infer());
169
170     let ty = tcx.erase_regions(ty);
171     if ty.has_escaping_bound_vars() {
172         return false;
173     }
174     let ty_params = tcx.mk_substs(ty_params.iter());
175     tcx.infer_ctxt().enter(|infcx| {
176         infcx
177             .type_implements_trait(trait_id, ty, ty_params, param_env)
178             .must_apply_modulo_regions()
179     })
180 }
181
182 /// Checks whether this type implements `Drop`.
183 pub fn has_drop<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
184     match ty.ty_adt_def() {
185         Some(def) => def.has_dtor(cx.tcx),
186         None => false,
187     }
188 }
189
190 // Returns whether the type has #[must_use] attribute
191 pub fn is_must_use_ty<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
192     match ty.kind() {
193         ty::Adt(adt, _) => cx.tcx.has_attr(adt.did(), sym::must_use),
194         ty::Foreign(did) => cx.tcx.has_attr(*did, sym::must_use),
195         ty::Slice(ty) | ty::Array(ty, _) | ty::RawPtr(ty::TypeAndMut { ty, .. }) | ty::Ref(_, ty, _) => {
196             // for the Array case we don't need to care for the len == 0 case
197             // because we don't want to lint functions returning empty arrays
198             is_must_use_ty(cx, *ty)
199         },
200         ty::Tuple(substs) => substs.iter().any(|ty| is_must_use_ty(cx, ty)),
201         ty::Opaque(def_id, _) => {
202             for (predicate, _) in cx.tcx.explicit_item_bounds(*def_id) {
203                 if let ty::PredicateKind::Trait(trait_predicate) = predicate.kind().skip_binder() {
204                     if cx.tcx.has_attr(trait_predicate.trait_ref.def_id, sym::must_use) {
205                         return true;
206                     }
207                 }
208             }
209             false
210         },
211         ty::Dynamic(binder, _, _) => {
212             for predicate in binder.iter() {
213                 if let ty::ExistentialPredicate::Trait(ref trait_ref) = predicate.skip_binder() {
214                     if cx.tcx.has_attr(trait_ref.def_id, sym::must_use) {
215                         return true;
216                     }
217                 }
218             }
219             false
220         },
221         _ => false,
222     }
223 }
224
225 // FIXME: Per https://doc.rust-lang.org/nightly/nightly-rustc/rustc_trait_selection/infer/at/struct.At.html#method.normalize
226 // this function can be removed once the `normalize` method does not panic when normalization does
227 // not succeed
228 /// Checks if `Ty` is normalizable. This function is useful
229 /// to avoid crashes on `layout_of`.
230 pub fn is_normalizable<'tcx>(cx: &LateContext<'tcx>, param_env: ty::ParamEnv<'tcx>, ty: Ty<'tcx>) -> bool {
231     is_normalizable_helper(cx, param_env, ty, &mut FxHashMap::default())
232 }
233
234 fn is_normalizable_helper<'tcx>(
235     cx: &LateContext<'tcx>,
236     param_env: ty::ParamEnv<'tcx>,
237     ty: Ty<'tcx>,
238     cache: &mut FxHashMap<Ty<'tcx>, bool>,
239 ) -> bool {
240     if let Some(&cached_result) = cache.get(&ty) {
241         return cached_result;
242     }
243     // prevent recursive loops, false-negative is better than endless loop leading to stack overflow
244     cache.insert(ty, false);
245     let result = cx.tcx.infer_ctxt().enter(|infcx| {
246         let cause = rustc_middle::traits::ObligationCause::dummy();
247         if infcx.at(&cause, param_env).normalize(ty).is_ok() {
248             match ty.kind() {
249                 ty::Adt(def, substs) => def.variants().iter().all(|variant| {
250                     variant
251                         .fields
252                         .iter()
253                         .all(|field| is_normalizable_helper(cx, param_env, field.ty(cx.tcx, substs), cache))
254                 }),
255                 _ => ty.walk().all(|generic_arg| match generic_arg.unpack() {
256                     GenericArgKind::Type(inner_ty) if inner_ty != ty => {
257                         is_normalizable_helper(cx, param_env, inner_ty, cache)
258                     },
259                     _ => true, // if inner_ty == ty, we've already checked it
260                 }),
261             }
262         } else {
263             false
264         }
265     });
266     cache.insert(ty, result);
267     result
268 }
269
270 /// Returns `true` if the given type is a non aggregate primitive (a `bool` or `char`, any
271 /// integer or floating-point number type). For checking aggregation of primitive types (e.g.
272 /// tuples and slices of primitive type) see `is_recursively_primitive_type`
273 pub fn is_non_aggregate_primitive_type(ty: Ty<'_>) -> bool {
274     matches!(ty.kind(), ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Float(_))
275 }
276
277 /// Returns `true` if the given type is a primitive (a `bool` or `char`, any integer or
278 /// floating-point number type, a `str`, or an array, slice, or tuple of those types).
279 pub fn is_recursively_primitive_type(ty: Ty<'_>) -> bool {
280     match *ty.kind() {
281         ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::Str => true,
282         ty::Ref(_, inner, _) if *inner.kind() == ty::Str => true,
283         ty::Array(inner_type, _) | ty::Slice(inner_type) => is_recursively_primitive_type(inner_type),
284         ty::Tuple(inner_types) => inner_types.iter().all(is_recursively_primitive_type),
285         _ => false,
286     }
287 }
288
289 /// Checks if the type is a reference equals to a diagnostic item
290 pub fn is_type_ref_to_diagnostic_item(cx: &LateContext<'_>, ty: Ty<'_>, diag_item: Symbol) -> bool {
291     match ty.kind() {
292         ty::Ref(_, ref_ty, _) => match ref_ty.kind() {
293             ty::Adt(adt, _) => cx.tcx.is_diagnostic_item(diag_item, adt.did()),
294             _ => false,
295         },
296         _ => false,
297     }
298 }
299
300 /// Checks if the type is equal to a diagnostic item. To check if a type implements a
301 /// trait marked with a diagnostic item use [`implements_trait`].
302 ///
303 /// For a further exploitation what diagnostic items are see [diagnostic items] in
304 /// rustc-dev-guide.
305 ///
306 /// ---
307 ///
308 /// If you change the signature, remember to update the internal lint `MatchTypeOnDiagItem`
309 ///
310 /// [Diagnostic Items]: https://rustc-dev-guide.rust-lang.org/diagnostics/diagnostic-items.html
311 pub fn is_type_diagnostic_item(cx: &LateContext<'_>, ty: Ty<'_>, diag_item: Symbol) -> bool {
312     match ty.kind() {
313         ty::Adt(adt, _) => cx.tcx.is_diagnostic_item(diag_item, adt.did()),
314         _ => false,
315     }
316 }
317
318 /// Checks if the type is equal to a lang item.
319 ///
320 /// Returns `false` if the `LangItem` is not defined.
321 pub fn is_type_lang_item(cx: &LateContext<'_>, ty: Ty<'_>, lang_item: hir::LangItem) -> bool {
322     match ty.kind() {
323         ty::Adt(adt, _) => cx
324             .tcx
325             .lang_items()
326             .require(lang_item)
327             .map_or(false, |li| li == adt.did()),
328         _ => false,
329     }
330 }
331
332 /// Return `true` if the passed `typ` is `isize` or `usize`.
333 pub fn is_isize_or_usize(typ: Ty<'_>) -> bool {
334     matches!(typ.kind(), ty::Int(IntTy::Isize) | ty::Uint(UintTy::Usize))
335 }
336
337 /// Checks if type is struct, enum or union type with the given def path.
338 ///
339 /// If the type is a diagnostic item, use `is_type_diagnostic_item` instead.
340 /// If you change the signature, remember to update the internal lint `MatchTypeOnDiagItem`
341 pub fn match_type(cx: &LateContext<'_>, ty: Ty<'_>, path: &[&str]) -> bool {
342     match ty.kind() {
343         ty::Adt(adt, _) => match_def_path(cx, adt.did(), path),
344         _ => false,
345     }
346 }
347
348 /// Checks if the drop order for a type matters. Some std types implement drop solely to
349 /// deallocate memory. For these types, and composites containing them, changing the drop order
350 /// won't result in any observable side effects.
351 pub fn needs_ordered_drop<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
352     fn needs_ordered_drop_inner<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>, seen: &mut FxHashSet<Ty<'tcx>>) -> bool {
353         if !seen.insert(ty) {
354             return false;
355         }
356         if !ty.has_significant_drop(cx.tcx, cx.param_env) {
357             false
358         }
359         // Check for std types which implement drop, but only for memory allocation.
360         else if is_type_lang_item(cx, ty, LangItem::OwnedBox)
361             || matches!(
362                 get_type_diagnostic_name(cx, ty),
363                 Some(sym::HashSet | sym::Rc | sym::Arc | sym::cstring_type)
364             )
365             || match_type(cx, ty, &paths::WEAK_RC)
366             || match_type(cx, ty, &paths::WEAK_ARC)
367         {
368             // Check all of the generic arguments.
369             if let ty::Adt(_, subs) = ty.kind() {
370                 subs.types().any(|ty| needs_ordered_drop_inner(cx, ty, seen))
371             } else {
372                 true
373             }
374         } else if !cx
375             .tcx
376             .lang_items()
377             .drop_trait()
378             .map_or(false, |id| implements_trait(cx, ty, id, &[]))
379         {
380             // This type doesn't implement drop, so no side effects here.
381             // Check if any component type has any.
382             match ty.kind() {
383                 ty::Tuple(fields) => fields.iter().any(|ty| needs_ordered_drop_inner(cx, ty, seen)),
384                 ty::Array(ty, _) => needs_ordered_drop_inner(cx, *ty, seen),
385                 ty::Adt(adt, subs) => adt
386                     .all_fields()
387                     .map(|f| f.ty(cx.tcx, subs))
388                     .any(|ty| needs_ordered_drop_inner(cx, ty, seen)),
389                 _ => true,
390             }
391         } else {
392             true
393         }
394     }
395
396     needs_ordered_drop_inner(cx, ty, &mut FxHashSet::default())
397 }
398
399 /// Peels off all references on the type. Returns the underlying type and the number of references
400 /// removed.
401 pub fn peel_mid_ty_refs(ty: Ty<'_>) -> (Ty<'_>, usize) {
402     fn peel(ty: Ty<'_>, count: usize) -> (Ty<'_>, usize) {
403         if let ty::Ref(_, ty, _) = ty.kind() {
404             peel(*ty, count + 1)
405         } else {
406             (ty, count)
407         }
408     }
409     peel(ty, 0)
410 }
411
412 /// Peels off all references on the type. Returns the underlying type, the number of references
413 /// removed, and whether the pointer is ultimately mutable or not.
414 pub fn peel_mid_ty_refs_is_mutable(ty: Ty<'_>) -> (Ty<'_>, usize, Mutability) {
415     fn f(ty: Ty<'_>, count: usize, mutability: Mutability) -> (Ty<'_>, usize, Mutability) {
416         match ty.kind() {
417             ty::Ref(_, ty, Mutability::Mut) => f(*ty, count + 1, mutability),
418             ty::Ref(_, ty, Mutability::Not) => f(*ty, count + 1, Mutability::Not),
419             _ => (ty, count, mutability),
420         }
421     }
422     f(ty, 0, Mutability::Mut)
423 }
424
425 /// Returns `true` if the given type is an `unsafe` function.
426 pub fn type_is_unsafe_function<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
427     match ty.kind() {
428         ty::FnDef(..) | ty::FnPtr(_) => ty.fn_sig(cx.tcx).unsafety() == Unsafety::Unsafe,
429         _ => false,
430     }
431 }
432
433 /// Returns the base type for HIR references and pointers.
434 pub fn walk_ptrs_hir_ty<'tcx>(ty: &'tcx hir::Ty<'tcx>) -> &'tcx hir::Ty<'tcx> {
435     match ty.kind {
436         TyKind::Ptr(ref mut_ty) | TyKind::Rptr(_, ref mut_ty) => walk_ptrs_hir_ty(mut_ty.ty),
437         _ => ty,
438     }
439 }
440
441 /// Returns the base type for references and raw pointers, and count reference
442 /// depth.
443 pub fn walk_ptrs_ty_depth(ty: Ty<'_>) -> (Ty<'_>, usize) {
444     fn inner(ty: Ty<'_>, depth: usize) -> (Ty<'_>, usize) {
445         match ty.kind() {
446             ty::Ref(_, ty, _) => inner(*ty, depth + 1),
447             _ => (ty, depth),
448         }
449     }
450     inner(ty, 0)
451 }
452
453 /// Returns `true` if types `a` and `b` are same types having same `Const` generic args,
454 /// otherwise returns `false`
455 pub fn same_type_and_consts<'tcx>(a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
456     match (&a.kind(), &b.kind()) {
457         (&ty::Adt(did_a, substs_a), &ty::Adt(did_b, substs_b)) => {
458             if did_a != did_b {
459                 return false;
460             }
461
462             substs_a
463                 .iter()
464                 .zip(substs_b.iter())
465                 .all(|(arg_a, arg_b)| match (arg_a.unpack(), arg_b.unpack()) {
466                     (GenericArgKind::Const(inner_a), GenericArgKind::Const(inner_b)) => inner_a == inner_b,
467                     (GenericArgKind::Type(type_a), GenericArgKind::Type(type_b)) => {
468                         same_type_and_consts(type_a, type_b)
469                     },
470                     _ => true,
471                 })
472         },
473         _ => a == b,
474     }
475 }
476
477 /// Checks if a given type looks safe to be uninitialized.
478 pub fn is_uninit_value_valid_for_ty(cx: &LateContext<'_>, ty: Ty<'_>) -> bool {
479     match *ty.kind() {
480         ty::Array(component, _) => is_uninit_value_valid_for_ty(cx, component),
481         ty::Tuple(types) => types.iter().all(|ty| is_uninit_value_valid_for_ty(cx, ty)),
482         ty::Adt(adt, _) => cx.tcx.lang_items().maybe_uninit() == Some(adt.did()),
483         _ => false,
484     }
485 }
486
487 /// Gets an iterator over all predicates which apply to the given item.
488 pub fn all_predicates_of(tcx: TyCtxt<'_>, id: DefId) -> impl Iterator<Item = &(Predicate<'_>, Span)> {
489     let mut next_id = Some(id);
490     iter::from_fn(move || {
491         next_id.take().map(|id| {
492             let preds = tcx.predicates_of(id);
493             next_id = preds.parent;
494             preds.predicates.iter()
495         })
496     })
497     .flatten()
498 }
499
500 /// A signature for a function like type.
501 #[derive(Clone, Copy)]
502 pub enum ExprFnSig<'tcx> {
503     Sig(Binder<'tcx, FnSig<'tcx>>, Option<DefId>),
504     Closure(Option<&'tcx FnDecl<'tcx>>, Binder<'tcx, FnSig<'tcx>>),
505     Trait(Binder<'tcx, Ty<'tcx>>, Option<Binder<'tcx, Ty<'tcx>>>, Option<DefId>),
506 }
507 impl<'tcx> ExprFnSig<'tcx> {
508     /// Gets the argument type at the given offset. This will return `None` when the index is out of
509     /// bounds only for variadic functions, otherwise this will panic.
510     pub fn input(self, i: usize) -> Option<Binder<'tcx, Ty<'tcx>>> {
511         match self {
512             Self::Sig(sig, _) => {
513                 if sig.c_variadic() {
514                     sig.inputs().map_bound(|inputs| inputs.get(i).copied()).transpose()
515                 } else {
516                     Some(sig.input(i))
517                 }
518             },
519             Self::Closure(_, sig) => Some(sig.input(0).map_bound(|ty| ty.tuple_fields()[i])),
520             Self::Trait(inputs, _, _) => Some(inputs.map_bound(|ty| ty.tuple_fields()[i])),
521         }
522     }
523
524     /// Gets the argument type at the given offset. For closures this will also get the type as
525     /// written. This will return `None` when the index is out of bounds only for variadic
526     /// functions, otherwise this will panic.
527     pub fn input_with_hir(self, i: usize) -> Option<(Option<&'tcx hir::Ty<'tcx>>, Binder<'tcx, Ty<'tcx>>)> {
528         match self {
529             Self::Sig(sig, _) => {
530                 if sig.c_variadic() {
531                     sig.inputs()
532                         .map_bound(|inputs| inputs.get(i).copied())
533                         .transpose()
534                         .map(|arg| (None, arg))
535                 } else {
536                     Some((None, sig.input(i)))
537                 }
538             },
539             Self::Closure(decl, sig) => Some((
540                 decl.and_then(|decl| decl.inputs.get(i)),
541                 sig.input(0).map_bound(|ty| ty.tuple_fields()[i]),
542             )),
543             Self::Trait(inputs, _, _) => Some((None, inputs.map_bound(|ty| ty.tuple_fields()[i]))),
544         }
545     }
546
547     /// Gets the result type, if one could be found. Note that the result type of a trait may not be
548     /// specified.
549     pub fn output(self) -> Option<Binder<'tcx, Ty<'tcx>>> {
550         match self {
551             Self::Sig(sig, _) | Self::Closure(_, sig) => Some(sig.output()),
552             Self::Trait(_, output, _) => output,
553         }
554     }
555
556     pub fn predicates_id(&self) -> Option<DefId> {
557         if let ExprFnSig::Sig(_, id) | ExprFnSig::Trait(_, _, id) = *self {
558             id
559         } else {
560             None
561         }
562     }
563 }
564
565 /// If the expression is function like, get the signature for it.
566 pub fn expr_sig<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'_>) -> Option<ExprFnSig<'tcx>> {
567     if let Res::Def(DefKind::Fn | DefKind::Ctor(_, CtorKind::Fn) | DefKind::AssocFn, id) = path_res(cx, expr) {
568         Some(ExprFnSig::Sig(cx.tcx.fn_sig(id), Some(id)))
569     } else {
570         ty_sig(cx, cx.typeck_results().expr_ty_adjusted(expr).peel_refs())
571     }
572 }
573
574 /// If the type is function like, get the signature for it.
575 pub fn ty_sig<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> Option<ExprFnSig<'tcx>> {
576     if ty.is_box() {
577         return ty_sig(cx, ty.boxed_ty());
578     }
579     match *ty.kind() {
580         ty::Closure(id, subs) => {
581             let decl = id
582                 .as_local()
583                 .and_then(|id| cx.tcx.hir().fn_decl_by_hir_id(cx.tcx.hir().local_def_id_to_hir_id(id)));
584             Some(ExprFnSig::Closure(decl, subs.as_closure().sig()))
585         },
586         ty::FnDef(id, subs) => Some(ExprFnSig::Sig(cx.tcx.bound_fn_sig(id).subst(cx.tcx, subs), Some(id))),
587         ty::Opaque(id, _) => sig_from_bounds(cx, ty, cx.tcx.item_bounds(id), cx.tcx.opt_parent(id)),
588         ty::FnPtr(sig) => Some(ExprFnSig::Sig(sig, None)),
589         ty::Dynamic(bounds, _, _) => {
590             let lang_items = cx.tcx.lang_items();
591             match bounds.principal() {
592                 Some(bound)
593                     if Some(bound.def_id()) == lang_items.fn_trait()
594                         || Some(bound.def_id()) == lang_items.fn_once_trait()
595                         || Some(bound.def_id()) == lang_items.fn_mut_trait() =>
596                 {
597                     let output = bounds
598                         .projection_bounds()
599                         .find(|p| lang_items.fn_once_output().map_or(false, |id| id == p.item_def_id()))
600                         .map(|p| p.map_bound(|p| p.term.ty().unwrap()));
601                     Some(ExprFnSig::Trait(bound.map_bound(|b| b.substs.type_at(0)), output, None))
602                 },
603                 _ => None,
604             }
605         },
606         ty::Projection(proj) => match cx.tcx.try_normalize_erasing_regions(cx.param_env, ty) {
607             Ok(normalized_ty) if normalized_ty != ty => ty_sig(cx, normalized_ty),
608             _ => sig_for_projection(cx, proj).or_else(|| sig_from_bounds(cx, ty, cx.param_env.caller_bounds(), None)),
609         },
610         ty::Param(_) => sig_from_bounds(cx, ty, cx.param_env.caller_bounds(), None),
611         _ => None,
612     }
613 }
614
615 fn sig_from_bounds<'tcx>(
616     cx: &LateContext<'tcx>,
617     ty: Ty<'tcx>,
618     predicates: &'tcx [Predicate<'tcx>],
619     predicates_id: Option<DefId>,
620 ) -> Option<ExprFnSig<'tcx>> {
621     let mut inputs = None;
622     let mut output = None;
623     let lang_items = cx.tcx.lang_items();
624
625     for pred in predicates {
626         match pred.kind().skip_binder() {
627             PredicateKind::Trait(p)
628                 if (lang_items.fn_trait() == Some(p.def_id())
629                     || lang_items.fn_mut_trait() == Some(p.def_id())
630                     || lang_items.fn_once_trait() == Some(p.def_id()))
631                     && p.self_ty() == ty =>
632             {
633                 let i = pred.kind().rebind(p.trait_ref.substs.type_at(1));
634                 if inputs.map_or(false, |inputs| i != inputs) {
635                     // Multiple different fn trait impls. Is this even allowed?
636                     return None;
637                 }
638                 inputs = Some(i);
639             },
640             PredicateKind::Projection(p)
641                 if Some(p.projection_ty.item_def_id) == lang_items.fn_once_output()
642                     && p.projection_ty.self_ty() == ty =>
643             {
644                 if output.is_some() {
645                     // Multiple different fn trait impls. Is this even allowed?
646                     return None;
647                 }
648                 output = Some(pred.kind().rebind(p.term.ty().unwrap()));
649             },
650             _ => (),
651         }
652     }
653
654     inputs.map(|ty| ExprFnSig::Trait(ty, output, predicates_id))
655 }
656
657 fn sig_for_projection<'tcx>(cx: &LateContext<'tcx>, ty: ProjectionTy<'tcx>) -> Option<ExprFnSig<'tcx>> {
658     let mut inputs = None;
659     let mut output = None;
660     let lang_items = cx.tcx.lang_items();
661
662     for pred in cx
663         .tcx
664         .bound_explicit_item_bounds(ty.item_def_id)
665         .transpose_iter()
666         .map(|x| x.map_bound(|(p, _)| p))
667     {
668         match pred.0.kind().skip_binder() {
669             PredicateKind::Trait(p)
670                 if (lang_items.fn_trait() == Some(p.def_id())
671                     || lang_items.fn_mut_trait() == Some(p.def_id())
672                     || lang_items.fn_once_trait() == Some(p.def_id())) =>
673             {
674                 let i = pred
675                     .map_bound(|pred| pred.kind().rebind(p.trait_ref.substs.type_at(1)))
676                     .subst(cx.tcx, ty.substs);
677
678                 if inputs.map_or(false, |inputs| inputs != i) {
679                     // Multiple different fn trait impls. Is this even allowed?
680                     return None;
681                 }
682                 inputs = Some(i);
683             },
684             PredicateKind::Projection(p) if Some(p.projection_ty.item_def_id) == lang_items.fn_once_output() => {
685                 if output.is_some() {
686                     // Multiple different fn trait impls. Is this even allowed?
687                     return None;
688                 }
689                 output = Some(
690                     pred.map_bound(|pred| pred.kind().rebind(p.term.ty().unwrap()))
691                         .subst(cx.tcx, ty.substs),
692                 );
693             },
694             _ => (),
695         }
696     }
697
698     inputs.map(|ty| ExprFnSig::Trait(ty, output, None))
699 }
700
701 #[derive(Clone, Copy)]
702 pub enum EnumValue {
703     Unsigned(u128),
704     Signed(i128),
705 }
706 impl core::ops::Add<u32> for EnumValue {
707     type Output = Self;
708     fn add(self, n: u32) -> Self::Output {
709         match self {
710             Self::Unsigned(x) => Self::Unsigned(x + u128::from(n)),
711             Self::Signed(x) => Self::Signed(x + i128::from(n)),
712         }
713     }
714 }
715
716 /// Attempts to read the given constant as though it were an an enum value.
717 #[expect(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
718 pub fn read_explicit_enum_value(tcx: TyCtxt<'_>, id: DefId) -> Option<EnumValue> {
719     if let Ok(ConstValue::Scalar(Scalar::Int(value))) = tcx.const_eval_poly(id) {
720         match tcx.type_of(id).kind() {
721             ty::Int(_) => Some(EnumValue::Signed(match value.size().bytes() {
722                 1 => i128::from(value.assert_bits(Size::from_bytes(1)) as u8 as i8),
723                 2 => i128::from(value.assert_bits(Size::from_bytes(2)) as u16 as i16),
724                 4 => i128::from(value.assert_bits(Size::from_bytes(4)) as u32 as i32),
725                 8 => i128::from(value.assert_bits(Size::from_bytes(8)) as u64 as i64),
726                 16 => value.assert_bits(Size::from_bytes(16)) as i128,
727                 _ => return None,
728             })),
729             ty::Uint(_) => Some(EnumValue::Unsigned(match value.size().bytes() {
730                 1 => value.assert_bits(Size::from_bytes(1)),
731                 2 => value.assert_bits(Size::from_bytes(2)),
732                 4 => value.assert_bits(Size::from_bytes(4)),
733                 8 => value.assert_bits(Size::from_bytes(8)),
734                 16 => value.assert_bits(Size::from_bytes(16)),
735                 _ => return None,
736             })),
737             _ => None,
738         }
739     } else {
740         None
741     }
742 }
743
744 /// Gets the value of the given variant.
745 pub fn get_discriminant_value(tcx: TyCtxt<'_>, adt: AdtDef<'_>, i: VariantIdx) -> EnumValue {
746     let variant = &adt.variant(i);
747     match variant.discr {
748         VariantDiscr::Explicit(id) => read_explicit_enum_value(tcx, id).unwrap(),
749         VariantDiscr::Relative(x) => match adt.variant((i.as_usize() - x as usize).into()).discr {
750             VariantDiscr::Explicit(id) => read_explicit_enum_value(tcx, id).unwrap() + x,
751             VariantDiscr::Relative(_) => EnumValue::Unsigned(x.into()),
752         },
753     }
754 }
755
756 /// Check if the given type is either `core::ffi::c_void`, `std::os::raw::c_void`, or one of the
757 /// platform specific `libc::<platform>::c_void` types in libc.
758 pub fn is_c_void(cx: &LateContext<'_>, ty: Ty<'_>) -> bool {
759     if let ty::Adt(adt, _) = ty.kind()
760         && let &[krate, .., name] = &*cx.get_def_path(adt.did())
761         && let sym::libc | sym::core | sym::std = krate
762         && name.as_str() == "c_void"
763     {
764         true
765     } else {
766         false
767     }
768 }
769
770 pub fn for_each_top_level_late_bound_region<B>(
771     ty: Ty<'_>,
772     f: impl FnMut(BoundRegion) -> ControlFlow<B>,
773 ) -> ControlFlow<B> {
774     struct V<F> {
775         index: u32,
776         f: F,
777     }
778     impl<'tcx, B, F: FnMut(BoundRegion) -> ControlFlow<B>> TypeVisitor<'tcx> for V<F> {
779         type BreakTy = B;
780         fn visit_region(&mut self, r: Region<'tcx>) -> ControlFlow<Self::BreakTy> {
781             if let RegionKind::ReLateBound(idx, bound) = r.kind() && idx.as_u32() == self.index {
782                 (self.f)(bound)
783             } else {
784                 ControlFlow::Continue(())
785             }
786         }
787         fn visit_binder<T: TypeVisitable<'tcx>>(&mut self, t: &Binder<'tcx, T>) -> ControlFlow<Self::BreakTy> {
788             self.index += 1;
789             let res = t.super_visit_with(self);
790             self.index -= 1;
791             res
792         }
793     }
794     ty.visit_with(&mut V { index: 0, f })
795 }
796
797 /// Gets the struct or enum variant from the given `Res`
798 pub fn variant_of_res<'tcx>(cx: &LateContext<'tcx>, res: Res) -> Option<&'tcx VariantDef> {
799     match res {
800         Res::Def(DefKind::Struct, id) => Some(cx.tcx.adt_def(id).non_enum_variant()),
801         Res::Def(DefKind::Variant, id) => Some(cx.tcx.adt_def(cx.tcx.parent(id)).variant_with_id(id)),
802         Res::Def(DefKind::Ctor(CtorOf::Struct, _), id) => Some(cx.tcx.adt_def(cx.tcx.parent(id)).non_enum_variant()),
803         Res::Def(DefKind::Ctor(CtorOf::Variant, _), id) => {
804             let var_id = cx.tcx.parent(id);
805             Some(cx.tcx.adt_def(cx.tcx.parent(var_id)).variant_with_id(var_id))
806         },
807         Res::SelfCtor(id) => Some(cx.tcx.type_of(id).ty_adt_def().unwrap().non_enum_variant()),
808         _ => None,
809     }
810 }
811
812 /// Checks if the type is a type parameter implementing `FnOnce`, but not `FnMut`.
813 pub fn ty_is_fn_once_param<'tcx>(tcx: TyCtxt<'_>, ty: Ty<'tcx>, predicates: &'tcx [Predicate<'_>]) -> bool {
814     let ty::Param(ty) = *ty.kind() else {
815         return false;
816     };
817     let lang = tcx.lang_items();
818     let (Some(fn_once_id), Some(fn_mut_id), Some(fn_id))
819         = (lang.fn_once_trait(), lang.fn_mut_trait(), lang.fn_trait())
820     else {
821         return false;
822     };
823     predicates
824         .iter()
825         .try_fold(false, |found, p| {
826             if let PredicateKind::Trait(p) = p.kind().skip_binder()
827             && let ty::Param(self_ty) = p.trait_ref.self_ty().kind()
828             && ty.index == self_ty.index
829         {
830             // This should use `super_traits_of`, but that's a private function.
831             if p.trait_ref.def_id == fn_once_id {
832                 return Some(true);
833             } else if p.trait_ref.def_id == fn_mut_id || p.trait_ref.def_id == fn_id {
834                 return None;
835             }
836         }
837             Some(found)
838         })
839         .unwrap_or(false)
840 }
841
842 /// Comes up with an "at least" guesstimate for the type's size, not taking into
843 /// account the layout of type parameters.
844 pub fn approx_ty_size<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> u64 {
845     use rustc_middle::ty::layout::LayoutOf;
846     if !is_normalizable(cx, cx.param_env, ty) {
847         return 0;
848     }
849     match (cx.layout_of(ty).map(|layout| layout.size.bytes()), ty.kind()) {
850         (Ok(size), _) => size,
851         (Err(_), ty::Tuple(list)) => list.as_substs().types().map(|t| approx_ty_size(cx, t)).sum(),
852         (Err(_), ty::Array(t, n)) => {
853             n.try_eval_usize(cx.tcx, cx.param_env).unwrap_or_default() * approx_ty_size(cx, *t)
854         },
855         (Err(_), ty::Adt(def, subst)) if def.is_struct() => def
856             .variants()
857             .iter()
858             .map(|v| {
859                 v.fields
860                     .iter()
861                     .map(|field| approx_ty_size(cx, field.ty(cx.tcx, subst)))
862                     .sum::<u64>()
863             })
864             .sum(),
865         (Err(_), ty::Adt(def, subst)) if def.is_enum() => def
866             .variants()
867             .iter()
868             .map(|v| {
869                 v.fields
870                     .iter()
871                     .map(|field| approx_ty_size(cx, field.ty(cx.tcx, subst)))
872                     .sum::<u64>()
873             })
874             .max()
875             .unwrap_or_default(),
876         (Err(_), ty::Adt(def, subst)) if def.is_union() => def
877             .variants()
878             .iter()
879             .map(|v| {
880                 v.fields
881                     .iter()
882                     .map(|field| approx_ty_size(cx, field.ty(cx.tcx, subst)))
883                     .max()
884                     .unwrap_or_default()
885             })
886             .max()
887             .unwrap_or_default(),
888         (Err(_), _) => 0,
889     }
890 }