1 use rustc_data_structures::svh::Svh;
3 use rustc_hir::def_id::{CrateNum, DefId, LocalDefId, LOCAL_CRATE};
4 use rustc_middle::hir::map as hir_map;
5 use rustc_middle::ty::subst::Subst;
6 use rustc_middle::ty::{self, ToPredicate, Ty, TyCtxt, WithConstness};
7 use rustc_session::CrateDisambiguator;
8 use rustc_span::symbol::Symbol;
10 use rustc_trait_selection::traits;
12 fn sized_constraint_for_ty<'tcx>(
19 let result = match ty.kind {
20 Bool | Char | Int(..) | Uint(..) | Float(..) | RawPtr(..) | Ref(..) | FnDef(..)
21 | FnPtr(_) | Array(..) | Closure(..) | Generator(..) | Never => vec![],
23 Str | Dynamic(..) | Slice(_) | Foreign(..) | Error | GeneratorWitness(..) => {
24 // these are never sized - return the target type
28 Tuple(ref tys) => match tys.last() {
30 Some(ty) => sized_constraint_for_ty(tcx, adtdef, ty.expect_ty()),
35 let adt_tys = adt.sized_constraint(tcx);
36 debug!("sized_constraint_for_ty({:?}) intermediate = {:?}", ty, adt_tys);
39 .map(|ty| ty.subst(tcx, substs))
40 .flat_map(|ty| sized_constraint_for_ty(tcx, adtdef, ty))
44 Projection(..) | Opaque(..) => {
45 // must calculate explicitly.
46 // FIXME: consider special-casing always-Sized projections
50 UnnormalizedProjection(..) => bug!("only used with chalk-engine"),
53 // perf hack: if there is a `T: Sized` bound, then
54 // we know that `T` is Sized and do not need to check
57 let sized_trait = match tcx.lang_items().sized_trait() {
61 let sized_predicate = ty::Binder::dummy(ty::TraitRef {
63 substs: tcx.mk_substs_trait(ty, &[]),
67 let predicates = tcx.predicates_of(adtdef.did).predicates;
68 if predicates.iter().any(|(p, _)| *p == sized_predicate) { vec![] } else { vec![ty] }
71 Placeholder(..) | Bound(..) | Infer(..) => {
72 bug!("unexpected type `{:?}` in sized_constraint_for_ty", ty)
75 debug!("sized_constraint_for_ty({:?}) = {:?}", ty, result);
79 fn associated_item_from_trait_item_ref(
81 parent_def_id: LocalDefId,
82 parent_vis: &hir::Visibility<'_>,
83 trait_item_ref: &hir::TraitItemRef,
85 let def_id = tcx.hir().local_def_id(trait_item_ref.id.hir_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),
90 hir::AssocItemKind::OpaqueTy => bug!("only impls can have opaque types"),
94 ident: trait_item_ref.ident,
96 // Visibility of trait items is inherited from their traits.
97 vis: ty::Visibility::from_hir(parent_vis, trait_item_ref.id.hir_id, tcx),
98 defaultness: trait_item_ref.defaultness,
99 def_id: def_id.to_def_id(),
100 container: ty::TraitContainer(parent_def_id.to_def_id()),
101 fn_has_self_parameter: has_self,
105 fn associated_item_from_impl_item_ref(
107 parent_def_id: LocalDefId,
108 impl_item_ref: &hir::ImplItemRef<'_>,
110 let def_id = tcx.hir().local_def_id(impl_item_ref.id.hir_id);
111 let (kind, has_self) = match impl_item_ref.kind {
112 hir::AssocItemKind::Const => (ty::AssocKind::Const, false),
113 hir::AssocItemKind::Fn { has_self } => (ty::AssocKind::Fn, has_self),
114 hir::AssocItemKind::Type => (ty::AssocKind::Type, false),
115 hir::AssocItemKind::OpaqueTy => (ty::AssocKind::OpaqueTy, false),
119 ident: impl_item_ref.ident,
121 // Visibility of trait impl items doesn't matter.
122 vis: ty::Visibility::from_hir(&impl_item_ref.vis, impl_item_ref.id.hir_id, tcx),
123 defaultness: impl_item_ref.defaultness,
124 def_id: def_id.to_def_id(),
125 container: ty::ImplContainer(parent_def_id.to_def_id()),
126 fn_has_self_parameter: has_self,
130 fn associated_item(tcx: TyCtxt<'_>, def_id: DefId) -> ty::AssocItem {
131 let id = tcx.hir().as_local_hir_id(def_id.expect_local());
132 let parent_id = tcx.hir().get_parent_item(id);
133 let parent_def_id = tcx.hir().local_def_id(parent_id);
134 let parent_item = tcx.hir().expect_item(parent_id);
135 match parent_item.kind {
136 hir::ItemKind::Impl { ref items, .. } => {
137 if let Some(impl_item_ref) = items.iter().find(|i| i.id.hir_id == id) {
139 associated_item_from_impl_item_ref(tcx, parent_def_id, impl_item_ref);
140 debug_assert_eq!(assoc_item.def_id, def_id);
145 hir::ItemKind::Trait(.., ref trait_item_refs) => {
146 if let Some(trait_item_ref) = trait_item_refs.iter().find(|i| i.id.hir_id == id) {
147 let assoc_item = associated_item_from_trait_item_ref(
153 debug_assert_eq!(assoc_item.def_id, def_id);
163 "unexpected parent of trait or impl item or item not found: {:?}",
168 fn impl_defaultness(tcx: TyCtxt<'_>, def_id: DefId) -> hir::Defaultness {
169 let hir_id = tcx.hir().as_local_hir_id(def_id.expect_local());
170 let item = tcx.hir().expect_item(hir_id);
171 if let hir::ItemKind::Impl { defaultness, .. } = item.kind {
174 bug!("`impl_defaultness` called on {:?}", item);
178 /// Calculates the `Sized` constraint.
180 /// In fact, there are only a few options for the types in the constraint:
181 /// - an obviously-unsized type
182 /// - a type parameter or projection whose Sizedness can't be known
183 /// - a tuple of type parameters or projections, if there are multiple
185 /// - a Error, if a type contained itself. The representability
186 /// check should catch this case.
187 fn adt_sized_constraint(tcx: TyCtxt<'_>, def_id: DefId) -> ty::AdtSizedConstraint<'_> {
188 let def = tcx.adt_def(def_id);
190 let result = tcx.mk_type_list(
193 .flat_map(|v| v.fields.last())
194 .flat_map(|f| sized_constraint_for_ty(tcx, def, tcx.type_of(f.did))),
197 debug!("adt_sized_constraint: {:?} => {:?}", def, result);
199 ty::AdtSizedConstraint(result)
202 fn associated_item_def_ids(tcx: TyCtxt<'_>, def_id: DefId) -> &[DefId] {
203 let id = tcx.hir().as_local_hir_id(def_id.expect_local());
204 let item = tcx.hir().expect_item(id);
206 hir::ItemKind::Trait(.., ref trait_item_refs) => tcx.arena.alloc_from_iter(
209 .map(|trait_item_ref| trait_item_ref.id)
210 .map(|id| tcx.hir().local_def_id(id.hir_id).to_def_id()),
212 hir::ItemKind::Impl { ref items, .. } => tcx.arena.alloc_from_iter(
215 .map(|impl_item_ref| impl_item_ref.id)
216 .map(|id| tcx.hir().local_def_id(id.hir_id).to_def_id()),
218 hir::ItemKind::TraitAlias(..) => &[],
219 _ => span_bug!(item.span, "associated_item_def_ids: not impl or trait"),
223 fn associated_items(tcx: TyCtxt<'_>, def_id: DefId) -> ty::AssociatedItems<'_> {
224 let items = tcx.associated_item_def_ids(def_id).iter().map(|did| tcx.associated_item(*did));
225 ty::AssociatedItems::new(items)
228 fn def_span(tcx: TyCtxt<'_>, def_id: DefId) -> Span {
229 tcx.hir().span_if_local(def_id).unwrap()
232 /// If the given `DefId` describes an item belonging to a trait,
233 /// returns the `DefId` of the trait that the trait item belongs to;
234 /// otherwise, returns `None`.
235 fn trait_of_item(tcx: TyCtxt<'_>, def_id: DefId) -> Option<DefId> {
236 tcx.opt_associated_item(def_id).and_then(|associated_item| match associated_item.container {
237 ty::TraitContainer(def_id) => Some(def_id),
238 ty::ImplContainer(_) => None,
242 /// See `ParamEnv` struct definition for details.
243 fn param_env(tcx: TyCtxt<'_>, def_id: DefId) -> ty::ParamEnv<'_> {
244 // The param_env of an impl Trait type is its defining function's param_env
245 if let Some(parent) = ty::is_impl_trait_defn(tcx, def_id) {
246 return param_env(tcx, parent);
248 // Compute the bounds on Self and the type parameters.
250 let ty::InstantiatedPredicates { predicates, .. } =
251 tcx.predicates_of(def_id).instantiate_identity(tcx);
253 // Finally, we have to normalize the bounds in the environment, in
254 // case they contain any associated type projections. This process
255 // can yield errors if the put in illegal associated types, like
256 // `<i32 as Foo>::Bar` where `i32` does not implement `Foo`. We
257 // report these errors right here; this doesn't actually feel
258 // right to me, because constructing the environment feels like a
259 // kind of a "idempotent" action, but I'm not sure where would be
260 // a better place. In practice, we construct environments for
261 // every fn once during type checking, and we'll abort if there
262 // are any errors at that point, so after type checking you can be
263 // sure that this will succeed without errors anyway.
265 let unnormalized_env =
266 ty::ParamEnv::new(tcx.intern_predicates(&predicates), traits::Reveal::UserFacing, None);
270 .map(|def_id| tcx.hir().as_local_hir_id(def_id))
271 .map_or(hir::CRATE_HIR_ID, |id| {
272 tcx.hir().maybe_body_owned_by(id).map_or(id, |body| body.hir_id)
274 let cause = traits::ObligationCause::misc(tcx.def_span(def_id), body_id);
275 traits::normalize_param_env_or_error(tcx, def_id, unnormalized_env, cause)
278 fn crate_disambiguator(tcx: TyCtxt<'_>, crate_num: CrateNum) -> CrateDisambiguator {
279 assert_eq!(crate_num, LOCAL_CRATE);
280 tcx.sess.local_crate_disambiguator()
283 fn original_crate_name(tcx: TyCtxt<'_>, crate_num: CrateNum) -> Symbol {
284 assert_eq!(crate_num, LOCAL_CRATE);
288 fn crate_hash(tcx: TyCtxt<'_>, crate_num: CrateNum) -> Svh {
289 tcx.index_hir(crate_num).crate_hash
292 fn instance_def_size_estimate<'tcx>(
294 instance_def: ty::InstanceDef<'tcx>,
299 InstanceDef::Item(..) | InstanceDef::DropGlue(..) => {
300 let mir = tcx.instance_mir(instance_def);
301 mir.basic_blocks().iter().map(|bb| bb.statements.len()).sum()
303 // Estimate the size of other compiler-generated shims to be 1.
308 /// If `def_id` is an issue 33140 hack impl, returns its self type; otherwise, returns `None`.
310 /// See [`ty::ImplOverlapKind::Issue33140`] for more details.
311 fn issue33140_self_ty(tcx: TyCtxt<'_>, def_id: DefId) -> Option<Ty<'_>> {
312 debug!("issue33140_self_ty({:?})", def_id);
315 .impl_trait_ref(def_id)
316 .unwrap_or_else(|| bug!("issue33140_self_ty called on inherent impl {:?}", def_id));
318 debug!("issue33140_self_ty({:?}), trait-ref={:?}", def_id, trait_ref);
320 let is_marker_like = tcx.impl_polarity(def_id) == ty::ImplPolarity::Positive
321 && tcx.associated_item_def_ids(trait_ref.def_id).is_empty();
323 // Check whether these impls would be ok for a marker trait.
325 debug!("issue33140_self_ty - not marker-like!");
329 // impl must be `impl Trait for dyn Marker1 + Marker2 + ...`
330 if trait_ref.substs.len() != 1 {
331 debug!("issue33140_self_ty - impl has substs!");
335 let predicates = tcx.predicates_of(def_id);
336 if predicates.parent.is_some() || !predicates.predicates.is_empty() {
337 debug!("issue33140_self_ty - impl has predicates {:?}!", predicates);
341 let self_ty = trait_ref.self_ty();
342 let self_ty_matches = match self_ty.kind {
343 ty::Dynamic(ref data, ty::ReStatic) => data.principal().is_none(),
348 debug!("issue33140_self_ty - MATCHES!");
351 debug!("issue33140_self_ty - non-matching self type");
356 /// Check if a function is async.
357 fn asyncness(tcx: TyCtxt<'_>, def_id: DefId) -> hir::IsAsync {
358 let hir_id = tcx.hir().as_local_hir_id(def_id.expect_local());
360 let node = tcx.hir().get(hir_id);
362 let fn_like = hir_map::blocks::FnLikeNode::from_node(node).unwrap_or_else(|| {
363 bug!("asyncness: expected fn-like node but got `{:?}`", def_id);
369 pub fn provide(providers: &mut ty::query::Providers<'_>) {
370 *providers = ty::query::Providers {
373 associated_item_def_ids,
375 adt_sized_constraint,
382 instance_def_size_estimate,