1 use rustc_data_structures::fx::FxIndexSet;
2 use rustc_data_structures::svh::Svh;
4 use rustc_hir::def_id::{CrateNum, DefId, LocalDefId, LOCAL_CRATE};
5 use rustc_middle::hir::map as hir_map;
6 use rustc_middle::ty::subst::Subst;
7 use rustc_middle::ty::{
8 self, Binder, Predicate, PredicateKind, ToPredicate, Ty, TyCtxt, WithConstness,
10 use rustc_session::CrateDisambiguator;
11 use rustc_span::symbol::Symbol;
13 use rustc_trait_selection::traits;
15 fn sized_constraint_for_ty<'tcx>(
22 let result = match ty.kind() {
23 Bool | Char | Int(..) | Uint(..) | Float(..) | RawPtr(..) | Ref(..) | FnDef(..)
24 | FnPtr(_) | Array(..) | Closure(..) | Generator(..) | Never => vec![],
26 Str | Dynamic(..) | Slice(_) | Foreign(..) | Error(_) | GeneratorWitness(..) => {
27 // these are never sized - return the target type
31 Tuple(ref tys) => match tys.last() {
33 Some(ty) => sized_constraint_for_ty(tcx, adtdef, ty.expect_ty()),
38 let adt_tys = adt.sized_constraint(tcx);
39 debug!("sized_constraint_for_ty({:?}) intermediate = {:?}", ty, adt_tys);
42 .map(|ty| ty.subst(tcx, substs))
43 .flat_map(|ty| sized_constraint_for_ty(tcx, adtdef, ty))
47 Projection(..) | Opaque(..) => {
48 // must calculate explicitly.
49 // FIXME: consider special-casing always-Sized projections
54 // perf hack: if there is a `T: Sized` bound, then
55 // we know that `T` is Sized and do not need to check
58 let sized_trait = match tcx.lang_items().sized_trait() {
62 let sized_predicate = ty::Binder::dummy(ty::TraitRef {
64 substs: tcx.mk_substs_trait(ty, &[]),
68 let predicates = tcx.predicates_of(adtdef.did).predicates;
69 if predicates.iter().any(|(p, _)| *p == sized_predicate) { vec![] } else { vec![ty] }
72 Placeholder(..) | Bound(..) | Infer(..) => {
73 bug!("unexpected type `{:?}` in sized_constraint_for_ty", ty)
76 debug!("sized_constraint_for_ty({:?}) = {:?}", ty, result);
80 fn associated_item_from_trait_item_ref(
82 parent_def_id: LocalDefId,
83 trait_item_ref: &hir::TraitItemRef,
85 let def_id = trait_item_ref.id.def_id;
86 let (kind, has_self) = match trait_item_ref.kind {
87 hir::AssocItemKind::Const => (ty::AssocKind::Const, false),
88 hir::AssocItemKind::Fn { has_self } => (ty::AssocKind::Fn, has_self),
89 hir::AssocItemKind::Type => (ty::AssocKind::Type, false),
93 ident: trait_item_ref.ident,
95 vis: tcx.visibility(def_id),
96 defaultness: trait_item_ref.defaultness,
97 def_id: def_id.to_def_id(),
98 container: ty::TraitContainer(parent_def_id.to_def_id()),
99 fn_has_self_parameter: has_self,
103 fn associated_item_from_impl_item_ref(
105 parent_def_id: LocalDefId,
106 impl_item_ref: &hir::ImplItemRef<'_>,
108 let def_id = impl_item_ref.id.def_id;
109 let (kind, has_self) = match impl_item_ref.kind {
110 hir::AssocItemKind::Const => (ty::AssocKind::Const, false),
111 hir::AssocItemKind::Fn { has_self } => (ty::AssocKind::Fn, has_self),
112 hir::AssocItemKind::Type => (ty::AssocKind::Type, false),
116 ident: impl_item_ref.ident,
118 vis: tcx.visibility(def_id),
119 defaultness: impl_item_ref.defaultness,
120 def_id: def_id.to_def_id(),
121 container: ty::ImplContainer(parent_def_id.to_def_id()),
122 fn_has_self_parameter: has_self,
126 fn associated_item(tcx: TyCtxt<'_>, def_id: DefId) -> ty::AssocItem {
127 let id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
128 let parent_id = tcx.hir().get_parent_item(id);
129 let parent_def_id = tcx.hir().local_def_id(parent_id);
130 let parent_item = tcx.hir().expect_item(parent_id);
131 match parent_item.kind {
132 hir::ItemKind::Impl(ref impl_) => {
133 if let Some(impl_item_ref) =
134 impl_.items.iter().find(|i| i.id.def_id.to_def_id() == def_id)
137 associated_item_from_impl_item_ref(tcx, parent_def_id, impl_item_ref);
138 debug_assert_eq!(assoc_item.def_id, def_id);
143 hir::ItemKind::Trait(.., ref trait_item_refs) => {
144 if let Some(trait_item_ref) =
145 trait_item_refs.iter().find(|i| i.id.def_id.to_def_id() == def_id)
148 associated_item_from_trait_item_ref(tcx, parent_def_id, trait_item_ref);
149 debug_assert_eq!(assoc_item.def_id, def_id);
159 "unexpected parent of trait or impl item or item not found: {:?}",
164 fn impl_defaultness(tcx: TyCtxt<'_>, def_id: DefId) -> hir::Defaultness {
165 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
166 let item = tcx.hir().expect_item(hir_id);
167 if let hir::ItemKind::Impl(impl_) = &item.kind {
170 bug!("`impl_defaultness` called on {:?}", item);
174 /// Calculates the `Sized` constraint.
176 /// In fact, there are only a few options for the types in the constraint:
177 /// - an obviously-unsized type
178 /// - a type parameter or projection whose Sizedness can't be known
179 /// - a tuple of type parameters or projections, if there are multiple
181 /// - a Error, if a type contained itself. The representability
182 /// check should catch this case.
183 fn adt_sized_constraint(tcx: TyCtxt<'_>, def_id: DefId) -> ty::AdtSizedConstraint<'_> {
184 let def = tcx.adt_def(def_id);
186 let result = tcx.mk_type_list(
189 .flat_map(|v| v.fields.last())
190 .flat_map(|f| sized_constraint_for_ty(tcx, def, tcx.type_of(f.did))),
193 debug!("adt_sized_constraint: {:?} => {:?}", def, result);
195 ty::AdtSizedConstraint(result)
198 fn associated_item_def_ids(tcx: TyCtxt<'_>, def_id: DefId) -> &[DefId] {
199 let id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
200 let item = tcx.hir().expect_item(id);
202 hir::ItemKind::Trait(.., ref trait_item_refs) => tcx.arena.alloc_from_iter(
203 trait_item_refs.iter().map(|trait_item_ref| trait_item_ref.id.def_id.to_def_id()),
205 hir::ItemKind::Impl(ref impl_) => tcx.arena.alloc_from_iter(
206 impl_.items.iter().map(|impl_item_ref| impl_item_ref.id.def_id.to_def_id()),
208 hir::ItemKind::TraitAlias(..) => &[],
209 _ => span_bug!(item.span, "associated_item_def_ids: not impl or trait"),
213 fn associated_items(tcx: TyCtxt<'_>, def_id: DefId) -> ty::AssociatedItems<'_> {
214 let items = tcx.associated_item_def_ids(def_id).iter().map(|did| tcx.associated_item(*did));
215 ty::AssociatedItems::new(items)
218 fn def_ident_span(tcx: TyCtxt<'_>, def_id: DefId) -> Option<Span> {
219 tcx.hir().get_if_local(def_id).and_then(|node| node.ident()).map(|ident| ident.span)
222 /// If the given `DefId` describes an item belonging to a trait,
223 /// returns the `DefId` of the trait that the trait item belongs to;
224 /// otherwise, returns `None`.
225 fn trait_of_item(tcx: TyCtxt<'_>, def_id: DefId) -> Option<DefId> {
226 tcx.opt_associated_item(def_id).and_then(|associated_item| match associated_item.container {
227 ty::TraitContainer(def_id) => Some(def_id),
228 ty::ImplContainer(_) => None,
232 /// See `ParamEnv` struct definition for details.
233 fn param_env(tcx: TyCtxt<'_>, def_id: DefId) -> ty::ParamEnv<'_> {
234 // The param_env of an impl Trait type is its defining function's param_env
235 if let Some(parent) = ty::is_impl_trait_defn(tcx, def_id) {
236 return param_env(tcx, parent);
238 // Compute the bounds on Self and the type parameters.
240 let ty::InstantiatedPredicates { mut predicates, .. } =
241 tcx.predicates_of(def_id).instantiate_identity(tcx);
243 // Finally, we have to normalize the bounds in the environment, in
244 // case they contain any associated type projections. This process
245 // can yield errors if the put in illegal associated types, like
246 // `<i32 as Foo>::Bar` where `i32` does not implement `Foo`. We
247 // report these errors right here; this doesn't actually feel
248 // right to me, because constructing the environment feels like a
249 // kind of a "idempotent" action, but I'm not sure where would be
250 // a better place. In practice, we construct environments for
251 // every fn once during type checking, and we'll abort if there
252 // are any errors at that point, so after type checking you can be
253 // sure that this will succeed without errors anyway.
255 if tcx.sess.opts.debugging_opts.chalk {
256 let environment = well_formed_types_in_env(tcx, def_id);
257 predicates.extend(environment);
260 let unnormalized_env =
261 ty::ParamEnv::new(tcx.intern_predicates(&predicates), traits::Reveal::UserFacing);
265 .map(|def_id| tcx.hir().local_def_id_to_hir_id(def_id))
266 .map_or(hir::CRATE_HIR_ID, |id| {
267 tcx.hir().maybe_body_owned_by(id).map_or(id, |body| body.hir_id)
269 let cause = traits::ObligationCause::misc(tcx.def_span(def_id), body_id);
270 traits::normalize_param_env_or_error(tcx, def_id, unnormalized_env, cause)
273 /// Elaborate the environment.
275 /// Collect a list of `Predicate`'s used for building the `ParamEnv`. Adds `TypeWellFormedFromEnv`'s
276 /// that are assumed to be well-formed (because they come from the environment).
278 /// Used only in chalk mode.
279 fn well_formed_types_in_env<'tcx>(
282 ) -> &'tcx ty::List<Predicate<'tcx>> {
283 use rustc_hir::{ForeignItemKind, ImplItemKind, ItemKind, Node, TraitItemKind};
284 use rustc_middle::ty::subst::GenericArgKind;
286 debug!("environment(def_id = {:?})", def_id);
288 // The environment of an impl Trait type is its defining function's environment.
289 if let Some(parent) = ty::is_impl_trait_defn(tcx, def_id) {
290 return well_formed_types_in_env(tcx, parent);
293 // Compute the bounds on `Self` and the type parameters.
294 let ty::InstantiatedPredicates { predicates, .. } =
295 tcx.predicates_of(def_id).instantiate_identity(tcx);
297 let clauses = predicates.into_iter();
299 if !def_id.is_local() {
300 return ty::List::empty();
302 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
303 let node = tcx.hir().get(hir_id);
312 let node_kind = match node {
313 Node::TraitItem(item) => match item.kind {
314 TraitItemKind::Fn(..) => NodeKind::Fn,
315 _ => NodeKind::Other,
318 Node::ImplItem(item) => match item.kind {
319 ImplItemKind::Fn(..) => NodeKind::Fn,
320 _ => NodeKind::Other,
323 Node::Item(item) => match item.kind {
324 ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }) => NodeKind::TraitImpl,
325 ItemKind::Impl(hir::Impl { of_trait: None, .. }) => NodeKind::InherentImpl,
326 ItemKind::Fn(..) => NodeKind::Fn,
327 _ => NodeKind::Other,
330 Node::ForeignItem(item) => match item.kind {
331 ForeignItemKind::Fn(..) => NodeKind::Fn,
332 _ => NodeKind::Other,
336 _ => NodeKind::Other,
339 // FIXME(eddyb) isn't the unordered nature of this a hazard?
340 let mut inputs = FxIndexSet::default();
343 // In a trait impl, we assume that the header trait ref and all its
344 // constituents are well-formed.
345 NodeKind::TraitImpl => {
346 let trait_ref = tcx.impl_trait_ref(def_id).expect("not an impl");
348 // FIXME(chalk): this has problems because of late-bound regions
349 //inputs.extend(trait_ref.substs.iter().flat_map(|arg| arg.walk()));
350 inputs.extend(trait_ref.substs.iter());
353 // In an inherent impl, we assume that the receiver type and all its
354 // constituents are well-formed.
355 NodeKind::InherentImpl => {
356 let self_ty = tcx.type_of(def_id);
357 inputs.extend(self_ty.walk());
360 // In an fn, we assume that the arguments and all their constituents are
363 let fn_sig = tcx.fn_sig(def_id);
364 let fn_sig = tcx.liberate_late_bound_regions(def_id, fn_sig);
366 inputs.extend(fn_sig.inputs().iter().flat_map(|ty| ty.walk()));
369 NodeKind::Other => (),
371 let input_clauses = inputs.into_iter().filter_map(|arg| {
373 GenericArgKind::Type(ty) => {
374 let binder = Binder::dummy(PredicateKind::TypeWellFormedFromEnv(ty));
375 Some(tcx.mk_predicate(binder))
378 // FIXME(eddyb) no WF conditions from lifetimes?
379 GenericArgKind::Lifetime(_) => None,
381 // FIXME(eddyb) support const generics in Chalk
382 GenericArgKind::Const(_) => None,
386 tcx.mk_predicates(clauses.chain(input_clauses))
389 fn param_env_reveal_all_normalized(tcx: TyCtxt<'_>, def_id: DefId) -> ty::ParamEnv<'_> {
390 tcx.param_env(def_id).with_reveal_all_normalized(tcx)
393 fn crate_disambiguator(tcx: TyCtxt<'_>, crate_num: CrateNum) -> CrateDisambiguator {
394 assert_eq!(crate_num, LOCAL_CRATE);
395 tcx.sess.local_crate_disambiguator()
398 fn original_crate_name(tcx: TyCtxt<'_>, crate_num: CrateNum) -> Symbol {
399 assert_eq!(crate_num, LOCAL_CRATE);
403 fn crate_hash(tcx: TyCtxt<'_>, crate_num: CrateNum) -> Svh {
404 tcx.index_hir(crate_num).crate_hash
407 fn instance_def_size_estimate<'tcx>(
409 instance_def: ty::InstanceDef<'tcx>,
414 InstanceDef::Item(..) | InstanceDef::DropGlue(..) => {
415 let mir = tcx.instance_mir(instance_def);
416 mir.basic_blocks().iter().map(|bb| bb.statements.len()).sum()
418 // Estimate the size of other compiler-generated shims to be 1.
423 /// If `def_id` is an issue 33140 hack impl, returns its self type; otherwise, returns `None`.
425 /// See [`ty::ImplOverlapKind::Issue33140`] for more details.
426 fn issue33140_self_ty(tcx: TyCtxt<'_>, def_id: DefId) -> Option<Ty<'_>> {
427 debug!("issue33140_self_ty({:?})", def_id);
430 .impl_trait_ref(def_id)
431 .unwrap_or_else(|| bug!("issue33140_self_ty called on inherent impl {:?}", def_id));
433 debug!("issue33140_self_ty({:?}), trait-ref={:?}", def_id, trait_ref);
435 let is_marker_like = tcx.impl_polarity(def_id) == ty::ImplPolarity::Positive
436 && tcx.associated_item_def_ids(trait_ref.def_id).is_empty();
438 // Check whether these impls would be ok for a marker trait.
440 debug!("issue33140_self_ty - not marker-like!");
444 // impl must be `impl Trait for dyn Marker1 + Marker2 + ...`
445 if trait_ref.substs.len() != 1 {
446 debug!("issue33140_self_ty - impl has substs!");
450 let predicates = tcx.predicates_of(def_id);
451 if predicates.parent.is_some() || !predicates.predicates.is_empty() {
452 debug!("issue33140_self_ty - impl has predicates {:?}!", predicates);
456 let self_ty = trait_ref.self_ty();
457 let self_ty_matches = match self_ty.kind() {
458 ty::Dynamic(ref data, ty::ReStatic) => data.principal().is_none(),
463 debug!("issue33140_self_ty - MATCHES!");
466 debug!("issue33140_self_ty - non-matching self type");
471 /// Check if a function is async.
472 fn asyncness(tcx: TyCtxt<'_>, def_id: DefId) -> hir::IsAsync {
473 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
475 let node = tcx.hir().get(hir_id);
477 let fn_like = hir_map::blocks::FnLikeNode::from_node(node).unwrap_or_else(|| {
478 bug!("asyncness: expected fn-like node but got `{:?}`", def_id);
484 /// Don't call this directly: use ``tcx.conservative_is_privately_uninhabited`` instead.
485 #[instrument(level = "debug", skip(tcx))]
486 pub fn conservative_is_privately_uninhabited_raw<'tcx>(
488 param_env_and: ty::ParamEnvAnd<'tcx, Ty<'tcx>>,
490 let (param_env, ty) = param_env_and.into_parts();
493 debug!("ty::Never =>");
496 ty::Adt(def, _) if def.is_union() => {
497 debug!("ty::Adt(def, _) if def.is_union() =>");
498 // For now, `union`s are never considered uninhabited.
501 ty::Adt(def, substs) => {
502 debug!("ty::Adt(def, _) if def.is_not_union() =>");
503 // Any ADT is uninhabited if either:
504 // (a) It has no variants (i.e. an empty `enum`);
505 // (b) Each of its variants (a single one in the case of a `struct`) has at least
506 // one uninhabited field.
507 def.variants.iter().all(|var| {
508 var.fields.iter().any(|field| {
509 let ty = tcx.type_of(field.did).subst(tcx, substs);
510 tcx.conservative_is_privately_uninhabited(param_env.and(ty))
515 debug!("ty::Tuple(..) =>");
516 ty.tuple_fields().any(|ty| tcx.conservative_is_privately_uninhabited(param_env.and(ty)))
518 ty::Array(ty, len) => {
519 debug!("ty::Array(ty, len) =>");
520 match len.try_eval_usize(tcx, param_env) {
521 Some(0) | None => false,
522 // If the array is definitely non-empty, it's uninhabited if
523 // the type of its elements is uninhabited.
524 Some(1..) => tcx.conservative_is_privately_uninhabited(param_env.and(ty)),
528 debug!("ty::Ref(..) =>");
529 // References to uninitialised memory is valid for any type, including
530 // uninhabited types, in unsafe code, so we treat all references as
541 pub fn provide(providers: &mut ty::query::Providers) {
542 *providers = ty::query::Providers {
545 associated_item_def_ids,
547 adt_sized_constraint,
550 param_env_reveal_all_normalized,
555 instance_def_size_estimate,
558 conservative_is_privately_uninhabited: conservative_is_privately_uninhabited_raw,