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