]> git.lizzy.rs Git - rust.git/blob - src/librustc_ty/ty.rs
Auto merge of #65989 - Aaron1011:fix/normalize-param-env, r=nikomatsakis
[rust.git] / src / librustc_ty / ty.rs
1 use rustc_data_structures::svh::Svh;
2 use rustc_hir as hir;
3 use rustc_hir::def::DefKind;
4 use rustc_hir::def_id::{CrateNum, DefId, LocalDefId, LOCAL_CRATE};
5 use rustc_infer::traits::util;
6 use rustc_middle::hir::map as hir_map;
7 use rustc_middle::ty::subst::{InternalSubsts, Subst};
8 use rustc_middle::ty::{self, ToPredicate, Ty, TyCtxt, WithConstness};
9 use rustc_session::CrateDisambiguator;
10 use rustc_span::symbol::Symbol;
11 use rustc_span::Span;
12 use rustc_trait_selection::traits;
13
14 fn sized_constraint_for_ty<'tcx>(
15     tcx: TyCtxt<'tcx>,
16     adtdef: &ty::AdtDef,
17     ty: Ty<'tcx>,
18 ) -> Vec<Ty<'tcx>> {
19     use ty::TyKind::*;
20
21     let result = match ty.kind {
22         Bool | Char | Int(..) | Uint(..) | Float(..) | RawPtr(..) | Ref(..) | FnDef(..)
23         | FnPtr(_) | Array(..) | Closure(..) | Generator(..) | Never => vec![],
24
25         Str | Dynamic(..) | Slice(_) | Foreign(..) | Error(_) | GeneratorWitness(..) => {
26             // these are never sized - return the target type
27             vec![ty]
28         }
29
30         Tuple(ref tys) => match tys.last() {
31             None => vec![],
32             Some(ty) => sized_constraint_for_ty(tcx, adtdef, ty.expect_ty()),
33         },
34
35         Adt(adt, substs) => {
36             // recursive case
37             let adt_tys = adt.sized_constraint(tcx);
38             debug!("sized_constraint_for_ty({:?}) intermediate = {:?}", ty, adt_tys);
39             adt_tys
40                 .iter()
41                 .map(|ty| ty.subst(tcx, substs))
42                 .flat_map(|ty| sized_constraint_for_ty(tcx, adtdef, ty))
43                 .collect()
44         }
45
46         Projection(..) | Opaque(..) => {
47             // must calculate explicitly.
48             // FIXME: consider special-casing always-Sized projections
49             vec![ty]
50         }
51
52         Param(..) => {
53             // perf hack: if there is a `T: Sized` bound, then
54             // we know that `T` is Sized and do not need to check
55             // it on the impl.
56
57             let sized_trait = match tcx.lang_items().sized_trait() {
58                 Some(x) => x,
59                 _ => return vec![ty],
60             };
61             let sized_predicate = ty::Binder::dummy(ty::TraitRef {
62                 def_id: sized_trait,
63                 substs: tcx.mk_substs_trait(ty, &[]),
64             })
65             .without_const()
66             .to_predicate(tcx);
67             let predicates = tcx.predicates_of(adtdef.did).predicates;
68             if predicates.iter().any(|(p, _)| *p == sized_predicate) { vec![] } else { vec![ty] }
69         }
70
71         Placeholder(..) | Bound(..) | Infer(..) => {
72             bug!("unexpected type `{:?}` in sized_constraint_for_ty", ty)
73         }
74     };
75     debug!("sized_constraint_for_ty({:?}) = {:?}", ty, result);
76     result
77 }
78
79 fn associated_item_from_trait_item_ref(
80     tcx: TyCtxt<'_>,
81     parent_def_id: LocalDefId,
82     parent_vis: &hir::Visibility<'_>,
83     trait_item_ref: &hir::TraitItemRef,
84 ) -> ty::AssocItem {
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     };
91
92     ty::AssocItem {
93         ident: trait_item_ref.ident,
94         kind,
95         // Visibility of trait items is inherited from their traits.
96         vis: ty::Visibility::from_hir(parent_vis, trait_item_ref.id.hir_id, tcx),
97         defaultness: trait_item_ref.defaultness,
98         def_id: def_id.to_def_id(),
99         container: ty::TraitContainer(parent_def_id.to_def_id()),
100         fn_has_self_parameter: has_self,
101     }
102 }
103
104 fn associated_item_from_impl_item_ref(
105     tcx: TyCtxt<'_>,
106     parent_def_id: LocalDefId,
107     impl_item_ref: &hir::ImplItemRef<'_>,
108 ) -> ty::AssocItem {
109     let def_id = tcx.hir().local_def_id(impl_item_ref.id.hir_id);
110     let (kind, has_self) = match impl_item_ref.kind {
111         hir::AssocItemKind::Const => (ty::AssocKind::Const, false),
112         hir::AssocItemKind::Fn { has_self } => (ty::AssocKind::Fn, has_self),
113         hir::AssocItemKind::Type => (ty::AssocKind::Type, false),
114     };
115
116     ty::AssocItem {
117         ident: impl_item_ref.ident,
118         kind,
119         // Visibility of trait impl items doesn't matter.
120         vis: ty::Visibility::from_hir(&impl_item_ref.vis, impl_item_ref.id.hir_id, tcx),
121         defaultness: impl_item_ref.defaultness,
122         def_id: def_id.to_def_id(),
123         container: ty::ImplContainer(parent_def_id.to_def_id()),
124         fn_has_self_parameter: has_self,
125     }
126 }
127
128 fn associated_item(tcx: TyCtxt<'_>, def_id: DefId) -> ty::AssocItem {
129     let id = tcx.hir().as_local_hir_id(def_id.expect_local());
130     let parent_id = tcx.hir().get_parent_item(id);
131     let parent_def_id = tcx.hir().local_def_id(parent_id);
132     let parent_item = tcx.hir().expect_item(parent_id);
133     match parent_item.kind {
134         hir::ItemKind::Impl { ref items, .. } => {
135             if let Some(impl_item_ref) = items.iter().find(|i| i.id.hir_id == id) {
136                 let assoc_item =
137                     associated_item_from_impl_item_ref(tcx, parent_def_id, impl_item_ref);
138                 debug_assert_eq!(assoc_item.def_id, def_id);
139                 return assoc_item;
140             }
141         }
142
143         hir::ItemKind::Trait(.., ref trait_item_refs) => {
144             if let Some(trait_item_ref) = trait_item_refs.iter().find(|i| i.id.hir_id == id) {
145                 let assoc_item = associated_item_from_trait_item_ref(
146                     tcx,
147                     parent_def_id,
148                     &parent_item.vis,
149                     trait_item_ref,
150                 );
151                 debug_assert_eq!(assoc_item.def_id, def_id);
152                 return assoc_item;
153             }
154         }
155
156         _ => {}
157     }
158
159     span_bug!(
160         parent_item.span,
161         "unexpected parent of trait or impl item or item not found: {:?}",
162         parent_item.kind
163     )
164 }
165
166 fn impl_defaultness(tcx: TyCtxt<'_>, def_id: DefId) -> hir::Defaultness {
167     let hir_id = tcx.hir().as_local_hir_id(def_id.expect_local());
168     let item = tcx.hir().expect_item(hir_id);
169     if let hir::ItemKind::Impl { defaultness, .. } = item.kind {
170         defaultness
171     } else {
172         bug!("`impl_defaultness` called on {:?}", item);
173     }
174 }
175
176 /// Calculates the `Sized` constraint.
177 ///
178 /// In fact, there are only a few options for the types in the constraint:
179 ///     - an obviously-unsized type
180 ///     - a type parameter or projection whose Sizedness can't be known
181 ///     - a tuple of type parameters or projections, if there are multiple
182 ///       such.
183 ///     - a Error, if a type contained itself. The representability
184 ///       check should catch this case.
185 fn adt_sized_constraint(tcx: TyCtxt<'_>, def_id: DefId) -> ty::AdtSizedConstraint<'_> {
186     let def = tcx.adt_def(def_id);
187
188     let result = tcx.mk_type_list(
189         def.variants
190             .iter()
191             .flat_map(|v| v.fields.last())
192             .flat_map(|f| sized_constraint_for_ty(tcx, def, tcx.type_of(f.did))),
193     );
194
195     debug!("adt_sized_constraint: {:?} => {:?}", def, result);
196
197     ty::AdtSizedConstraint(result)
198 }
199
200 fn associated_item_def_ids(tcx: TyCtxt<'_>, def_id: DefId) -> &[DefId] {
201     let id = tcx.hir().as_local_hir_id(def_id.expect_local());
202     let item = tcx.hir().expect_item(id);
203     match item.kind {
204         hir::ItemKind::Trait(.., ref trait_item_refs) => tcx.arena.alloc_from_iter(
205             trait_item_refs
206                 .iter()
207                 .map(|trait_item_ref| trait_item_ref.id)
208                 .map(|id| tcx.hir().local_def_id(id.hir_id).to_def_id()),
209         ),
210         hir::ItemKind::Impl { ref items, .. } => tcx.arena.alloc_from_iter(
211             items
212                 .iter()
213                 .map(|impl_item_ref| impl_item_ref.id)
214                 .map(|id| tcx.hir().local_def_id(id.hir_id).to_def_id()),
215         ),
216         hir::ItemKind::TraitAlias(..) => &[],
217         _ => span_bug!(item.span, "associated_item_def_ids: not impl or trait"),
218     }
219 }
220
221 fn associated_items(tcx: TyCtxt<'_>, def_id: DefId) -> ty::AssociatedItems<'_> {
222     let items = tcx.associated_item_def_ids(def_id).iter().map(|did| tcx.associated_item(*did));
223     ty::AssociatedItems::new(items)
224 }
225
226 fn def_span(tcx: TyCtxt<'_>, def_id: DefId) -> Span {
227     tcx.hir().span_if_local(def_id).unwrap()
228 }
229
230 /// If the given `DefId` describes an item belonging to a trait,
231 /// returns the `DefId` of the trait that the trait item belongs to;
232 /// otherwise, returns `None`.
233 fn trait_of_item(tcx: TyCtxt<'_>, def_id: DefId) -> Option<DefId> {
234     tcx.opt_associated_item(def_id).and_then(|associated_item| match associated_item.container {
235         ty::TraitContainer(def_id) => Some(def_id),
236         ty::ImplContainer(_) => None,
237     })
238 }
239
240 /// See `ParamEnv` struct definition for details.
241 fn param_env(tcx: TyCtxt<'_>, def_id: DefId) -> ty::ParamEnv<'_> {
242     // The param_env of an impl Trait type is its defining function's param_env
243     if let Some(parent) = ty::is_impl_trait_defn(tcx, def_id) {
244         return param_env(tcx, parent);
245     }
246     // Compute the bounds on Self and the type parameters.
247
248     let ty::InstantiatedPredicates { predicates, .. } =
249         tcx.predicates_of(def_id).instantiate_identity(tcx);
250
251     // Finally, we have to normalize the bounds in the environment, in
252     // case they contain any associated type projections. This process
253     // can yield errors if the put in illegal associated types, like
254     // `<i32 as Foo>::Bar` where `i32` does not implement `Foo`. We
255     // report these errors right here; this doesn't actually feel
256     // right to me, because constructing the environment feels like a
257     // kind of a "idempotent" action, but I'm not sure where would be
258     // a better place. In practice, we construct environments for
259     // every fn once during type checking, and we'll abort if there
260     // are any errors at that point, so after type checking you can be
261     // sure that this will succeed without errors anyway.
262
263     let unnormalized_env = ty::ParamEnv::new(
264         tcx.intern_predicates(&predicates),
265         traits::Reveal::UserFacing,
266         tcx.sess.opts.debugging_opts.chalk.then_some(def_id),
267     );
268
269     let body_id = def_id
270         .as_local()
271         .map(|def_id| tcx.hir().as_local_hir_id(def_id))
272         .map_or(hir::CRATE_HIR_ID, |id| {
273             tcx.hir().maybe_body_owned_by(id).map_or(id, |body| body.hir_id)
274         });
275     let cause = traits::ObligationCause::misc(tcx.def_span(def_id), body_id);
276     traits::normalize_param_env_or_error(tcx, def_id, unnormalized_env, cause)
277 }
278
279 fn param_env_reveal_all_normalized(tcx: TyCtxt<'_>, def_id: DefId) -> ty::ParamEnv<'_> {
280     tcx.param_env(def_id).with_reveal_all_normalized(tcx)
281 }
282
283 fn crate_disambiguator(tcx: TyCtxt<'_>, crate_num: CrateNum) -> CrateDisambiguator {
284     assert_eq!(crate_num, LOCAL_CRATE);
285     tcx.sess.local_crate_disambiguator()
286 }
287
288 fn original_crate_name(tcx: TyCtxt<'_>, crate_num: CrateNum) -> Symbol {
289     assert_eq!(crate_num, LOCAL_CRATE);
290     tcx.crate_name
291 }
292
293 fn crate_hash(tcx: TyCtxt<'_>, crate_num: CrateNum) -> Svh {
294     tcx.index_hir(crate_num).crate_hash
295 }
296
297 fn instance_def_size_estimate<'tcx>(
298     tcx: TyCtxt<'tcx>,
299     instance_def: ty::InstanceDef<'tcx>,
300 ) -> usize {
301     use ty::InstanceDef;
302
303     match instance_def {
304         InstanceDef::Item(..) | InstanceDef::DropGlue(..) => {
305             let mir = tcx.instance_mir(instance_def);
306             mir.basic_blocks().iter().map(|bb| bb.statements.len()).sum()
307         }
308         // Estimate the size of other compiler-generated shims to be 1.
309         _ => 1,
310     }
311 }
312
313 /// If `def_id` is an issue 33140 hack impl, returns its self type; otherwise, returns `None`.
314 ///
315 /// See [`ty::ImplOverlapKind::Issue33140`] for more details.
316 fn issue33140_self_ty(tcx: TyCtxt<'_>, def_id: DefId) -> Option<Ty<'_>> {
317     debug!("issue33140_self_ty({:?})", def_id);
318
319     let trait_ref = tcx
320         .impl_trait_ref(def_id)
321         .unwrap_or_else(|| bug!("issue33140_self_ty called on inherent impl {:?}", def_id));
322
323     debug!("issue33140_self_ty({:?}), trait-ref={:?}", def_id, trait_ref);
324
325     let is_marker_like = tcx.impl_polarity(def_id) == ty::ImplPolarity::Positive
326         && tcx.associated_item_def_ids(trait_ref.def_id).is_empty();
327
328     // Check whether these impls would be ok for a marker trait.
329     if !is_marker_like {
330         debug!("issue33140_self_ty - not marker-like!");
331         return None;
332     }
333
334     // impl must be `impl Trait for dyn Marker1 + Marker2 + ...`
335     if trait_ref.substs.len() != 1 {
336         debug!("issue33140_self_ty - impl has substs!");
337         return None;
338     }
339
340     let predicates = tcx.predicates_of(def_id);
341     if predicates.parent.is_some() || !predicates.predicates.is_empty() {
342         debug!("issue33140_self_ty - impl has predicates {:?}!", predicates);
343         return None;
344     }
345
346     let self_ty = trait_ref.self_ty();
347     let self_ty_matches = match self_ty.kind {
348         ty::Dynamic(ref data, ty::ReStatic) => data.principal().is_none(),
349         _ => false,
350     };
351
352     if self_ty_matches {
353         debug!("issue33140_self_ty - MATCHES!");
354         Some(self_ty)
355     } else {
356         debug!("issue33140_self_ty - non-matching self type");
357         None
358     }
359 }
360
361 /// Check if a function is async.
362 fn asyncness(tcx: TyCtxt<'_>, def_id: DefId) -> hir::IsAsync {
363     let hir_id = tcx.hir().as_local_hir_id(def_id.expect_local());
364
365     let node = tcx.hir().get(hir_id);
366
367     let fn_like = hir_map::blocks::FnLikeNode::from_node(node).unwrap_or_else(|| {
368         bug!("asyncness: expected fn-like node but got `{:?}`", def_id);
369     });
370
371     fn_like.asyncness()
372 }
373
374 /// For associated types we allow bounds written on the associated type
375 /// (`type X: Trait`) to be used as candidates. We also allow the same bounds
376 /// when desugared as bounds on the trait `where Self::X: Trait`.
377 ///
378 /// Note that this filtering is done with the items identity substs to
379 /// simplify checking that these bounds are met in impls. This means that
380 /// a bound such as `for<'b> <Self as X<'b>>::U: Clone` can't be used, as in
381 /// `hr-associated-type-bound-1.rs`.
382 fn associated_type_projection_predicates(
383     tcx: TyCtxt<'_>,
384     assoc_item_def_id: DefId,
385 ) -> &'_ ty::List<ty::Predicate<'_>> {
386     let generic_trait_bounds = tcx.predicates_of(assoc_item_def_id);
387     // We include predicates from the trait as well to handle
388     // `where Self::X: Trait`.
389     let item_bounds = generic_trait_bounds.instantiate_identity(tcx);
390     let item_predicates = util::elaborate_predicates(tcx, item_bounds.predicates.into_iter());
391
392     let assoc_item_ty = ty::ProjectionTy {
393         item_def_id: assoc_item_def_id,
394         substs: InternalSubsts::identity_for_item(tcx, assoc_item_def_id),
395     };
396
397     let predicates = item_predicates.filter_map(|obligation| {
398         let pred = obligation.predicate;
399         match pred.skip_binders() {
400             ty::PredicateAtom::Trait(tr, _) => {
401                 if let ty::Projection(p) = tr.self_ty().kind {
402                     if p == assoc_item_ty {
403                         return Some(pred);
404                     }
405                 }
406             }
407             ty::PredicateAtom::Projection(proj) => {
408                 if let ty::Projection(p) = proj.projection_ty.self_ty().kind {
409                     if p == assoc_item_ty {
410                         return Some(pred);
411                     }
412                 }
413             }
414             ty::PredicateAtom::TypeOutlives(outlives) => {
415                 if let ty::Projection(p) = outlives.0.kind {
416                     if p == assoc_item_ty {
417                         return Some(pred);
418                     }
419                 }
420             }
421             _ => {}
422         }
423         None
424     });
425
426     let result = tcx.mk_predicates(predicates);
427     debug!(
428         "associated_type_projection_predicates({}) = {:?}",
429         tcx.def_path_str(assoc_item_def_id),
430         result
431     );
432     result
433 }
434
435 /// Opaque types don't have the same issues as associated types: the only
436 /// predicates on an opaque type (excluding those it inherits from its parent
437 /// item) should be of the form we're expecting.
438 fn opaque_type_projection_predicates(
439     tcx: TyCtxt<'_>,
440     def_id: DefId,
441 ) -> &'_ ty::List<ty::Predicate<'_>> {
442     let substs = InternalSubsts::identity_for_item(tcx, def_id);
443
444     let bounds = tcx.predicates_of(def_id);
445     let predicates =
446         util::elaborate_predicates(tcx, bounds.predicates.into_iter().map(|&(pred, _)| pred));
447
448     let filtered_predicates = predicates.filter_map(|obligation| {
449         let pred = obligation.predicate;
450         match pred.skip_binders() {
451             ty::PredicateAtom::Trait(tr, _) => {
452                 if let ty::Opaque(opaque_def_id, opaque_substs) = tr.self_ty().kind {
453                     if opaque_def_id == def_id && opaque_substs == substs {
454                         return Some(pred);
455                     }
456                 }
457             }
458             ty::PredicateAtom::Projection(proj) => {
459                 if let ty::Opaque(opaque_def_id, opaque_substs) = proj.projection_ty.self_ty().kind
460                 {
461                     if opaque_def_id == def_id && opaque_substs == substs {
462                         return Some(pred);
463                     }
464                 }
465             }
466             ty::PredicateAtom::TypeOutlives(outlives) => {
467                 if let ty::Opaque(opaque_def_id, opaque_substs) = outlives.0.kind {
468                     if opaque_def_id == def_id && opaque_substs == substs {
469                         return Some(pred);
470                     }
471                 } else {
472                     // These can come from elaborating other predicates
473                     return None;
474                 }
475             }
476             // These can come from elaborating other predicates
477             ty::PredicateAtom::RegionOutlives(_) => return None,
478             _ => {}
479         }
480         tcx.sess.delay_span_bug(
481             obligation.cause.span(tcx),
482             &format!("unexpected predicate {:?} on opaque type", pred),
483         );
484         None
485     });
486
487     let result = tcx.mk_predicates(filtered_predicates);
488     debug!("opaque_type_projection_predicates({}) = {:?}", tcx.def_path_str(def_id), result);
489     result
490 }
491
492 fn projection_predicates(tcx: TyCtxt<'_>, def_id: DefId) -> &'_ ty::List<ty::Predicate<'_>> {
493     match tcx.def_kind(def_id) {
494         DefKind::AssocTy => associated_type_projection_predicates(tcx, def_id),
495         DefKind::OpaqueTy => opaque_type_projection_predicates(tcx, def_id),
496         k => bug!("projection_predicates called on {}", k.descr(def_id)),
497     }
498 }
499
500 pub fn provide(providers: &mut ty::query::Providers) {
501     *providers = ty::query::Providers {
502         asyncness,
503         associated_item,
504         associated_item_def_ids,
505         associated_items,
506         adt_sized_constraint,
507         def_span,
508         param_env,
509         param_env_reveal_all_normalized,
510         trait_of_item,
511         crate_disambiguator,
512         original_crate_name,
513         crate_hash,
514         instance_def_size_estimate,
515         issue33140_self_ty,
516         impl_defaultness,
517         projection_predicates,
518         ..*providers
519     };
520 }