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