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