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