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_span::{sym, Span};
7 use rustc_trait_selection::traits;
9 fn sized_constraint_for_ty<'tcx>(
11 adtdef: ty::AdtDef<'tcx>,
16 let result = match ty.kind() {
17 Bool | Char | Int(..) | Uint(..) | Float(..) | RawPtr(..) | Ref(..) | FnDef(..)
18 | FnPtr(_) | Array(..) | Closure(..) | Generator(..) | Never => vec![],
20 Str | Dynamic(..) | Slice(_) | Foreign(..) | Error(_) | GeneratorWitness(..) => {
21 // these are never sized - return the target type
25 Tuple(ref tys) => match tys.last() {
27 Some(&ty) => sized_constraint_for_ty(tcx, adtdef, ty),
32 let adt_tys = adt.sized_constraint(tcx);
33 debug!("sized_constraint_for_ty({:?}) intermediate = {:?}", ty, adt_tys);
36 .map(|ty| 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 let item = tcx.hir().expect_item(def_id.expect_local());
73 if let hir::ItemKind::Impl(impl_) = &item.kind {
76 bug!("`impl_defaultness` called on {:?}", item);
80 /// Calculates the `Sized` constraint.
82 /// In fact, there are only a few options for the types in the constraint:
83 /// - an obviously-unsized type
84 /// - a type parameter or projection whose Sizedness can't be known
85 /// - a tuple of type parameters or projections, if there are multiple
87 /// - an Error, if a type contained itself. The representability
88 /// check should catch this case.
89 fn adt_sized_constraint(tcx: TyCtxt<'_>, def_id: DefId) -> ty::AdtSizedConstraint<'_> {
90 let def = tcx.adt_def(def_id);
92 let result = tcx.mk_type_list(
95 .flat_map(|v| v.fields.last())
96 .flat_map(|f| sized_constraint_for_ty(tcx, def, tcx.type_of(f.did))),
99 debug!("adt_sized_constraint: {:?} => {:?}", def, result);
101 ty::AdtSizedConstraint(result)
104 fn def_ident_span(tcx: TyCtxt<'_>, def_id: DefId) -> Option<Span> {
106 .get_if_local(def_id)
107 .and_then(|node| match node {
108 // A `Ctor` doesn't have an identifier itself, but its parent
109 // struct/variant does. Compare with `hir::Map::opt_span`.
110 hir::Node::Ctor(ctor) => ctor
112 .and_then(|ctor_id| tcx.hir().find(tcx.hir().get_parent_node(ctor_id)))
113 .and_then(|parent| parent.ident()),
116 .map(|ident| ident.span)
119 /// See `ParamEnv` struct definition for details.
120 #[instrument(level = "debug", skip(tcx))]
121 fn param_env(tcx: TyCtxt<'_>, def_id: DefId) -> ty::ParamEnv<'_> {
122 // The param_env of an impl Trait type is its defining function's param_env
123 if let Some(parent) = ty::is_impl_trait_defn(tcx, def_id) {
124 return param_env(tcx, parent.to_def_id());
126 // Compute the bounds on Self and the type parameters.
128 let ty::InstantiatedPredicates { mut predicates, .. } =
129 tcx.predicates_of(def_id).instantiate_identity(tcx);
131 // Finally, we have to normalize the bounds in the environment, in
132 // case they contain any associated type projections. This process
133 // can yield errors if the put in illegal associated types, like
134 // `<i32 as Foo>::Bar` where `i32` does not implement `Foo`. We
135 // report these errors right here; this doesn't actually feel
136 // right to me, because constructing the environment feels like a
137 // kind of an "idempotent" action, but I'm not sure where would be
138 // a better place. In practice, we construct environments for
139 // every fn once during type checking, and we'll abort if there
140 // are any errors at that point, so outside of type inference you can be
141 // sure that this will succeed without errors anyway.
143 if tcx.sess.opts.debugging_opts.chalk {
144 let environment = well_formed_types_in_env(tcx, def_id);
145 predicates.extend(environment);
148 let local_did = def_id.as_local();
149 let hir_id = local_did.map(|def_id| tcx.hir().local_def_id_to_hir_id(def_id));
151 let constness = match hir_id {
152 Some(hir_id) => match tcx.hir().get(hir_id) {
153 hir::Node::TraitItem(hir::TraitItem { kind: hir::TraitItemKind::Fn(..), .. })
154 if tcx.has_attr(def_id, sym::default_method_body_is_const) =>
156 hir::Constness::Const
159 hir::Node::Item(hir::Item { kind: hir::ItemKind::Const(..), .. })
160 | hir::Node::Item(hir::Item { kind: hir::ItemKind::Static(..), .. })
161 | hir::Node::TraitItem(hir::TraitItem {
162 kind: hir::TraitItemKind::Const(..), ..
164 | hir::Node::AnonConst(_)
165 | hir::Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Const(..), .. })
166 | hir::Node::ImplItem(hir::ImplItem {
168 hir::ImplItemKind::Fn(
170 header: hir::FnHeader { constness: hir::Constness::Const, .. },
176 }) => hir::Constness::Const,
178 hir::Node::ImplItem(hir::ImplItem {
179 kind: hir::ImplItemKind::TyAlias(..) | hir::ImplItemKind::Fn(..),
182 let parent_hir_id = tcx.hir().get_parent_node(hir_id);
183 match tcx.hir().get(parent_hir_id) {
184 hir::Node::Item(hir::Item {
185 kind: hir::ItemKind::Impl(hir::Impl { constness, .. }),
189 tcx.def_span(parent_hir_id.owner),
190 "impl item's parent node is not an impl",
195 hir::Node::Item(hir::Item {
197 hir::ItemKind::Fn(hir::FnSig { header: hir::FnHeader { constness, .. }, .. }, ..),
200 | hir::Node::TraitItem(hir::TraitItem {
202 hir::TraitItemKind::Fn(
203 hir::FnSig { header: hir::FnHeader { constness, .. }, .. },
208 | hir::Node::Item(hir::Item {
209 kind: hir::ItemKind::Impl(hir::Impl { constness, .. }),
213 _ => hir::Constness::NotConst,
215 None => hir::Constness::NotConst,
218 let unnormalized_env = ty::ParamEnv::new(
219 tcx.intern_predicates(&predicates),
220 traits::Reveal::UserFacing,
224 let body_id = hir_id.map_or(hir::CRATE_HIR_ID, |id| {
225 tcx.hir().maybe_body_owned_by(id).map_or(id, |body| body.hir_id)
227 let cause = traits::ObligationCause::misc(tcx.def_span(def_id), body_id);
228 traits::normalize_param_env_or_error(tcx, def_id, unnormalized_env, cause)
231 /// Elaborate the environment.
233 /// Collect a list of `Predicate`'s used for building the `ParamEnv`. Adds `TypeWellFormedFromEnv`'s
234 /// that are assumed to be well-formed (because they come from the environment).
236 /// Used only in chalk mode.
237 fn well_formed_types_in_env<'tcx>(
240 ) -> &'tcx ty::List<Predicate<'tcx>> {
241 use rustc_hir::{ForeignItemKind, ImplItemKind, ItemKind, Node, TraitItemKind};
242 use rustc_middle::ty::subst::GenericArgKind;
244 debug!("environment(def_id = {:?})", def_id);
246 // The environment of an impl Trait type is its defining function's environment.
247 if let Some(parent) = ty::is_impl_trait_defn(tcx, def_id) {
248 return well_formed_types_in_env(tcx, parent.to_def_id());
251 // Compute the bounds on `Self` and the type parameters.
252 let ty::InstantiatedPredicates { predicates, .. } =
253 tcx.predicates_of(def_id).instantiate_identity(tcx);
255 let clauses = predicates.into_iter();
257 if !def_id.is_local() {
258 return ty::List::empty();
260 let node = tcx.hir().get_by_def_id(def_id.expect_local());
269 let node_kind = match node {
270 Node::TraitItem(item) => match item.kind {
271 TraitItemKind::Fn(..) => NodeKind::Fn,
272 _ => NodeKind::Other,
275 Node::ImplItem(item) => match item.kind {
276 ImplItemKind::Fn(..) => NodeKind::Fn,
277 _ => NodeKind::Other,
280 Node::Item(item) => match item.kind {
281 ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }) => NodeKind::TraitImpl,
282 ItemKind::Impl(hir::Impl { of_trait: None, .. }) => NodeKind::InherentImpl,
283 ItemKind::Fn(..) => NodeKind::Fn,
284 _ => NodeKind::Other,
287 Node::ForeignItem(item) => match item.kind {
288 ForeignItemKind::Fn(..) => NodeKind::Fn,
289 _ => NodeKind::Other,
293 _ => NodeKind::Other,
296 // FIXME(eddyb) isn't the unordered nature of this a hazard?
297 let mut inputs = FxIndexSet::default();
300 // In a trait impl, we assume that the header trait ref and all its
301 // constituents are well-formed.
302 NodeKind::TraitImpl => {
303 let trait_ref = tcx.impl_trait_ref(def_id).expect("not an impl");
305 // FIXME(chalk): this has problems because of late-bound regions
306 //inputs.extend(trait_ref.substs.iter().flat_map(|arg| arg.walk()));
307 inputs.extend(trait_ref.substs.iter());
310 // In an inherent impl, we assume that the receiver type and all its
311 // constituents are well-formed.
312 NodeKind::InherentImpl => {
313 let self_ty = tcx.type_of(def_id);
314 inputs.extend(self_ty.walk());
317 // In an fn, we assume that the arguments and all their constituents are
320 let fn_sig = tcx.fn_sig(def_id);
321 let fn_sig = tcx.liberate_late_bound_regions(def_id, fn_sig);
323 inputs.extend(fn_sig.inputs().iter().flat_map(|ty| ty.walk()));
326 NodeKind::Other => (),
328 let input_clauses = inputs.into_iter().filter_map(|arg| {
330 GenericArgKind::Type(ty) => {
331 let binder = Binder::dummy(PredicateKind::TypeWellFormedFromEnv(ty));
332 Some(tcx.mk_predicate(binder))
335 // FIXME(eddyb) no WF conditions from lifetimes?
336 GenericArgKind::Lifetime(_) => None,
338 // FIXME(eddyb) support const generics in Chalk
339 GenericArgKind::Const(_) => None,
343 tcx.mk_predicates(clauses.chain(input_clauses))
346 fn param_env_reveal_all_normalized(tcx: TyCtxt<'_>, def_id: DefId) -> ty::ParamEnv<'_> {
347 tcx.param_env(def_id).with_reveal_all_normalized(tcx)
350 fn instance_def_size_estimate<'tcx>(
352 instance_def: ty::InstanceDef<'tcx>,
357 InstanceDef::Item(..) | InstanceDef::DropGlue(..) => {
358 let mir = tcx.instance_mir(instance_def);
359 mir.basic_blocks().iter().map(|bb| bb.statements.len() + 1).sum()
361 // Estimate the size of other compiler-generated shims to be 1.
366 /// If `def_id` is an issue 33140 hack impl, returns its self type; otherwise, returns `None`.
368 /// See [`ty::ImplOverlapKind::Issue33140`] for more details.
369 fn issue33140_self_ty(tcx: TyCtxt<'_>, def_id: DefId) -> Option<Ty<'_>> {
370 debug!("issue33140_self_ty({:?})", def_id);
373 .impl_trait_ref(def_id)
374 .unwrap_or_else(|| bug!("issue33140_self_ty called on inherent impl {:?}", def_id));
376 debug!("issue33140_self_ty({:?}), trait-ref={:?}", def_id, trait_ref);
378 let is_marker_like = tcx.impl_polarity(def_id) == ty::ImplPolarity::Positive
379 && tcx.associated_item_def_ids(trait_ref.def_id).is_empty();
381 // Check whether these impls would be ok for a marker trait.
383 debug!("issue33140_self_ty - not marker-like!");
387 // impl must be `impl Trait for dyn Marker1 + Marker2 + ...`
388 if trait_ref.substs.len() != 1 {
389 debug!("issue33140_self_ty - impl has substs!");
393 let predicates = tcx.predicates_of(def_id);
394 if predicates.parent.is_some() || !predicates.predicates.is_empty() {
395 debug!("issue33140_self_ty - impl has predicates {:?}!", predicates);
399 let self_ty = trait_ref.self_ty();
400 let self_ty_matches = match self_ty.kind() {
401 ty::Dynamic(ref data, re) if re.is_static() => data.principal().is_none(),
406 debug!("issue33140_self_ty - MATCHES!");
409 debug!("issue33140_self_ty - non-matching self type");
414 /// Check if a function is async.
415 fn asyncness(tcx: TyCtxt<'_>, def_id: DefId) -> hir::IsAsync {
416 let node = tcx.hir().get_by_def_id(def_id.expect_local());
418 let fn_kind = node.fn_kind().unwrap_or_else(|| {
419 bug!("asyncness: expected fn-like node but got `{:?}`", def_id);
425 /// Don't call this directly: use ``tcx.conservative_is_privately_uninhabited`` instead.
426 #[instrument(level = "debug", skip(tcx))]
427 pub fn conservative_is_privately_uninhabited_raw<'tcx>(
429 param_env_and: ty::ParamEnvAnd<'tcx, Ty<'tcx>>,
431 let (param_env, ty) = param_env_and.into_parts();
434 debug!("ty::Never =>");
437 ty::Adt(def, _) if def.is_union() => {
438 debug!("ty::Adt(def, _) if def.is_union() =>");
439 // For now, `union`s are never considered uninhabited.
442 ty::Adt(def, substs) => {
443 debug!("ty::Adt(def, _) if def.is_not_union() =>");
444 // Any ADT is uninhabited if either:
445 // (a) It has no variants (i.e. an empty `enum`);
446 // (b) Each of its variants (a single one in the case of a `struct`) has at least
447 // one uninhabited field.
448 def.variants().iter().all(|var| {
449 var.fields.iter().any(|field| {
450 let ty = tcx.type_of(field.did).subst(tcx, substs);
451 tcx.conservative_is_privately_uninhabited(param_env.and(ty))
455 ty::Tuple(fields) => {
456 debug!("ty::Tuple(..) =>");
457 fields.iter().any(|ty| tcx.conservative_is_privately_uninhabited(param_env.and(ty)))
459 ty::Array(ty, len) => {
460 debug!("ty::Array(ty, len) =>");
461 match len.try_eval_usize(tcx, param_env) {
462 Some(0) | None => false,
463 // If the array is definitely non-empty, it's uninhabited if
464 // the type of its elements is uninhabited.
465 Some(1..) => tcx.conservative_is_privately_uninhabited(param_env.and(*ty)),
469 debug!("ty::Ref(..) =>");
470 // References to uninitialised memory is valid for any type, including
471 // uninhabited types, in unsafe code, so we treat all references as
482 pub fn provide(providers: &mut ty::query::Providers) {
483 *providers = ty::query::Providers {
485 adt_sized_constraint,
488 param_env_reveal_all_normalized,
489 instance_def_size_estimate,
492 conservative_is_privately_uninhabited: conservative_is_privately_uninhabited_raw,