]> git.lizzy.rs Git - rust.git/blob - clippy_utils/src/ty.rs
Extract some util functions
[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.types().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.types().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.tcx.lang_items().require(lang_item).map_or(false, |li| li == adt.did),
298         _ => false,
299     }
300 }
301
302 /// Return `true` if the passed `typ` is `isize` or `usize`.
303 pub fn is_isize_or_usize(typ: Ty<'_>) -> bool {
304     matches!(typ.kind(), ty::Int(IntTy::Isize) | ty::Uint(UintTy::Usize))
305 }
306
307 /// Checks if type is struct, enum or union type with the given def path.
308 ///
309 /// If the type is a diagnostic item, use `is_type_diagnostic_item` instead.
310 /// If you change the signature, remember to update the internal lint `MatchTypeOnDiagItem`
311 pub fn match_type(cx: &LateContext<'_>, ty: Ty<'_>, path: &[&str]) -> bool {
312     match ty.kind() {
313         ty::Adt(adt, _) => match_def_path(cx, adt.did, path),
314         _ => false,
315     }
316 }
317
318 /// Peels off all references on the type. Returns the underlying type and the number of references
319 /// removed.
320 pub fn peel_mid_ty_refs(ty: Ty<'_>) -> (Ty<'_>, usize) {
321     fn peel(ty: Ty<'_>, count: usize) -> (Ty<'_>, usize) {
322         if let ty::Ref(_, ty, _) = ty.kind() {
323             peel(ty, count + 1)
324         } else {
325             (ty, count)
326         }
327     }
328     peel(ty, 0)
329 }
330
331 /// Peels off all references on the type.Returns the underlying type, the number of references
332 /// removed, and whether the pointer is ultimately mutable or not.
333 pub fn peel_mid_ty_refs_is_mutable(ty: Ty<'_>) -> (Ty<'_>, usize, Mutability) {
334     fn f(ty: Ty<'_>, count: usize, mutability: Mutability) -> (Ty<'_>, usize, Mutability) {
335         match ty.kind() {
336             ty::Ref(_, ty, Mutability::Mut) => f(ty, count + 1, mutability),
337             ty::Ref(_, ty, Mutability::Not) => f(ty, count + 1, Mutability::Not),
338             _ => (ty, count, mutability),
339         }
340     }
341     f(ty, 0, Mutability::Mut)
342 }
343
344 /// Returns `true` if the given type is an `unsafe` function.
345 pub fn type_is_unsafe_function<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
346     match ty.kind() {
347         ty::FnDef(..) | ty::FnPtr(_) => ty.fn_sig(cx.tcx).unsafety() == Unsafety::Unsafe,
348         _ => false,
349     }
350 }
351
352 /// Returns the base type for HIR references and pointers.
353 pub fn walk_ptrs_hir_ty<'tcx>(ty: &'tcx hir::Ty<'tcx>) -> &'tcx hir::Ty<'tcx> {
354     match ty.kind {
355         TyKind::Ptr(ref mut_ty) | TyKind::Rptr(_, ref mut_ty) => walk_ptrs_hir_ty(mut_ty.ty),
356         _ => ty,
357     }
358 }
359
360 /// Returns the base type for references and raw pointers, and count reference
361 /// depth.
362 pub fn walk_ptrs_ty_depth(ty: Ty<'_>) -> (Ty<'_>, usize) {
363     fn inner(ty: Ty<'_>, depth: usize) -> (Ty<'_>, usize) {
364         match ty.kind() {
365             ty::Ref(_, ty, _) => inner(ty, depth + 1),
366             _ => (ty, depth),
367         }
368     }
369     inner(ty, 0)
370 }
371
372 /// Returns `true` if types `a` and `b` are same types having same `Const` generic args,
373 /// otherwise returns `false`
374 pub fn same_type_and_consts<'tcx>(a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
375     match (&a.kind(), &b.kind()) {
376         (&ty::Adt(did_a, substs_a), &ty::Adt(did_b, substs_b)) => {
377             if did_a != did_b {
378                 return false;
379             }
380
381             substs_a
382                 .iter()
383                 .zip(substs_b.iter())
384                 .all(|(arg_a, arg_b)| match (arg_a.unpack(), arg_b.unpack()) {
385                     (GenericArgKind::Const(inner_a), GenericArgKind::Const(inner_b)) => inner_a == inner_b,
386                     (GenericArgKind::Type(type_a), GenericArgKind::Type(type_b)) => {
387                         same_type_and_consts(type_a, type_b)
388                     },
389                     _ => true,
390                 })
391         },
392         _ => a == b,
393     }
394 }
395
396 /// Checks if a given type looks safe to be uninitialized.
397 pub fn is_uninit_value_valid_for_ty(cx: &LateContext<'_>, ty: Ty<'_>) -> bool {
398     match ty.kind() {
399         ty::Array(component, _) => is_uninit_value_valid_for_ty(cx, component),
400         ty::Tuple(types) => types.types().all(|ty| is_uninit_value_valid_for_ty(cx, ty)),
401         ty::Adt(adt, _) => cx.tcx.lang_items().maybe_uninit() == Some(adt.did),
402         _ => false,
403     }
404 }
405
406 /// Gets an iterator over all predicates which apply to the given item.
407 pub fn all_predicates_of(tcx: TyCtxt<'_>, id: DefId) -> impl Iterator<Item = &(Predicate<'_>, Span)> {
408     let mut next_id = Some(id);
409     iter::from_fn(move || {
410         next_id.take().map(|id| {
411             let preds = tcx.predicates_of(id);
412             next_id = preds.parent;
413             preds.predicates.iter()
414         })
415     })
416     .flatten()
417 }
418
419 /// A signature for a function like type.
420 #[derive(Clone, Copy)]
421 pub enum ExprFnSig<'tcx> {
422     Sig(Binder<'tcx, FnSig<'tcx>>),
423     Closure(Binder<'tcx, FnSig<'tcx>>),
424     Trait(Binder<'tcx, Ty<'tcx>>, Option<Binder<'tcx, Ty<'tcx>>>),
425 }
426 impl<'tcx> ExprFnSig<'tcx> {
427     /// Gets the argument type at the given offset.
428     pub fn input(self, i: usize) -> Binder<'tcx, Ty<'tcx>> {
429         match self {
430             Self::Sig(sig) => sig.input(i),
431             Self::Closure(sig) => sig.input(0).map_bound(|ty| ty.tuple_element_ty(i).unwrap()),
432             Self::Trait(inputs, _) => inputs.map_bound(|ty| ty.tuple_element_ty(i).unwrap()),
433         }
434     }
435
436     /// Gets the result type, if one could be found. Note that the result type of a trait may not be
437     /// specified.
438     pub fn output(self) -> Option<Binder<'tcx, Ty<'tcx>>> {
439         match self {
440             Self::Sig(sig) | Self::Closure(sig) => Some(sig.output()),
441             Self::Trait(_, output) => output,
442         }
443     }
444 }
445
446 /// If the expression is function like, get the signature for it.
447 pub fn expr_sig<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'_>) -> Option<ExprFnSig<'tcx>> {
448     if let Res::Def(DefKind::Fn | DefKind::Ctor(_, CtorKind::Fn) | DefKind::AssocFn, id) = path_res(cx, expr) {
449         Some(ExprFnSig::Sig(cx.tcx.fn_sig(id)))
450     } else {
451         let ty = cx.typeck_results().expr_ty_adjusted(expr).peel_refs();
452         match *ty.kind() {
453             ty::Closure(_, subs) => Some(ExprFnSig::Closure(subs.as_closure().sig())),
454             ty::FnDef(id, subs) => Some(ExprFnSig::Sig(cx.tcx.fn_sig(id).subst(cx.tcx, subs))),
455             ty::FnPtr(sig) => Some(ExprFnSig::Sig(sig)),
456             ty::Dynamic(bounds, _) => {
457                 let lang_items = cx.tcx.lang_items();
458                 match bounds.principal() {
459                     Some(bound)
460                         if Some(bound.def_id()) == lang_items.fn_trait()
461                             || Some(bound.def_id()) == lang_items.fn_once_trait()
462                             || Some(bound.def_id()) == lang_items.fn_mut_trait() =>
463                     {
464                         let output = bounds
465                             .projection_bounds()
466                             .find(|p| lang_items.fn_once_output().map_or(false, |id| id == p.item_def_id()))
467                             .map(|p| p.map_bound(|p| p.term.ty().expect("return type was a const")));
468                         Some(ExprFnSig::Trait(bound.map_bound(|b| b.substs.type_at(0)), output))
469                     },
470                     _ => None,
471                 }
472             },
473             ty::Param(_) | ty::Projection(..) => {
474                 let mut inputs = None;
475                 let mut output = None;
476                 let lang_items = cx.tcx.lang_items();
477
478                 for (pred, _) in all_predicates_of(cx.tcx, cx.typeck_results().hir_owner.to_def_id()) {
479                     let mut is_input = false;
480                     if let Some(ty) = pred
481                         .kind()
482                         .map_bound(|pred| match pred {
483                             PredicateKind::Trait(p)
484                                 if (lang_items.fn_trait() == Some(p.def_id())
485                                     || lang_items.fn_mut_trait() == Some(p.def_id())
486                                     || lang_items.fn_once_trait() == Some(p.def_id()))
487                                     && p.self_ty() == ty =>
488                             {
489                                 is_input = true;
490                                 Some(p.trait_ref.substs.type_at(1))
491                             },
492                             PredicateKind::Projection(p)
493                                 if Some(p.projection_ty.item_def_id) == lang_items.fn_once_output()
494                                     && p.projection_ty.self_ty() == ty =>
495                             {
496                                 is_input = false;
497                                 p.term.ty()
498                             },
499                             _ => None,
500                         })
501                         .transpose()
502                     {
503                         if is_input && inputs.is_none() {
504                             inputs = Some(ty);
505                         } else if !is_input && output.is_none() {
506                             output = Some(ty);
507                         } else {
508                             // Multiple different fn trait impls. Is this even allowed?
509                             return None;
510                         }
511                     }
512                 }
513
514                 inputs.map(|ty| ExprFnSig::Trait(ty, output))
515             },
516             _ => None,
517         }
518     }
519 }
520
521 #[derive(Clone, Copy)]
522 pub enum EnumValue {
523     Unsigned(u128),
524     Signed(i128),
525 }
526 impl core::ops::Add<u32> for EnumValue {
527     type Output = Self;
528     fn add(self, n: u32) -> Self::Output {
529         match self {
530             Self::Unsigned(x) => Self::Unsigned(x + u128::from(n)),
531             Self::Signed(x) => Self::Signed(x + i128::from(n)),
532         }
533     }
534 }
535
536 /// Attempts to read the given constant as though it were an an enum value.
537 #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
538 pub fn read_explicit_enum_value(tcx: TyCtxt<'_>, id: DefId) -> Option<EnumValue> {
539     if let Ok(ConstValue::Scalar(Scalar::Int(value))) = tcx.const_eval_poly(id) {
540         match tcx.type_of(id).kind() {
541             ty::Int(_) => Some(EnumValue::Signed(match value.size().bytes() {
542                 1 => i128::from(value.assert_bits(Size::from_bytes(1)) as u8 as i8),
543                 2 => i128::from(value.assert_bits(Size::from_bytes(2)) as u16 as i16),
544                 4 => i128::from(value.assert_bits(Size::from_bytes(4)) as u32 as i32),
545                 8 => i128::from(value.assert_bits(Size::from_bytes(8)) as u64 as i64),
546                 16 => value.assert_bits(Size::from_bytes(16)) as i128,
547                 _ => return None,
548             })),
549             ty::Uint(_) => Some(EnumValue::Unsigned(match value.size().bytes() {
550                 1 => value.assert_bits(Size::from_bytes(1)),
551                 2 => value.assert_bits(Size::from_bytes(2)),
552                 4 => value.assert_bits(Size::from_bytes(4)),
553                 8 => value.assert_bits(Size::from_bytes(8)),
554                 16 => value.assert_bits(Size::from_bytes(16)),
555                 _ => return None,
556             })),
557             _ => None,
558         }
559     } else {
560         None
561     }
562 }
563
564 /// Gets the value of the given variant.
565 pub fn get_discriminant_value(tcx: TyCtxt<'_>, adt: &'_ AdtDef, i: VariantIdx) -> EnumValue {
566     let variant = &adt.variants[i];
567     match variant.discr {
568         VariantDiscr::Explicit(id) => read_explicit_enum_value(tcx, id).unwrap(),
569         VariantDiscr::Relative(x) => match adt.variants[(i.as_usize() - x as usize).into()].discr {
570             VariantDiscr::Explicit(id) => read_explicit_enum_value(tcx, id).unwrap() + x,
571             VariantDiscr::Relative(_) => EnumValue::Unsigned(x.into()),
572         },
573     }
574 }