1 //! Util methods for [`rustc_middle::ty`]
3 #![allow(clippy::module_name_repetitions)]
5 use rustc_ast::ast::Mutability;
6 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
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, ParamEnv, Predicate, PredicateKind, Ty, TyCtxt, TypeFoldable, UintTy,
19 use rustc_span::symbol::Ident;
20 use rustc_span::{sym, Span, Symbol, DUMMY_SP};
21 use rustc_target::abi::{Size, VariantIdx};
22 use rustc_trait_selection::infer::InferCtxtExt;
23 use rustc_trait_selection::traits::query::normalize::AtExt;
26 use crate::{match_def_path, path_res, paths};
28 // Checks if the given type implements copy.
29 pub fn is_copy<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
30 ty.is_copy_modulo_regions(cx.tcx.at(DUMMY_SP), cx.param_env)
33 /// Checks whether a type can be partially moved.
34 pub fn can_partially_move_ty<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
35 if has_drop(cx, ty) || is_copy(cx, ty) {
39 ty::Param(_) => false,
40 ty::Adt(def, subs) => def.all_fields().any(|f| !is_copy(cx, f.ty(cx.tcx, subs))),
45 /// Walks into `ty` and returns `true` if any inner type is the same as `other_ty`
46 pub fn contains_ty<'tcx>(ty: Ty<'tcx>, other_ty: Ty<'tcx>) -> bool {
47 ty.walk().any(|inner| match inner.unpack() {
48 GenericArgKind::Type(inner_ty) => other_ty == inner_ty,
49 GenericArgKind::Lifetime(_) | GenericArgKind::Const(_) => false,
53 /// Walks into `ty` and returns `true` if any inner type is an instance of the given adt
55 pub fn contains_adt_constructor<'tcx>(ty: Ty<'tcx>, adt: AdtDef<'tcx>) -> bool {
56 ty.walk().any(|inner| match inner.unpack() {
57 GenericArgKind::Type(inner_ty) => inner_ty.ty_adt_def() == Some(adt),
58 GenericArgKind::Lifetime(_) | GenericArgKind::Const(_) => false,
62 /// Resolves `<T as Iterator>::Item` for `T`
63 /// Do not invoke without first verifying that the type implements `Iterator`
64 pub fn get_iterator_item_ty<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> Option<Ty<'tcx>> {
66 .get_diagnostic_item(sym::Iterator)
67 .and_then(|iter_did| get_associated_type(cx, ty, iter_did, "Item"))
70 /// Returns the associated type `name` for `ty` as an implementation of `trait_id`.
71 /// Do not invoke without first verifying that the type implements the trait.
72 pub fn get_associated_type<'tcx>(
73 cx: &LateContext<'tcx>,
77 ) -> Option<Ty<'tcx>> {
79 .associated_items(trait_id)
80 .find_by_name_and_kind(cx.tcx, Ident::from_str(name), ty::AssocKind::Type, trait_id)
82 let proj = cx.tcx.mk_projection(assoc.def_id, cx.tcx.mk_substs_trait(ty, &[]));
83 cx.tcx.normalize_erasing_regions(cx.param_env, proj)
87 /// Get the diagnostic name of a type, e.g. `sym::HashMap`. To check if a type
88 /// implements a trait marked with a diagnostic item use [`implements_trait`].
90 /// For a further exploitation what diagnostic items are see [diagnostic items] in
93 /// [Diagnostic Items]: https://rustc-dev-guide.rust-lang.org/diagnostics/diagnostic-items.html
94 pub fn get_type_diagnostic_name(cx: &LateContext<'_>, ty: Ty<'_>) -> Option<Symbol> {
96 ty::Adt(adt, _) => cx.tcx.get_diagnostic_name(adt.did()),
101 /// Returns true if ty has `iter` or `iter_mut` methods
102 pub fn has_iter_method(cx: &LateContext<'_>, probably_ref_ty: Ty<'_>) -> Option<Symbol> {
103 // FIXME: instead of this hard-coded list, we should check if `<adt>::iter`
104 // exists and has the desired signature. Unfortunately FnCtxt is not exported
105 // so we can't use its `lookup_method` method.
106 let into_iter_collections: &[Symbol] = &[
122 let ty_to_check = match probably_ref_ty.kind() {
123 ty::Ref(_, ty_to_check, _) => *ty_to_check,
124 _ => probably_ref_ty,
127 let def_id = match ty_to_check.kind() {
128 ty::Array(..) => return Some(sym::array),
129 ty::Slice(..) => return Some(sym::slice),
130 ty::Adt(adt, _) => adt.did(),
134 for &name in into_iter_collections {
135 if cx.tcx.is_diagnostic_item(name, def_id) {
136 return Some(cx.tcx.item_name(def_id));
142 /// Checks whether a type implements a trait.
143 /// The function returns false in case the type contains an inference variable.
146 /// * [`get_trait_def_id`](super::get_trait_def_id) to get a trait [`DefId`].
147 /// * [Common tools for writing lints] for an example how to use this function and other options.
149 /// [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
150 pub fn implements_trait<'tcx>(
151 cx: &LateContext<'tcx>,
154 ty_params: &[GenericArg<'tcx>],
156 implements_trait_with_env(cx.tcx, cx.param_env, ty, trait_id, ty_params)
159 /// Same as `implements_trait` but allows using a `ParamEnv` different from the lint context.
160 pub fn implements_trait_with_env<'tcx>(
162 param_env: ParamEnv<'tcx>,
165 ty_params: &[GenericArg<'tcx>],
167 // Clippy shouldn't have infer types
168 assert!(!ty.needs_infer());
170 let ty = tcx.erase_regions(ty);
171 if ty.has_escaping_bound_vars() {
174 let ty_params = tcx.mk_substs(ty_params.iter());
175 tcx.infer_ctxt().enter(|infcx| {
177 .type_implements_trait(trait_id, ty, ty_params, param_env)
178 .must_apply_modulo_regions()
182 /// Checks whether this type implements `Drop`.
183 pub fn has_drop<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
184 match ty.ty_adt_def() {
185 Some(def) => def.has_dtor(cx.tcx),
190 // Returns whether the type has #[must_use] attribute
191 pub fn is_must_use_ty<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
193 ty::Adt(adt, _) => cx.tcx.has_attr(adt.did(), sym::must_use),
194 ty::Foreign(did) => cx.tcx.has_attr(*did, sym::must_use),
195 ty::Slice(ty) | ty::Array(ty, _) | ty::RawPtr(ty::TypeAndMut { ty, .. }) | ty::Ref(_, ty, _) => {
196 // for the Array case we don't need to care for the len == 0 case
197 // because we don't want to lint functions returning empty arrays
198 is_must_use_ty(cx, *ty)
200 ty::Tuple(substs) => substs.iter().any(|ty| is_must_use_ty(cx, ty)),
201 ty::Opaque(def_id, _) => {
202 for (predicate, _) in cx.tcx.explicit_item_bounds(*def_id) {
203 if let ty::PredicateKind::Trait(trait_predicate) = predicate.kind().skip_binder() {
204 if cx.tcx.has_attr(trait_predicate.trait_ref.def_id, sym::must_use) {
211 ty::Dynamic(binder, _) => {
212 for predicate in binder.iter() {
213 if let ty::ExistentialPredicate::Trait(ref trait_ref) = predicate.skip_binder() {
214 if cx.tcx.has_attr(trait_ref.def_id, sym::must_use) {
225 // FIXME: Per https://doc.rust-lang.org/nightly/nightly-rustc/rustc_trait_selection/infer/at/struct.At.html#method.normalize
226 // this function can be removed once the `normalize` method does not panic when normalization does
228 /// Checks if `Ty` is normalizable. This function is useful
229 /// to avoid crashes on `layout_of`.
230 pub fn is_normalizable<'tcx>(cx: &LateContext<'tcx>, param_env: ty::ParamEnv<'tcx>, ty: Ty<'tcx>) -> bool {
231 is_normalizable_helper(cx, param_env, ty, &mut FxHashMap::default())
234 fn is_normalizable_helper<'tcx>(
235 cx: &LateContext<'tcx>,
236 param_env: ty::ParamEnv<'tcx>,
238 cache: &mut FxHashMap<Ty<'tcx>, bool>,
240 if let Some(&cached_result) = cache.get(&ty) {
241 return cached_result;
243 // prevent recursive loops, false-negative is better than endless loop leading to stack overflow
244 cache.insert(ty, false);
245 let result = cx.tcx.infer_ctxt().enter(|infcx| {
246 let cause = rustc_middle::traits::ObligationCause::dummy();
247 if infcx.at(&cause, param_env).normalize(ty).is_ok() {
249 ty::Adt(def, substs) => def.variants().iter().all(|variant| {
253 .all(|field| is_normalizable_helper(cx, param_env, field.ty(cx.tcx, substs), cache))
255 _ => ty.walk().all(|generic_arg| match generic_arg.unpack() {
256 GenericArgKind::Type(inner_ty) if inner_ty != ty => {
257 is_normalizable_helper(cx, param_env, inner_ty, cache)
259 _ => true, // if inner_ty == ty, we've already checked it
266 cache.insert(ty, result);
270 /// Returns `true` if the given type is a non aggregate primitive (a `bool` or `char`, any
271 /// integer or floating-point number type). For checking aggregation of primitive types (e.g.
272 /// tuples and slices of primitive type) see `is_recursively_primitive_type`
273 pub fn is_non_aggregate_primitive_type(ty: Ty<'_>) -> bool {
274 matches!(ty.kind(), ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Float(_))
277 /// Returns `true` if the given type is a primitive (a `bool` or `char`, any integer or
278 /// floating-point number type, a `str`, or an array, slice, or tuple of those types).
279 pub fn is_recursively_primitive_type(ty: Ty<'_>) -> bool {
281 ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::Str => true,
282 ty::Ref(_, inner, _) if *inner.kind() == ty::Str => true,
283 ty::Array(inner_type, _) | ty::Slice(inner_type) => is_recursively_primitive_type(inner_type),
284 ty::Tuple(inner_types) => inner_types.iter().all(is_recursively_primitive_type),
289 /// Checks if the type is a reference equals to a diagnostic item
290 pub fn is_type_ref_to_diagnostic_item(cx: &LateContext<'_>, ty: Ty<'_>, diag_item: Symbol) -> bool {
292 ty::Ref(_, ref_ty, _) => match ref_ty.kind() {
293 ty::Adt(adt, _) => cx.tcx.is_diagnostic_item(diag_item, adt.did()),
300 /// Checks if the type is equal to a diagnostic item. To check if a type implements a
301 /// trait marked with a diagnostic item use [`implements_trait`].
303 /// For a further exploitation what diagnostic items are see [diagnostic items] in
308 /// If you change the signature, remember to update the internal lint `MatchTypeOnDiagItem`
310 /// [Diagnostic Items]: https://rustc-dev-guide.rust-lang.org/diagnostics/diagnostic-items.html
311 pub fn is_type_diagnostic_item(cx: &LateContext<'_>, ty: Ty<'_>, diag_item: Symbol) -> bool {
313 ty::Adt(adt, _) => cx.tcx.is_diagnostic_item(diag_item, adt.did()),
318 /// Checks if the type is equal to a lang item.
320 /// Returns `false` if the `LangItem` is not defined.
321 pub fn is_type_lang_item(cx: &LateContext<'_>, ty: Ty<'_>, lang_item: hir::LangItem) -> bool {
323 ty::Adt(adt, _) => cx
327 .map_or(false, |li| li == adt.did()),
332 /// Return `true` if the passed `typ` is `isize` or `usize`.
333 pub fn is_isize_or_usize(typ: Ty<'_>) -> bool {
334 matches!(typ.kind(), ty::Int(IntTy::Isize) | ty::Uint(UintTy::Usize))
337 /// Checks if type is struct, enum or union type with the given def path.
339 /// If the type is a diagnostic item, use `is_type_diagnostic_item` instead.
340 /// If you change the signature, remember to update the internal lint `MatchTypeOnDiagItem`
341 pub fn match_type(cx: &LateContext<'_>, ty: Ty<'_>, path: &[&str]) -> bool {
343 ty::Adt(adt, _) => match_def_path(cx, adt.did(), path),
348 /// Checks if the drop order for a type matters. Some std types implement drop solely to
349 /// deallocate memory. For these types, and composites containing them, changing the drop order
350 /// won't result in any observable side effects.
351 pub fn needs_ordered_drop<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
352 fn needs_ordered_drop_inner<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>, seen: &mut FxHashSet<Ty<'tcx>>) -> bool {
353 if !seen.insert(ty) {
356 if !ty.has_significant_drop(cx.tcx, cx.param_env) {
359 // Check for std types which implement drop, but only for memory allocation.
360 else if is_type_lang_item(cx, ty, LangItem::OwnedBox)
362 get_type_diagnostic_name(cx, ty),
363 Some(sym::HashSet | sym::Rc | sym::Arc | sym::cstring_type)
365 || match_type(cx, ty, &paths::WEAK_RC)
366 || match_type(cx, ty, &paths::WEAK_ARC)
368 // Check all of the generic arguments.
369 if let ty::Adt(_, subs) = ty.kind() {
370 subs.types().any(|ty| needs_ordered_drop_inner(cx, ty, seen))
378 .map_or(false, |id| implements_trait(cx, ty, id, &[]))
380 // This type doesn't implement drop, so no side effects here.
381 // Check if any component type has any.
383 ty::Tuple(fields) => fields.iter().any(|ty| needs_ordered_drop_inner(cx, ty, seen)),
384 ty::Array(ty, _) => needs_ordered_drop_inner(cx, *ty, seen),
385 ty::Adt(adt, subs) => adt
387 .map(|f| f.ty(cx.tcx, subs))
388 .any(|ty| needs_ordered_drop_inner(cx, ty, seen)),
396 needs_ordered_drop_inner(cx, ty, &mut FxHashSet::default())
399 /// Peels off all references on the type. Returns the underlying type and the number of references
401 pub fn peel_mid_ty_refs(ty: Ty<'_>) -> (Ty<'_>, usize) {
402 fn peel(ty: Ty<'_>, count: usize) -> (Ty<'_>, usize) {
403 if let ty::Ref(_, ty, _) = ty.kind() {
412 /// Peels off all references on the type.Returns the underlying type, the number of references
413 /// removed, and whether the pointer is ultimately mutable or not.
414 pub fn peel_mid_ty_refs_is_mutable(ty: Ty<'_>) -> (Ty<'_>, usize, Mutability) {
415 fn f(ty: Ty<'_>, count: usize, mutability: Mutability) -> (Ty<'_>, usize, Mutability) {
417 ty::Ref(_, ty, Mutability::Mut) => f(*ty, count + 1, mutability),
418 ty::Ref(_, ty, Mutability::Not) => f(*ty, count + 1, Mutability::Not),
419 _ => (ty, count, mutability),
422 f(ty, 0, Mutability::Mut)
425 /// Returns `true` if the given type is an `unsafe` function.
426 pub fn type_is_unsafe_function<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
428 ty::FnDef(..) | ty::FnPtr(_) => ty.fn_sig(cx.tcx).unsafety() == Unsafety::Unsafe,
433 /// Returns the base type for HIR references and pointers.
434 pub fn walk_ptrs_hir_ty<'tcx>(ty: &'tcx hir::Ty<'tcx>) -> &'tcx hir::Ty<'tcx> {
436 TyKind::Ptr(ref mut_ty) | TyKind::Rptr(_, ref mut_ty) => walk_ptrs_hir_ty(mut_ty.ty),
441 /// Returns the base type for references and raw pointers, and count reference
443 pub fn walk_ptrs_ty_depth(ty: Ty<'_>) -> (Ty<'_>, usize) {
444 fn inner(ty: Ty<'_>, depth: usize) -> (Ty<'_>, usize) {
446 ty::Ref(_, ty, _) => inner(*ty, depth + 1),
453 /// Returns `true` if types `a` and `b` are same types having same `Const` generic args,
454 /// otherwise returns `false`
455 pub fn same_type_and_consts<'tcx>(a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
456 match (&a.kind(), &b.kind()) {
457 (&ty::Adt(did_a, substs_a), &ty::Adt(did_b, substs_b)) => {
464 .zip(substs_b.iter())
465 .all(|(arg_a, arg_b)| match (arg_a.unpack(), arg_b.unpack()) {
466 (GenericArgKind::Const(inner_a), GenericArgKind::Const(inner_b)) => inner_a == inner_b,
467 (GenericArgKind::Type(type_a), GenericArgKind::Type(type_b)) => {
468 same_type_and_consts(type_a, type_b)
477 /// Checks if a given type looks safe to be uninitialized.
478 pub fn is_uninit_value_valid_for_ty(cx: &LateContext<'_>, ty: Ty<'_>) -> bool {
480 ty::Array(component, _) => is_uninit_value_valid_for_ty(cx, component),
481 ty::Tuple(types) => types.iter().all(|ty| is_uninit_value_valid_for_ty(cx, ty)),
482 ty::Adt(adt, _) => cx.tcx.lang_items().maybe_uninit() == Some(adt.did()),
487 /// Gets an iterator over all predicates which apply to the given item.
488 pub fn all_predicates_of(tcx: TyCtxt<'_>, id: DefId) -> impl Iterator<Item = &(Predicate<'_>, Span)> {
489 let mut next_id = Some(id);
490 iter::from_fn(move || {
491 next_id.take().map(|id| {
492 let preds = tcx.predicates_of(id);
493 next_id = preds.parent;
494 preds.predicates.iter()
500 /// A signature for a function like type.
501 #[derive(Clone, Copy)]
502 pub enum ExprFnSig<'tcx> {
503 Sig(Binder<'tcx, FnSig<'tcx>>),
504 Closure(Binder<'tcx, FnSig<'tcx>>),
505 Trait(Binder<'tcx, Ty<'tcx>>, Option<Binder<'tcx, Ty<'tcx>>>),
507 impl<'tcx> ExprFnSig<'tcx> {
508 /// Gets the argument type at the given offset.
509 pub fn input(self, i: usize) -> Binder<'tcx, Ty<'tcx>> {
511 Self::Sig(sig) => sig.input(i),
512 Self::Closure(sig) => sig.input(0).map_bound(|ty| ty.tuple_fields()[i]),
513 Self::Trait(inputs, _) => inputs.map_bound(|ty| ty.tuple_fields()[i]),
517 /// Gets the result type, if one could be found. Note that the result type of a trait may not be
519 pub fn output(self) -> Option<Binder<'tcx, Ty<'tcx>>> {
521 Self::Sig(sig) | Self::Closure(sig) => Some(sig.output()),
522 Self::Trait(_, output) => output,
527 /// If the expression is function like, get the signature for it.
528 pub fn expr_sig<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'_>) -> Option<ExprFnSig<'tcx>> {
529 if let Res::Def(DefKind::Fn | DefKind::Ctor(_, CtorKind::Fn) | DefKind::AssocFn, id) = path_res(cx, expr) {
530 Some(ExprFnSig::Sig(cx.tcx.fn_sig(id)))
532 let ty = cx.typeck_results().expr_ty_adjusted(expr).peel_refs();
534 ty::Closure(_, subs) => Some(ExprFnSig::Closure(subs.as_closure().sig())),
535 ty::FnDef(id, subs) => Some(ExprFnSig::Sig(cx.tcx.bound_fn_sig(id).subst(cx.tcx, subs))),
536 ty::FnPtr(sig) => Some(ExprFnSig::Sig(sig)),
537 ty::Dynamic(bounds, _) => {
538 let lang_items = cx.tcx.lang_items();
539 match bounds.principal() {
541 if Some(bound.def_id()) == lang_items.fn_trait()
542 || Some(bound.def_id()) == lang_items.fn_once_trait()
543 || Some(bound.def_id()) == lang_items.fn_mut_trait() =>
547 .find(|p| lang_items.fn_once_output().map_or(false, |id| id == p.item_def_id()))
548 .map(|p| p.map_bound(|p| p.term.ty().expect("return type was a const")));
549 Some(ExprFnSig::Trait(bound.map_bound(|b| b.substs.type_at(0)), output))
554 ty::Param(_) | ty::Projection(..) => {
555 let mut inputs = None;
556 let mut output = None;
557 let lang_items = cx.tcx.lang_items();
559 for (pred, _) in all_predicates_of(cx.tcx, cx.typeck_results().hir_owner.to_def_id()) {
560 let mut is_input = false;
561 if let Some(ty) = pred
563 .map_bound(|pred| match pred {
564 PredicateKind::Trait(p)
565 if (lang_items.fn_trait() == Some(p.def_id())
566 || lang_items.fn_mut_trait() == Some(p.def_id())
567 || lang_items.fn_once_trait() == Some(p.def_id()))
568 && p.self_ty() == ty =>
571 Some(p.trait_ref.substs.type_at(1))
573 PredicateKind::Projection(p)
574 if Some(p.projection_ty.item_def_id) == lang_items.fn_once_output()
575 && p.projection_ty.self_ty() == ty =>
584 if is_input && inputs.is_none() {
586 } else if !is_input && output.is_none() {
589 // Multiple different fn trait impls. Is this even allowed?
595 inputs.map(|ty| ExprFnSig::Trait(ty, output))
602 #[derive(Clone, Copy)]
607 impl core::ops::Add<u32> for EnumValue {
609 fn add(self, n: u32) -> Self::Output {
611 Self::Unsigned(x) => Self::Unsigned(x + u128::from(n)),
612 Self::Signed(x) => Self::Signed(x + i128::from(n)),
617 /// Attempts to read the given constant as though it were an an enum value.
618 #[expect(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
619 pub fn read_explicit_enum_value(tcx: TyCtxt<'_>, id: DefId) -> Option<EnumValue> {
620 if let Ok(ConstValue::Scalar(Scalar::Int(value))) = tcx.const_eval_poly(id) {
621 match tcx.type_of(id).kind() {
622 ty::Int(_) => Some(EnumValue::Signed(match value.size().bytes() {
623 1 => i128::from(value.assert_bits(Size::from_bytes(1)) as u8 as i8),
624 2 => i128::from(value.assert_bits(Size::from_bytes(2)) as u16 as i16),
625 4 => i128::from(value.assert_bits(Size::from_bytes(4)) as u32 as i32),
626 8 => i128::from(value.assert_bits(Size::from_bytes(8)) as u64 as i64),
627 16 => value.assert_bits(Size::from_bytes(16)) as i128,
630 ty::Uint(_) => Some(EnumValue::Unsigned(match value.size().bytes() {
631 1 => value.assert_bits(Size::from_bytes(1)),
632 2 => value.assert_bits(Size::from_bytes(2)),
633 4 => value.assert_bits(Size::from_bytes(4)),
634 8 => value.assert_bits(Size::from_bytes(8)),
635 16 => value.assert_bits(Size::from_bytes(16)),
645 /// Gets the value of the given variant.
646 pub fn get_discriminant_value(tcx: TyCtxt<'_>, adt: AdtDef<'_>, i: VariantIdx) -> EnumValue {
647 let variant = &adt.variant(i);
648 match variant.discr {
649 VariantDiscr::Explicit(id) => read_explicit_enum_value(tcx, id).unwrap(),
650 VariantDiscr::Relative(x) => match adt.variant((i.as_usize() - x as usize).into()).discr {
651 VariantDiscr::Explicit(id) => read_explicit_enum_value(tcx, id).unwrap() + x,
652 VariantDiscr::Relative(_) => EnumValue::Unsigned(x.into()),
657 /// Check if the given type is either `core::ffi::c_void`, `std::os::raw::c_void`, or one of the
658 /// platform specific `libc::<platform>::c_void` types in libc.
659 pub fn is_c_void(cx: &LateContext<'_>, ty: Ty<'_>) -> bool {
660 if let ty::Adt(adt, _) = ty.kind()
661 && let &[krate, .., name] = &*cx.get_def_path(adt.did())
662 && let sym::libc | sym::core | sym::std = krate
663 && name.as_str() == "c_void"