1 use rustc_data_structures::fx::FxIndexSet;
3 use rustc_hir::def_id::{CrateNum, DefId, LocalDefId, LOCAL_CRATE};
4 use rustc_middle::hir::map as hir_map;
5 use rustc_middle::ty::subst::Subst;
6 use rustc_middle::ty::{
7 self, Binder, Predicate, PredicateKind, ToPredicate, Ty, TyCtxt, WithConstness,
9 use rustc_session::CrateDisambiguator;
11 use rustc_trait_selection::traits;
13 fn sized_constraint_for_ty<'tcx>(
20 let result = match ty.kind() {
21 Bool | Char | Int(..) | Uint(..) | Float(..) | RawPtr(..) | Ref(..) | FnDef(..)
22 | FnPtr(_) | Array(..) | Closure(..) | Generator(..) | Never => vec![],
24 Str | Dynamic(..) | Slice(_) | Foreign(..) | Error(_) | GeneratorWitness(..) => {
25 // these are never sized - return the target type
29 Tuple(ref tys) => match tys.last() {
31 Some(ty) => sized_constraint_for_ty(tcx, adtdef, ty.expect_ty()),
36 let adt_tys = adt.sized_constraint(tcx);
37 debug!("sized_constraint_for_ty({:?}) intermediate = {:?}", ty, adt_tys);
40 .map(|ty| ty.subst(tcx, substs))
41 .flat_map(|ty| sized_constraint_for_ty(tcx, adtdef, ty))
45 Projection(..) | Opaque(..) => {
46 // must calculate explicitly.
47 // FIXME: consider special-casing always-Sized projections
52 // perf hack: if there is a `T: Sized` bound, then
53 // we know that `T` is Sized and do not need to check
56 let sized_trait = match tcx.lang_items().sized_trait() {
60 let sized_predicate = ty::Binder::dummy(ty::TraitRef {
62 substs: tcx.mk_substs_trait(ty, &[]),
66 let predicates = tcx.predicates_of(adtdef.did).predicates;
67 if predicates.iter().any(|(p, _)| *p == sized_predicate) { vec![] } else { vec![ty] }
70 Placeholder(..) | Bound(..) | Infer(..) => {
71 bug!("unexpected type `{:?}` in sized_constraint_for_ty", ty)
74 debug!("sized_constraint_for_ty({:?}) = {:?}", ty, result);
78 fn associated_item_from_trait_item_ref(
80 parent_def_id: LocalDefId,
81 trait_item_ref: &hir::TraitItemRef,
83 let def_id = trait_item_ref.id.def_id;
84 let (kind, has_self) = match trait_item_ref.kind {
85 hir::AssocItemKind::Const => (ty::AssocKind::Const, false),
86 hir::AssocItemKind::Fn { has_self } => (ty::AssocKind::Fn, has_self),
87 hir::AssocItemKind::Type => (ty::AssocKind::Type, false),
91 ident: trait_item_ref.ident,
93 vis: tcx.visibility(def_id),
94 defaultness: trait_item_ref.defaultness,
95 def_id: def_id.to_def_id(),
96 container: ty::TraitContainer(parent_def_id.to_def_id()),
97 fn_has_self_parameter: has_self,
101 fn associated_item_from_impl_item_ref(
103 parent_def_id: LocalDefId,
104 impl_item_ref: &hir::ImplItemRef<'_>,
106 let def_id = impl_item_ref.id.def_id;
107 let (kind, has_self) = match impl_item_ref.kind {
108 hir::AssocItemKind::Const => (ty::AssocKind::Const, false),
109 hir::AssocItemKind::Fn { has_self } => (ty::AssocKind::Fn, has_self),
110 hir::AssocItemKind::Type => (ty::AssocKind::Type, false),
114 ident: impl_item_ref.ident,
116 vis: tcx.visibility(def_id),
117 defaultness: impl_item_ref.defaultness,
118 def_id: def_id.to_def_id(),
119 container: ty::ImplContainer(parent_def_id.to_def_id()),
120 fn_has_self_parameter: has_self,
124 fn associated_item(tcx: TyCtxt<'_>, def_id: DefId) -> ty::AssocItem {
125 let id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
126 let parent_id = tcx.hir().get_parent_item(id);
127 let parent_def_id = tcx.hir().local_def_id(parent_id);
128 let parent_item = tcx.hir().expect_item(parent_id);
129 match parent_item.kind {
130 hir::ItemKind::Impl(ref impl_) => {
131 if let Some(impl_item_ref) =
132 impl_.items.iter().find(|i| i.id.def_id.to_def_id() == def_id)
135 associated_item_from_impl_item_ref(tcx, parent_def_id, impl_item_ref);
136 debug_assert_eq!(assoc_item.def_id, def_id);
141 hir::ItemKind::Trait(.., ref trait_item_refs) => {
142 if let Some(trait_item_ref) =
143 trait_item_refs.iter().find(|i| i.id.def_id.to_def_id() == def_id)
146 associated_item_from_trait_item_ref(tcx, parent_def_id, trait_item_ref);
147 debug_assert_eq!(assoc_item.def_id, def_id);
157 "unexpected parent of trait or impl item or item not found: {:?}",
162 fn impl_defaultness(tcx: TyCtxt<'_>, def_id: DefId) -> hir::Defaultness {
163 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
164 let item = tcx.hir().expect_item(hir_id);
165 if let hir::ItemKind::Impl(impl_) = &item.kind {
168 bug!("`impl_defaultness` called on {:?}", item);
172 /// Calculates the `Sized` constraint.
174 /// In fact, there are only a few options for the types in the constraint:
175 /// - an obviously-unsized type
176 /// - a type parameter or projection whose Sizedness can't be known
177 /// - a tuple of type parameters or projections, if there are multiple
179 /// - a Error, if a type contained itself. The representability
180 /// check should catch this case.
181 fn adt_sized_constraint(tcx: TyCtxt<'_>, def_id: DefId) -> ty::AdtSizedConstraint<'_> {
182 let def = tcx.adt_def(def_id);
184 let result = tcx.mk_type_list(
187 .flat_map(|v| v.fields.last())
188 .flat_map(|f| sized_constraint_for_ty(tcx, def, tcx.type_of(f.did))),
191 debug!("adt_sized_constraint: {:?} => {:?}", def, result);
193 ty::AdtSizedConstraint(result)
196 fn associated_item_def_ids(tcx: TyCtxt<'_>, def_id: DefId) -> &[DefId] {
197 let id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
198 let item = tcx.hir().expect_item(id);
200 hir::ItemKind::Trait(.., ref trait_item_refs) => tcx.arena.alloc_from_iter(
201 trait_item_refs.iter().map(|trait_item_ref| trait_item_ref.id.def_id.to_def_id()),
203 hir::ItemKind::Impl(ref impl_) => tcx.arena.alloc_from_iter(
204 impl_.items.iter().map(|impl_item_ref| impl_item_ref.id.def_id.to_def_id()),
206 hir::ItemKind::TraitAlias(..) => &[],
207 _ => span_bug!(item.span, "associated_item_def_ids: not impl or trait"),
211 fn associated_items(tcx: TyCtxt<'_>, def_id: DefId) -> ty::AssocItems<'_> {
212 let items = tcx.associated_item_def_ids(def_id).iter().map(|did| tcx.associated_item(*did));
213 ty::AssocItems::new(items)
216 fn def_ident_span(tcx: TyCtxt<'_>, def_id: DefId) -> Option<Span> {
217 tcx.hir().get_if_local(def_id).and_then(|node| node.ident()).map(|ident| ident.span)
220 /// If the given `DefId` describes an item belonging to a trait,
221 /// returns the `DefId` of the trait that the trait item belongs to;
222 /// otherwise, returns `None`.
223 fn trait_of_item(tcx: TyCtxt<'_>, def_id: DefId) -> Option<DefId> {
224 tcx.opt_associated_item(def_id).and_then(|associated_item| match associated_item.container {
225 ty::TraitContainer(def_id) => Some(def_id),
226 ty::ImplContainer(_) => None,
230 /// See `ParamEnv` struct definition for details.
231 fn param_env(tcx: TyCtxt<'_>, def_id: DefId) -> ty::ParamEnv<'_> {
232 // The param_env of an impl Trait type is its defining function's param_env
233 if let Some(parent) = ty::is_impl_trait_defn(tcx, def_id) {
234 return param_env(tcx, parent);
236 // Compute the bounds on Self and the type parameters.
238 let ty::InstantiatedPredicates { mut predicates, .. } =
239 tcx.predicates_of(def_id).instantiate_identity(tcx);
241 // Finally, we have to normalize the bounds in the environment, in
242 // case they contain any associated type projections. This process
243 // can yield errors if the put in illegal associated types, like
244 // `<i32 as Foo>::Bar` where `i32` does not implement `Foo`. We
245 // report these errors right here; this doesn't actually feel
246 // right to me, because constructing the environment feels like a
247 // kind of a "idempotent" action, but I'm not sure where would be
248 // a better place. In practice, we construct environments for
249 // every fn once during type checking, and we'll abort if there
250 // are any errors at that point, so after type checking you can be
251 // sure that this will succeed without errors anyway.
253 if tcx.sess.opts.debugging_opts.chalk {
254 let environment = well_formed_types_in_env(tcx, def_id);
255 predicates.extend(environment);
258 let unnormalized_env =
259 ty::ParamEnv::new(tcx.intern_predicates(&predicates), traits::Reveal::UserFacing);
263 .map(|def_id| tcx.hir().local_def_id_to_hir_id(def_id))
264 .map_or(hir::CRATE_HIR_ID, |id| {
265 tcx.hir().maybe_body_owned_by(id).map_or(id, |body| body.hir_id)
267 let cause = traits::ObligationCause::misc(tcx.def_span(def_id), body_id);
268 traits::normalize_param_env_or_error(tcx, def_id, unnormalized_env, cause)
271 /// Elaborate the environment.
273 /// Collect a list of `Predicate`'s used for building the `ParamEnv`. Adds `TypeWellFormedFromEnv`'s
274 /// that are assumed to be well-formed (because they come from the environment).
276 /// Used only in chalk mode.
277 fn well_formed_types_in_env<'tcx>(
280 ) -> &'tcx ty::List<Predicate<'tcx>> {
281 use rustc_hir::{ForeignItemKind, ImplItemKind, ItemKind, Node, TraitItemKind};
282 use rustc_middle::ty::subst::GenericArgKind;
284 debug!("environment(def_id = {:?})", def_id);
286 // The environment of an impl Trait type is its defining function's environment.
287 if let Some(parent) = ty::is_impl_trait_defn(tcx, def_id) {
288 return well_formed_types_in_env(tcx, parent);
291 // Compute the bounds on `Self` and the type parameters.
292 let ty::InstantiatedPredicates { predicates, .. } =
293 tcx.predicates_of(def_id).instantiate_identity(tcx);
295 let clauses = predicates.into_iter();
297 if !def_id.is_local() {
298 return ty::List::empty();
300 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
301 let node = tcx.hir().get(hir_id);
310 let node_kind = match node {
311 Node::TraitItem(item) => match item.kind {
312 TraitItemKind::Fn(..) => NodeKind::Fn,
313 _ => NodeKind::Other,
316 Node::ImplItem(item) => match item.kind {
317 ImplItemKind::Fn(..) => NodeKind::Fn,
318 _ => NodeKind::Other,
321 Node::Item(item) => match item.kind {
322 ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }) => NodeKind::TraitImpl,
323 ItemKind::Impl(hir::Impl { of_trait: None, .. }) => NodeKind::InherentImpl,
324 ItemKind::Fn(..) => NodeKind::Fn,
325 _ => NodeKind::Other,
328 Node::ForeignItem(item) => match item.kind {
329 ForeignItemKind::Fn(..) => NodeKind::Fn,
330 _ => NodeKind::Other,
334 _ => NodeKind::Other,
337 // FIXME(eddyb) isn't the unordered nature of this a hazard?
338 let mut inputs = FxIndexSet::default();
341 // In a trait impl, we assume that the header trait ref and all its
342 // constituents are well-formed.
343 NodeKind::TraitImpl => {
344 let trait_ref = tcx.impl_trait_ref(def_id).expect("not an impl");
346 // FIXME(chalk): this has problems because of late-bound regions
347 //inputs.extend(trait_ref.substs.iter().flat_map(|arg| arg.walk()));
348 inputs.extend(trait_ref.substs.iter());
351 // In an inherent impl, we assume that the receiver type and all its
352 // constituents are well-formed.
353 NodeKind::InherentImpl => {
354 let self_ty = tcx.type_of(def_id);
355 inputs.extend(self_ty.walk());
358 // In an fn, we assume that the arguments and all their constituents are
361 let fn_sig = tcx.fn_sig(def_id);
362 let fn_sig = tcx.liberate_late_bound_regions(def_id, fn_sig);
364 inputs.extend(fn_sig.inputs().iter().flat_map(|ty| ty.walk()));
367 NodeKind::Other => (),
369 let input_clauses = inputs.into_iter().filter_map(|arg| {
371 GenericArgKind::Type(ty) => {
372 let binder = Binder::dummy(PredicateKind::TypeWellFormedFromEnv(ty));
373 Some(tcx.mk_predicate(binder))
376 // FIXME(eddyb) no WF conditions from lifetimes?
377 GenericArgKind::Lifetime(_) => None,
379 // FIXME(eddyb) support const generics in Chalk
380 GenericArgKind::Const(_) => None,
384 tcx.mk_predicates(clauses.chain(input_clauses))
387 fn param_env_reveal_all_normalized(tcx: TyCtxt<'_>, def_id: DefId) -> ty::ParamEnv<'_> {
388 tcx.param_env(def_id).with_reveal_all_normalized(tcx)
391 fn crate_disambiguator(tcx: TyCtxt<'_>, crate_num: CrateNum) -> CrateDisambiguator {
392 assert_eq!(crate_num, LOCAL_CRATE);
393 tcx.sess.local_crate_disambiguator()
396 fn instance_def_size_estimate<'tcx>(
398 instance_def: ty::InstanceDef<'tcx>,
403 InstanceDef::Item(..) | InstanceDef::DropGlue(..) => {
404 let mir = tcx.instance_mir(instance_def);
405 mir.basic_blocks().iter().map(|bb| bb.statements.len() + 1).sum()
407 // Estimate the size of other compiler-generated shims to be 1.
412 /// If `def_id` is an issue 33140 hack impl, returns its self type; otherwise, returns `None`.
414 /// See [`ty::ImplOverlapKind::Issue33140`] for more details.
415 fn issue33140_self_ty(tcx: TyCtxt<'_>, def_id: DefId) -> Option<Ty<'_>> {
416 debug!("issue33140_self_ty({:?})", def_id);
419 .impl_trait_ref(def_id)
420 .unwrap_or_else(|| bug!("issue33140_self_ty called on inherent impl {:?}", def_id));
422 debug!("issue33140_self_ty({:?}), trait-ref={:?}", def_id, trait_ref);
424 let is_marker_like = tcx.impl_polarity(def_id) == ty::ImplPolarity::Positive
425 && tcx.associated_item_def_ids(trait_ref.def_id).is_empty();
427 // Check whether these impls would be ok for a marker trait.
429 debug!("issue33140_self_ty - not marker-like!");
433 // impl must be `impl Trait for dyn Marker1 + Marker2 + ...`
434 if trait_ref.substs.len() != 1 {
435 debug!("issue33140_self_ty - impl has substs!");
439 let predicates = tcx.predicates_of(def_id);
440 if predicates.parent.is_some() || !predicates.predicates.is_empty() {
441 debug!("issue33140_self_ty - impl has predicates {:?}!", predicates);
445 let self_ty = trait_ref.self_ty();
446 let self_ty_matches = match self_ty.kind() {
447 ty::Dynamic(ref data, ty::ReStatic) => data.principal().is_none(),
452 debug!("issue33140_self_ty - MATCHES!");
455 debug!("issue33140_self_ty - non-matching self type");
460 /// Check if a function is async.
461 fn asyncness(tcx: TyCtxt<'_>, def_id: DefId) -> hir::IsAsync {
462 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
464 let node = tcx.hir().get(hir_id);
466 let fn_like = hir_map::blocks::FnLikeNode::from_node(node).unwrap_or_else(|| {
467 bug!("asyncness: expected fn-like node but got `{:?}`", def_id);
473 /// Don't call this directly: use ``tcx.conservative_is_privately_uninhabited`` instead.
474 #[instrument(level = "debug", skip(tcx))]
475 pub fn conservative_is_privately_uninhabited_raw<'tcx>(
477 param_env_and: ty::ParamEnvAnd<'tcx, Ty<'tcx>>,
479 let (param_env, ty) = param_env_and.into_parts();
482 debug!("ty::Never =>");
485 ty::Adt(def, _) if def.is_union() => {
486 debug!("ty::Adt(def, _) if def.is_union() =>");
487 // For now, `union`s are never considered uninhabited.
490 ty::Adt(def, substs) => {
491 debug!("ty::Adt(def, _) if def.is_not_union() =>");
492 // Any ADT is uninhabited if either:
493 // (a) It has no variants (i.e. an empty `enum`);
494 // (b) Each of its variants (a single one in the case of a `struct`) has at least
495 // one uninhabited field.
496 def.variants.iter().all(|var| {
497 var.fields.iter().any(|field| {
498 let ty = tcx.type_of(field.did).subst(tcx, substs);
499 tcx.conservative_is_privately_uninhabited(param_env.and(ty))
504 debug!("ty::Tuple(..) =>");
505 ty.tuple_fields().any(|ty| tcx.conservative_is_privately_uninhabited(param_env.and(ty)))
507 ty::Array(ty, len) => {
508 debug!("ty::Array(ty, len) =>");
509 match len.try_eval_usize(tcx, param_env) {
510 Some(0) | None => false,
511 // If the array is definitely non-empty, it's uninhabited if
512 // the type of its elements is uninhabited.
513 Some(1..) => tcx.conservative_is_privately_uninhabited(param_env.and(ty)),
517 debug!("ty::Ref(..) =>");
518 // References to uninitialised memory is valid for any type, including
519 // uninhabited types, in unsafe code, so we treat all references as
530 pub fn provide(providers: &mut ty::query::Providers) {
531 *providers = ty::query::Providers {
534 associated_item_def_ids,
536 adt_sized_constraint,
539 param_env_reveal_all_normalized,
542 instance_def_size_estimate,
545 conservative_is_privately_uninhabited: conservative_is_privately_uninhabited_raw,