1 use rustc_data_structures::fx::FxIndexSet;
3 use rustc_hir::def_id::{DefId, LocalDefId};
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,
10 use rustc_trait_selection::traits;
12 fn sized_constraint_for_ty<'tcx>(
19 let result = match ty.kind() {
20 Bool | Char | Int(..) | Uint(..) | Float(..) | RawPtr(..) | Ref(..) | FnDef(..)
21 | FnPtr(_) | Array(..) | Closure(..) | Generator(..) | Never => vec![],
23 Str | Dynamic(..) | Slice(_) | Foreign(..) | Error(_) | GeneratorWitness(..) => {
24 // these are never sized - return the target type
28 Tuple(ref tys) => match tys.last() {
30 Some(ty) => sized_constraint_for_ty(tcx, adtdef, ty.expect_ty()),
35 let adt_tys = adt.sized_constraint(tcx);
36 debug!("sized_constraint_for_ty({:?}) intermediate = {:?}", ty, adt_tys);
39 .map(|ty| ty.subst(tcx, substs))
40 .flat_map(|ty| sized_constraint_for_ty(tcx, adtdef, ty))
44 Projection(..) | Opaque(..) => {
45 // must calculate explicitly.
46 // FIXME: consider special-casing always-Sized projections
51 // perf hack: if there is a `T: Sized` bound, then
52 // we know that `T` is Sized and do not need to check
55 let sized_trait = match tcx.lang_items().sized_trait() {
59 let sized_predicate = ty::Binder::dummy(ty::TraitRef {
61 substs: tcx.mk_substs_trait(ty, &[]),
65 let predicates = tcx.predicates_of(adtdef.did).predicates;
66 if predicates.iter().any(|(p, _)| *p == sized_predicate) { vec![] } else { vec![ty] }
69 Placeholder(..) | Bound(..) | Infer(..) => {
70 bug!("unexpected type `{:?}` in sized_constraint_for_ty", ty)
73 debug!("sized_constraint_for_ty({:?}) = {:?}", ty, result);
77 fn associated_item_from_trait_item_ref(
79 parent_def_id: LocalDefId,
80 trait_item_ref: &hir::TraitItemRef,
82 let def_id = trait_item_ref.id.def_id;
83 let (kind, has_self) = match trait_item_ref.kind {
84 hir::AssocItemKind::Const => (ty::AssocKind::Const, false),
85 hir::AssocItemKind::Fn { has_self } => (ty::AssocKind::Fn, has_self),
86 hir::AssocItemKind::Type => (ty::AssocKind::Type, false),
90 ident: trait_item_ref.ident,
92 vis: tcx.visibility(def_id),
93 defaultness: trait_item_ref.defaultness,
94 def_id: def_id.to_def_id(),
95 container: ty::TraitContainer(parent_def_id.to_def_id()),
96 fn_has_self_parameter: has_self,
100 fn associated_item_from_impl_item_ref(
102 parent_def_id: LocalDefId,
103 impl_item_ref: &hir::ImplItemRef<'_>,
105 let def_id = impl_item_ref.id.def_id;
106 let (kind, has_self) = match impl_item_ref.kind {
107 hir::AssocItemKind::Const => (ty::AssocKind::Const, false),
108 hir::AssocItemKind::Fn { has_self } => (ty::AssocKind::Fn, has_self),
109 hir::AssocItemKind::Type => (ty::AssocKind::Type, false),
113 ident: impl_item_ref.ident,
115 vis: tcx.visibility(def_id),
116 defaultness: impl_item_ref.defaultness,
117 def_id: def_id.to_def_id(),
118 container: ty::ImplContainer(parent_def_id.to_def_id()),
119 fn_has_self_parameter: has_self,
123 fn associated_item(tcx: TyCtxt<'_>, def_id: DefId) -> ty::AssocItem {
124 let id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
125 let parent_id = tcx.hir().get_parent_item(id);
126 let parent_def_id = tcx.hir().local_def_id(parent_id);
127 let parent_item = tcx.hir().expect_item(parent_id);
128 match parent_item.kind {
129 hir::ItemKind::Impl(ref impl_) => {
130 if let Some(impl_item_ref) =
131 impl_.items.iter().find(|i| i.id.def_id.to_def_id() == def_id)
134 associated_item_from_impl_item_ref(tcx, parent_def_id, impl_item_ref);
135 debug_assert_eq!(assoc_item.def_id, def_id);
140 hir::ItemKind::Trait(.., ref trait_item_refs) => {
141 if let Some(trait_item_ref) =
142 trait_item_refs.iter().find(|i| i.id.def_id.to_def_id() == def_id)
145 associated_item_from_trait_item_ref(tcx, parent_def_id, trait_item_ref);
146 debug_assert_eq!(assoc_item.def_id, def_id);
156 "unexpected parent of trait or impl item or item not found: {:?}",
161 fn impl_defaultness(tcx: TyCtxt<'_>, def_id: DefId) -> hir::Defaultness {
162 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
163 let item = tcx.hir().expect_item(hir_id);
164 if let hir::ItemKind::Impl(impl_) = &item.kind {
167 bug!("`impl_defaultness` called on {:?}", item);
171 fn impl_constness(tcx: TyCtxt<'_>, def_id: DefId) -> hir::Constness {
172 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
173 let item = tcx.hir().expect_item(hir_id);
174 if let hir::ItemKind::Impl(impl_) = &item.kind {
177 bug!("`impl_constness` called on {:?}", item);
181 /// Calculates the `Sized` constraint.
183 /// In fact, there are only a few options for the types in the constraint:
184 /// - an obviously-unsized type
185 /// - a type parameter or projection whose Sizedness can't be known
186 /// - a tuple of type parameters or projections, if there are multiple
188 /// - a Error, if a type contained itself. The representability
189 /// check should catch this case.
190 fn adt_sized_constraint(tcx: TyCtxt<'_>, def_id: DefId) -> ty::AdtSizedConstraint<'_> {
191 let def = tcx.adt_def(def_id);
193 let result = tcx.mk_type_list(
196 .flat_map(|v| v.fields.last())
197 .flat_map(|f| sized_constraint_for_ty(tcx, def, tcx.type_of(f.did))),
200 debug!("adt_sized_constraint: {:?} => {:?}", def, result);
202 ty::AdtSizedConstraint(result)
205 fn associated_item_def_ids(tcx: TyCtxt<'_>, def_id: DefId) -> &[DefId] {
206 let id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
207 let item = tcx.hir().expect_item(id);
209 hir::ItemKind::Trait(.., ref trait_item_refs) => tcx.arena.alloc_from_iter(
210 trait_item_refs.iter().map(|trait_item_ref| trait_item_ref.id.def_id.to_def_id()),
212 hir::ItemKind::Impl(ref impl_) => tcx.arena.alloc_from_iter(
213 impl_.items.iter().map(|impl_item_ref| impl_item_ref.id.def_id.to_def_id()),
215 hir::ItemKind::TraitAlias(..) => &[],
216 _ => span_bug!(item.span, "associated_item_def_ids: not impl or trait"),
220 fn associated_items(tcx: TyCtxt<'_>, def_id: DefId) -> ty::AssocItems<'_> {
221 let items = tcx.associated_item_def_ids(def_id).iter().map(|did| tcx.associated_item(*did));
222 ty::AssocItems::new(items)
225 fn def_ident_span(tcx: TyCtxt<'_>, def_id: DefId) -> Option<Span> {
226 tcx.hir().get_if_local(def_id).and_then(|node| node.ident()).map(|ident| ident.span)
229 /// If the given `DefId` describes an item belonging to a trait,
230 /// returns the `DefId` of the trait that the trait item belongs to;
231 /// otherwise, returns `None`.
232 fn trait_of_item(tcx: TyCtxt<'_>, def_id: DefId) -> Option<DefId> {
233 tcx.opt_associated_item(def_id).and_then(|associated_item| match associated_item.container {
234 ty::TraitContainer(def_id) => Some(def_id),
235 ty::ImplContainer(_) => None,
239 /// See `ParamEnv` struct definition for details.
240 fn param_env(tcx: TyCtxt<'_>, def_id: DefId) -> ty::ParamEnv<'_> {
241 // The param_env of an impl Trait type is its defining function's param_env
242 if let Some(parent) = ty::is_impl_trait_defn(tcx, def_id) {
243 return param_env(tcx, parent);
245 // Compute the bounds on Self and the type parameters.
247 let ty::InstantiatedPredicates { mut predicates, .. } =
248 tcx.predicates_of(def_id).instantiate_identity(tcx);
250 // Finally, we have to normalize the bounds in the environment, in
251 // case they contain any associated type projections. This process
252 // can yield errors if the put in illegal associated types, like
253 // `<i32 as Foo>::Bar` where `i32` does not implement `Foo`. We
254 // report these errors right here; this doesn't actually feel
255 // right to me, because constructing the environment feels like a
256 // kind of a "idempotent" action, but I'm not sure where would be
257 // a better place. In practice, we construct environments for
258 // every fn once during type checking, and we'll abort if there
259 // are any errors at that point, so after type checking you can be
260 // sure that this will succeed without errors anyway.
262 if tcx.sess.opts.debugging_opts.chalk {
263 let environment = well_formed_types_in_env(tcx, def_id);
264 predicates.extend(environment);
267 let unnormalized_env =
268 ty::ParamEnv::new(tcx.intern_predicates(&predicates), traits::Reveal::UserFacing);
272 .map(|def_id| tcx.hir().local_def_id_to_hir_id(def_id))
273 .map_or(hir::CRATE_HIR_ID, |id| {
274 tcx.hir().maybe_body_owned_by(id).map_or(id, |body| body.hir_id)
276 let cause = traits::ObligationCause::misc(tcx.def_span(def_id), body_id);
277 traits::normalize_param_env_or_error(tcx, def_id, unnormalized_env, cause)
280 /// Elaborate the environment.
282 /// Collect a list of `Predicate`'s used for building the `ParamEnv`. Adds `TypeWellFormedFromEnv`'s
283 /// that are assumed to be well-formed (because they come from the environment).
285 /// Used only in chalk mode.
286 fn well_formed_types_in_env<'tcx>(
289 ) -> &'tcx ty::List<Predicate<'tcx>> {
290 use rustc_hir::{ForeignItemKind, ImplItemKind, ItemKind, Node, TraitItemKind};
291 use rustc_middle::ty::subst::GenericArgKind;
293 debug!("environment(def_id = {:?})", def_id);
295 // The environment of an impl Trait type is its defining function's environment.
296 if let Some(parent) = ty::is_impl_trait_defn(tcx, def_id) {
297 return well_formed_types_in_env(tcx, parent);
300 // Compute the bounds on `Self` and the type parameters.
301 let ty::InstantiatedPredicates { predicates, .. } =
302 tcx.predicates_of(def_id).instantiate_identity(tcx);
304 let clauses = predicates.into_iter();
306 if !def_id.is_local() {
307 return ty::List::empty();
309 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
310 let node = tcx.hir().get(hir_id);
319 let node_kind = match node {
320 Node::TraitItem(item) => match item.kind {
321 TraitItemKind::Fn(..) => NodeKind::Fn,
322 _ => NodeKind::Other,
325 Node::ImplItem(item) => match item.kind {
326 ImplItemKind::Fn(..) => NodeKind::Fn,
327 _ => NodeKind::Other,
330 Node::Item(item) => match item.kind {
331 ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }) => NodeKind::TraitImpl,
332 ItemKind::Impl(hir::Impl { of_trait: None, .. }) => NodeKind::InherentImpl,
333 ItemKind::Fn(..) => NodeKind::Fn,
334 _ => NodeKind::Other,
337 Node::ForeignItem(item) => match item.kind {
338 ForeignItemKind::Fn(..) => NodeKind::Fn,
339 _ => NodeKind::Other,
343 _ => NodeKind::Other,
346 // FIXME(eddyb) isn't the unordered nature of this a hazard?
347 let mut inputs = FxIndexSet::default();
350 // In a trait impl, we assume that the header trait ref and all its
351 // constituents are well-formed.
352 NodeKind::TraitImpl => {
353 let trait_ref = tcx.impl_trait_ref(def_id).expect("not an impl");
355 // FIXME(chalk): this has problems because of late-bound regions
356 //inputs.extend(trait_ref.substs.iter().flat_map(|arg| arg.walk()));
357 inputs.extend(trait_ref.substs.iter());
360 // In an inherent impl, we assume that the receiver type and all its
361 // constituents are well-formed.
362 NodeKind::InherentImpl => {
363 let self_ty = tcx.type_of(def_id);
364 inputs.extend(self_ty.walk());
367 // In an fn, we assume that the arguments and all their constituents are
370 let fn_sig = tcx.fn_sig(def_id);
371 let fn_sig = tcx.liberate_late_bound_regions(def_id, fn_sig);
373 inputs.extend(fn_sig.inputs().iter().flat_map(|ty| ty.walk()));
376 NodeKind::Other => (),
378 let input_clauses = inputs.into_iter().filter_map(|arg| {
380 GenericArgKind::Type(ty) => {
381 let binder = Binder::dummy(PredicateKind::TypeWellFormedFromEnv(ty));
382 Some(tcx.mk_predicate(binder))
385 // FIXME(eddyb) no WF conditions from lifetimes?
386 GenericArgKind::Lifetime(_) => None,
388 // FIXME(eddyb) support const generics in Chalk
389 GenericArgKind::Const(_) => None,
393 tcx.mk_predicates(clauses.chain(input_clauses))
396 fn param_env_reveal_all_normalized(tcx: TyCtxt<'_>, def_id: DefId) -> ty::ParamEnv<'_> {
397 tcx.param_env(def_id).with_reveal_all_normalized(tcx)
400 fn instance_def_size_estimate<'tcx>(
402 instance_def: ty::InstanceDef<'tcx>,
407 InstanceDef::Item(..) | InstanceDef::DropGlue(..) => {
408 let mir = tcx.instance_mir(instance_def);
409 mir.basic_blocks().iter().map(|bb| bb.statements.len() + 1).sum()
411 // Estimate the size of other compiler-generated shims to be 1.
416 /// If `def_id` is an issue 33140 hack impl, returns its self type; otherwise, returns `None`.
418 /// See [`ty::ImplOverlapKind::Issue33140`] for more details.
419 fn issue33140_self_ty(tcx: TyCtxt<'_>, def_id: DefId) -> Option<Ty<'_>> {
420 debug!("issue33140_self_ty({:?})", def_id);
423 .impl_trait_ref(def_id)
424 .unwrap_or_else(|| bug!("issue33140_self_ty called on inherent impl {:?}", def_id));
426 debug!("issue33140_self_ty({:?}), trait-ref={:?}", def_id, trait_ref);
428 let is_marker_like = tcx.impl_polarity(def_id) == ty::ImplPolarity::Positive
429 && tcx.associated_item_def_ids(trait_ref.def_id).is_empty();
431 // Check whether these impls would be ok for a marker trait.
433 debug!("issue33140_self_ty - not marker-like!");
437 // impl must be `impl Trait for dyn Marker1 + Marker2 + ...`
438 if trait_ref.substs.len() != 1 {
439 debug!("issue33140_self_ty - impl has substs!");
443 let predicates = tcx.predicates_of(def_id);
444 if predicates.parent.is_some() || !predicates.predicates.is_empty() {
445 debug!("issue33140_self_ty - impl has predicates {:?}!", predicates);
449 let self_ty = trait_ref.self_ty();
450 let self_ty_matches = match self_ty.kind() {
451 ty::Dynamic(ref data, ty::ReStatic) => data.principal().is_none(),
456 debug!("issue33140_self_ty - MATCHES!");
459 debug!("issue33140_self_ty - non-matching self type");
464 /// Check if a function is async.
465 fn asyncness(tcx: TyCtxt<'_>, def_id: DefId) -> hir::IsAsync {
466 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
468 let node = tcx.hir().get(hir_id);
470 let fn_like = hir_map::blocks::FnLikeNode::from_node(node).unwrap_or_else(|| {
471 bug!("asyncness: expected fn-like node but got `{:?}`", def_id);
477 /// Don't call this directly: use ``tcx.conservative_is_privately_uninhabited`` instead.
478 #[instrument(level = "debug", skip(tcx))]
479 pub fn conservative_is_privately_uninhabited_raw<'tcx>(
481 param_env_and: ty::ParamEnvAnd<'tcx, Ty<'tcx>>,
483 let (param_env, ty) = param_env_and.into_parts();
486 debug!("ty::Never =>");
489 ty::Adt(def, _) if def.is_union() => {
490 debug!("ty::Adt(def, _) if def.is_union() =>");
491 // For now, `union`s are never considered uninhabited.
494 ty::Adt(def, substs) => {
495 debug!("ty::Adt(def, _) if def.is_not_union() =>");
496 // Any ADT is uninhabited if either:
497 // (a) It has no variants (i.e. an empty `enum`);
498 // (b) Each of its variants (a single one in the case of a `struct`) has at least
499 // one uninhabited field.
500 def.variants.iter().all(|var| {
501 var.fields.iter().any(|field| {
502 let ty = tcx.type_of(field.did).subst(tcx, substs);
503 tcx.conservative_is_privately_uninhabited(param_env.and(ty))
508 debug!("ty::Tuple(..) =>");
509 ty.tuple_fields().any(|ty| tcx.conservative_is_privately_uninhabited(param_env.and(ty)))
511 ty::Array(ty, len) => {
512 debug!("ty::Array(ty, len) =>");
513 match len.try_eval_usize(tcx, param_env) {
514 Some(0) | None => false,
515 // If the array is definitely non-empty, it's uninhabited if
516 // the type of its elements is uninhabited.
517 Some(1..) => tcx.conservative_is_privately_uninhabited(param_env.and(ty)),
521 debug!("ty::Ref(..) =>");
522 // References to uninitialised memory is valid for any type, including
523 // uninhabited types, in unsafe code, so we treat all references as
534 pub fn provide(providers: &mut ty::query::Providers) {
535 *providers = ty::query::Providers {
538 associated_item_def_ids,
540 adt_sized_constraint,
543 param_env_reveal_all_normalized,
545 instance_def_size_estimate,
549 conservative_is_privately_uninhabited: conservative_is_privately_uninhabited_raw,