]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_ty_utils/src/ty.rs
29f1761b84d2b3e54b4bf5d4340535cf452ab0a4
[rust.git] / compiler / rustc_ty_utils / src / ty.rs
1 use rustc_data_structures::fx::FxIndexSet;
2 use rustc_data_structures::svh::Svh;
3 use rustc_hir as hir;
4 use rustc_hir::def_id::{CrateNum, DefId, LocalDefId, LOCAL_CRATE};
5 use rustc_middle::hir::map as hir_map;
6 use rustc_middle::ty::subst::Subst;
7 use rustc_middle::ty::{
8     self, Binder, Predicate, PredicateKind, ToPredicate, Ty, TyCtxt, WithConstness,
9 };
10 use rustc_session::CrateDisambiguator;
11 use rustc_span::symbol::Symbol;
12 use rustc_span::Span;
13 use rustc_trait_selection::traits;
14
15 fn sized_constraint_for_ty<'tcx>(
16     tcx: TyCtxt<'tcx>,
17     adtdef: &ty::AdtDef,
18     ty: Ty<'tcx>,
19 ) -> Vec<Ty<'tcx>> {
20     use ty::TyKind::*;
21
22     let result = match ty.kind() {
23         Bool | Char | Int(..) | Uint(..) | Float(..) | RawPtr(..) | Ref(..) | FnDef(..)
24         | FnPtr(_) | Array(..) | Closure(..) | Generator(..) | Never => vec![],
25
26         Str | Dynamic(..) | Slice(_) | Foreign(..) | Error(_) | GeneratorWitness(..) => {
27             // these are never sized - return the target type
28             vec![ty]
29         }
30
31         Tuple(ref tys) => match tys.last() {
32             None => vec![],
33             Some(ty) => sized_constraint_for_ty(tcx, adtdef, ty.expect_ty()),
34         },
35
36         Adt(adt, substs) => {
37             // recursive case
38             let adt_tys = adt.sized_constraint(tcx);
39             debug!("sized_constraint_for_ty({:?}) intermediate = {:?}", ty, adt_tys);
40             adt_tys
41                 .iter()
42                 .map(|ty| ty.subst(tcx, substs))
43                 .flat_map(|ty| sized_constraint_for_ty(tcx, adtdef, ty))
44                 .collect()
45         }
46
47         Projection(..) | Opaque(..) => {
48             // must calculate explicitly.
49             // FIXME: consider special-casing always-Sized projections
50             vec![ty]
51         }
52
53         Param(..) => {
54             // perf hack: if there is a `T: Sized` bound, then
55             // we know that `T` is Sized and do not need to check
56             // it on the impl.
57
58             let sized_trait = match tcx.lang_items().sized_trait() {
59                 Some(x) => x,
60                 _ => return vec![ty],
61             };
62             let sized_predicate = ty::Binder::dummy(ty::TraitRef {
63                 def_id: sized_trait,
64                 substs: tcx.mk_substs_trait(ty, &[]),
65             })
66             .without_const()
67             .to_predicate(tcx);
68             let predicates = tcx.predicates_of(adtdef.did).predicates;
69             if predicates.iter().any(|(p, _)| *p == sized_predicate) { vec![] } else { vec![ty] }
70         }
71
72         Placeholder(..) | Bound(..) | Infer(..) => {
73             bug!("unexpected type `{:?}` in sized_constraint_for_ty", ty)
74         }
75     };
76     debug!("sized_constraint_for_ty({:?}) = {:?}", ty, result);
77     result
78 }
79
80 fn associated_item_from_trait_item_ref(
81     tcx: TyCtxt<'_>,
82     parent_def_id: LocalDefId,
83     trait_item_ref: &hir::TraitItemRef,
84 ) -> ty::AssocItem {
85     let def_id = trait_item_ref.id.def_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         vis: tcx.visibility(def_id),
96         defaultness: trait_item_ref.defaultness,
97         def_id: def_id.to_def_id(),
98         container: ty::TraitContainer(parent_def_id.to_def_id()),
99         fn_has_self_parameter: has_self,
100     }
101 }
102
103 fn associated_item_from_impl_item_ref(
104     tcx: TyCtxt<'_>,
105     parent_def_id: LocalDefId,
106     impl_item_ref: &hir::ImplItemRef<'_>,
107 ) -> ty::AssocItem {
108     let def_id = impl_item_ref.id.def_id;
109     let (kind, has_self) = match impl_item_ref.kind {
110         hir::AssocItemKind::Const => (ty::AssocKind::Const, false),
111         hir::AssocItemKind::Fn { has_self } => (ty::AssocKind::Fn, has_self),
112         hir::AssocItemKind::Type => (ty::AssocKind::Type, false),
113     };
114
115     ty::AssocItem {
116         ident: impl_item_ref.ident,
117         kind,
118         vis: tcx.visibility(def_id),
119         defaultness: impl_item_ref.defaultness,
120         def_id: def_id.to_def_id(),
121         container: ty::ImplContainer(parent_def_id.to_def_id()),
122         fn_has_self_parameter: has_self,
123     }
124 }
125
126 fn associated_item(tcx: TyCtxt<'_>, def_id: DefId) -> ty::AssocItem {
127     let id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
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 impl_) => {
133             if let Some(impl_item_ref) =
134                 impl_.items.iter().find(|i| i.id.def_id.to_def_id() == def_id)
135             {
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) =
145                 trait_item_refs.iter().find(|i| i.id.def_id.to_def_id() == def_id)
146             {
147                 let assoc_item =
148                     associated_item_from_trait_item_ref(tcx, parent_def_id, trait_item_ref);
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 fn impl_defaultness(tcx: TyCtxt<'_>, def_id: DefId) -> hir::Defaultness {
165     let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
166     let item = tcx.hir().expect_item(hir_id);
167     if let hir::ItemKind::Impl(impl_) = &item.kind {
168         impl_.defaultness
169     } else {
170         bug!("`impl_defaultness` called on {:?}", item);
171     }
172 }
173
174 /// Calculates the `Sized` constraint.
175 ///
176 /// In fact, there are only a few options for the types in the constraint:
177 ///     - an obviously-unsized type
178 ///     - a type parameter or projection whose Sizedness can't be known
179 ///     - a tuple of type parameters or projections, if there are multiple
180 ///       such.
181 ///     - a Error, if a type contained itself. The representability
182 ///       check should catch this case.
183 fn adt_sized_constraint(tcx: TyCtxt<'_>, def_id: DefId) -> ty::AdtSizedConstraint<'_> {
184     let def = tcx.adt_def(def_id);
185
186     let result = tcx.mk_type_list(
187         def.variants
188             .iter()
189             .flat_map(|v| v.fields.last())
190             .flat_map(|f| sized_constraint_for_ty(tcx, def, tcx.type_of(f.did))),
191     );
192
193     debug!("adt_sized_constraint: {:?} => {:?}", def, result);
194
195     ty::AdtSizedConstraint(result)
196 }
197
198 fn associated_item_def_ids(tcx: TyCtxt<'_>, def_id: DefId) -> &[DefId] {
199     let id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
200     let item = tcx.hir().expect_item(id);
201     match item.kind {
202         hir::ItemKind::Trait(.., ref trait_item_refs) => tcx.arena.alloc_from_iter(
203             trait_item_refs.iter().map(|trait_item_ref| trait_item_ref.id.def_id.to_def_id()),
204         ),
205         hir::ItemKind::Impl(ref impl_) => tcx.arena.alloc_from_iter(
206             impl_.items.iter().map(|impl_item_ref| impl_item_ref.id.def_id.to_def_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: TyCtxt<'_>, def_id: DefId) -> ty::AssociatedItems<'_> {
214     let items = tcx.associated_item_def_ids(def_id).iter().map(|did| tcx.associated_item(*did));
215     ty::AssociatedItems::new(items)
216 }
217
218 fn def_ident_span(tcx: TyCtxt<'_>, def_id: DefId) -> Option<Span> {
219     tcx.hir().get_if_local(def_id).and_then(|node| node.ident()).map(|ident| ident.span)
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 { mut 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     if tcx.sess.opts.debugging_opts.chalk {
256         let environment = well_formed_types_in_env(tcx, def_id);
257         predicates.extend(environment);
258     }
259
260     let unnormalized_env =
261         ty::ParamEnv::new(tcx.intern_predicates(&predicates), traits::Reveal::UserFacing);
262
263     let body_id = def_id
264         .as_local()
265         .map(|def_id| tcx.hir().local_def_id_to_hir_id(def_id))
266         .map_or(hir::CRATE_HIR_ID, |id| {
267             tcx.hir().maybe_body_owned_by(id).map_or(id, |body| body.hir_id)
268         });
269     let cause = traits::ObligationCause::misc(tcx.def_span(def_id), body_id);
270     traits::normalize_param_env_or_error(tcx, def_id, unnormalized_env, cause)
271 }
272
273 /// Elaborate the environment.
274 ///
275 /// Collect a list of `Predicate`'s used for building the `ParamEnv`. Adds `TypeWellFormedFromEnv`'s
276 /// that are assumed to be well-formed (because they come from the environment).
277 ///
278 /// Used only in chalk mode.
279 fn well_formed_types_in_env<'tcx>(
280     tcx: TyCtxt<'tcx>,
281     def_id: DefId,
282 ) -> &'tcx ty::List<Predicate<'tcx>> {
283     use rustc_hir::{ForeignItemKind, ImplItemKind, ItemKind, Node, TraitItemKind};
284     use rustc_middle::ty::subst::GenericArgKind;
285
286     debug!("environment(def_id = {:?})", def_id);
287
288     // The environment of an impl Trait type is its defining function's environment.
289     if let Some(parent) = ty::is_impl_trait_defn(tcx, def_id) {
290         return well_formed_types_in_env(tcx, parent);
291     }
292
293     // Compute the bounds on `Self` and the type parameters.
294     let ty::InstantiatedPredicates { predicates, .. } =
295         tcx.predicates_of(def_id).instantiate_identity(tcx);
296
297     let clauses = predicates.into_iter();
298
299     if !def_id.is_local() {
300         return ty::List::empty();
301     }
302     let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
303     let node = tcx.hir().get(hir_id);
304
305     enum NodeKind {
306         TraitImpl,
307         InherentImpl,
308         Fn,
309         Other,
310     }
311
312     let node_kind = match node {
313         Node::TraitItem(item) => match item.kind {
314             TraitItemKind::Fn(..) => NodeKind::Fn,
315             _ => NodeKind::Other,
316         },
317
318         Node::ImplItem(item) => match item.kind {
319             ImplItemKind::Fn(..) => NodeKind::Fn,
320             _ => NodeKind::Other,
321         },
322
323         Node::Item(item) => match item.kind {
324             ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }) => NodeKind::TraitImpl,
325             ItemKind::Impl(hir::Impl { of_trait: None, .. }) => NodeKind::InherentImpl,
326             ItemKind::Fn(..) => NodeKind::Fn,
327             _ => NodeKind::Other,
328         },
329
330         Node::ForeignItem(item) => match item.kind {
331             ForeignItemKind::Fn(..) => NodeKind::Fn,
332             _ => NodeKind::Other,
333         },
334
335         // FIXME: closures?
336         _ => NodeKind::Other,
337     };
338
339     // FIXME(eddyb) isn't the unordered nature of this a hazard?
340     let mut inputs = FxIndexSet::default();
341
342     match node_kind {
343         // In a trait impl, we assume that the header trait ref and all its
344         // constituents are well-formed.
345         NodeKind::TraitImpl => {
346             let trait_ref = tcx.impl_trait_ref(def_id).expect("not an impl");
347
348             // FIXME(chalk): this has problems because of late-bound regions
349             //inputs.extend(trait_ref.substs.iter().flat_map(|arg| arg.walk()));
350             inputs.extend(trait_ref.substs.iter());
351         }
352
353         // In an inherent impl, we assume that the receiver type and all its
354         // constituents are well-formed.
355         NodeKind::InherentImpl => {
356             let self_ty = tcx.type_of(def_id);
357             inputs.extend(self_ty.walk());
358         }
359
360         // In an fn, we assume that the arguments and all their constituents are
361         // well-formed.
362         NodeKind::Fn => {
363             let fn_sig = tcx.fn_sig(def_id);
364             let fn_sig = tcx.liberate_late_bound_regions(def_id, fn_sig);
365
366             inputs.extend(fn_sig.inputs().iter().flat_map(|ty| ty.walk()));
367         }
368
369         NodeKind::Other => (),
370     }
371     let input_clauses = inputs.into_iter().filter_map(|arg| {
372         match arg.unpack() {
373             GenericArgKind::Type(ty) => {
374                 let binder = Binder::dummy(PredicateKind::TypeWellFormedFromEnv(ty));
375                 Some(tcx.mk_predicate(binder))
376             }
377
378             // FIXME(eddyb) no WF conditions from lifetimes?
379             GenericArgKind::Lifetime(_) => None,
380
381             // FIXME(eddyb) support const generics in Chalk
382             GenericArgKind::Const(_) => None,
383         }
384     });
385
386     tcx.mk_predicates(clauses.chain(input_clauses))
387 }
388
389 fn param_env_reveal_all_normalized(tcx: TyCtxt<'_>, def_id: DefId) -> ty::ParamEnv<'_> {
390     tcx.param_env(def_id).with_reveal_all_normalized(tcx)
391 }
392
393 fn crate_disambiguator(tcx: TyCtxt<'_>, crate_num: CrateNum) -> CrateDisambiguator {
394     assert_eq!(crate_num, LOCAL_CRATE);
395     tcx.sess.local_crate_disambiguator()
396 }
397
398 fn original_crate_name(tcx: TyCtxt<'_>, crate_num: CrateNum) -> Symbol {
399     assert_eq!(crate_num, LOCAL_CRATE);
400     tcx.crate_name
401 }
402
403 fn crate_hash(tcx: TyCtxt<'_>, crate_num: CrateNum) -> Svh {
404     tcx.index_hir(crate_num).crate_hash
405 }
406
407 fn instance_def_size_estimate<'tcx>(
408     tcx: TyCtxt<'tcx>,
409     instance_def: ty::InstanceDef<'tcx>,
410 ) -> usize {
411     use ty::InstanceDef;
412
413     match instance_def {
414         InstanceDef::Item(..) | InstanceDef::DropGlue(..) => {
415             let mir = tcx.instance_mir(instance_def);
416             mir.basic_blocks().iter().map(|bb| bb.statements.len()).sum()
417         }
418         // Estimate the size of other compiler-generated shims to be 1.
419         _ => 1,
420     }
421 }
422
423 /// If `def_id` is an issue 33140 hack impl, returns its self type; otherwise, returns `None`.
424 ///
425 /// See [`ty::ImplOverlapKind::Issue33140`] for more details.
426 fn issue33140_self_ty(tcx: TyCtxt<'_>, def_id: DefId) -> Option<Ty<'_>> {
427     debug!("issue33140_self_ty({:?})", def_id);
428
429     let trait_ref = tcx
430         .impl_trait_ref(def_id)
431         .unwrap_or_else(|| bug!("issue33140_self_ty called on inherent impl {:?}", def_id));
432
433     debug!("issue33140_self_ty({:?}), trait-ref={:?}", def_id, trait_ref);
434
435     let is_marker_like = tcx.impl_polarity(def_id) == ty::ImplPolarity::Positive
436         && tcx.associated_item_def_ids(trait_ref.def_id).is_empty();
437
438     // Check whether these impls would be ok for a marker trait.
439     if !is_marker_like {
440         debug!("issue33140_self_ty - not marker-like!");
441         return None;
442     }
443
444     // impl must be `impl Trait for dyn Marker1 + Marker2 + ...`
445     if trait_ref.substs.len() != 1 {
446         debug!("issue33140_self_ty - impl has substs!");
447         return None;
448     }
449
450     let predicates = tcx.predicates_of(def_id);
451     if predicates.parent.is_some() || !predicates.predicates.is_empty() {
452         debug!("issue33140_self_ty - impl has predicates {:?}!", predicates);
453         return None;
454     }
455
456     let self_ty = trait_ref.self_ty();
457     let self_ty_matches = match self_ty.kind() {
458         ty::Dynamic(ref data, ty::ReStatic) => data.principal().is_none(),
459         _ => false,
460     };
461
462     if self_ty_matches {
463         debug!("issue33140_self_ty - MATCHES!");
464         Some(self_ty)
465     } else {
466         debug!("issue33140_self_ty - non-matching self type");
467         None
468     }
469 }
470
471 /// Check if a function is async.
472 fn asyncness(tcx: TyCtxt<'_>, def_id: DefId) -> hir::IsAsync {
473     let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
474
475     let node = tcx.hir().get(hir_id);
476
477     let fn_like = hir_map::blocks::FnLikeNode::from_node(node).unwrap_or_else(|| {
478         bug!("asyncness: expected fn-like node but got `{:?}`", def_id);
479     });
480
481     fn_like.asyncness()
482 }
483
484 /// Don't call this directly: use ``tcx.conservative_is_privately_uninhabited`` instead.
485 #[instrument(level = "debug", skip(tcx))]
486 pub fn conservative_is_privately_uninhabited_raw<'tcx>(
487     tcx: TyCtxt<'tcx>,
488     param_env_and: ty::ParamEnvAnd<'tcx, Ty<'tcx>>,
489 ) -> bool {
490     let (param_env, ty) = param_env_and.into_parts();
491     match ty.kind() {
492         ty::Never => {
493             debug!("ty::Never =>");
494             true
495         }
496         ty::Adt(def, _) if def.is_union() => {
497             debug!("ty::Adt(def, _) if def.is_union() =>");
498             // For now, `union`s are never considered uninhabited.
499             false
500         }
501         ty::Adt(def, substs) => {
502             debug!("ty::Adt(def, _) if def.is_not_union() =>");
503             // Any ADT is uninhabited if either:
504             // (a) It has no variants (i.e. an empty `enum`);
505             // (b) Each of its variants (a single one in the case of a `struct`) has at least
506             //     one uninhabited field.
507             def.variants.iter().all(|var| {
508                 var.fields.iter().any(|field| {
509                     let ty = tcx.type_of(field.did).subst(tcx, substs);
510                     tcx.conservative_is_privately_uninhabited(param_env.and(ty))
511                 })
512             })
513         }
514         ty::Tuple(..) => {
515             debug!("ty::Tuple(..) =>");
516             ty.tuple_fields().any(|ty| tcx.conservative_is_privately_uninhabited(param_env.and(ty)))
517         }
518         ty::Array(ty, len) => {
519             debug!("ty::Array(ty, len) =>");
520             match len.try_eval_usize(tcx, param_env) {
521                 Some(0) | None => false,
522                 // If the array is definitely non-empty, it's uninhabited if
523                 // the type of its elements is uninhabited.
524                 Some(1..) => tcx.conservative_is_privately_uninhabited(param_env.and(ty)),
525             }
526         }
527         ty::Ref(..) => {
528             debug!("ty::Ref(..) =>");
529             // References to uninitialised memory is valid for any type, including
530             // uninhabited types, in unsafe code, so we treat all references as
531             // inhabited.
532             false
533         }
534         _ => {
535             debug!("_ =>");
536             false
537         }
538     }
539 }
540
541 pub fn provide(providers: &mut ty::query::Providers) {
542     *providers = ty::query::Providers {
543         asyncness,
544         associated_item,
545         associated_item_def_ids,
546         associated_items,
547         adt_sized_constraint,
548         def_ident_span,
549         param_env,
550         param_env_reveal_all_normalized,
551         trait_of_item,
552         crate_disambiguator,
553         original_crate_name,
554         crate_hash,
555         instance_def_size_estimate,
556         issue33140_self_ty,
557         impl_defaultness,
558         conservative_is_privately_uninhabited: conservative_is_privately_uninhabited_raw,
559         ..*providers
560     };
561 }