1 //! Util methods for [`rustc_middle::ty`]
3 #![allow(clippy::module_name_repetitions)]
5 use core::ops::ControlFlow;
6 use rustc_ast::ast::Mutability;
7 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
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::{
13 type_variable::{TypeVariableOrigin, TypeVariableOriginKind},
16 use rustc_lint::LateContext;
17 use rustc_middle::mir::interpret::{ConstValue, Scalar};
18 use rustc_middle::ty::{
19 self, AdtDef, AliasTy, AssocKind, Binder, BoundRegion, DefIdTree, FnSig, IntTy, List, ParamEnv, Predicate,
20 PredicateKind, Region, RegionKind, SubstsRef, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable, TypeVisitor, UintTy,
21 VariantDef, VariantDiscr,
23 use rustc_middle::ty::{GenericArg, GenericArgKind};
24 use rustc_span::symbol::Ident;
25 use rustc_span::{sym, Span, Symbol, DUMMY_SP};
26 use rustc_target::abi::{Size, VariantIdx};
27 use rustc_trait_selection::infer::InferCtxtExt;
28 use rustc_trait_selection::traits::query::normalize::QueryNormalizeExt;
31 use crate::{match_def_path, path_res, paths};
33 /// Checks if the given type implements copy.
34 pub fn is_copy<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
35 ty.is_copy_modulo_regions(cx.tcx, cx.param_env)
38 /// This checks whether a given type is known to implement Debug.
39 pub fn has_debug_impl<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
41 .get_diagnostic_item(sym::Debug)
42 .map_or(false, |debug| implements_trait(cx, ty, debug, &[]))
45 /// Checks whether a type can be partially moved.
46 pub fn can_partially_move_ty<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
47 if has_drop(cx, ty) || is_copy(cx, ty) {
51 ty::Param(_) => false,
52 ty::Adt(def, subs) => def.all_fields().any(|f| !is_copy(cx, f.ty(cx.tcx, subs))),
57 /// Walks into `ty` and returns `true` if any inner type is an instance of the given adt
59 pub fn contains_adt_constructor<'tcx>(ty: Ty<'tcx>, adt: AdtDef<'tcx>) -> bool {
60 ty.walk().any(|inner| match inner.unpack() {
61 GenericArgKind::Type(inner_ty) => inner_ty.ty_adt_def() == Some(adt),
62 GenericArgKind::Lifetime(_) | GenericArgKind::Const(_) => false,
66 /// Walks into `ty` and returns `true` if any inner type is an instance of the given type, or adt
67 /// constructor of the same type.
69 /// This method also recurses into opaque type predicates, so call it with `impl Trait<U>` and `U`
70 /// will also return `true`.
71 pub fn contains_ty_adt_constructor_opaque<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>, needle: Ty<'tcx>) -> bool {
72 fn contains_ty_adt_constructor_opaque_inner<'tcx>(
73 cx: &LateContext<'tcx>,
76 seen: &mut FxHashSet<DefId>,
78 ty.walk().any(|inner| match inner.unpack() {
79 GenericArgKind::Type(inner_ty) => {
80 if inner_ty == needle {
84 if inner_ty.ty_adt_def() == needle.ty_adt_def() {
88 if let ty::Alias(ty::Opaque, ty::AliasTy { def_id, .. }) = *inner_ty.kind() {
89 if !seen.insert(def_id) {
93 for &(predicate, _span) in cx.tcx.explicit_item_bounds(def_id) {
94 match predicate.kind().skip_binder() {
95 // For `impl Trait<U>`, it will register a predicate of `T: Trait<U>`, so we go through
96 // and check substituions to find `U`.
97 ty::PredicateKind::Clause(ty::Clause::Trait(trait_predicate)) => {
102 .skip(1) // Skip the implicit `Self` generic parameter
103 .any(|ty| contains_ty_adt_constructor_opaque_inner(cx, ty, needle, seen))
108 // For `impl Trait<Assoc=U>`, it will register a predicate of `<T as Trait>::Assoc = U`,
109 // so we check the term for `U`.
110 ty::PredicateKind::Clause(ty::Clause::Projection(projection_predicate)) => {
111 if let ty::TermKind::Ty(ty) = projection_predicate.term.unpack() {
112 if contains_ty_adt_constructor_opaque_inner(cx, ty, needle, seen) {
124 GenericArgKind::Lifetime(_) | GenericArgKind::Const(_) => false,
128 // A hash set to ensure that the same opaque type (`impl Trait` in RPIT or TAIT) is not
130 let mut seen = FxHashSet::default();
131 contains_ty_adt_constructor_opaque_inner(cx, ty, needle, &mut seen)
134 /// Resolves `<T as Iterator>::Item` for `T`
135 /// Do not invoke without first verifying that the type implements `Iterator`
136 pub fn get_iterator_item_ty<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> Option<Ty<'tcx>> {
138 .get_diagnostic_item(sym::Iterator)
139 .and_then(|iter_did| cx.get_associated_type(ty, iter_did, "Item"))
142 /// Get the diagnostic name of a type, e.g. `sym::HashMap`. To check if a type
143 /// implements a trait marked with a diagnostic item use [`implements_trait`].
145 /// For a further exploitation what diagnostic items are see [diagnostic items] in
148 /// [Diagnostic Items]: https://rustc-dev-guide.rust-lang.org/diagnostics/diagnostic-items.html
149 pub fn get_type_diagnostic_name(cx: &LateContext<'_>, ty: Ty<'_>) -> Option<Symbol> {
151 ty::Adt(adt, _) => cx.tcx.get_diagnostic_name(adt.did()),
156 /// Returns true if ty has `iter` or `iter_mut` methods
157 pub fn has_iter_method(cx: &LateContext<'_>, probably_ref_ty: Ty<'_>) -> Option<Symbol> {
158 // FIXME: instead of this hard-coded list, we should check if `<adt>::iter`
159 // exists and has the desired signature. Unfortunately FnCtxt is not exported
160 // so we can't use its `lookup_method` method.
161 let into_iter_collections: &[Symbol] = &[
177 let ty_to_check = match probably_ref_ty.kind() {
178 ty::Ref(_, ty_to_check, _) => *ty_to_check,
179 _ => probably_ref_ty,
182 let def_id = match ty_to_check.kind() {
183 ty::Array(..) => return Some(sym::array),
184 ty::Slice(..) => return Some(sym::slice),
185 ty::Adt(adt, _) => adt.did(),
189 for &name in into_iter_collections {
190 if cx.tcx.is_diagnostic_item(name, def_id) {
191 return Some(cx.tcx.item_name(def_id));
197 /// Checks whether a type implements a trait.
198 /// The function returns false in case the type contains an inference variable.
201 /// * [`get_trait_def_id`](super::get_trait_def_id) to get a trait [`DefId`].
202 /// * [Common tools for writing lints] for an example how to use this function and other options.
204 /// [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
205 pub fn implements_trait<'tcx>(
206 cx: &LateContext<'tcx>,
209 ty_params: &[GenericArg<'tcx>],
211 implements_trait_with_env(
216 ty_params.iter().map(|&arg| Some(arg)),
220 /// Same as `implements_trait` but allows using a `ParamEnv` different from the lint context.
221 pub fn implements_trait_with_env<'tcx>(
223 param_env: ParamEnv<'tcx>,
226 ty_params: impl IntoIterator<Item = Option<GenericArg<'tcx>>>,
228 // Clippy shouldn't have infer types
229 assert!(!ty.needs_infer());
231 let ty = tcx.erase_regions(ty);
232 if ty.has_escaping_bound_vars() {
235 let infcx = tcx.infer_ctxt().build();
236 let orig = TypeVariableOrigin {
237 kind: TypeVariableOriginKind::MiscVariable,
240 let ty_params = tcx.mk_substs(
243 .map(|arg| arg.unwrap_or_else(|| infcx.next_ty_var(orig).into())),
246 .type_implements_trait(trait_id, [ty.into()].into_iter().chain(ty_params), param_env)
247 .must_apply_modulo_regions()
250 /// Checks whether this type implements `Drop`.
251 pub fn has_drop<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
252 match ty.ty_adt_def() {
253 Some(def) => def.has_dtor(cx.tcx),
258 // Returns whether the type has #[must_use] attribute
259 pub fn is_must_use_ty<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
261 ty::Adt(adt, _) => cx.tcx.has_attr(adt.did(), sym::must_use),
262 ty::Foreign(did) => cx.tcx.has_attr(*did, sym::must_use),
263 ty::Slice(ty) | ty::Array(ty, _) | ty::RawPtr(ty::TypeAndMut { ty, .. }) | ty::Ref(_, ty, _) => {
264 // for the Array case we don't need to care for the len == 0 case
265 // because we don't want to lint functions returning empty arrays
266 is_must_use_ty(cx, *ty)
268 ty::Tuple(substs) => substs.iter().any(|ty| is_must_use_ty(cx, ty)),
269 ty::Alias(ty::Opaque, ty::AliasTy { def_id, .. }) => {
270 for (predicate, _) in cx.tcx.explicit_item_bounds(*def_id) {
271 if let ty::PredicateKind::Clause(ty::Clause::Trait(trait_predicate)) = predicate.kind().skip_binder() {
272 if cx.tcx.has_attr(trait_predicate.trait_ref.def_id, sym::must_use) {
279 ty::Dynamic(binder, _, _) => {
280 for predicate in binder.iter() {
281 if let ty::ExistentialPredicate::Trait(ref trait_ref) = predicate.skip_binder() {
282 if cx.tcx.has_attr(trait_ref.def_id, sym::must_use) {
293 // FIXME: Per https://doc.rust-lang.org/nightly/nightly-rustc/rustc_trait_selection/infer/at/struct.At.html#method.normalize
294 // this function can be removed once the `normalize` method does not panic when normalization does
296 /// Checks if `Ty` is normalizable. This function is useful
297 /// to avoid crashes on `layout_of`.
298 pub fn is_normalizable<'tcx>(cx: &LateContext<'tcx>, param_env: ty::ParamEnv<'tcx>, ty: Ty<'tcx>) -> bool {
299 is_normalizable_helper(cx, param_env, ty, &mut FxHashMap::default())
302 fn is_normalizable_helper<'tcx>(
303 cx: &LateContext<'tcx>,
304 param_env: ty::ParamEnv<'tcx>,
306 cache: &mut FxHashMap<Ty<'tcx>, bool>,
308 if let Some(&cached_result) = cache.get(&ty) {
309 return cached_result;
311 // prevent recursive loops, false-negative is better than endless loop leading to stack overflow
312 cache.insert(ty, false);
313 let infcx = cx.tcx.infer_ctxt().build();
314 let cause = rustc_middle::traits::ObligationCause::dummy();
315 let result = if infcx.at(&cause, param_env).query_normalize(ty).is_ok() {
317 ty::Adt(def, substs) => def.variants().iter().all(|variant| {
321 .all(|field| is_normalizable_helper(cx, param_env, field.ty(cx.tcx, substs), cache))
323 _ => ty.walk().all(|generic_arg| match generic_arg.unpack() {
324 GenericArgKind::Type(inner_ty) if inner_ty != ty => {
325 is_normalizable_helper(cx, param_env, inner_ty, cache)
327 _ => true, // if inner_ty == ty, we've already checked it
333 cache.insert(ty, result);
337 /// Returns `true` if the given type is a non aggregate primitive (a `bool` or `char`, any
338 /// integer or floating-point number type). For checking aggregation of primitive types (e.g.
339 /// tuples and slices of primitive type) see `is_recursively_primitive_type`
340 pub fn is_non_aggregate_primitive_type(ty: Ty<'_>) -> bool {
341 matches!(ty.kind(), ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Float(_))
344 /// Returns `true` if the given type is a primitive (a `bool` or `char`, any integer or
345 /// floating-point number type, a `str`, or an array, slice, or tuple of those types).
346 pub fn is_recursively_primitive_type(ty: Ty<'_>) -> bool {
348 ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::Str => true,
349 ty::Ref(_, inner, _) if *inner.kind() == ty::Str => true,
350 ty::Array(inner_type, _) | ty::Slice(inner_type) => is_recursively_primitive_type(inner_type),
351 ty::Tuple(inner_types) => inner_types.iter().all(is_recursively_primitive_type),
356 /// Checks if the type is a reference equals to a diagnostic item
357 pub fn is_type_ref_to_diagnostic_item(cx: &LateContext<'_>, ty: Ty<'_>, diag_item: Symbol) -> bool {
359 ty::Ref(_, ref_ty, _) => match ref_ty.kind() {
360 ty::Adt(adt, _) => cx.tcx.is_diagnostic_item(diag_item, adt.did()),
367 /// Checks if the type is equal to a diagnostic item. To check if a type implements a
368 /// trait marked with a diagnostic item use [`implements_trait`].
370 /// For a further exploitation what diagnostic items are see [diagnostic items] in
375 /// If you change the signature, remember to update the internal lint `MatchTypeOnDiagItem`
377 /// [Diagnostic Items]: https://rustc-dev-guide.rust-lang.org/diagnostics/diagnostic-items.html
378 pub fn is_type_diagnostic_item(cx: &LateContext<'_>, ty: Ty<'_>, diag_item: Symbol) -> bool {
380 ty::Adt(adt, _) => cx.tcx.is_diagnostic_item(diag_item, adt.did()),
385 /// Checks if the type is equal to a lang item.
387 /// Returns `false` if the `LangItem` is not defined.
388 pub fn is_type_lang_item(cx: &LateContext<'_>, ty: Ty<'_>, lang_item: hir::LangItem) -> bool {
390 ty::Adt(adt, _) => cx.tcx.lang_items().get(lang_item) == Some(adt.did()),
395 /// Return `true` if the passed `typ` is `isize` or `usize`.
396 pub fn is_isize_or_usize(typ: Ty<'_>) -> bool {
397 matches!(typ.kind(), ty::Int(IntTy::Isize) | ty::Uint(UintTy::Usize))
400 /// Checks if type is struct, enum or union type with the given def path.
402 /// If the type is a diagnostic item, use `is_type_diagnostic_item` instead.
403 /// If you change the signature, remember to update the internal lint `MatchTypeOnDiagItem`
404 pub fn match_type(cx: &LateContext<'_>, ty: Ty<'_>, path: &[&str]) -> bool {
406 ty::Adt(adt, _) => match_def_path(cx, adt.did(), path),
411 /// Checks if the drop order for a type matters. Some std types implement drop solely to
412 /// deallocate memory. For these types, and composites containing them, changing the drop order
413 /// won't result in any observable side effects.
414 pub fn needs_ordered_drop<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
415 fn needs_ordered_drop_inner<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>, seen: &mut FxHashSet<Ty<'tcx>>) -> bool {
416 if !seen.insert(ty) {
419 if !ty.has_significant_drop(cx.tcx, cx.param_env) {
422 // Check for std types which implement drop, but only for memory allocation.
423 else if is_type_lang_item(cx, ty, LangItem::OwnedBox)
425 get_type_diagnostic_name(cx, ty),
426 Some(sym::HashSet | sym::Rc | sym::Arc | sym::cstring_type)
428 || match_type(cx, ty, &paths::WEAK_RC)
429 || match_type(cx, ty, &paths::WEAK_ARC)
431 // Check all of the generic arguments.
432 if let ty::Adt(_, subs) = ty.kind() {
433 subs.types().any(|ty| needs_ordered_drop_inner(cx, ty, seen))
441 .map_or(false, |id| implements_trait(cx, ty, id, &[]))
443 // This type doesn't implement drop, so no side effects here.
444 // Check if any component type has any.
446 ty::Tuple(fields) => fields.iter().any(|ty| needs_ordered_drop_inner(cx, ty, seen)),
447 ty::Array(ty, _) => needs_ordered_drop_inner(cx, *ty, seen),
448 ty::Adt(adt, subs) => adt
450 .map(|f| f.ty(cx.tcx, subs))
451 .any(|ty| needs_ordered_drop_inner(cx, ty, seen)),
459 needs_ordered_drop_inner(cx, ty, &mut FxHashSet::default())
462 /// Peels off all references on the type. Returns the underlying type and the number of references
464 pub fn peel_mid_ty_refs(ty: Ty<'_>) -> (Ty<'_>, usize) {
465 fn peel(ty: Ty<'_>, count: usize) -> (Ty<'_>, usize) {
466 if let ty::Ref(_, ty, _) = ty.kind() {
475 /// Peels off all references on the type. Returns the underlying type, the number of references
476 /// removed, and whether the pointer is ultimately mutable or not.
477 pub fn peel_mid_ty_refs_is_mutable(ty: Ty<'_>) -> (Ty<'_>, usize, Mutability) {
478 fn f(ty: Ty<'_>, count: usize, mutability: Mutability) -> (Ty<'_>, usize, Mutability) {
480 ty::Ref(_, ty, Mutability::Mut) => f(*ty, count + 1, mutability),
481 ty::Ref(_, ty, Mutability::Not) => f(*ty, count + 1, Mutability::Not),
482 _ => (ty, count, mutability),
485 f(ty, 0, Mutability::Mut)
488 /// Returns `true` if the given type is an `unsafe` function.
489 pub fn type_is_unsafe_function<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
491 ty::FnDef(..) | ty::FnPtr(_) => ty.fn_sig(cx.tcx).unsafety() == Unsafety::Unsafe,
496 /// Returns the base type for HIR references and pointers.
497 pub fn walk_ptrs_hir_ty<'tcx>(ty: &'tcx hir::Ty<'tcx>) -> &'tcx hir::Ty<'tcx> {
499 TyKind::Ptr(ref mut_ty) | TyKind::Ref(_, ref mut_ty) => walk_ptrs_hir_ty(mut_ty.ty),
504 /// Returns the base type for references and raw pointers, and count reference
506 pub fn walk_ptrs_ty_depth(ty: Ty<'_>) -> (Ty<'_>, usize) {
507 fn inner(ty: Ty<'_>, depth: usize) -> (Ty<'_>, usize) {
509 ty::Ref(_, ty, _) => inner(*ty, depth + 1),
516 /// Returns `true` if types `a` and `b` are same types having same `Const` generic args,
517 /// otherwise returns `false`
518 pub fn same_type_and_consts<'tcx>(a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
519 match (&a.kind(), &b.kind()) {
520 (&ty::Adt(did_a, substs_a), &ty::Adt(did_b, substs_b)) => {
527 .zip(substs_b.iter())
528 .all(|(arg_a, arg_b)| match (arg_a.unpack(), arg_b.unpack()) {
529 (GenericArgKind::Const(inner_a), GenericArgKind::Const(inner_b)) => inner_a == inner_b,
530 (GenericArgKind::Type(type_a), GenericArgKind::Type(type_b)) => {
531 same_type_and_consts(type_a, type_b)
540 /// Checks if a given type looks safe to be uninitialized.
541 pub fn is_uninit_value_valid_for_ty(cx: &LateContext<'_>, ty: Ty<'_>) -> bool {
543 ty::Array(component, _) => is_uninit_value_valid_for_ty(cx, component),
544 ty::Tuple(types) => types.iter().all(|ty| is_uninit_value_valid_for_ty(cx, ty)),
545 ty::Adt(adt, _) => cx.tcx.lang_items().maybe_uninit() == Some(adt.did()),
550 /// Gets an iterator over all predicates which apply to the given item.
551 pub fn all_predicates_of(tcx: TyCtxt<'_>, id: DefId) -> impl Iterator<Item = &(Predicate<'_>, Span)> {
552 let mut next_id = Some(id);
553 iter::from_fn(move || {
554 next_id.take().map(|id| {
555 let preds = tcx.predicates_of(id);
556 next_id = preds.parent;
557 preds.predicates.iter()
563 /// A signature for a function like type.
564 #[derive(Clone, Copy)]
565 pub enum ExprFnSig<'tcx> {
566 Sig(Binder<'tcx, FnSig<'tcx>>, Option<DefId>),
567 Closure(Option<&'tcx FnDecl<'tcx>>, Binder<'tcx, FnSig<'tcx>>),
568 Trait(Binder<'tcx, Ty<'tcx>>, Option<Binder<'tcx, Ty<'tcx>>>, Option<DefId>),
570 impl<'tcx> ExprFnSig<'tcx> {
571 /// Gets the argument type at the given offset. This will return `None` when the index is out of
572 /// bounds only for variadic functions, otherwise this will panic.
573 pub fn input(self, i: usize) -> Option<Binder<'tcx, Ty<'tcx>>> {
575 Self::Sig(sig, _) => {
576 if sig.c_variadic() {
577 sig.inputs().map_bound(|inputs| inputs.get(i).copied()).transpose()
582 Self::Closure(_, sig) => Some(sig.input(0).map_bound(|ty| ty.tuple_fields()[i])),
583 Self::Trait(inputs, _, _) => Some(inputs.map_bound(|ty| ty.tuple_fields()[i])),
587 /// Gets the argument type at the given offset. For closures this will also get the type as
588 /// written. This will return `None` when the index is out of bounds only for variadic
589 /// functions, otherwise this will panic.
590 pub fn input_with_hir(self, i: usize) -> Option<(Option<&'tcx hir::Ty<'tcx>>, Binder<'tcx, Ty<'tcx>>)> {
592 Self::Sig(sig, _) => {
593 if sig.c_variadic() {
595 .map_bound(|inputs| inputs.get(i).copied())
597 .map(|arg| (None, arg))
599 Some((None, sig.input(i)))
602 Self::Closure(decl, sig) => Some((
603 decl.and_then(|decl| decl.inputs.get(i)),
604 sig.input(0).map_bound(|ty| ty.tuple_fields()[i]),
606 Self::Trait(inputs, _, _) => Some((None, inputs.map_bound(|ty| ty.tuple_fields()[i]))),
610 /// Gets the result type, if one could be found. Note that the result type of a trait may not be
612 pub fn output(self) -> Option<Binder<'tcx, Ty<'tcx>>> {
614 Self::Sig(sig, _) | Self::Closure(_, sig) => Some(sig.output()),
615 Self::Trait(_, output, _) => output,
619 pub fn predicates_id(&self) -> Option<DefId> {
620 if let ExprFnSig::Sig(_, id) | ExprFnSig::Trait(_, _, id) = *self {
628 /// If the expression is function like, get the signature for it.
629 pub fn expr_sig<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'_>) -> Option<ExprFnSig<'tcx>> {
630 if let Res::Def(DefKind::Fn | DefKind::Ctor(_, CtorKind::Fn) | DefKind::AssocFn, id) = path_res(cx, expr) {
631 Some(ExprFnSig::Sig(cx.tcx.fn_sig(id), Some(id)))
633 ty_sig(cx, cx.typeck_results().expr_ty_adjusted(expr).peel_refs())
637 /// If the type is function like, get the signature for it.
638 pub fn ty_sig<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> Option<ExprFnSig<'tcx>> {
640 return ty_sig(cx, ty.boxed_ty());
643 ty::Closure(id, subs) => {
646 .and_then(|id| cx.tcx.hir().fn_decl_by_hir_id(cx.tcx.hir().local_def_id_to_hir_id(id)));
647 Some(ExprFnSig::Closure(decl, subs.as_closure().sig()))
649 ty::FnDef(id, subs) => Some(ExprFnSig::Sig(cx.tcx.bound_fn_sig(id).subst(cx.tcx, subs), Some(id))),
650 ty::Alias(ty::Opaque, ty::AliasTy { def_id, .. }) => {
651 sig_from_bounds(cx, ty, cx.tcx.item_bounds(def_id), cx.tcx.opt_parent(def_id))
653 ty::FnPtr(sig) => Some(ExprFnSig::Sig(sig, None)),
654 ty::Dynamic(bounds, _, _) => {
655 let lang_items = cx.tcx.lang_items();
656 match bounds.principal() {
658 if Some(bound.def_id()) == lang_items.fn_trait()
659 || Some(bound.def_id()) == lang_items.fn_once_trait()
660 || Some(bound.def_id()) == lang_items.fn_mut_trait() =>
664 .find(|p| lang_items.fn_once_output().map_or(false, |id| id == p.item_def_id()))
665 .map(|p| p.map_bound(|p| p.term.ty().unwrap()));
666 Some(ExprFnSig::Trait(bound.map_bound(|b| b.substs.type_at(0)), output, None))
671 ty::Alias(ty::Projection, proj) => match cx.tcx.try_normalize_erasing_regions(cx.param_env, ty) {
672 Ok(normalized_ty) if normalized_ty != ty => ty_sig(cx, normalized_ty),
673 _ => sig_for_projection(cx, proj).or_else(|| sig_from_bounds(cx, ty, cx.param_env.caller_bounds(), None)),
675 ty::Param(_) => sig_from_bounds(cx, ty, cx.param_env.caller_bounds(), None),
680 fn sig_from_bounds<'tcx>(
681 cx: &LateContext<'tcx>,
683 predicates: &'tcx [Predicate<'tcx>],
684 predicates_id: Option<DefId>,
685 ) -> Option<ExprFnSig<'tcx>> {
686 let mut inputs = None;
687 let mut output = None;
688 let lang_items = cx.tcx.lang_items();
690 for pred in predicates {
691 match pred.kind().skip_binder() {
692 PredicateKind::Clause(ty::Clause::Trait(p))
693 if (lang_items.fn_trait() == Some(p.def_id())
694 || lang_items.fn_mut_trait() == Some(p.def_id())
695 || lang_items.fn_once_trait() == Some(p.def_id()))
696 && p.self_ty() == ty =>
698 let i = pred.kind().rebind(p.trait_ref.substs.type_at(1));
699 if inputs.map_or(false, |inputs| i != inputs) {
700 // Multiple different fn trait impls. Is this even allowed?
705 PredicateKind::Clause(ty::Clause::Projection(p))
706 if Some(p.projection_ty.def_id) == lang_items.fn_once_output() && p.projection_ty.self_ty() == ty =>
708 if output.is_some() {
709 // Multiple different fn trait impls. Is this even allowed?
712 output = Some(pred.kind().rebind(p.term.ty().unwrap()));
718 inputs.map(|ty| ExprFnSig::Trait(ty, output, predicates_id))
721 fn sig_for_projection<'tcx>(cx: &LateContext<'tcx>, ty: AliasTy<'tcx>) -> Option<ExprFnSig<'tcx>> {
722 let mut inputs = None;
723 let mut output = None;
724 let lang_items = cx.tcx.lang_items();
728 .bound_explicit_item_bounds(ty.def_id)
729 .subst_iter_copied(cx.tcx, ty.substs)
731 match pred.kind().skip_binder() {
732 PredicateKind::Clause(ty::Clause::Trait(p))
733 if (lang_items.fn_trait() == Some(p.def_id())
734 || lang_items.fn_mut_trait() == Some(p.def_id())
735 || lang_items.fn_once_trait() == Some(p.def_id())) =>
737 let i = pred.kind().rebind(p.trait_ref.substs.type_at(1));
739 if inputs.map_or(false, |inputs| inputs != i) {
740 // Multiple different fn trait impls. Is this even allowed?
745 PredicateKind::Clause(ty::Clause::Projection(p))
746 if Some(p.projection_ty.def_id) == lang_items.fn_once_output() =>
748 if output.is_some() {
749 // Multiple different fn trait impls. Is this even allowed?
752 output = pred.kind().rebind(p.term.ty()).transpose();
758 inputs.map(|ty| ExprFnSig::Trait(ty, output, None))
761 #[derive(Clone, Copy)]
766 impl core::ops::Add<u32> for EnumValue {
768 fn add(self, n: u32) -> Self::Output {
770 Self::Unsigned(x) => Self::Unsigned(x + u128::from(n)),
771 Self::Signed(x) => Self::Signed(x + i128::from(n)),
776 /// Attempts to read the given constant as though it were an enum value.
777 #[expect(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
778 pub fn read_explicit_enum_value(tcx: TyCtxt<'_>, id: DefId) -> Option<EnumValue> {
779 if let Ok(ConstValue::Scalar(Scalar::Int(value))) = tcx.const_eval_poly(id) {
780 match tcx.type_of(id).kind() {
781 ty::Int(_) => Some(EnumValue::Signed(match value.size().bytes() {
782 1 => i128::from(value.assert_bits(Size::from_bytes(1)) as u8 as i8),
783 2 => i128::from(value.assert_bits(Size::from_bytes(2)) as u16 as i16),
784 4 => i128::from(value.assert_bits(Size::from_bytes(4)) as u32 as i32),
785 8 => i128::from(value.assert_bits(Size::from_bytes(8)) as u64 as i64),
786 16 => value.assert_bits(Size::from_bytes(16)) as i128,
789 ty::Uint(_) => Some(EnumValue::Unsigned(match value.size().bytes() {
790 1 => value.assert_bits(Size::from_bytes(1)),
791 2 => value.assert_bits(Size::from_bytes(2)),
792 4 => value.assert_bits(Size::from_bytes(4)),
793 8 => value.assert_bits(Size::from_bytes(8)),
794 16 => value.assert_bits(Size::from_bytes(16)),
804 /// Gets the value of the given variant.
805 pub fn get_discriminant_value(tcx: TyCtxt<'_>, adt: AdtDef<'_>, i: VariantIdx) -> EnumValue {
806 let variant = &adt.variant(i);
807 match variant.discr {
808 VariantDiscr::Explicit(id) => read_explicit_enum_value(tcx, id).unwrap(),
809 VariantDiscr::Relative(x) => match adt.variant((i.as_usize() - x as usize).into()).discr {
810 VariantDiscr::Explicit(id) => read_explicit_enum_value(tcx, id).unwrap() + x,
811 VariantDiscr::Relative(_) => EnumValue::Unsigned(x.into()),
816 /// Check if the given type is either `core::ffi::c_void`, `std::os::raw::c_void`, or one of the
817 /// platform specific `libc::<platform>::c_void` types in libc.
818 pub fn is_c_void(cx: &LateContext<'_>, ty: Ty<'_>) -> bool {
819 if let ty::Adt(adt, _) = ty.kind()
820 && let &[krate, .., name] = &*cx.get_def_path(adt.did())
821 && let sym::libc | sym::core | sym::std = krate
822 && name.as_str() == "c_void"
830 pub fn for_each_top_level_late_bound_region<B>(
832 f: impl FnMut(BoundRegion) -> ControlFlow<B>,
833 ) -> ControlFlow<B> {
838 impl<'tcx, B, F: FnMut(BoundRegion) -> ControlFlow<B>> TypeVisitor<'tcx> for V<F> {
840 fn visit_region(&mut self, r: Region<'tcx>) -> ControlFlow<Self::BreakTy> {
841 if let RegionKind::ReLateBound(idx, bound) = r.kind() && idx.as_u32() == self.index {
844 ControlFlow::Continue(())
847 fn visit_binder<T: TypeVisitable<'tcx>>(&mut self, t: &Binder<'tcx, T>) -> ControlFlow<Self::BreakTy> {
849 let res = t.super_visit_with(self);
854 ty.visit_with(&mut V { index: 0, f })
857 pub struct AdtVariantInfo {
862 pub fields_size: Vec<(usize, u64)>,
865 impl AdtVariantInfo {
866 /// Returns ADT variants ordered by size
867 pub fn new<'tcx>(cx: &LateContext<'tcx>, adt: AdtDef<'tcx>, subst: &'tcx List<GenericArg<'tcx>>) -> Vec<Self> {
868 let mut variants_size = adt
872 .map(|(i, variant)| {
873 let mut fields_size = variant
877 .map(|(i, f)| (i, approx_ty_size(cx, f.ty(cx.tcx, subst))))
878 .collect::<Vec<_>>();
879 fields_size.sort_by(|(_, a_size), (_, b_size)| (a_size.cmp(b_size)));
883 size: fields_size.iter().map(|(_, size)| size).sum(),
887 .collect::<Vec<_>>();
888 variants_size.sort_by(|a, b| (b.size.cmp(&a.size)));
893 /// Gets the struct or enum variant from the given `Res`
894 pub fn variant_of_res<'tcx>(cx: &LateContext<'tcx>, res: Res) -> Option<&'tcx VariantDef> {
896 Res::Def(DefKind::Struct, id) => Some(cx.tcx.adt_def(id).non_enum_variant()),
897 Res::Def(DefKind::Variant, id) => Some(cx.tcx.adt_def(cx.tcx.parent(id)).variant_with_id(id)),
898 Res::Def(DefKind::Ctor(CtorOf::Struct, _), id) => Some(cx.tcx.adt_def(cx.tcx.parent(id)).non_enum_variant()),
899 Res::Def(DefKind::Ctor(CtorOf::Variant, _), id) => {
900 let var_id = cx.tcx.parent(id);
901 Some(cx.tcx.adt_def(cx.tcx.parent(var_id)).variant_with_id(var_id))
903 Res::SelfCtor(id) => Some(cx.tcx.type_of(id).ty_adt_def().unwrap().non_enum_variant()),
908 /// Checks if the type is a type parameter implementing `FnOnce`, but not `FnMut`.
909 pub fn ty_is_fn_once_param<'tcx>(tcx: TyCtxt<'_>, ty: Ty<'tcx>, predicates: &'tcx [Predicate<'_>]) -> bool {
910 let ty::Param(ty) = *ty.kind() else {
913 let lang = tcx.lang_items();
914 let (Some(fn_once_id), Some(fn_mut_id), Some(fn_id))
915 = (lang.fn_once_trait(), lang.fn_mut_trait(), lang.fn_trait())
921 .try_fold(false, |found, p| {
922 if let PredicateKind::Clause(ty::Clause::Trait(p)) = p.kind().skip_binder()
923 && let ty::Param(self_ty) = p.trait_ref.self_ty().kind()
924 && ty.index == self_ty.index
926 // This should use `super_traits_of`, but that's a private function.
927 if p.trait_ref.def_id == fn_once_id {
929 } else if p.trait_ref.def_id == fn_mut_id || p.trait_ref.def_id == fn_id {
938 /// Comes up with an "at least" guesstimate for the type's size, not taking into
939 /// account the layout of type parameters.
940 pub fn approx_ty_size<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> u64 {
941 use rustc_middle::ty::layout::LayoutOf;
942 if !is_normalizable(cx, cx.param_env, ty) {
945 match (cx.layout_of(ty).map(|layout| layout.size.bytes()), ty.kind()) {
946 (Ok(size), _) => size,
947 (Err(_), ty::Tuple(list)) => list.as_substs().types().map(|t| approx_ty_size(cx, t)).sum(),
948 (Err(_), ty::Array(t, n)) => {
949 n.try_eval_usize(cx.tcx, cx.param_env).unwrap_or_default() * approx_ty_size(cx, *t)
951 (Err(_), ty::Adt(def, subst)) if def.is_struct() => def
957 .map(|field| approx_ty_size(cx, field.ty(cx.tcx, subst)))
961 (Err(_), ty::Adt(def, subst)) if def.is_enum() => def
967 .map(|field| approx_ty_size(cx, field.ty(cx.tcx, subst)))
971 .unwrap_or_default(),
972 (Err(_), ty::Adt(def, subst)) if def.is_union() => def
978 .map(|field| approx_ty_size(cx, field.ty(cx.tcx, subst)))
983 .unwrap_or_default(),
988 /// Makes the projection type for the named associated type in the given impl or trait impl.
990 /// This function is for associated types which are "known" to exist, and as such, will only return
991 /// `None` when debug assertions are disabled in order to prevent ICE's. With debug assertions
992 /// enabled this will check that the named associated type exists, the correct number of
993 /// substitutions are given, and that the correct kinds of substitutions are given (lifetime,
994 /// constant or type). This will not check if type normalization would succeed.
995 pub fn make_projection<'tcx>(
999 substs: impl IntoIterator<Item = impl Into<GenericArg<'tcx>>>,
1000 ) -> Option<AliasTy<'tcx>> {
1003 container_id: DefId,
1005 substs: SubstsRef<'tcx>,
1006 ) -> Option<AliasTy<'tcx>> {
1007 let Some(assoc_item) = tcx
1008 .associated_items(container_id)
1009 .find_by_name_and_kind(tcx, Ident::with_dummy_span(assoc_ty), AssocKind::Type, container_id)
1011 debug_assert!(false, "type `{assoc_ty}` not found in `{container_id:?}`");
1014 #[cfg(debug_assertions)]
1016 let generics = tcx.generics_of(assoc_item.def_id);
1017 let generic_count = generics.parent_count + generics.params.len();
1018 let params = generics
1020 .map_or([].as_slice(), |id| &*tcx.generics_of(id).params)
1022 .chain(&generics.params)
1026 generic_count == substs.len(),
1027 "wrong number of substs for `{:?}`: found `{}` expected `{generic_count}`.\n\
1028 note: the expected parameters are: {:#?}\n\
1029 the given arguments are: `{substs:#?}`",
1032 params.map(ty::GenericParamDefKind::descr).collect::<Vec<_>>(),
1035 if let Some((idx, (param, arg))) = params
1037 .zip(substs.iter().map(GenericArg::unpack))
1039 .find(|(_, (param, arg))| {
1042 (ty::GenericParamDefKind::Lifetime, GenericArgKind::Lifetime(_))
1043 | (ty::GenericParamDefKind::Type { .. }, GenericArgKind::Type(_))
1044 | (ty::GenericParamDefKind::Const { .. }, GenericArgKind::Const(_))
1050 "mismatched subst type at index {idx}: expected a {}, found `{arg:?}`\n\
1051 note: the expected parameters are {:#?}\n\
1052 the given arguments are {substs:#?}",
1054 params.map(ty::GenericParamDefKind::descr).collect::<Vec<_>>()
1059 Some(tcx.mk_alias_ty(assoc_item.def_id, substs))
1065 tcx.mk_substs(substs.into_iter().map(Into::into)),
1069 /// Normalizes the named associated type in the given impl or trait impl.
1071 /// This function is for associated types which are "known" to be valid with the given
1072 /// substitutions, and as such, will only return `None` when debug assertions are disabled in order
1073 /// to prevent ICE's. With debug assertions enabled this will check that that type normalization
1074 /// succeeds as well as everything checked by `make_projection`.
1075 pub fn make_normalized_projection<'tcx>(
1077 param_env: ParamEnv<'tcx>,
1078 container_id: DefId,
1080 substs: impl IntoIterator<Item = impl Into<GenericArg<'tcx>>>,
1081 ) -> Option<Ty<'tcx>> {
1082 fn helper<'tcx>(tcx: TyCtxt<'tcx>, param_env: ParamEnv<'tcx>, ty: AliasTy<'tcx>) -> Option<Ty<'tcx>> {
1083 #[cfg(debug_assertions)]
1084 if let Some((i, subst)) = ty
1088 .find(|(_, subst)| subst.has_late_bound_regions())
1092 "substs contain late-bound region at index `{i}` which can't be normalized.\n\
1093 use `TyCtxt::erase_late_bound_regions`\n\
1094 note: subst is `{subst:#?}`",
1098 match tcx.try_normalize_erasing_regions(param_env, tcx.mk_projection(ty.def_id, ty.substs)) {
1101 debug_assert!(false, "failed to normalize type `{ty}`: {e:#?}");
1106 helper(tcx, param_env, make_projection(tcx, container_id, assoc_ty, substs)?)