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