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