1 use rustc_data_structures::fx::FxIndexSet;
3 use rustc_hir::def_id::DefId;
4 use rustc_middle::ty::{self, Binder, Predicate, PredicateKind, ToPredicate, Ty, TyCtxt};
5 use rustc_trait_selection::traits;
7 fn sized_constraint_for_ty<'tcx>(
9 adtdef: ty::AdtDef<'tcx>,
12 use rustc_type_ir::sty::TyKind::*;
14 let result = match ty.kind() {
15 Bool | Char | Int(..) | Uint(..) | Float(..) | RawPtr(..) | Ref(..) | FnDef(..)
16 | FnPtr(_) | Array(..) | Closure(..) | Generator(..) | Never => vec![],
18 Str | Dynamic(..) | Slice(_) | Foreign(..) | Error(_) | GeneratorWitness(..) => {
19 // these are never sized - return the target type
23 Tuple(ref tys) => match tys.last() {
25 Some(&ty) => sized_constraint_for_ty(tcx, adtdef, ty),
30 let adt_tys = adt.sized_constraint(tcx);
31 debug!("sized_constraint_for_ty({:?}) intermediate = {:?}", ty, adt_tys);
35 .map(|ty| adt_tys.rebind(*ty).subst(tcx, substs))
36 .flat_map(|ty| sized_constraint_for_ty(tcx, adtdef, ty))
40 Projection(..) | Opaque(..) => {
41 // must calculate explicitly.
42 // FIXME: consider special-casing always-Sized projections
47 // perf hack: if there is a `T: Sized` bound, then
48 // we know that `T` is Sized and do not need to check
51 let Some(sized_trait) = tcx.lang_items().sized_trait() else { return vec![ty] };
52 let sized_predicate = ty::Binder::dummy(ty::TraitRef {
54 substs: tcx.mk_substs_trait(ty, &[]),
58 let predicates = tcx.predicates_of(adtdef.did()).predicates;
59 if predicates.iter().any(|(p, _)| *p == sized_predicate) { vec![] } else { vec![ty] }
62 Placeholder(..) | Bound(..) | Infer(..) => {
63 bug!("unexpected type `{:?}` in sized_constraint_for_ty", ty)
66 debug!("sized_constraint_for_ty({:?}) = {:?}", ty, result);
70 fn impl_defaultness(tcx: TyCtxt<'_>, def_id: DefId) -> hir::Defaultness {
71 match tcx.hir().get_by_def_id(def_id.expect_local()) {
72 hir::Node::Item(hir::Item { kind: hir::ItemKind::Impl(impl_), .. }) => impl_.defaultness,
73 hir::Node::ImplItem(hir::ImplItem { defaultness, .. })
74 | hir::Node::TraitItem(hir::TraitItem { defaultness, .. }) => *defaultness,
76 bug!("`impl_defaultness` called on {:?}", node);
81 /// Calculates the `Sized` constraint.
83 /// In fact, there are only a few options for the types in the constraint:
84 /// - an obviously-unsized type
85 /// - a type parameter or projection whose Sizedness can't be known
86 /// - a tuple of type parameters or projections, if there are multiple
88 /// - an Error, if a type is infinitely sized
89 fn adt_sized_constraint(tcx: TyCtxt<'_>, def_id: DefId) -> &[Ty<'_>] {
90 if let Some(def_id) = def_id.as_local() {
91 if matches!(tcx.representability(def_id), ty::Representability::Infinite) {
92 return tcx.intern_type_list(&[tcx.ty_error()]);
95 let def = tcx.adt_def(def_id);
97 let result = tcx.mk_type_list(
100 .flat_map(|v| v.fields.last())
101 .flat_map(|f| sized_constraint_for_ty(tcx, def, tcx.type_of(f.did))),
104 debug!("adt_sized_constraint: {:?} => {:?}", def, result);
109 /// See `ParamEnv` struct definition for details.
110 fn param_env(tcx: TyCtxt<'_>, def_id: DefId) -> ty::ParamEnv<'_> {
111 // Compute the bounds on Self and the type parameters.
112 let ty::InstantiatedPredicates { mut predicates, .. } =
113 tcx.predicates_of(def_id).instantiate_identity(tcx);
115 // Finally, we have to normalize the bounds in the environment, in
116 // case they contain any associated type projections. This process
117 // can yield errors if the put in illegal associated types, like
118 // `<i32 as Foo>::Bar` where `i32` does not implement `Foo`. We
119 // report these errors right here; this doesn't actually feel
120 // right to me, because constructing the environment feels like a
121 // kind of an "idempotent" action, but I'm not sure where would be
122 // a better place. In practice, we construct environments for
123 // every fn once during type checking, and we'll abort if there
124 // are any errors at that point, so outside of type inference you can be
125 // sure that this will succeed without errors anyway.
127 if tcx.sess.opts.unstable_opts.chalk {
128 let environment = well_formed_types_in_env(tcx, def_id);
129 predicates.extend(environment);
132 let local_did = def_id.as_local();
133 let hir_id = local_did.map(|def_id| tcx.hir().local_def_id_to_hir_id(def_id));
135 // FIXME(consts): This is not exactly in line with the constness query.
136 let constness = match hir_id {
137 Some(hir_id) => match tcx.hir().get(hir_id) {
138 hir::Node::TraitItem(hir::TraitItem { kind: hir::TraitItemKind::Fn(..), .. })
139 if tcx.is_const_default_method(def_id) =>
141 hir::Constness::Const
144 hir::Node::Item(hir::Item { kind: hir::ItemKind::Const(..), .. })
145 | hir::Node::Item(hir::Item { kind: hir::ItemKind::Static(..), .. })
146 | hir::Node::TraitItem(hir::TraitItem {
147 kind: hir::TraitItemKind::Const(..), ..
149 | hir::Node::AnonConst(_)
150 | hir::Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Const(..), .. })
151 | hir::Node::ImplItem(hir::ImplItem {
153 hir::ImplItemKind::Fn(
155 header: hir::FnHeader { constness: hir::Constness::Const, .. },
161 }) => hir::Constness::Const,
163 hir::Node::ImplItem(hir::ImplItem {
164 kind: hir::ImplItemKind::Type(..) | hir::ImplItemKind::Fn(..),
167 let parent_hir_id = tcx.hir().get_parent_node(hir_id);
168 match tcx.hir().get(parent_hir_id) {
169 hir::Node::Item(hir::Item {
170 kind: hir::ItemKind::Impl(hir::Impl { constness, .. }),
174 tcx.def_span(parent_hir_id.owner),
175 "impl item's parent node is not an impl",
180 hir::Node::Item(hir::Item {
182 hir::ItemKind::Fn(hir::FnSig { header: hir::FnHeader { constness, .. }, .. }, ..),
185 | hir::Node::TraitItem(hir::TraitItem {
187 hir::TraitItemKind::Fn(
188 hir::FnSig { header: hir::FnHeader { constness, .. }, .. },
193 | hir::Node::Item(hir::Item {
194 kind: hir::ItemKind::Impl(hir::Impl { constness, .. }),
198 _ => hir::Constness::NotConst,
200 // FIXME(consts): It's suspicious that a param-env for a foreign item
201 // will always have NotConst param-env, though we don't typically use
202 // that param-env for anything meaningful right now, so it's likely
204 None => hir::Constness::NotConst,
207 let unnormalized_env = ty::ParamEnv::new(
208 tcx.intern_predicates(&predicates),
209 traits::Reveal::UserFacing,
214 local_did.and_then(|id| tcx.hir().maybe_body_owned_by(id).map(|body| body.hir_id));
215 let body_id = match body_id {
217 None if hir_id.is_some() => hir_id.unwrap(),
218 _ => hir::CRATE_HIR_ID,
221 let cause = traits::ObligationCause::misc(tcx.def_span(def_id), body_id);
222 traits::normalize_param_env_or_error(tcx, unnormalized_env, cause)
225 /// Elaborate the environment.
227 /// Collect a list of `Predicate`'s used for building the `ParamEnv`. Adds `TypeWellFormedFromEnv`'s
228 /// that are assumed to be well-formed (because they come from the environment).
230 /// Used only in chalk mode.
231 fn well_formed_types_in_env<'tcx>(
234 ) -> &'tcx ty::List<Predicate<'tcx>> {
235 use rustc_hir::{ForeignItemKind, ImplItemKind, ItemKind, Node, TraitItemKind};
236 use rustc_middle::ty::subst::GenericArgKind;
238 debug!("environment(def_id = {:?})", def_id);
240 // The environment of an impl Trait type is its defining function's environment.
241 if let Some(parent) = ty::is_impl_trait_defn(tcx, def_id) {
242 return well_formed_types_in_env(tcx, parent.to_def_id());
245 // Compute the bounds on `Self` and the type parameters.
246 let ty::InstantiatedPredicates { predicates, .. } =
247 tcx.predicates_of(def_id).instantiate_identity(tcx);
249 let clauses = predicates.into_iter();
251 if !def_id.is_local() {
252 return ty::List::empty();
254 let node = tcx.hir().get_by_def_id(def_id.expect_local());
263 let node_kind = match node {
264 Node::TraitItem(item) => match item.kind {
265 TraitItemKind::Fn(..) => NodeKind::Fn,
266 _ => NodeKind::Other,
269 Node::ImplItem(item) => match item.kind {
270 ImplItemKind::Fn(..) => NodeKind::Fn,
271 _ => NodeKind::Other,
274 Node::Item(item) => match item.kind {
275 ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }) => NodeKind::TraitImpl,
276 ItemKind::Impl(hir::Impl { of_trait: None, .. }) => NodeKind::InherentImpl,
277 ItemKind::Fn(..) => NodeKind::Fn,
278 _ => NodeKind::Other,
281 Node::ForeignItem(item) => match item.kind {
282 ForeignItemKind::Fn(..) => NodeKind::Fn,
283 _ => NodeKind::Other,
287 _ => NodeKind::Other,
290 // FIXME(eddyb) isn't the unordered nature of this a hazard?
291 let mut inputs = FxIndexSet::default();
294 // In a trait impl, we assume that the header trait ref and all its
295 // constituents are well-formed.
296 NodeKind::TraitImpl => {
297 let trait_ref = tcx.impl_trait_ref(def_id).expect("not an impl");
299 // FIXME(chalk): this has problems because of late-bound regions
300 //inputs.extend(trait_ref.substs.iter().flat_map(|arg| arg.walk()));
301 inputs.extend(trait_ref.substs.iter());
304 // In an inherent impl, we assume that the receiver type and all its
305 // constituents are well-formed.
306 NodeKind::InherentImpl => {
307 let self_ty = tcx.type_of(def_id);
308 inputs.extend(self_ty.walk());
311 // In an fn, we assume that the arguments and all their constituents are
314 let fn_sig = tcx.fn_sig(def_id);
315 let fn_sig = tcx.liberate_late_bound_regions(def_id, fn_sig);
317 inputs.extend(fn_sig.inputs().iter().flat_map(|ty| ty.walk()));
320 NodeKind::Other => (),
322 let input_clauses = inputs.into_iter().filter_map(|arg| {
324 GenericArgKind::Type(ty) => {
325 let binder = Binder::dummy(PredicateKind::TypeWellFormedFromEnv(ty));
326 Some(tcx.mk_predicate(binder))
329 // FIXME(eddyb) no WF conditions from lifetimes?
330 GenericArgKind::Lifetime(_) => None,
332 // FIXME(eddyb) support const generics in Chalk
333 GenericArgKind::Const(_) => None,
337 tcx.mk_predicates(clauses.chain(input_clauses))
340 fn param_env_reveal_all_normalized(tcx: TyCtxt<'_>, def_id: DefId) -> ty::ParamEnv<'_> {
341 tcx.param_env(def_id).with_reveal_all_normalized(tcx)
344 fn instance_def_size_estimate<'tcx>(
346 instance_def: ty::InstanceDef<'tcx>,
351 InstanceDef::Item(..) | InstanceDef::DropGlue(..) => {
352 let mir = tcx.instance_mir(instance_def);
353 mir.basic_blocks.iter().map(|bb| bb.statements.len() + 1).sum()
355 // Estimate the size of other compiler-generated shims to be 1.
360 /// If `def_id` is an issue 33140 hack impl, returns its self type; otherwise, returns `None`.
362 /// See [`ty::ImplOverlapKind::Issue33140`] for more details.
363 fn issue33140_self_ty(tcx: TyCtxt<'_>, def_id: DefId) -> Option<Ty<'_>> {
364 debug!("issue33140_self_ty({:?})", def_id);
367 .impl_trait_ref(def_id)
368 .unwrap_or_else(|| bug!("issue33140_self_ty called on inherent impl {:?}", def_id));
370 debug!("issue33140_self_ty({:?}), trait-ref={:?}", def_id, trait_ref);
372 let is_marker_like = tcx.impl_polarity(def_id) == ty::ImplPolarity::Positive
373 && tcx.associated_item_def_ids(trait_ref.def_id).is_empty();
375 // Check whether these impls would be ok for a marker trait.
377 debug!("issue33140_self_ty - not marker-like!");
381 // impl must be `impl Trait for dyn Marker1 + Marker2 + ...`
382 if trait_ref.substs.len() != 1 {
383 debug!("issue33140_self_ty - impl has substs!");
387 let predicates = tcx.predicates_of(def_id);
388 if predicates.parent.is_some() || !predicates.predicates.is_empty() {
389 debug!("issue33140_self_ty - impl has predicates {:?}!", predicates);
393 let self_ty = trait_ref.self_ty();
394 let self_ty_matches = match self_ty.kind() {
395 ty::Dynamic(ref data, re, _) if re.is_static() => data.principal().is_none(),
400 debug!("issue33140_self_ty - MATCHES!");
403 debug!("issue33140_self_ty - non-matching self type");
408 /// Check if a function is async.
409 fn asyncness(tcx: TyCtxt<'_>, def_id: DefId) -> hir::IsAsync {
410 let node = tcx.hir().get_by_def_id(def_id.expect_local());
411 node.fn_sig().map_or(hir::IsAsync::NotAsync, |sig| sig.header.asyncness)
414 pub fn provide(providers: &mut ty::query::Providers) {
415 *providers = ty::query::Providers {
417 adt_sized_constraint,
419 param_env_reveal_all_normalized,
420 instance_def_size_estimate,