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