]> git.lizzy.rs Git - rust.git/blob - src/librustc_ty/ty.rs
Move some const-eval `build-pass` tests to `check-pass`
[rust.git] / src / librustc_ty / ty.rs
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;
6 use rustc_hir as hir;
7 use rustc_hir::def_id::{CrateNum, DefId, LOCAL_CRATE};
8 use rustc_infer::traits;
9 use rustc_span::symbol::Symbol;
10 use rustc_span::Span;
11
12 fn sized_constraint_for_ty<'tcx>(
13     tcx: TyCtxt<'tcx>,
14     adtdef: &ty::AdtDef,
15     ty: Ty<'tcx>,
16 ) -> Vec<Ty<'tcx>> {
17     use ty::TyKind::*;
18
19     let result = match ty.kind {
20         Bool | Char | Int(..) | Uint(..) | Float(..) | RawPtr(..) | Ref(..) | FnDef(..)
21         | FnPtr(_) | Array(..) | Closure(..) | Generator(..) | Never => vec![],
22
23         Str | Dynamic(..) | Slice(_) | Foreign(..) | Error | GeneratorWitness(..) => {
24             // these are never sized - return the target type
25             vec![ty]
26         }
27
28         Tuple(ref tys) => match tys.last() {
29             None => vec![],
30             Some(ty) => sized_constraint_for_ty(tcx, adtdef, ty.expect_ty()),
31         },
32
33         Adt(adt, substs) => {
34             // recursive case
35             let adt_tys = adt.sized_constraint(tcx);
36             debug!("sized_constraint_for_ty({:?}) intermediate = {:?}", ty, adt_tys);
37             adt_tys
38                 .iter()
39                 .map(|ty| ty.subst(tcx, substs))
40                 .flat_map(|ty| sized_constraint_for_ty(tcx, adtdef, ty))
41                 .collect()
42         }
43
44         Projection(..) | Opaque(..) => {
45             // must calculate explicitly.
46             // FIXME: consider special-casing always-Sized projections
47             vec![ty]
48         }
49
50         UnnormalizedProjection(..) => bug!("only used with chalk-engine"),
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();
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: DefId,
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::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"),
91     };
92
93     ty::AssocItem {
94         ident: trait_item_ref.ident,
95         kind,
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,
100         container: ty::TraitContainer(parent_def_id),
101         method_has_self_argument: has_self,
102     }
103 }
104
105 fn associated_item_from_impl_item_ref(
106     tcx: TyCtxt<'_>,
107     parent_def_id: DefId,
108     impl_item_ref: &hir::ImplItemRef<'_>,
109 ) -> ty::AssocItem {
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),
116     };
117
118     ty::AssocItem {
119         ident: impl_item_ref.ident,
120         kind,
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,
125         container: ty::ImplContainer(parent_def_id),
126         method_has_self_argument: has_self,
127     }
128 }
129
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) {
138                 let assoc_item =
139                     associated_item_from_impl_item_ref(tcx, parent_def_id, impl_item_ref);
140                 debug_assert_eq!(assoc_item.def_id, def_id);
141                 return assoc_item;
142             }
143         }
144
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(
148                     tcx,
149                     parent_def_id,
150                     &parent_item.vis,
151                     trait_item_ref,
152                 );
153                 debug_assert_eq!(assoc_item.def_id, def_id);
154                 return assoc_item;
155             }
156         }
157
158         _ => {}
159     }
160
161     span_bug!(
162         parent_item.span,
163         "unexpected parent of trait or impl item or item not found: {:?}",
164         parent_item.kind
165     )
166 }
167
168 /// Calculates the `Sized` constraint.
169 ///
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
174 ///       such.
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);
179
180     let result = tcx.mk_type_list(
181         def.variants
182             .iter()
183             .flat_map(|v| v.fields.last())
184             .flat_map(|f| sized_constraint_for_ty(tcx, def, tcx.type_of(f.did))),
185     );
186
187     debug!("adt_sized_constraint: {:?} => {:?}", def, result);
188
189     ty::AdtSizedConstraint(result)
190 }
191
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);
195     match item.kind {
196         hir::ItemKind::Trait(.., ref trait_item_refs) => tcx.arena.alloc_from_iter(
197             trait_item_refs
198                 .iter()
199                 .map(|trait_item_ref| trait_item_ref.id)
200                 .map(|id| tcx.hir().local_def_id(id.hir_id)),
201         ),
202         hir::ItemKind::Impl { ref items, .. } => tcx.arena.alloc_from_iter(
203             items
204                 .iter()
205                 .map(|impl_item_ref| impl_item_ref.id)
206                 .map(|id| tcx.hir().local_def_id(id.hir_id)),
207         ),
208         hir::ItemKind::TraitAlias(..) => &[],
209         _ => span_bug!(item.span, "associated_item_def_ids: not impl or trait"),
210     }
211 }
212
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))
216 }
217
218 fn def_span(tcx: TyCtxt<'_>, def_id: DefId) -> Span {
219     tcx.hir().span_if_local(def_id).unwrap()
220 }
221
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,
229     })
230 }
231
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);
237     }
238     // Compute the bounds on Self and the type parameters.
239
240     let ty::InstantiatedPredicates { predicates, .. } =
241         tcx.predicates_of(def_id).instantiate_identity(tcx);
242
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.
254
255     let unnormalized_env =
256         ty::ParamEnv::new(tcx.intern_predicates(&predicates), traits::Reveal::UserFacing, None);
257
258     let body_id = tcx.hir().as_local_hir_id(def_id).map_or(hir::DUMMY_HIR_ID, |id| {
259         tcx.hir().maybe_body_owned_by(id).map_or(id, |body| body.hir_id)
260     });
261     let cause = traits::ObligationCause::misc(tcx.def_span(def_id), body_id);
262     traits::normalize_param_env_or_error(tcx, def_id, unnormalized_env, cause)
263 }
264
265 fn crate_disambiguator(tcx: TyCtxt<'_>, crate_num: CrateNum) -> CrateDisambiguator {
266     assert_eq!(crate_num, LOCAL_CRATE);
267     tcx.sess.local_crate_disambiguator()
268 }
269
270 fn original_crate_name(tcx: TyCtxt<'_>, crate_num: CrateNum) -> Symbol {
271     assert_eq!(crate_num, LOCAL_CRATE);
272     tcx.crate_name
273 }
274
275 fn crate_hash(tcx: TyCtxt<'_>, crate_num: CrateNum) -> Svh {
276     assert_eq!(crate_num, LOCAL_CRATE);
277     tcx.hir().crate_hash
278 }
279
280 fn instance_def_size_estimate<'tcx>(
281     tcx: TyCtxt<'tcx>,
282     instance_def: ty::InstanceDef<'tcx>,
283 ) -> usize {
284     use ty::InstanceDef;
285
286     match instance_def {
287         InstanceDef::Item(..) | InstanceDef::DropGlue(..) => {
288             let mir = tcx.instance_mir(instance_def);
289             mir.basic_blocks().iter().map(|bb| bb.statements.len()).sum()
290         }
291         // Estimate the size of other compiler-generated shims to be 1.
292         _ => 1,
293     }
294 }
295
296 /// If `def_id` is an issue 33140 hack impl, returns its self type; otherwise, returns `None`.
297 ///
298 /// See [`ImplOverlapKind::Issue33140`] for more details.
299 fn issue33140_self_ty(tcx: TyCtxt<'_>, def_id: DefId) -> Option<Ty<'_>> {
300     debug!("issue33140_self_ty({:?})", def_id);
301
302     let trait_ref = tcx
303         .impl_trait_ref(def_id)
304         .unwrap_or_else(|| bug!("issue33140_self_ty called on inherent impl {:?}", def_id));
305
306     debug!("issue33140_self_ty({:?}), trait-ref={:?}", def_id, trait_ref);
307
308     let is_marker_like = tcx.impl_polarity(def_id) == ty::ImplPolarity::Positive
309         && tcx.associated_item_def_ids(trait_ref.def_id).is_empty();
310
311     // Check whether these impls would be ok for a marker trait.
312     if !is_marker_like {
313         debug!("issue33140_self_ty - not marker-like!");
314         return None;
315     }
316
317     // impl must be `impl Trait for dyn Marker1 + Marker2 + ...`
318     if trait_ref.substs.len() != 1 {
319         debug!("issue33140_self_ty - impl has substs!");
320         return None;
321     }
322
323     let predicates = tcx.predicates_of(def_id);
324     if predicates.parent.is_some() || !predicates.predicates.is_empty() {
325         debug!("issue33140_self_ty - impl has predicates {:?}!", predicates);
326         return None;
327     }
328
329     let self_ty = trait_ref.self_ty();
330     let self_ty_matches = match self_ty.kind {
331         ty::Dynamic(ref data, ty::ReStatic) => data.principal().is_none(),
332         _ => false,
333     };
334
335     if self_ty_matches {
336         debug!("issue33140_self_ty - MATCHES!");
337         Some(self_ty)
338     } else {
339         debug!("issue33140_self_ty - non-matching self type");
340         None
341     }
342 }
343
344 /// Check if a function is async.
345 fn asyncness(tcx: TyCtxt<'_>, def_id: DefId) -> hir::IsAsync {
346     let hir_id = tcx
347         .hir()
348         .as_local_hir_id(def_id)
349         .unwrap_or_else(|| bug!("asyncness: expected local `DefId`, got `{:?}`", def_id));
350
351     let node = tcx.hir().get(hir_id);
352
353     let fn_like = hir_map::blocks::FnLikeNode::from_node(node).unwrap_or_else(|| {
354         bug!("asyncness: expected fn-like node but got `{:?}`", def_id);
355     });
356
357     fn_like.asyncness()
358 }
359
360 pub fn provide(providers: &mut ty::query::Providers<'_>) {
361     *providers = ty::query::Providers {
362         asyncness,
363         associated_item,
364         associated_item_def_ids,
365         associated_items,
366         adt_sized_constraint,
367         def_span,
368         param_env,
369         trait_of_item,
370         crate_disambiguator,
371         original_crate_name,
372         crate_hash,
373         instance_def_size_estimate,
374         issue33140_self_ty,
375         ..*providers
376     };
377 }