1 use rustc_data_structures::fx::FxIndexSet;
3 use rustc_hir::def_id::{DefId, LocalDefId};
4 use rustc_middle::ty::subst::Subst;
5 use rustc_middle::ty::{
6 self, Binder, Predicate, PredicateKind, ToPredicate, Ty, TyCtxt, WithConstness,
9 use rustc_trait_selection::traits;
11 fn sized_constraint_for_ty<'tcx>(
18 let result = match ty.kind() {
19 Bool | Char | Int(..) | Uint(..) | Float(..) | RawPtr(..) | Ref(..) | FnDef(..)
20 | FnPtr(_) | Array(..) | Closure(..) | Generator(..) | Never => vec![],
22 Str | Dynamic(..) | Slice(_) | Foreign(..) | Error(_) | GeneratorWitness(..) => {
23 // these are never sized - return the target type
27 Tuple(ref tys) => match tys.last() {
29 Some(ty) => sized_constraint_for_ty(tcx, adtdef, ty.expect_ty()),
34 let adt_tys = adt.sized_constraint(tcx);
35 debug!("sized_constraint_for_ty({:?}) intermediate = {:?}", ty, adt_tys);
38 .map(|ty| ty.subst(tcx, substs))
39 .flat_map(|ty| sized_constraint_for_ty(tcx, adtdef, ty))
43 Projection(..) | Opaque(..) => {
44 // must calculate explicitly.
45 // FIXME: consider special-casing always-Sized projections
50 // perf hack: if there is a `T: Sized` bound, then
51 // we know that `T` is Sized and do not need to check
54 let sized_trait = match tcx.lang_items().sized_trait() {
58 let sized_predicate = ty::Binder::dummy(ty::TraitRef {
60 substs: tcx.mk_substs_trait(ty, &[]),
64 let predicates = tcx.predicates_of(adtdef.did).predicates;
65 if predicates.iter().any(|(p, _)| *p == sized_predicate) { vec![] } else { vec![ty] }
68 Placeholder(..) | Bound(..) | Infer(..) => {
69 bug!("unexpected type `{:?}` in sized_constraint_for_ty", ty)
72 debug!("sized_constraint_for_ty({:?}) = {:?}", ty, result);
76 fn associated_item_from_trait_item_ref(
78 parent_def_id: LocalDefId,
79 trait_item_ref: &hir::TraitItemRef,
81 let def_id = trait_item_ref.id.def_id;
82 let (kind, has_self) = match trait_item_ref.kind {
83 hir::AssocItemKind::Const => (ty::AssocKind::Const, false),
84 hir::AssocItemKind::Fn { has_self } => (ty::AssocKind::Fn, has_self),
85 hir::AssocItemKind::Type => (ty::AssocKind::Type, false),
89 ident: trait_item_ref.ident,
91 vis: tcx.visibility(def_id),
92 defaultness: trait_item_ref.defaultness,
93 def_id: def_id.to_def_id(),
94 container: ty::TraitContainer(parent_def_id.to_def_id()),
95 fn_has_self_parameter: has_self,
99 fn associated_item_from_impl_item_ref(
101 parent_def_id: LocalDefId,
102 impl_item_ref: &hir::ImplItemRef,
104 let def_id = impl_item_ref.id.def_id;
105 let (kind, has_self) = match impl_item_ref.kind {
106 hir::AssocItemKind::Const => (ty::AssocKind::Const, false),
107 hir::AssocItemKind::Fn { has_self } => (ty::AssocKind::Fn, has_self),
108 hir::AssocItemKind::Type => (ty::AssocKind::Type, false),
112 ident: impl_item_ref.ident,
114 vis: tcx.visibility(def_id),
115 defaultness: impl_item_ref.defaultness,
116 def_id: def_id.to_def_id(),
117 container: ty::ImplContainer(parent_def_id.to_def_id()),
118 fn_has_self_parameter: has_self,
122 fn associated_item(tcx: TyCtxt<'_>, def_id: DefId) -> ty::AssocItem {
123 let id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
124 let parent_id = tcx.hir().get_parent_item(id);
125 let parent_def_id = tcx.hir().local_def_id(parent_id);
126 let parent_item = tcx.hir().expect_item(parent_id);
127 match parent_item.kind {
128 hir::ItemKind::Impl(ref impl_) => {
129 if let Some(impl_item_ref) =
130 impl_.items.iter().find(|i| i.id.def_id.to_def_id() == def_id)
133 associated_item_from_impl_item_ref(tcx, parent_def_id, impl_item_ref);
134 debug_assert_eq!(assoc_item.def_id, def_id);
139 hir::ItemKind::Trait(.., ref trait_item_refs) => {
140 if let Some(trait_item_ref) =
141 trait_item_refs.iter().find(|i| i.id.def_id.to_def_id() == def_id)
144 associated_item_from_trait_item_ref(tcx, parent_def_id, trait_item_ref);
145 debug_assert_eq!(assoc_item.def_id, def_id);
155 "unexpected parent of trait or impl item or item not found: {:?}",
160 fn impl_defaultness(tcx: TyCtxt<'_>, def_id: DefId) -> hir::Defaultness {
161 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
162 let item = tcx.hir().expect_item(hir_id);
163 if let hir::ItemKind::Impl(impl_) = &item.kind {
166 bug!("`impl_defaultness` called on {:?}", item);
170 fn impl_constness(tcx: TyCtxt<'_>, def_id: DefId) -> hir::Constness {
171 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
172 let item = tcx.hir().expect_item(hir_id);
173 if let hir::ItemKind::Impl(impl_) = &item.kind {
176 bug!("`impl_constness` called on {:?}", item);
180 /// Calculates the `Sized` constraint.
182 /// In fact, there are only a few options for the types in the constraint:
183 /// - an obviously-unsized type
184 /// - a type parameter or projection whose Sizedness can't be known
185 /// - a tuple of type parameters or projections, if there are multiple
187 /// - an Error, if a type contained itself. The representability
188 /// check should catch this case.
189 fn adt_sized_constraint(tcx: TyCtxt<'_>, def_id: DefId) -> ty::AdtSizedConstraint<'_> {
190 let def = tcx.adt_def(def_id);
192 let result = tcx.mk_type_list(
195 .flat_map(|v| v.fields.last())
196 .flat_map(|f| sized_constraint_for_ty(tcx, def, tcx.type_of(f.did))),
199 debug!("adt_sized_constraint: {:?} => {:?}", def, result);
201 ty::AdtSizedConstraint(result)
204 fn associated_item_def_ids(tcx: TyCtxt<'_>, def_id: DefId) -> &[DefId] {
205 let id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
206 let item = tcx.hir().expect_item(id);
208 hir::ItemKind::Trait(.., ref trait_item_refs) => tcx.arena.alloc_from_iter(
209 trait_item_refs.iter().map(|trait_item_ref| trait_item_ref.id.def_id.to_def_id()),
211 hir::ItemKind::Impl(ref impl_) => tcx.arena.alloc_from_iter(
212 impl_.items.iter().map(|impl_item_ref| impl_item_ref.id.def_id.to_def_id()),
214 hir::ItemKind::TraitAlias(..) => &[],
215 _ => span_bug!(item.span, "associated_item_def_ids: not impl or trait"),
219 fn associated_items(tcx: TyCtxt<'_>, def_id: DefId) -> ty::AssocItems<'_> {
220 let items = tcx.associated_item_def_ids(def_id).iter().map(|did| tcx.associated_item(*did));
221 ty::AssocItems::new(items)
224 fn def_ident_span(tcx: TyCtxt<'_>, def_id: DefId) -> Option<Span> {
226 .get_if_local(def_id)
227 .and_then(|node| match node {
228 // A `Ctor` doesn't have an identifier itself, but its parent
229 // struct/variant does. Compare with `hir::Map::opt_span`.
230 hir::Node::Ctor(ctor) => ctor
232 .and_then(|ctor_id| tcx.hir().find(tcx.hir().get_parent_node(ctor_id)))
233 .and_then(|parent| parent.ident()),
236 .map(|ident| ident.span)
239 /// If the given `DefId` describes an item belonging to a trait,
240 /// returns the `DefId` of the trait that the trait item belongs to;
241 /// otherwise, returns `None`.
242 fn trait_of_item(tcx: TyCtxt<'_>, def_id: DefId) -> Option<DefId> {
243 tcx.opt_associated_item(def_id).and_then(|associated_item| match associated_item.container {
244 ty::TraitContainer(def_id) => Some(def_id),
245 ty::ImplContainer(_) => None,
249 /// See `ParamEnv` struct definition for details.
250 fn param_env(tcx: TyCtxt<'_>, def_id: DefId) -> ty::ParamEnv<'_> {
251 // The param_env of an impl Trait type is its defining function's param_env
252 if let Some(parent) = ty::is_impl_trait_defn(tcx, def_id) {
253 return param_env(tcx, parent);
255 // Compute the bounds on Self and the type parameters.
257 let ty::InstantiatedPredicates { mut predicates, .. } =
258 tcx.predicates_of(def_id).instantiate_identity(tcx);
260 // Finally, we have to normalize the bounds in the environment, in
261 // case they contain any associated type projections. This process
262 // can yield errors if the put in illegal associated types, like
263 // `<i32 as Foo>::Bar` where `i32` does not implement `Foo`. We
264 // report these errors right here; this doesn't actually feel
265 // right to me, because constructing the environment feels like a
266 // kind of an "idempotent" action, but I'm not sure where would be
267 // a better place. In practice, we construct environments for
268 // every fn once during type checking, and we'll abort if there
269 // are any errors at that point, so after type checking you can be
270 // sure that this will succeed without errors anyway.
272 if tcx.sess.opts.debugging_opts.chalk {
273 let environment = well_formed_types_in_env(tcx, def_id);
274 predicates.extend(environment);
277 let unnormalized_env =
278 ty::ParamEnv::new(tcx.intern_predicates(&predicates), traits::Reveal::UserFacing);
282 .map(|def_id| tcx.hir().local_def_id_to_hir_id(def_id))
283 .map_or(hir::CRATE_HIR_ID, |id| {
284 tcx.hir().maybe_body_owned_by(id).map_or(id, |body| body.hir_id)
286 let cause = traits::ObligationCause::misc(tcx.def_span(def_id), body_id);
287 traits::normalize_param_env_or_error(tcx, def_id, unnormalized_env, cause)
290 /// Elaborate the environment.
292 /// Collect a list of `Predicate`'s used for building the `ParamEnv`. Adds `TypeWellFormedFromEnv`'s
293 /// that are assumed to be well-formed (because they come from the environment).
295 /// Used only in chalk mode.
296 fn well_formed_types_in_env<'tcx>(
299 ) -> &'tcx ty::List<Predicate<'tcx>> {
300 use rustc_hir::{ForeignItemKind, ImplItemKind, ItemKind, Node, TraitItemKind};
301 use rustc_middle::ty::subst::GenericArgKind;
303 debug!("environment(def_id = {:?})", def_id);
305 // The environment of an impl Trait type is its defining function's environment.
306 if let Some(parent) = ty::is_impl_trait_defn(tcx, def_id) {
307 return well_formed_types_in_env(tcx, parent);
310 // Compute the bounds on `Self` and the type parameters.
311 let ty::InstantiatedPredicates { predicates, .. } =
312 tcx.predicates_of(def_id).instantiate_identity(tcx);
314 let clauses = predicates.into_iter();
316 if !def_id.is_local() {
317 return ty::List::empty();
319 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
320 let node = tcx.hir().get(hir_id);
329 let node_kind = match node {
330 Node::TraitItem(item) => match item.kind {
331 TraitItemKind::Fn(..) => NodeKind::Fn,
332 _ => NodeKind::Other,
335 Node::ImplItem(item) => match item.kind {
336 ImplItemKind::Fn(..) => NodeKind::Fn,
337 _ => NodeKind::Other,
340 Node::Item(item) => match item.kind {
341 ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }) => NodeKind::TraitImpl,
342 ItemKind::Impl(hir::Impl { of_trait: None, .. }) => NodeKind::InherentImpl,
343 ItemKind::Fn(..) => NodeKind::Fn,
344 _ => NodeKind::Other,
347 Node::ForeignItem(item) => match item.kind {
348 ForeignItemKind::Fn(..) => NodeKind::Fn,
349 _ => NodeKind::Other,
353 _ => NodeKind::Other,
356 // FIXME(eddyb) isn't the unordered nature of this a hazard?
357 let mut inputs = FxIndexSet::default();
360 // In a trait impl, we assume that the header trait ref and all its
361 // constituents are well-formed.
362 NodeKind::TraitImpl => {
363 let trait_ref = tcx.impl_trait_ref(def_id).expect("not an impl");
365 // FIXME(chalk): this has problems because of late-bound regions
366 //inputs.extend(trait_ref.substs.iter().flat_map(|arg| arg.walk()));
367 inputs.extend(trait_ref.substs.iter());
370 // In an inherent impl, we assume that the receiver type and all its
371 // constituents are well-formed.
372 NodeKind::InherentImpl => {
373 let self_ty = tcx.type_of(def_id);
374 inputs.extend(self_ty.walk(tcx));
377 // In an fn, we assume that the arguments and all their constituents are
380 let fn_sig = tcx.fn_sig(def_id);
381 let fn_sig = tcx.liberate_late_bound_regions(def_id, fn_sig);
383 inputs.extend(fn_sig.inputs().iter().flat_map(|ty| ty.walk(tcx)));
386 NodeKind::Other => (),
388 let input_clauses = inputs.into_iter().filter_map(|arg| {
390 GenericArgKind::Type(ty) => {
391 let binder = Binder::dummy(PredicateKind::TypeWellFormedFromEnv(ty));
392 Some(tcx.mk_predicate(binder))
395 // FIXME(eddyb) no WF conditions from lifetimes?
396 GenericArgKind::Lifetime(_) => None,
398 // FIXME(eddyb) support const generics in Chalk
399 GenericArgKind::Const(_) => None,
403 tcx.mk_predicates(clauses.chain(input_clauses))
406 fn param_env_reveal_all_normalized(tcx: TyCtxt<'_>, def_id: DefId) -> ty::ParamEnv<'_> {
407 tcx.param_env(def_id).with_reveal_all_normalized(tcx)
410 fn instance_def_size_estimate<'tcx>(
412 instance_def: ty::InstanceDef<'tcx>,
417 InstanceDef::Item(..) | InstanceDef::DropGlue(..) => {
418 let mir = tcx.instance_mir(instance_def);
419 mir.basic_blocks().iter().map(|bb| bb.statements.len() + 1).sum()
421 // Estimate the size of other compiler-generated shims to be 1.
426 /// If `def_id` is an issue 33140 hack impl, returns its self type; otherwise, returns `None`.
428 /// See [`ty::ImplOverlapKind::Issue33140`] for more details.
429 fn issue33140_self_ty(tcx: TyCtxt<'_>, def_id: DefId) -> Option<Ty<'_>> {
430 debug!("issue33140_self_ty({:?})", def_id);
433 .impl_trait_ref(def_id)
434 .unwrap_or_else(|| bug!("issue33140_self_ty called on inherent impl {:?}", def_id));
436 debug!("issue33140_self_ty({:?}), trait-ref={:?}", def_id, trait_ref);
438 let is_marker_like = tcx.impl_polarity(def_id) == ty::ImplPolarity::Positive
439 && tcx.associated_item_def_ids(trait_ref.def_id).is_empty();
441 // Check whether these impls would be ok for a marker trait.
443 debug!("issue33140_self_ty - not marker-like!");
447 // impl must be `impl Trait for dyn Marker1 + Marker2 + ...`
448 if trait_ref.substs.len() != 1 {
449 debug!("issue33140_self_ty - impl has substs!");
453 let predicates = tcx.predicates_of(def_id);
454 if predicates.parent.is_some() || !predicates.predicates.is_empty() {
455 debug!("issue33140_self_ty - impl has predicates {:?}!", predicates);
459 let self_ty = trait_ref.self_ty();
460 let self_ty_matches = match self_ty.kind() {
461 ty::Dynamic(ref data, ty::ReStatic) => data.principal().is_none(),
466 debug!("issue33140_self_ty - MATCHES!");
469 debug!("issue33140_self_ty - non-matching self type");
474 /// Check if a function is async.
475 fn asyncness(tcx: TyCtxt<'_>, def_id: DefId) -> hir::IsAsync {
476 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
478 let node = tcx.hir().get(hir_id);
480 let fn_kind = node.fn_kind().unwrap_or_else(|| {
481 bug!("asyncness: expected fn-like node but got `{:?}`", def_id);
487 /// Don't call this directly: use ``tcx.conservative_is_privately_uninhabited`` instead.
488 #[instrument(level = "debug", skip(tcx))]
489 pub fn conservative_is_privately_uninhabited_raw<'tcx>(
491 param_env_and: ty::ParamEnvAnd<'tcx, Ty<'tcx>>,
493 let (param_env, ty) = param_env_and.into_parts();
496 debug!("ty::Never =>");
499 ty::Adt(def, _) if def.is_union() => {
500 debug!("ty::Adt(def, _) if def.is_union() =>");
501 // For now, `union`s are never considered uninhabited.
504 ty::Adt(def, substs) => {
505 debug!("ty::Adt(def, _) if def.is_not_union() =>");
506 // Any ADT is uninhabited if either:
507 // (a) It has no variants (i.e. an empty `enum`);
508 // (b) Each of its variants (a single one in the case of a `struct`) has at least
509 // one uninhabited field.
510 def.variants.iter().all(|var| {
511 var.fields.iter().any(|field| {
512 let ty = tcx.type_of(field.did).subst(tcx, substs);
513 tcx.conservative_is_privately_uninhabited(param_env.and(ty))
518 debug!("ty::Tuple(..) =>");
519 ty.tuple_fields().any(|ty| tcx.conservative_is_privately_uninhabited(param_env.and(ty)))
521 ty::Array(ty, len) => {
522 debug!("ty::Array(ty, len) =>");
523 match len.try_eval_usize(tcx, param_env) {
524 Some(0) | None => false,
525 // If the array is definitely non-empty, it's uninhabited if
526 // the type of its elements is uninhabited.
527 Some(1..) => tcx.conservative_is_privately_uninhabited(param_env.and(ty)),
531 debug!("ty::Ref(..) =>");
532 // References to uninitialised memory is valid for any type, including
533 // uninhabited types, in unsafe code, so we treat all references as
544 pub fn provide(providers: &mut ty::query::Providers) {
545 *providers = ty::query::Providers {
548 associated_item_def_ids,
550 adt_sized_constraint,
553 param_env_reveal_all_normalized,
555 instance_def_size_estimate,
559 conservative_is_privately_uninhabited: conservative_is_privately_uninhabited_raw,