1 use rustc::hir::map as hir_map;
2 use rustc::session::CrateDisambiguator;
3 use rustc::ty::subst::Subst;
4 use rustc::ty::{self, ToPredicate, Ty, TyCtxt, WithConstness};
5 use rustc_data_structures::svh::Svh;
7 use rustc_hir::def_id::{CrateNum, DefId, LOCAL_CRATE};
8 use rustc_infer::traits;
9 use rustc_span::symbol::Symbol;
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(
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::Method { has_self } => (ty::AssocKind::Method, 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,
100 container: ty::TraitContainer(parent_def_id),
101 method_has_self_argument: has_self,
105 fn associated_item_from_impl_item_ref(
107 parent_def_id: DefId,
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::Method { has_self } => (ty::AssocKind::Method, 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,
125 container: ty::ImplContainer(parent_def_id),
126 method_has_self_argument: has_self,
130 fn associated_item(tcx: TyCtxt<'_>, def_id: DefId) -> ty::AssocItem {
131 let id = tcx.hir().as_local_hir_id(def_id).unwrap();
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 /// Calculates the `Sized` constraint.
170 /// In fact, there are only a few options for the types in the constraint:
171 /// - an obviously-unsized type
172 /// - a type parameter or projection whose Sizedness can't be known
173 /// - a tuple of type parameters or projections, if there are multiple
175 /// - a Error, if a type contained itself. The representability
176 /// check should catch this case.
177 fn adt_sized_constraint(tcx: TyCtxt<'_>, def_id: DefId) -> ty::AdtSizedConstraint<'_> {
178 let def = tcx.adt_def(def_id);
180 let result = tcx.mk_type_list(
183 .flat_map(|v| v.fields.last())
184 .flat_map(|f| sized_constraint_for_ty(tcx, def, tcx.type_of(f.did))),
187 debug!("adt_sized_constraint: {:?} => {:?}", def, result);
189 ty::AdtSizedConstraint(result)
192 fn associated_item_def_ids(tcx: TyCtxt<'_>, def_id: DefId) -> &[DefId] {
193 let id = tcx.hir().as_local_hir_id(def_id).unwrap();
194 let item = tcx.hir().expect_item(id);
196 hir::ItemKind::Trait(.., ref trait_item_refs) => tcx.arena.alloc_from_iter(
199 .map(|trait_item_ref| trait_item_ref.id)
200 .map(|id| tcx.hir().local_def_id(id.hir_id)),
202 hir::ItemKind::Impl { ref items, .. } => tcx.arena.alloc_from_iter(
205 .map(|impl_item_ref| impl_item_ref.id)
206 .map(|id| tcx.hir().local_def_id(id.hir_id)),
208 hir::ItemKind::TraitAlias(..) => &[],
209 _ => span_bug!(item.span, "associated_item_def_ids: not impl or trait"),
213 fn associated_items<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> &'tcx ty::AssociatedItems {
214 let items = tcx.associated_item_def_ids(def_id).iter().map(|did| tcx.associated_item(*did));
215 tcx.arena.alloc(ty::AssociatedItems::new(items))
218 fn def_span(tcx: TyCtxt<'_>, def_id: DefId) -> Span {
219 tcx.hir().span_if_local(def_id).unwrap()
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 { 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 let unnormalized_env = ty::ParamEnv::new(
256 tcx.intern_predicates(&predicates),
257 traits::Reveal::UserFacing,
258 tcx.sess.opts.debugging_opts.chalk.then_some(def_id),
261 let body_id = tcx.hir().as_local_hir_id(def_id).map_or(hir::DUMMY_HIR_ID, |id| {
262 tcx.hir().maybe_body_owned_by(id).map_or(id, |body| body.hir_id)
264 let cause = traits::ObligationCause::misc(tcx.def_span(def_id), body_id);
265 traits::normalize_param_env_or_error(tcx, def_id, unnormalized_env, cause)
268 fn crate_disambiguator(tcx: TyCtxt<'_>, crate_num: CrateNum) -> CrateDisambiguator {
269 assert_eq!(crate_num, LOCAL_CRATE);
270 tcx.sess.local_crate_disambiguator()
273 fn original_crate_name(tcx: TyCtxt<'_>, crate_num: CrateNum) -> Symbol {
274 assert_eq!(crate_num, LOCAL_CRATE);
278 fn crate_hash(tcx: TyCtxt<'_>, crate_num: CrateNum) -> Svh {
279 assert_eq!(crate_num, LOCAL_CRATE);
283 fn instance_def_size_estimate<'tcx>(
285 instance_def: ty::InstanceDef<'tcx>,
290 InstanceDef::Item(..) | InstanceDef::DropGlue(..) => {
291 let mir = tcx.instance_mir(instance_def);
292 mir.basic_blocks().iter().map(|bb| bb.statements.len()).sum()
294 // Estimate the size of other compiler-generated shims to be 1.
299 /// If `def_id` is an issue 33140 hack impl, returns its self type; otherwise, returns `None`.
301 /// See [`ImplOverlapKind::Issue33140`] for more details.
302 fn issue33140_self_ty(tcx: TyCtxt<'_>, def_id: DefId) -> Option<Ty<'_>> {
303 debug!("issue33140_self_ty({:?})", def_id);
306 .impl_trait_ref(def_id)
307 .unwrap_or_else(|| bug!("issue33140_self_ty called on inherent impl {:?}", def_id));
309 debug!("issue33140_self_ty({:?}), trait-ref={:?}", def_id, trait_ref);
311 let is_marker_like = tcx.impl_polarity(def_id) == ty::ImplPolarity::Positive
312 && tcx.associated_item_def_ids(trait_ref.def_id).is_empty();
314 // Check whether these impls would be ok for a marker trait.
316 debug!("issue33140_self_ty - not marker-like!");
320 // impl must be `impl Trait for dyn Marker1 + Marker2 + ...`
321 if trait_ref.substs.len() != 1 {
322 debug!("issue33140_self_ty - impl has substs!");
326 let predicates = tcx.predicates_of(def_id);
327 if predicates.parent.is_some() || !predicates.predicates.is_empty() {
328 debug!("issue33140_self_ty - impl has predicates {:?}!", predicates);
332 let self_ty = trait_ref.self_ty();
333 let self_ty_matches = match self_ty.kind {
334 ty::Dynamic(ref data, ty::ReStatic) => data.principal().is_none(),
339 debug!("issue33140_self_ty - MATCHES!");
342 debug!("issue33140_self_ty - non-matching self type");
347 /// Check if a function is async.
348 fn asyncness(tcx: TyCtxt<'_>, def_id: DefId) -> hir::IsAsync {
351 .as_local_hir_id(def_id)
352 .unwrap_or_else(|| bug!("asyncness: expected local `DefId`, got `{:?}`", def_id));
354 let node = tcx.hir().get(hir_id);
356 let fn_like = hir_map::blocks::FnLikeNode::from_node(node).unwrap_or_else(|| {
357 bug!("asyncness: expected fn-like node but got `{:?}`", def_id);
363 pub fn provide(providers: &mut ty::query::Providers<'_>) {
364 *providers = ty::query::Providers {
367 associated_item_def_ids,
369 adt_sized_constraint,
376 instance_def_size_estimate,