]> git.lizzy.rs Git - rust.git/blob - src/librustc_ty/ty.rs
Rollup merge of #68845 - dwrensha:fix-68783, r=estebank
[rust.git] / src / librustc_ty / ty.rs
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, WithConstness};
6 use rustc_data_structures::svh::Svh;
7 use rustc_hir as hir;
8 use rustc_hir::def_id::{CrateNum, DefId, LOCAL_CRATE};
9 use rustc_span::symbol::Symbol;
10 use rustc_span::Span;
11
12 fn sized_constraint_for_ty(tcx: TyCtxt<'tcx>, adtdef: &ty::AdtDef, ty: Ty<'tcx>) -> Vec<Ty<'tcx>> {
13     use ty::TyKind::*;
14
15     let result = match ty.kind {
16         Bool | Char | Int(..) | Uint(..) | Float(..) | RawPtr(..) | Ref(..) | FnDef(..)
17         | FnPtr(_) | Array(..) | Closure(..) | Generator(..) | Never => vec![],
18
19         Str | Dynamic(..) | Slice(_) | Foreign(..) | Error | GeneratorWitness(..) => {
20             // these are never sized - return the target type
21             vec![ty]
22         }
23
24         Tuple(ref tys) => match tys.last() {
25             None => vec![],
26             Some(ty) => sized_constraint_for_ty(tcx, adtdef, ty.expect_ty()),
27         },
28
29         Adt(adt, substs) => {
30             // recursive case
31             let adt_tys = adt.sized_constraint(tcx);
32             debug!("sized_constraint_for_ty({:?}) intermediate = {:?}", ty, adt_tys);
33             adt_tys
34                 .iter()
35                 .map(|ty| ty.subst(tcx, substs))
36                 .flat_map(|ty| sized_constraint_for_ty(tcx, adtdef, ty))
37                 .collect()
38         }
39
40         Projection(..) | Opaque(..) => {
41             // must calculate explicitly.
42             // FIXME: consider special-casing always-Sized projections
43             vec![ty]
44         }
45
46         UnnormalizedProjection(..) => bug!("only used with chalk-engine"),
47
48         Param(..) => {
49             // perf hack: if there is a `T: Sized` bound, then
50             // we know that `T` is Sized and do not need to check
51             // it on the impl.
52
53             let sized_trait = match tcx.lang_items().sized_trait() {
54                 Some(x) => x,
55                 _ => return vec![ty],
56             };
57             let sized_predicate = ty::Binder::dummy(ty::TraitRef {
58                 def_id: sized_trait,
59                 substs: tcx.mk_substs_trait(ty, &[]),
60             })
61             .without_const()
62             .to_predicate();
63             let predicates = tcx.predicates_of(adtdef.did).predicates;
64             if predicates.iter().any(|(p, _)| *p == sized_predicate) { vec![] } else { vec![ty] }
65         }
66
67         Placeholder(..) | Bound(..) | Infer(..) => {
68             bug!("unexpected type `{:?}` in sized_constraint_for_ty", ty)
69         }
70     };
71     debug!("sized_constraint_for_ty({:?}) = {:?}", ty, result);
72     result
73 }
74
75 fn associated_item_from_trait_item_ref(
76     tcx: TyCtxt<'_>,
77     parent_def_id: DefId,
78     parent_vis: &hir::Visibility<'_>,
79     trait_item_ref: &hir::TraitItemRef,
80 ) -> ty::AssocItem {
81     let def_id = tcx.hir().local_def_id(trait_item_ref.id.hir_id);
82     let (kind, has_self) = match trait_item_ref.kind {
83         hir::AssocItemKind::Const => (ty::AssocKind::Const, false),
84         hir::AssocItemKind::Method { has_self } => (ty::AssocKind::Method, has_self),
85         hir::AssocItemKind::Type => (ty::AssocKind::Type, false),
86         hir::AssocItemKind::OpaqueTy => bug!("only impls can have opaque types"),
87     };
88
89     ty::AssocItem {
90         ident: trait_item_ref.ident,
91         kind,
92         // Visibility of trait items is inherited from their traits.
93         vis: ty::Visibility::from_hir(parent_vis, trait_item_ref.id.hir_id, tcx),
94         defaultness: trait_item_ref.defaultness,
95         def_id,
96         container: ty::TraitContainer(parent_def_id),
97         method_has_self_argument: has_self,
98     }
99 }
100
101 fn associated_item_from_impl_item_ref(
102     tcx: TyCtxt<'_>,
103     parent_def_id: DefId,
104     impl_item_ref: &hir::ImplItemRef<'_>,
105 ) -> ty::AssocItem {
106     let def_id = tcx.hir().local_def_id(impl_item_ref.id.hir_id);
107     let (kind, has_self) = match impl_item_ref.kind {
108         hir::AssocItemKind::Const => (ty::AssocKind::Const, false),
109         hir::AssocItemKind::Method { has_self } => (ty::AssocKind::Method, has_self),
110         hir::AssocItemKind::Type => (ty::AssocKind::Type, false),
111         hir::AssocItemKind::OpaqueTy => (ty::AssocKind::OpaqueTy, false),
112     };
113
114     ty::AssocItem {
115         ident: impl_item_ref.ident,
116         kind,
117         // Visibility of trait impl items doesn't matter.
118         vis: ty::Visibility::from_hir(&impl_item_ref.vis, impl_item_ref.id.hir_id, tcx),
119         defaultness: impl_item_ref.defaultness,
120         def_id,
121         container: ty::ImplContainer(parent_def_id),
122         method_has_self_argument: has_self,
123     }
124 }
125
126 fn associated_item(tcx: TyCtxt<'_>, def_id: DefId) -> ty::AssocItem {
127     let id = tcx.hir().as_local_hir_id(def_id).unwrap();
128     let parent_id = tcx.hir().get_parent_item(id);
129     let parent_def_id = tcx.hir().local_def_id(parent_id);
130     let parent_item = tcx.hir().expect_item(parent_id);
131     match parent_item.kind {
132         hir::ItemKind::Impl { ref items, .. } => {
133             if let Some(impl_item_ref) = items.iter().find(|i| i.id.hir_id == id) {
134                 let assoc_item =
135                     associated_item_from_impl_item_ref(tcx, parent_def_id, impl_item_ref);
136                 debug_assert_eq!(assoc_item.def_id, def_id);
137                 return assoc_item;
138             }
139         }
140
141         hir::ItemKind::Trait(.., ref trait_item_refs) => {
142             if let Some(trait_item_ref) = trait_item_refs.iter().find(|i| i.id.hir_id == id) {
143                 let assoc_item = associated_item_from_trait_item_ref(
144                     tcx,
145                     parent_def_id,
146                     &parent_item.vis,
147                     trait_item_ref,
148                 );
149                 debug_assert_eq!(assoc_item.def_id, def_id);
150                 return assoc_item;
151             }
152         }
153
154         _ => {}
155     }
156
157     span_bug!(
158         parent_item.span,
159         "unexpected parent of trait or impl item or item not found: {:?}",
160         parent_item.kind
161     )
162 }
163
164 /// Calculates the `Sized` constraint.
165 ///
166 /// In fact, there are only a few options for the types in the constraint:
167 ///     - an obviously-unsized type
168 ///     - a type parameter or projection whose Sizedness can't be known
169 ///     - a tuple of type parameters or projections, if there are multiple
170 ///       such.
171 ///     - a Error, if a type contained itself. The representability
172 ///       check should catch this case.
173 fn adt_sized_constraint(tcx: TyCtxt<'_>, def_id: DefId) -> ty::AdtSizedConstraint<'_> {
174     let def = tcx.adt_def(def_id);
175
176     let result = tcx.mk_type_list(
177         def.variants
178             .iter()
179             .flat_map(|v| v.fields.last())
180             .flat_map(|f| sized_constraint_for_ty(tcx, def, tcx.type_of(f.did))),
181     );
182
183     debug!("adt_sized_constraint: {:?} => {:?}", def, result);
184
185     ty::AdtSizedConstraint(result)
186 }
187
188 fn associated_item_def_ids(tcx: TyCtxt<'_>, def_id: DefId) -> &[DefId] {
189     let id = tcx.hir().as_local_hir_id(def_id).unwrap();
190     let item = tcx.hir().expect_item(id);
191     match item.kind {
192         hir::ItemKind::Trait(.., ref trait_item_refs) => tcx.arena.alloc_from_iter(
193             trait_item_refs
194                 .iter()
195                 .map(|trait_item_ref| trait_item_ref.id)
196                 .map(|id| tcx.hir().local_def_id(id.hir_id)),
197         ),
198         hir::ItemKind::Impl { ref items, .. } => tcx.arena.alloc_from_iter(
199             items
200                 .iter()
201                 .map(|impl_item_ref| impl_item_ref.id)
202                 .map(|id| tcx.hir().local_def_id(id.hir_id)),
203         ),
204         hir::ItemKind::TraitAlias(..) => &[],
205         _ => span_bug!(item.span, "associated_item_def_ids: not impl or trait"),
206     }
207 }
208
209 fn associated_items<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> ty::AssocItemsIterator<'tcx> {
210     ty::AssocItemsIterator {
211         items: tcx.arena.alloc_from_iter(
212             tcx.associated_item_def_ids(def_id).iter().map(|did| tcx.associated_item(*did)),
213         ),
214     }
215 }
216
217 fn def_span(tcx: TyCtxt<'_>, def_id: DefId) -> Span {
218     tcx.hir().span_if_local(def_id).unwrap()
219 }
220
221 /// If the given `DefId` describes an item belonging to a trait,
222 /// returns the `DefId` of the trait that the trait item belongs to;
223 /// otherwise, returns `None`.
224 fn trait_of_item(tcx: TyCtxt<'_>, def_id: DefId) -> Option<DefId> {
225     tcx.opt_associated_item(def_id).and_then(|associated_item| match associated_item.container {
226         ty::TraitContainer(def_id) => Some(def_id),
227         ty::ImplContainer(_) => None,
228     })
229 }
230
231 /// See `ParamEnv` struct definition for details.
232 fn param_env(tcx: TyCtxt<'_>, def_id: DefId) -> ty::ParamEnv<'_> {
233     // The param_env of an impl Trait type is its defining function's param_env
234     if let Some(parent) = ty::is_impl_trait_defn(tcx, def_id) {
235         return param_env(tcx, parent);
236     }
237     // Compute the bounds on Self and the type parameters.
238
239     let ty::InstantiatedPredicates { predicates, .. } =
240         tcx.predicates_of(def_id).instantiate_identity(tcx);
241
242     // Finally, we have to normalize the bounds in the environment, in
243     // case they contain any associated type projections. This process
244     // can yield errors if the put in illegal associated types, like
245     // `<i32 as Foo>::Bar` where `i32` does not implement `Foo`. We
246     // report these errors right here; this doesn't actually feel
247     // right to me, because constructing the environment feels like a
248     // kind of a "idempotent" action, but I'm not sure where would be
249     // a better place. In practice, we construct environments for
250     // every fn once during type checking, and we'll abort if there
251     // are any errors at that point, so after type checking you can be
252     // sure that this will succeed without errors anyway.
253
254     let unnormalized_env = ty::ParamEnv::new(
255         tcx.intern_predicates(&predicates),
256         traits::Reveal::UserFacing,
257         tcx.sess.opts.debugging_opts.chalk.then_some(def_id),
258     );
259
260     let body_id = tcx.hir().as_local_hir_id(def_id).map_or(hir::DUMMY_HIR_ID, |id| {
261         tcx.hir().maybe_body_owned_by(id).map_or(id, |body| body.hir_id)
262     });
263     let cause = traits::ObligationCause::misc(tcx.def_span(def_id), body_id);
264     traits::normalize_param_env_or_error(tcx, def_id, unnormalized_env, cause)
265 }
266
267 fn crate_disambiguator(tcx: TyCtxt<'_>, crate_num: CrateNum) -> CrateDisambiguator {
268     assert_eq!(crate_num, LOCAL_CRATE);
269     tcx.sess.local_crate_disambiguator()
270 }
271
272 fn original_crate_name(tcx: TyCtxt<'_>, crate_num: CrateNum) -> Symbol {
273     assert_eq!(crate_num, LOCAL_CRATE);
274     tcx.crate_name
275 }
276
277 fn crate_hash(tcx: TyCtxt<'_>, crate_num: CrateNum) -> Svh {
278     assert_eq!(crate_num, LOCAL_CRATE);
279     tcx.hir().crate_hash
280 }
281
282 fn instance_def_size_estimate<'tcx>(
283     tcx: TyCtxt<'tcx>,
284     instance_def: ty::InstanceDef<'tcx>,
285 ) -> usize {
286     use ty::InstanceDef;
287
288     match instance_def {
289         InstanceDef::Item(..) | InstanceDef::DropGlue(..) => {
290             let mir = tcx.instance_mir(instance_def);
291             mir.basic_blocks().iter().map(|bb| bb.statements.len()).sum()
292         }
293         // Estimate the size of other compiler-generated shims to be 1.
294         _ => 1,
295     }
296 }
297
298 /// If `def_id` is an issue 33140 hack impl, returns its self type; otherwise, returns `None`.
299 ///
300 /// See [`ImplOverlapKind::Issue33140`] for more details.
301 fn issue33140_self_ty(tcx: TyCtxt<'_>, def_id: DefId) -> Option<Ty<'_>> {
302     debug!("issue33140_self_ty({:?})", def_id);
303
304     let trait_ref = tcx
305         .impl_trait_ref(def_id)
306         .unwrap_or_else(|| bug!("issue33140_self_ty called on inherent impl {:?}", def_id));
307
308     debug!("issue33140_self_ty({:?}), trait-ref={:?}", def_id, trait_ref);
309
310     let is_marker_like = tcx.impl_polarity(def_id) == ty::ImplPolarity::Positive
311         && tcx.associated_item_def_ids(trait_ref.def_id).is_empty();
312
313     // Check whether these impls would be ok for a marker trait.
314     if !is_marker_like {
315         debug!("issue33140_self_ty - not marker-like!");
316         return None;
317     }
318
319     // impl must be `impl Trait for dyn Marker1 + Marker2 + ...`
320     if trait_ref.substs.len() != 1 {
321         debug!("issue33140_self_ty - impl has substs!");
322         return None;
323     }
324
325     let predicates = tcx.predicates_of(def_id);
326     if predicates.parent.is_some() || !predicates.predicates.is_empty() {
327         debug!("issue33140_self_ty - impl has predicates {:?}!", predicates);
328         return None;
329     }
330
331     let self_ty = trait_ref.self_ty();
332     let self_ty_matches = match self_ty.kind {
333         ty::Dynamic(ref data, ty::ReStatic) => data.principal().is_none(),
334         _ => false,
335     };
336
337     if self_ty_matches {
338         debug!("issue33140_self_ty - MATCHES!");
339         Some(self_ty)
340     } else {
341         debug!("issue33140_self_ty - non-matching self type");
342         None
343     }
344 }
345
346 /// Check if a function is async.
347 fn asyncness(tcx: TyCtxt<'_>, def_id: DefId) -> hir::IsAsync {
348     let hir_id = tcx
349         .hir()
350         .as_local_hir_id(def_id)
351         .unwrap_or_else(|| bug!("asyncness: expected local `DefId`, got `{:?}`", def_id));
352
353     let node = tcx.hir().get(hir_id);
354
355     let fn_like = hir_map::blocks::FnLikeNode::from_node(node).unwrap_or_else(|| {
356         bug!("asyncness: expected fn-like node but got `{:?}`", def_id);
357     });
358
359     fn_like.asyncness()
360 }
361
362 pub fn provide(providers: &mut ty::query::Providers<'_>) {
363     *providers = ty::query::Providers {
364         asyncness,
365         associated_item,
366         associated_item_def_ids,
367         associated_items,
368         adt_sized_constraint,
369         def_span,
370         param_env,
371         trait_of_item,
372         crate_disambiguator,
373         original_crate_name,
374         crate_hash,
375         instance_def_size_estimate,
376         issue33140_self_ty,
377         ..*providers
378     };
379 }