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