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