1 use rustc::hir::map as hir_map;
2 use rustc::session::CrateDisambiguator;
3 use rustc::traits::{self};
4 use rustc::ty::subst::Subst;
5 use rustc::ty::{self, ToPredicate, Ty, TyCtxt};
6 use rustc_data_structures::svh::Svh;
8 use rustc_hir::def_id::{CrateNum, DefId, LOCAL_CRATE};
9 use rustc_span::symbol::Symbol;
12 fn sized_constraint_for_ty(tcx: TyCtxt<'tcx>, adtdef: &ty::AdtDef, ty: Ty<'tcx>) -> Vec<Ty<'tcx>> {
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.expect_ty()),
31 let adt_tys = adt.sized_constraint(tcx);
32 debug!("sized_constraint_for_ty({:?}) intermediate = {:?}", ty, adt_tys);
35 .map(|ty| 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
46 UnnormalizedProjection(..) => bug!("only used with chalk-engine"),
49 // perf hack: if there is a `T: Sized` bound, then
50 // we know that `T` is Sized and do not need to check
53 let sized_trait = match tcx.lang_items().sized_trait() {
57 let sized_predicate = ty::Binder::dummy(ty::TraitRef {
59 substs: tcx.mk_substs_trait(ty, &[]),
62 let predicates = tcx.predicates_of(adtdef.did).predicates;
63 if predicates.iter().any(|(p, _)| *p == sized_predicate) { vec![] } else { vec![ty] }
66 Placeholder(..) | Bound(..) | Infer(..) => {
67 bug!("unexpected type `{:?}` in sized_constraint_for_ty", ty)
70 debug!("sized_constraint_for_ty({:?}) = {:?}", ty, result);
74 fn associated_item_from_trait_item_ref(
77 parent_vis: &hir::Visibility<'_>,
78 trait_item_ref: &hir::TraitItemRef,
80 let def_id = tcx.hir().local_def_id(trait_item_ref.id.hir_id);
81 let (kind, has_self) = match trait_item_ref.kind {
82 hir::AssocItemKind::Const => (ty::AssocKind::Const, false),
83 hir::AssocItemKind::Method { has_self } => (ty::AssocKind::Method, has_self),
84 hir::AssocItemKind::Type => (ty::AssocKind::Type, false),
85 hir::AssocItemKind::OpaqueTy => bug!("only impls can have opaque types"),
89 ident: trait_item_ref.ident,
91 // Visibility of trait items is inherited from their traits.
92 vis: ty::Visibility::from_hir(parent_vis, trait_item_ref.id.hir_id, tcx),
93 defaultness: trait_item_ref.defaultness,
95 container: ty::TraitContainer(parent_def_id),
96 method_has_self_argument: has_self,
100 fn associated_item_from_impl_item_ref(
102 parent_def_id: DefId,
103 impl_item_ref: &hir::ImplItemRef<'_>,
105 let def_id = tcx.hir().local_def_id(impl_item_ref.id.hir_id);
106 let (kind, has_self) = match impl_item_ref.kind {
107 hir::AssocItemKind::Const => (ty::AssocKind::Const, false),
108 hir::AssocItemKind::Method { has_self } => (ty::AssocKind::Method, has_self),
109 hir::AssocItemKind::Type => (ty::AssocKind::Type, false),
110 hir::AssocItemKind::OpaqueTy => (ty::AssocKind::OpaqueTy, false),
114 ident: impl_item_ref.ident,
116 // Visibility of trait impl items doesn't matter.
117 vis: ty::Visibility::from_hir(&impl_item_ref.vis, impl_item_ref.id.hir_id, tcx),
118 defaultness: impl_item_ref.defaultness,
120 container: ty::ImplContainer(parent_def_id),
121 method_has_self_argument: has_self,
125 fn associated_item(tcx: TyCtxt<'_>, def_id: DefId) -> ty::AssocItem {
126 let id = tcx.hir().as_local_hir_id(def_id).unwrap();
127 let parent_id = tcx.hir().get_parent_item(id);
128 let parent_def_id = tcx.hir().local_def_id(parent_id);
129 let parent_item = tcx.hir().expect_item(parent_id);
130 match parent_item.kind {
131 hir::ItemKind::Impl { ref items, .. } => {
132 if let Some(impl_item_ref) = items.iter().find(|i| i.id.hir_id == id) {
134 associated_item_from_impl_item_ref(tcx, parent_def_id, impl_item_ref);
135 debug_assert_eq!(assoc_item.def_id, def_id);
140 hir::ItemKind::Trait(.., ref trait_item_refs) => {
141 if let Some(trait_item_ref) = trait_item_refs.iter().find(|i| i.id.hir_id == id) {
142 let assoc_item = associated_item_from_trait_item_ref(
148 debug_assert_eq!(assoc_item.def_id, def_id);
158 "unexpected parent of trait or impl item or item not found: {:?}",
163 /// Calculates the `Sized` constraint.
165 /// In fact, there are only a few options for the types in the constraint:
166 /// - an obviously-unsized type
167 /// - a type parameter or projection whose Sizedness can't be known
168 /// - a tuple of type parameters or projections, if there are multiple
170 /// - a Error, if a type contained itself. The representability
171 /// check should catch this case.
172 fn adt_sized_constraint(tcx: TyCtxt<'_>, def_id: DefId) -> ty::AdtSizedConstraint<'_> {
173 let def = tcx.adt_def(def_id);
175 let result = tcx.mk_type_list(
178 .flat_map(|v| v.fields.last())
179 .flat_map(|f| sized_constraint_for_ty(tcx, def, tcx.type_of(f.did))),
182 debug!("adt_sized_constraint: {:?} => {:?}", def, result);
184 ty::AdtSizedConstraint(result)
187 fn associated_item_def_ids(tcx: TyCtxt<'_>, def_id: DefId) -> &[DefId] {
188 let id = tcx.hir().as_local_hir_id(def_id).unwrap();
189 let item = tcx.hir().expect_item(id);
191 hir::ItemKind::Trait(.., ref trait_item_refs) => tcx.arena.alloc_from_iter(
194 .map(|trait_item_ref| trait_item_ref.id)
195 .map(|id| tcx.hir().local_def_id(id.hir_id)),
197 hir::ItemKind::Impl { ref items, .. } => tcx.arena.alloc_from_iter(
200 .map(|impl_item_ref| impl_item_ref.id)
201 .map(|id| tcx.hir().local_def_id(id.hir_id)),
203 hir::ItemKind::TraitAlias(..) => &[],
204 _ => span_bug!(item.span, "associated_item_def_ids: not impl or trait"),
208 fn def_span(tcx: TyCtxt<'_>, def_id: DefId) -> Span {
209 tcx.hir().span_if_local(def_id).unwrap()
212 /// If the given `DefId` describes an item belonging to a trait,
213 /// returns the `DefId` of the trait that the trait item belongs to;
214 /// otherwise, returns `None`.
215 fn trait_of_item(tcx: TyCtxt<'_>, def_id: DefId) -> Option<DefId> {
216 tcx.opt_associated_item(def_id).and_then(|associated_item| match associated_item.container {
217 ty::TraitContainer(def_id) => Some(def_id),
218 ty::ImplContainer(_) => None,
222 /// See `ParamEnv` struct definition for details.
223 fn param_env(tcx: TyCtxt<'_>, def_id: DefId) -> ty::ParamEnv<'_> {
224 // The param_env of an impl Trait type is its defining function's param_env
225 if let Some(parent) = ty::is_impl_trait_defn(tcx, def_id) {
226 return param_env(tcx, parent);
228 // Compute the bounds on Self and the type parameters.
230 let ty::InstantiatedPredicates { predicates } =
231 tcx.predicates_of(def_id).instantiate_identity(tcx);
233 // Finally, we have to normalize the bounds in the environment, in
234 // case they contain any associated type projections. This process
235 // can yield errors if the put in illegal associated types, like
236 // `<i32 as Foo>::Bar` where `i32` does not implement `Foo`. We
237 // report these errors right here; this doesn't actually feel
238 // right to me, because constructing the environment feels like a
239 // kind of a "idempotent" action, but I'm not sure where would be
240 // a better place. In practice, we construct environments for
241 // every fn once during type checking, and we'll abort if there
242 // are any errors at that point, so after type checking you can be
243 // sure that this will succeed without errors anyway.
245 let unnormalized_env = ty::ParamEnv::new(
246 tcx.intern_predicates(&predicates),
247 traits::Reveal::UserFacing,
248 tcx.sess.opts.debugging_opts.chalk.then_some(def_id),
251 let body_id = tcx.hir().as_local_hir_id(def_id).map_or(hir::DUMMY_HIR_ID, |id| {
252 tcx.hir().maybe_body_owned_by(id).map_or(id, |body| body.hir_id)
254 let cause = traits::ObligationCause::misc(tcx.def_span(def_id), body_id);
255 traits::normalize_param_env_or_error(tcx, def_id, unnormalized_env, cause)
258 fn crate_disambiguator(tcx: TyCtxt<'_>, crate_num: CrateNum) -> CrateDisambiguator {
259 assert_eq!(crate_num, LOCAL_CRATE);
260 tcx.sess.local_crate_disambiguator()
263 fn original_crate_name(tcx: TyCtxt<'_>, crate_num: CrateNum) -> Symbol {
264 assert_eq!(crate_num, LOCAL_CRATE);
265 tcx.crate_name.clone()
268 fn crate_hash(tcx: TyCtxt<'_>, crate_num: CrateNum) -> Svh {
269 assert_eq!(crate_num, LOCAL_CRATE);
273 fn instance_def_size_estimate<'tcx>(
275 instance_def: ty::InstanceDef<'tcx>,
280 InstanceDef::Item(..) | InstanceDef::DropGlue(..) => {
281 let mir = tcx.instance_mir(instance_def);
282 mir.basic_blocks().iter().map(|bb| bb.statements.len()).sum()
284 // Estimate the size of other compiler-generated shims to be 1.
289 /// If `def_id` is an issue 33140 hack impl, returns its self type; otherwise, returns `None`.
291 /// See [`ImplOverlapKind::Issue33140`] for more details.
292 fn issue33140_self_ty(tcx: TyCtxt<'_>, def_id: DefId) -> Option<Ty<'_>> {
293 debug!("issue33140_self_ty({:?})", def_id);
296 .impl_trait_ref(def_id)
297 .unwrap_or_else(|| bug!("issue33140_self_ty called on inherent impl {:?}", def_id));
299 debug!("issue33140_self_ty({:?}), trait-ref={:?}", def_id, trait_ref);
301 let is_marker_like = tcx.impl_polarity(def_id) == ty::ImplPolarity::Positive
302 && tcx.associated_item_def_ids(trait_ref.def_id).is_empty();
304 // Check whether these impls would be ok for a marker trait.
306 debug!("issue33140_self_ty - not marker-like!");
310 // impl must be `impl Trait for dyn Marker1 + Marker2 + ...`
311 if trait_ref.substs.len() != 1 {
312 debug!("issue33140_self_ty - impl has substs!");
316 let predicates = tcx.predicates_of(def_id);
317 if predicates.parent.is_some() || !predicates.predicates.is_empty() {
318 debug!("issue33140_self_ty - impl has predicates {:?}!", predicates);
322 let self_ty = trait_ref.self_ty();
323 let self_ty_matches = match self_ty.kind {
324 ty::Dynamic(ref data, ty::ReStatic) => data.principal().is_none(),
329 debug!("issue33140_self_ty - MATCHES!");
332 debug!("issue33140_self_ty - non-matching self type");
337 /// Check if a function is async.
338 fn asyncness(tcx: TyCtxt<'_>, def_id: DefId) -> hir::IsAsync {
341 .as_local_hir_id(def_id)
342 .unwrap_or_else(|| bug!("asyncness: expected local `DefId`, got `{:?}`", def_id));
344 let node = tcx.hir().get(hir_id);
346 let fn_like = hir_map::blocks::FnLikeNode::from_node(node).unwrap_or_else(|| {
347 bug!("asyncness: expected fn-like node but got `{:?}`", def_id);
353 pub fn provide(providers: &mut ty::query::Providers<'_>) {
354 *providers = ty::query::Providers {
357 associated_item_def_ids,
358 adt_sized_constraint,
365 instance_def_size_estimate,