]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_ty_utils/src/ty.rs
Rollup merge of #102072 - scottmcm:ptr-alignment-type, 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::{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 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 fn param_env(tcx: TyCtxt<'_>, def_id: DefId) -> ty::ParamEnv<'_> {
107     // The param_env of an impl Trait type is its defining function's param_env
108     if let Some(parent) = ty::is_impl_trait_defn(tcx, def_id) {
109         return param_env(tcx, parent.to_def_id());
110     }
111     // Compute the bounds on Self and the type parameters.
112
113     let ty::InstantiatedPredicates { mut predicates, .. } =
114         tcx.predicates_of(def_id).instantiate_identity(tcx);
115
116     // Finally, we have to normalize the bounds in the environment, in
117     // case they contain any associated type projections. This process
118     // can yield errors if the put in illegal associated types, like
119     // `<i32 as Foo>::Bar` where `i32` does not implement `Foo`. We
120     // report these errors right here; this doesn't actually feel
121     // right to me, because constructing the environment feels like a
122     // kind of an "idempotent" action, but I'm not sure where would be
123     // a better place. In practice, we construct environments for
124     // every fn once during type checking, and we'll abort if there
125     // are any errors at that point, so outside of type inference you can be
126     // sure that this will succeed without errors anyway.
127
128     if tcx.sess.opts.unstable_opts.chalk {
129         let environment = well_formed_types_in_env(tcx, def_id);
130         predicates.extend(environment);
131     }
132
133     let local_did = def_id.as_local();
134     let hir_id = local_did.map(|def_id| tcx.hir().local_def_id_to_hir_id(def_id));
135
136     let constness = match hir_id {
137         Some(hir_id) => match tcx.hir().get(hir_id) {
138             hir::Node::TraitItem(hir::TraitItem { kind: hir::TraitItemKind::Fn(..), .. })
139                 if tcx.is_const_default_method(def_id) =>
140             {
141                 hir::Constness::Const
142             }
143
144             hir::Node::Item(hir::Item { kind: hir::ItemKind::Const(..), .. })
145             | hir::Node::Item(hir::Item { kind: hir::ItemKind::Static(..), .. })
146             | hir::Node::TraitItem(hir::TraitItem {
147                 kind: hir::TraitItemKind::Const(..), ..
148             })
149             | hir::Node::AnonConst(_)
150             | hir::Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Const(..), .. })
151             | hir::Node::ImplItem(hir::ImplItem {
152                 kind:
153                     hir::ImplItemKind::Fn(
154                         hir::FnSig {
155                             header: hir::FnHeader { constness: hir::Constness::Const, .. },
156                             ..
157                         },
158                         ..,
159                     ),
160                 ..
161             }) => hir::Constness::Const,
162
163             hir::Node::ImplItem(hir::ImplItem {
164                 kind: hir::ImplItemKind::TyAlias(..) | hir::ImplItemKind::Fn(..),
165                 ..
166             }) => {
167                 let parent_hir_id = tcx.hir().get_parent_node(hir_id);
168                 match tcx.hir().get(parent_hir_id) {
169                     hir::Node::Item(hir::Item {
170                         kind: hir::ItemKind::Impl(hir::Impl { constness, .. }),
171                         ..
172                     }) => *constness,
173                     _ => span_bug!(
174                         tcx.def_span(parent_hir_id.owner),
175                         "impl item's parent node is not an impl",
176                     ),
177                 }
178             }
179
180             hir::Node::Item(hir::Item {
181                 kind:
182                     hir::ItemKind::Fn(hir::FnSig { header: hir::FnHeader { constness, .. }, .. }, ..),
183                 ..
184             })
185             | hir::Node::TraitItem(hir::TraitItem {
186                 kind:
187                     hir::TraitItemKind::Fn(
188                         hir::FnSig { header: hir::FnHeader { constness, .. }, .. },
189                         ..,
190                     ),
191                 ..
192             })
193             | hir::Node::Item(hir::Item {
194                 kind: hir::ItemKind::Impl(hir::Impl { constness, .. }),
195                 ..
196             }) => *constness,
197
198             _ => hir::Constness::NotConst,
199         },
200         None => hir::Constness::NotConst,
201     };
202
203     let unnormalized_env = ty::ParamEnv::new(
204         tcx.intern_predicates(&predicates),
205         traits::Reveal::UserFacing,
206         constness,
207     );
208
209     let body_id =
210         local_did.and_then(|id| tcx.hir().maybe_body_owned_by(id).map(|body| body.hir_id));
211     let body_id = match body_id {
212         Some(id) => id,
213         None if hir_id.is_some() => hir_id.unwrap(),
214         _ => hir::CRATE_HIR_ID,
215     };
216
217     let cause = traits::ObligationCause::misc(tcx.def_span(def_id), body_id);
218     traits::normalize_param_env_or_error(tcx, unnormalized_env, cause)
219 }
220
221 /// Elaborate the environment.
222 ///
223 /// Collect a list of `Predicate`'s used for building the `ParamEnv`. Adds `TypeWellFormedFromEnv`'s
224 /// that are assumed to be well-formed (because they come from the environment).
225 ///
226 /// Used only in chalk mode.
227 fn well_formed_types_in_env<'tcx>(
228     tcx: TyCtxt<'tcx>,
229     def_id: DefId,
230 ) -> &'tcx ty::List<Predicate<'tcx>> {
231     use rustc_hir::{ForeignItemKind, ImplItemKind, ItemKind, Node, TraitItemKind};
232     use rustc_middle::ty::subst::GenericArgKind;
233
234     debug!("environment(def_id = {:?})", def_id);
235
236     // The environment of an impl Trait type is its defining function's environment.
237     if let Some(parent) = ty::is_impl_trait_defn(tcx, def_id) {
238         return well_formed_types_in_env(tcx, parent.to_def_id());
239     }
240
241     // Compute the bounds on `Self` and the type parameters.
242     let ty::InstantiatedPredicates { predicates, .. } =
243         tcx.predicates_of(def_id).instantiate_identity(tcx);
244
245     let clauses = predicates.into_iter();
246
247     if !def_id.is_local() {
248         return ty::List::empty();
249     }
250     let node = tcx.hir().get_by_def_id(def_id.expect_local());
251
252     enum NodeKind {
253         TraitImpl,
254         InherentImpl,
255         Fn,
256         Other,
257     }
258
259     let node_kind = match node {
260         Node::TraitItem(item) => match item.kind {
261             TraitItemKind::Fn(..) => NodeKind::Fn,
262             _ => NodeKind::Other,
263         },
264
265         Node::ImplItem(item) => match item.kind {
266             ImplItemKind::Fn(..) => NodeKind::Fn,
267             _ => NodeKind::Other,
268         },
269
270         Node::Item(item) => match item.kind {
271             ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }) => NodeKind::TraitImpl,
272             ItemKind::Impl(hir::Impl { of_trait: None, .. }) => NodeKind::InherentImpl,
273             ItemKind::Fn(..) => NodeKind::Fn,
274             _ => NodeKind::Other,
275         },
276
277         Node::ForeignItem(item) => match item.kind {
278             ForeignItemKind::Fn(..) => NodeKind::Fn,
279             _ => NodeKind::Other,
280         },
281
282         // FIXME: closures?
283         _ => NodeKind::Other,
284     };
285
286     // FIXME(eddyb) isn't the unordered nature of this a hazard?
287     let mut inputs = FxIndexSet::default();
288
289     match node_kind {
290         // In a trait impl, we assume that the header trait ref and all its
291         // constituents are well-formed.
292         NodeKind::TraitImpl => {
293             let trait_ref = tcx.impl_trait_ref(def_id).expect("not an impl");
294
295             // FIXME(chalk): this has problems because of late-bound regions
296             //inputs.extend(trait_ref.substs.iter().flat_map(|arg| arg.walk()));
297             inputs.extend(trait_ref.substs.iter());
298         }
299
300         // In an inherent impl, we assume that the receiver type and all its
301         // constituents are well-formed.
302         NodeKind::InherentImpl => {
303             let self_ty = tcx.type_of(def_id);
304             inputs.extend(self_ty.walk());
305         }
306
307         // In an fn, we assume that the arguments and all their constituents are
308         // well-formed.
309         NodeKind::Fn => {
310             let fn_sig = tcx.fn_sig(def_id);
311             let fn_sig = tcx.liberate_late_bound_regions(def_id, fn_sig);
312
313             inputs.extend(fn_sig.inputs().iter().flat_map(|ty| ty.walk()));
314         }
315
316         NodeKind::Other => (),
317     }
318     let input_clauses = inputs.into_iter().filter_map(|arg| {
319         match arg.unpack() {
320             GenericArgKind::Type(ty) => {
321                 let binder = Binder::dummy(PredicateKind::TypeWellFormedFromEnv(ty));
322                 Some(tcx.mk_predicate(binder))
323             }
324
325             // FIXME(eddyb) no WF conditions from lifetimes?
326             GenericArgKind::Lifetime(_) => None,
327
328             // FIXME(eddyb) support const generics in Chalk
329             GenericArgKind::Const(_) => None,
330         }
331     });
332
333     tcx.mk_predicates(clauses.chain(input_clauses))
334 }
335
336 fn param_env_reveal_all_normalized(tcx: TyCtxt<'_>, def_id: DefId) -> ty::ParamEnv<'_> {
337     tcx.param_env(def_id).with_reveal_all_normalized(tcx)
338 }
339
340 fn instance_def_size_estimate<'tcx>(
341     tcx: TyCtxt<'tcx>,
342     instance_def: ty::InstanceDef<'tcx>,
343 ) -> usize {
344     use ty::InstanceDef;
345
346     match instance_def {
347         InstanceDef::Item(..) | InstanceDef::DropGlue(..) => {
348             let mir = tcx.instance_mir(instance_def);
349             mir.basic_blocks.iter().map(|bb| bb.statements.len() + 1).sum()
350         }
351         // Estimate the size of other compiler-generated shims to be 1.
352         _ => 1,
353     }
354 }
355
356 /// If `def_id` is an issue 33140 hack impl, returns its self type; otherwise, returns `None`.
357 ///
358 /// See [`ty::ImplOverlapKind::Issue33140`] for more details.
359 fn issue33140_self_ty(tcx: TyCtxt<'_>, def_id: DefId) -> Option<Ty<'_>> {
360     debug!("issue33140_self_ty({:?})", def_id);
361
362     let trait_ref = tcx
363         .impl_trait_ref(def_id)
364         .unwrap_or_else(|| bug!("issue33140_self_ty called on inherent impl {:?}", def_id));
365
366     debug!("issue33140_self_ty({:?}), trait-ref={:?}", def_id, trait_ref);
367
368     let is_marker_like = tcx.impl_polarity(def_id) == ty::ImplPolarity::Positive
369         && tcx.associated_item_def_ids(trait_ref.def_id).is_empty();
370
371     // Check whether these impls would be ok for a marker trait.
372     if !is_marker_like {
373         debug!("issue33140_self_ty - not marker-like!");
374         return None;
375     }
376
377     // impl must be `impl Trait for dyn Marker1 + Marker2 + ...`
378     if trait_ref.substs.len() != 1 {
379         debug!("issue33140_self_ty - impl has substs!");
380         return None;
381     }
382
383     let predicates = tcx.predicates_of(def_id);
384     if predicates.parent.is_some() || !predicates.predicates.is_empty() {
385         debug!("issue33140_self_ty - impl has predicates {:?}!", predicates);
386         return None;
387     }
388
389     let self_ty = trait_ref.self_ty();
390     let self_ty_matches = match self_ty.kind() {
391         ty::Dynamic(ref data, re, _) if re.is_static() => data.principal().is_none(),
392         _ => false,
393     };
394
395     if self_ty_matches {
396         debug!("issue33140_self_ty - MATCHES!");
397         Some(self_ty)
398     } else {
399         debug!("issue33140_self_ty - non-matching self type");
400         None
401     }
402 }
403
404 /// Check if a function is async.
405 fn asyncness(tcx: TyCtxt<'_>, def_id: DefId) -> hir::IsAsync {
406     let node = tcx.hir().get_by_def_id(def_id.expect_local());
407     if let Some(fn_kind) = node.fn_kind() { fn_kind.asyncness() } else { hir::IsAsync::NotAsync }
408 }
409
410 /// Don't call this directly: use ``tcx.conservative_is_privately_uninhabited`` instead.
411 pub fn conservative_is_privately_uninhabited_raw<'tcx>(
412     tcx: TyCtxt<'tcx>,
413     param_env_and: ty::ParamEnvAnd<'tcx, Ty<'tcx>>,
414 ) -> bool {
415     let (param_env, ty) = param_env_and.into_parts();
416     match ty.kind() {
417         ty::Never => {
418             debug!("ty::Never =>");
419             true
420         }
421         ty::Adt(def, _) if def.is_union() => {
422             debug!("ty::Adt(def, _) if def.is_union() =>");
423             // For now, `union`s are never considered uninhabited.
424             false
425         }
426         ty::Adt(def, substs) => {
427             debug!("ty::Adt(def, _) if def.is_not_union() =>");
428             // Any ADT is uninhabited if either:
429             // (a) It has no variants (i.e. an empty `enum`);
430             // (b) Each of its variants (a single one in the case of a `struct`) has at least
431             //     one uninhabited field.
432             def.variants().iter().all(|var| {
433                 var.fields.iter().any(|field| {
434                     let ty = tcx.bound_type_of(field.did).subst(tcx, substs);
435                     tcx.conservative_is_privately_uninhabited(param_env.and(ty))
436                 })
437             })
438         }
439         ty::Tuple(fields) => {
440             debug!("ty::Tuple(..) =>");
441             fields.iter().any(|ty| tcx.conservative_is_privately_uninhabited(param_env.and(ty)))
442         }
443         ty::Array(ty, len) => {
444             debug!("ty::Array(ty, len) =>");
445             match len.try_eval_usize(tcx, param_env) {
446                 Some(0) | None => false,
447                 // If the array is definitely non-empty, it's uninhabited if
448                 // the type of its elements is uninhabited.
449                 Some(1..) => tcx.conservative_is_privately_uninhabited(param_env.and(*ty)),
450             }
451         }
452         ty::Ref(..) => {
453             debug!("ty::Ref(..) =>");
454             // References to uninitialised memory is valid for any type, including
455             // uninhabited types, in unsafe code, so we treat all references as
456             // inhabited.
457             false
458         }
459         _ => {
460             debug!("_ =>");
461             false
462         }
463     }
464 }
465
466 pub fn provide(providers: &mut ty::query::Providers) {
467     *providers = ty::query::Providers {
468         asyncness,
469         adt_sized_constraint,
470         param_env,
471         param_env_reveal_all_normalized,
472         instance_def_size_estimate,
473         issue33140_self_ty,
474         impl_defaultness,
475         conservative_is_privately_uninhabited: conservative_is_privately_uninhabited_raw,
476         ..*providers
477     };
478 }