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