1 use rustc_data_structures::fx::FxIndexSet;
3 use rustc_hir::def_id::DefId;
4 use rustc_middle::ty::subst::Subst;
5 use rustc_middle::ty::{self, Binder, Predicate, PredicateKind, ToPredicate, Ty, TyCtxt};
6 use rustc_trait_selection::traits;
8 fn sized_constraint_for_ty<'tcx>(
10 adtdef: ty::AdtDef<'tcx>,
13 use rustc_type_ir::sty::TyKind::*;
15 let result = match ty.kind() {
16 Bool | Char | Int(..) | Uint(..) | Float(..) | RawPtr(..) | Ref(..) | FnDef(..)
17 | FnPtr(_) | Array(..) | Closure(..) | Generator(..) | Never => vec![],
19 Str | Dynamic(..) | Slice(_) | Foreign(..) | Error(_) | GeneratorWitness(..) => {
20 // these are never sized - return the target type
24 Tuple(ref tys) => match tys.last() {
26 Some(&ty) => sized_constraint_for_ty(tcx, adtdef, ty),
31 let adt_tys = adt.sized_constraint(tcx);
32 debug!("sized_constraint_for_ty({:?}) intermediate = {:?}", ty, adt_tys);
36 .map(|ty| adt_tys.rebind(*ty).subst(tcx, substs))
37 .flat_map(|ty| sized_constraint_for_ty(tcx, adtdef, ty))
41 Projection(..) | Opaque(..) => {
42 // must calculate explicitly.
43 // FIXME: consider special-casing always-Sized projections
48 // perf hack: if there is a `T: Sized` bound, then
49 // we know that `T` is Sized and do not need to check
52 let Some(sized_trait) = tcx.lang_items().sized_trait() else { return vec![ty] };
53 let sized_predicate = ty::Binder::dummy(ty::TraitRef {
55 substs: tcx.mk_substs_trait(ty, &[]),
59 let predicates = tcx.predicates_of(adtdef.did()).predicates;
60 if predicates.iter().any(|(p, _)| *p == sized_predicate) { vec![] } else { vec![ty] }
63 Placeholder(..) | Bound(..) | Infer(..) => {
64 bug!("unexpected type `{:?}` in sized_constraint_for_ty", ty)
67 debug!("sized_constraint_for_ty({:?}) = {:?}", ty, result);
71 fn impl_defaultness(tcx: TyCtxt<'_>, def_id: DefId) -> hir::Defaultness {
72 match tcx.hir().get_by_def_id(def_id.expect_local()) {
73 hir::Node::Item(hir::Item { kind: hir::ItemKind::Impl(impl_), .. }) => impl_.defaultness,
74 hir::Node::ImplItem(hir::ImplItem { defaultness, .. })
75 | hir::Node::TraitItem(hir::TraitItem { defaultness, .. }) => *defaultness,
77 bug!("`impl_defaultness` called on {:?}", node);
82 /// Calculates the `Sized` constraint.
84 /// In fact, there are only a few options for the types in the constraint:
85 /// - an obviously-unsized type
86 /// - a type parameter or projection whose Sizedness can't be known
87 /// - a tuple of type parameters or projections, if there are multiple
89 /// - an Error, if a type contained itself. The representability
90 /// check should catch this case.
91 fn adt_sized_constraint(tcx: TyCtxt<'_>, def_id: DefId) -> ty::AdtSizedConstraint<'_> {
92 let def = tcx.adt_def(def_id);
94 let result = tcx.mk_type_list(
97 .flat_map(|v| v.fields.last())
98 .flat_map(|f| sized_constraint_for_ty(tcx, def, tcx.type_of(f.did))),
101 debug!("adt_sized_constraint: {:?} => {:?}", def, result);
103 ty::AdtSizedConstraint(result)
106 /// See `ParamEnv` struct definition for details.
107 fn param_env(tcx: TyCtxt<'_>, def_id: DefId) -> ty::ParamEnv<'_> {
108 // The param_env of an impl Trait type is its defining function's param_env
109 if let Some(parent) = ty::is_impl_trait_defn(tcx, def_id) {
110 return param_env(tcx, parent.to_def_id());
112 // Compute the bounds on Self and the type parameters.
114 let ty::InstantiatedPredicates { mut predicates, .. } =
115 tcx.predicates_of(def_id).instantiate_identity(tcx);
117 // Finally, we have to normalize the bounds in the environment, in
118 // case they contain any associated type projections. This process
119 // can yield errors if the put in illegal associated types, like
120 // `<i32 as Foo>::Bar` where `i32` does not implement `Foo`. We
121 // report these errors right here; this doesn't actually feel
122 // right to me, because constructing the environment feels like a
123 // kind of an "idempotent" action, but I'm not sure where would be
124 // a better place. In practice, we construct environments for
125 // every fn once during type checking, and we'll abort if there
126 // are any errors at that point, so outside of type inference you can be
127 // sure that this will succeed without errors anyway.
129 if tcx.sess.opts.unstable_opts.chalk {
130 let environment = well_formed_types_in_env(tcx, def_id);
131 predicates.extend(environment);
134 let local_did = def_id.as_local();
135 let hir_id = local_did.map(|def_id| tcx.hir().local_def_id_to_hir_id(def_id));
137 let constness = match hir_id {
138 Some(hir_id) => match tcx.hir().get(hir_id) {
139 hir::Node::TraitItem(hir::TraitItem { kind: hir::TraitItemKind::Fn(..), .. })
140 if tcx.is_const_default_method(def_id) =>
142 hir::Constness::Const
145 hir::Node::Item(hir::Item { kind: hir::ItemKind::Const(..), .. })
146 | hir::Node::Item(hir::Item { kind: hir::ItemKind::Static(..), .. })
147 | hir::Node::TraitItem(hir::TraitItem {
148 kind: hir::TraitItemKind::Const(..), ..
150 | hir::Node::AnonConst(_)
151 | hir::Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Const(..), .. })
152 | hir::Node::ImplItem(hir::ImplItem {
154 hir::ImplItemKind::Fn(
156 header: hir::FnHeader { constness: hir::Constness::Const, .. },
162 }) => hir::Constness::Const,
164 hir::Node::ImplItem(hir::ImplItem {
165 kind: hir::ImplItemKind::TyAlias(..) | hir::ImplItemKind::Fn(..),
168 let parent_hir_id = tcx.hir().get_parent_node(hir_id);
169 match tcx.hir().get(parent_hir_id) {
170 hir::Node::Item(hir::Item {
171 kind: hir::ItemKind::Impl(hir::Impl { constness, .. }),
175 tcx.def_span(parent_hir_id.owner),
176 "impl item's parent node is not an impl",
181 hir::Node::Item(hir::Item {
183 hir::ItemKind::Fn(hir::FnSig { header: hir::FnHeader { constness, .. }, .. }, ..),
186 | hir::Node::TraitItem(hir::TraitItem {
188 hir::TraitItemKind::Fn(
189 hir::FnSig { header: hir::FnHeader { constness, .. }, .. },
194 | hir::Node::Item(hir::Item {
195 kind: hir::ItemKind::Impl(hir::Impl { constness, .. }),
199 _ => hir::Constness::NotConst,
201 None => hir::Constness::NotConst,
204 let unnormalized_env = ty::ParamEnv::new(
205 tcx.intern_predicates(&predicates),
206 traits::Reveal::UserFacing,
211 local_did.and_then(|id| tcx.hir().maybe_body_owned_by(id).map(|body| body.hir_id));
212 let body_id = match body_id {
214 None if hir_id.is_some() => hir_id.unwrap(),
215 _ => hir::CRATE_HIR_ID,
218 let cause = traits::ObligationCause::misc(tcx.def_span(def_id), body_id);
219 traits::normalize_param_env_or_error(tcx, unnormalized_env, cause)
222 /// Elaborate the environment.
224 /// Collect a list of `Predicate`'s used for building the `ParamEnv`. Adds `TypeWellFormedFromEnv`'s
225 /// that are assumed to be well-formed (because they come from the environment).
227 /// Used only in chalk mode.
228 fn well_formed_types_in_env<'tcx>(
231 ) -> &'tcx ty::List<Predicate<'tcx>> {
232 use rustc_hir::{ForeignItemKind, ImplItemKind, ItemKind, Node, TraitItemKind};
233 use rustc_middle::ty::subst::GenericArgKind;
235 debug!("environment(def_id = {:?})", def_id);
237 // The environment of an impl Trait type is its defining function's environment.
238 if let Some(parent) = ty::is_impl_trait_defn(tcx, def_id) {
239 return well_formed_types_in_env(tcx, parent.to_def_id());
242 // Compute the bounds on `Self` and the type parameters.
243 let ty::InstantiatedPredicates { predicates, .. } =
244 tcx.predicates_of(def_id).instantiate_identity(tcx);
246 let clauses = predicates.into_iter();
248 if !def_id.is_local() {
249 return ty::List::empty();
251 let node = tcx.hir().get_by_def_id(def_id.expect_local());
260 let node_kind = match node {
261 Node::TraitItem(item) => match item.kind {
262 TraitItemKind::Fn(..) => NodeKind::Fn,
263 _ => NodeKind::Other,
266 Node::ImplItem(item) => match item.kind {
267 ImplItemKind::Fn(..) => NodeKind::Fn,
268 _ => NodeKind::Other,
271 Node::Item(item) => match item.kind {
272 ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }) => NodeKind::TraitImpl,
273 ItemKind::Impl(hir::Impl { of_trait: None, .. }) => NodeKind::InherentImpl,
274 ItemKind::Fn(..) => NodeKind::Fn,
275 _ => NodeKind::Other,
278 Node::ForeignItem(item) => match item.kind {
279 ForeignItemKind::Fn(..) => NodeKind::Fn,
280 _ => NodeKind::Other,
284 _ => NodeKind::Other,
287 // FIXME(eddyb) isn't the unordered nature of this a hazard?
288 let mut inputs = FxIndexSet::default();
291 // In a trait impl, we assume that the header trait ref and all its
292 // constituents are well-formed.
293 NodeKind::TraitImpl => {
294 let trait_ref = tcx.impl_trait_ref(def_id).expect("not an impl");
296 // FIXME(chalk): this has problems because of late-bound regions
297 //inputs.extend(trait_ref.substs.iter().flat_map(|arg| arg.walk()));
298 inputs.extend(trait_ref.substs.iter());
301 // In an inherent impl, we assume that the receiver type and all its
302 // constituents are well-formed.
303 NodeKind::InherentImpl => {
304 let self_ty = tcx.type_of(def_id);
305 inputs.extend(self_ty.walk());
308 // In an fn, we assume that the arguments and all their constituents are
311 let fn_sig = tcx.fn_sig(def_id);
312 let fn_sig = tcx.liberate_late_bound_regions(def_id, fn_sig);
314 inputs.extend(fn_sig.inputs().iter().flat_map(|ty| ty.walk()));
317 NodeKind::Other => (),
319 let input_clauses = inputs.into_iter().filter_map(|arg| {
321 GenericArgKind::Type(ty) => {
322 let binder = Binder::dummy(PredicateKind::TypeWellFormedFromEnv(ty));
323 Some(tcx.mk_predicate(binder))
326 // FIXME(eddyb) no WF conditions from lifetimes?
327 GenericArgKind::Lifetime(_) => None,
329 // FIXME(eddyb) support const generics in Chalk
330 GenericArgKind::Const(_) => None,
334 tcx.mk_predicates(clauses.chain(input_clauses))
337 fn param_env_reveal_all_normalized(tcx: TyCtxt<'_>, def_id: DefId) -> ty::ParamEnv<'_> {
338 tcx.param_env(def_id).with_reveal_all_normalized(tcx)
341 fn instance_def_size_estimate<'tcx>(
343 instance_def: ty::InstanceDef<'tcx>,
348 InstanceDef::Item(..) | InstanceDef::DropGlue(..) => {
349 let mir = tcx.instance_mir(instance_def);
350 mir.basic_blocks.iter().map(|bb| bb.statements.len() + 1).sum()
352 // Estimate the size of other compiler-generated shims to be 1.
357 /// If `def_id` is an issue 33140 hack impl, returns its self type; otherwise, returns `None`.
359 /// See [`ty::ImplOverlapKind::Issue33140`] for more details.
360 fn issue33140_self_ty(tcx: TyCtxt<'_>, def_id: DefId) -> Option<Ty<'_>> {
361 debug!("issue33140_self_ty({:?})", def_id);
364 .impl_trait_ref(def_id)
365 .unwrap_or_else(|| bug!("issue33140_self_ty called on inherent impl {:?}", def_id));
367 debug!("issue33140_self_ty({:?}), trait-ref={:?}", def_id, trait_ref);
369 let is_marker_like = tcx.impl_polarity(def_id) == ty::ImplPolarity::Positive
370 && tcx.associated_item_def_ids(trait_ref.def_id).is_empty();
372 // Check whether these impls would be ok for a marker trait.
374 debug!("issue33140_self_ty - not marker-like!");
378 // impl must be `impl Trait for dyn Marker1 + Marker2 + ...`
379 if trait_ref.substs.len() != 1 {
380 debug!("issue33140_self_ty - impl has substs!");
384 let predicates = tcx.predicates_of(def_id);
385 if predicates.parent.is_some() || !predicates.predicates.is_empty() {
386 debug!("issue33140_self_ty - impl has predicates {:?}!", predicates);
390 let self_ty = trait_ref.self_ty();
391 let self_ty_matches = match self_ty.kind() {
392 ty::Dynamic(ref data, re, _) if re.is_static() => data.principal().is_none(),
397 debug!("issue33140_self_ty - MATCHES!");
400 debug!("issue33140_self_ty - non-matching self type");
405 /// Check if a function is async.
406 fn asyncness(tcx: TyCtxt<'_>, def_id: DefId) -> hir::IsAsync {
407 let node = tcx.hir().get_by_def_id(def_id.expect_local());
408 if let Some(fn_kind) = node.fn_kind() { fn_kind.asyncness() } else { hir::IsAsync::NotAsync }
411 /// Don't call this directly: use ``tcx.conservative_is_privately_uninhabited`` instead.
412 pub fn conservative_is_privately_uninhabited_raw<'tcx>(
414 param_env_and: ty::ParamEnvAnd<'tcx, Ty<'tcx>>,
416 let (param_env, ty) = param_env_and.into_parts();
419 debug!("ty::Never =>");
422 ty::Adt(def, _) if def.is_union() => {
423 debug!("ty::Adt(def, _) if def.is_union() =>");
424 // For now, `union`s are never considered uninhabited.
427 ty::Adt(def, substs) => {
428 debug!("ty::Adt(def, _) if def.is_not_union() =>");
429 // Any ADT is uninhabited if either:
430 // (a) It has no variants (i.e. an empty `enum`);
431 // (b) Each of its variants (a single one in the case of a `struct`) has at least
432 // one uninhabited field.
433 def.variants().iter().all(|var| {
434 var.fields.iter().any(|field| {
435 let ty = tcx.bound_type_of(field.did).subst(tcx, substs);
436 tcx.conservative_is_privately_uninhabited(param_env.and(ty))
440 ty::Tuple(fields) => {
441 debug!("ty::Tuple(..) =>");
442 fields.iter().any(|ty| tcx.conservative_is_privately_uninhabited(param_env.and(ty)))
444 ty::Array(ty, len) => {
445 debug!("ty::Array(ty, len) =>");
446 match len.try_eval_usize(tcx, param_env) {
447 Some(0) | None => false,
448 // If the array is definitely non-empty, it's uninhabited if
449 // the type of its elements is uninhabited.
450 Some(1..) => tcx.conservative_is_privately_uninhabited(param_env.and(*ty)),
454 debug!("ty::Ref(..) =>");
455 // References to uninitialised memory is valid for any type, including
456 // uninhabited types, in unsafe code, so we treat all references as
467 pub fn provide(providers: &mut ty::query::Providers) {
468 *providers = ty::query::Providers {
470 adt_sized_constraint,
472 param_env_reveal_all_normalized,
473 instance_def_size_estimate,
476 conservative_is_privately_uninhabited: conservative_is_privately_uninhabited_raw,