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