]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_ty_utils/src/ty.rs
Rollup merge of #102406 - mejrs:missing_copy, r=wesleywiser
[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(tcx.mk_trait_ref(sized_trait, [ty]))
53                 .without_const()
54                 .to_predicate(tcx);
55             let predicates = tcx.predicates_of(adtdef.did()).predicates;
56             if predicates.iter().any(|(p, _)| *p == sized_predicate) { vec![] } else { vec![ty] }
57         }
58
59         Placeholder(..) | Bound(..) | Infer(..) => {
60             bug!("unexpected type `{:?}` in sized_constraint_for_ty", ty)
61         }
62     };
63     debug!("sized_constraint_for_ty({:?}) = {:?}", ty, result);
64     result
65 }
66
67 fn impl_defaultness(tcx: TyCtxt<'_>, def_id: DefId) -> hir::Defaultness {
68     match tcx.hir().get_by_def_id(def_id.expect_local()) {
69         hir::Node::Item(hir::Item { kind: hir::ItemKind::Impl(impl_), .. }) => impl_.defaultness,
70         hir::Node::ImplItem(hir::ImplItem { defaultness, .. })
71         | hir::Node::TraitItem(hir::TraitItem { defaultness, .. }) => *defaultness,
72         node => {
73             bug!("`impl_defaultness` called on {:?}", node);
74         }
75     }
76 }
77
78 /// Calculates the `Sized` constraint.
79 ///
80 /// In fact, there are only a few options for the types in the constraint:
81 ///     - an obviously-unsized type
82 ///     - a type parameter or projection whose Sizedness can't be known
83 ///     - a tuple of type parameters or projections, if there are multiple
84 ///       such.
85 ///     - an Error, if a type is infinitely sized
86 fn adt_sized_constraint(tcx: TyCtxt<'_>, def_id: DefId) -> &[Ty<'_>] {
87     if let Some(def_id) = def_id.as_local() {
88         if matches!(tcx.representability(def_id), ty::Representability::Infinite) {
89             return tcx.intern_type_list(&[tcx.ty_error()]);
90         }
91     }
92     let def = tcx.adt_def(def_id);
93
94     let result = tcx.mk_type_list(
95         def.variants()
96             .iter()
97             .flat_map(|v| v.fields.last())
98             .flat_map(|f| sized_constraint_for_ty(tcx, def, tcx.type_of(f.did))),
99     );
100
101     debug!("adt_sized_constraint: {:?} => {:?}", def, result);
102
103     result
104 }
105
106 /// See `ParamEnv` struct definition for details.
107 fn param_env(tcx: TyCtxt<'_>, def_id: DefId) -> ty::ParamEnv<'_> {
108     // Compute the bounds on Self and the type parameters.
109     let ty::InstantiatedPredicates { mut predicates, .. } =
110         tcx.predicates_of(def_id).instantiate_identity(tcx);
111
112     // Finally, we have to normalize the bounds in the environment, in
113     // case they contain any associated type projections. This process
114     // can yield errors if the put in illegal associated types, like
115     // `<i32 as Foo>::Bar` where `i32` does not implement `Foo`. We
116     // report these errors right here; this doesn't actually feel
117     // right to me, because constructing the environment feels like a
118     // kind of an "idempotent" action, but I'm not sure where would be
119     // a better place. In practice, we construct environments for
120     // every fn once during type checking, and we'll abort if there
121     // are any errors at that point, so outside of type inference you can be
122     // sure that this will succeed without errors anyway.
123
124     if tcx.sess.opts.unstable_opts.chalk {
125         let environment = well_formed_types_in_env(tcx, def_id);
126         predicates.extend(environment);
127     }
128
129     let local_did = def_id.as_local();
130     let hir_id = local_did.map(|def_id| tcx.hir().local_def_id_to_hir_id(def_id));
131
132     // FIXME(consts): This is not exactly in line with the constness query.
133     let constness = match hir_id {
134         Some(hir_id) => match tcx.hir().get(hir_id) {
135             hir::Node::TraitItem(hir::TraitItem { kind: hir::TraitItemKind::Fn(..), .. })
136                 if tcx.is_const_default_method(def_id) =>
137             {
138                 hir::Constness::Const
139             }
140
141             hir::Node::Item(hir::Item { kind: hir::ItemKind::Const(..), .. })
142             | hir::Node::Item(hir::Item { kind: hir::ItemKind::Static(..), .. })
143             | hir::Node::TraitItem(hir::TraitItem {
144                 kind: hir::TraitItemKind::Const(..), ..
145             })
146             | hir::Node::AnonConst(_)
147             | hir::Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Const(..), .. })
148             | hir::Node::ImplItem(hir::ImplItem {
149                 kind:
150                     hir::ImplItemKind::Fn(
151                         hir::FnSig {
152                             header: hir::FnHeader { constness: hir::Constness::Const, .. },
153                             ..
154                         },
155                         ..,
156                     ),
157                 ..
158             }) => hir::Constness::Const,
159
160             hir::Node::ImplItem(hir::ImplItem {
161                 kind: hir::ImplItemKind::Type(..) | hir::ImplItemKind::Fn(..),
162                 ..
163             }) => {
164                 let parent_hir_id = tcx.hir().get_parent_node(hir_id);
165                 match tcx.hir().get(parent_hir_id) {
166                     hir::Node::Item(hir::Item {
167                         kind: hir::ItemKind::Impl(hir::Impl { constness, .. }),
168                         ..
169                     }) => *constness,
170                     _ => span_bug!(
171                         tcx.def_span(parent_hir_id.owner),
172                         "impl item's parent node is not an impl",
173                     ),
174                 }
175             }
176
177             hir::Node::Item(hir::Item {
178                 kind:
179                     hir::ItemKind::Fn(hir::FnSig { header: hir::FnHeader { constness, .. }, .. }, ..),
180                 ..
181             })
182             | hir::Node::TraitItem(hir::TraitItem {
183                 kind:
184                     hir::TraitItemKind::Fn(
185                         hir::FnSig { header: hir::FnHeader { constness, .. }, .. },
186                         ..,
187                     ),
188                 ..
189             })
190             | hir::Node::Item(hir::Item {
191                 kind: hir::ItemKind::Impl(hir::Impl { constness, .. }),
192                 ..
193             }) => *constness,
194
195             _ => hir::Constness::NotConst,
196         },
197         // FIXME(consts): It's suspicious that a param-env for a foreign item
198         // will always have NotConst param-env, though we don't typically use
199         // that param-env for anything meaningful right now, so it's likely
200         // not an issue.
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 =
211         local_did.and_then(|id| tcx.hir().maybe_body_owned_by(id).map(|body| body.hir_id));
212     let body_id = match body_id {
213         Some(id) => id,
214         None if hir_id.is_some() => hir_id.unwrap(),
215         _ => hir::CRATE_HIR_ID,
216     };
217
218     let cause = traits::ObligationCause::misc(tcx.def_span(def_id), body_id);
219     traits::normalize_param_env_or_error(tcx, unnormalized_env, cause)
220 }
221
222 /// Elaborate the environment.
223 ///
224 /// Collect a list of `Predicate`'s used for building the `ParamEnv`. Adds `TypeWellFormedFromEnv`'s
225 /// that are assumed to be well-formed (because they come from the environment).
226 ///
227 /// Used only in chalk mode.
228 fn well_formed_types_in_env<'tcx>(
229     tcx: TyCtxt<'tcx>,
230     def_id: DefId,
231 ) -> &'tcx ty::List<Predicate<'tcx>> {
232     use rustc_hir::{ForeignItemKind, ImplItemKind, ItemKind, Node, TraitItemKind};
233     use rustc_middle::ty::subst::GenericArgKind;
234
235     debug!("environment(def_id = {:?})", def_id);
236
237     // The environment of an impl Trait type is its defining function's environment.
238     if let Some(parent) = ty::is_impl_trait_defn(tcx, def_id) {
239         return well_formed_types_in_env(tcx, parent.to_def_id());
240     }
241
242     // Compute the bounds on `Self` and the type parameters.
243     let ty::InstantiatedPredicates { predicates, .. } =
244         tcx.predicates_of(def_id).instantiate_identity(tcx);
245
246     let clauses = predicates.into_iter();
247
248     if !def_id.is_local() {
249         return ty::List::empty();
250     }
251     let node = tcx.hir().get_by_def_id(def_id.expect_local());
252
253     enum NodeKind {
254         TraitImpl,
255         InherentImpl,
256         Fn,
257         Other,
258     }
259
260     let node_kind = match node {
261         Node::TraitItem(item) => match item.kind {
262             TraitItemKind::Fn(..) => NodeKind::Fn,
263             _ => NodeKind::Other,
264         },
265
266         Node::ImplItem(item) => match item.kind {
267             ImplItemKind::Fn(..) => NodeKind::Fn,
268             _ => NodeKind::Other,
269         },
270
271         Node::Item(item) => match item.kind {
272             ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }) => NodeKind::TraitImpl,
273             ItemKind::Impl(hir::Impl { of_trait: None, .. }) => NodeKind::InherentImpl,
274             ItemKind::Fn(..) => NodeKind::Fn,
275             _ => NodeKind::Other,
276         },
277
278         Node::ForeignItem(item) => match item.kind {
279             ForeignItemKind::Fn(..) => NodeKind::Fn,
280             _ => NodeKind::Other,
281         },
282
283         // FIXME: closures?
284         _ => NodeKind::Other,
285     };
286
287     // FIXME(eddyb) isn't the unordered nature of this a hazard?
288     let mut inputs = FxIndexSet::default();
289
290     match node_kind {
291         // In a trait impl, we assume that the header trait ref and all its
292         // constituents are well-formed.
293         NodeKind::TraitImpl => {
294             let trait_ref = tcx.impl_trait_ref(def_id).expect("not an impl");
295
296             // FIXME(chalk): this has problems because of late-bound regions
297             //inputs.extend(trait_ref.substs.iter().flat_map(|arg| arg.walk()));
298             inputs.extend(trait_ref.substs.iter());
299         }
300
301         // In an inherent impl, we assume that the receiver type and all its
302         // constituents are well-formed.
303         NodeKind::InherentImpl => {
304             let self_ty = tcx.type_of(def_id);
305             inputs.extend(self_ty.walk());
306         }
307
308         // In an fn, we assume that the arguments and all their constituents are
309         // well-formed.
310         NodeKind::Fn => {
311             let fn_sig = tcx.fn_sig(def_id);
312             let fn_sig = tcx.liberate_late_bound_regions(def_id, fn_sig);
313
314             inputs.extend(fn_sig.inputs().iter().flat_map(|ty| ty.walk()));
315         }
316
317         NodeKind::Other => (),
318     }
319     let input_clauses = inputs.into_iter().filter_map(|arg| {
320         match arg.unpack() {
321             GenericArgKind::Type(ty) => {
322                 let binder = Binder::dummy(PredicateKind::TypeWellFormedFromEnv(ty));
323                 Some(tcx.mk_predicate(binder))
324             }
325
326             // FIXME(eddyb) no WF conditions from lifetimes?
327             GenericArgKind::Lifetime(_) => None,
328
329             // FIXME(eddyb) support const generics in Chalk
330             GenericArgKind::Const(_) => None,
331         }
332     });
333
334     tcx.mk_predicates(clauses.chain(input_clauses))
335 }
336
337 fn param_env_reveal_all_normalized(tcx: TyCtxt<'_>, def_id: DefId) -> ty::ParamEnv<'_> {
338     tcx.param_env(def_id).with_reveal_all_normalized(tcx)
339 }
340
341 fn instance_def_size_estimate<'tcx>(
342     tcx: TyCtxt<'tcx>,
343     instance_def: ty::InstanceDef<'tcx>,
344 ) -> usize {
345     use ty::InstanceDef;
346
347     match instance_def {
348         InstanceDef::Item(..) | InstanceDef::DropGlue(..) => {
349             let mir = tcx.instance_mir(instance_def);
350             mir.basic_blocks.iter().map(|bb| bb.statements.len() + 1).sum()
351         }
352         // Estimate the size of other compiler-generated shims to be 1.
353         _ => 1,
354     }
355 }
356
357 /// If `def_id` is an issue 33140 hack impl, returns its self type; otherwise, returns `None`.
358 ///
359 /// See [`ty::ImplOverlapKind::Issue33140`] for more details.
360 fn issue33140_self_ty(tcx: TyCtxt<'_>, def_id: DefId) -> Option<Ty<'_>> {
361     debug!("issue33140_self_ty({:?})", def_id);
362
363     let trait_ref = tcx
364         .impl_trait_ref(def_id)
365         .unwrap_or_else(|| bug!("issue33140_self_ty called on inherent impl {:?}", def_id));
366
367     debug!("issue33140_self_ty({:?}), trait-ref={:?}", def_id, trait_ref);
368
369     let is_marker_like = tcx.impl_polarity(def_id) == ty::ImplPolarity::Positive
370         && tcx.associated_item_def_ids(trait_ref.def_id).is_empty();
371
372     // Check whether these impls would be ok for a marker trait.
373     if !is_marker_like {
374         debug!("issue33140_self_ty - not marker-like!");
375         return None;
376     }
377
378     // impl must be `impl Trait for dyn Marker1 + Marker2 + ...`
379     if trait_ref.substs.len() != 1 {
380         debug!("issue33140_self_ty - impl has substs!");
381         return None;
382     }
383
384     let predicates = tcx.predicates_of(def_id);
385     if predicates.parent.is_some() || !predicates.predicates.is_empty() {
386         debug!("issue33140_self_ty - impl has predicates {:?}!", predicates);
387         return None;
388     }
389
390     let self_ty = trait_ref.self_ty();
391     let self_ty_matches = match self_ty.kind() {
392         ty::Dynamic(ref data, re, _) if re.is_static() => data.principal().is_none(),
393         _ => false,
394     };
395
396     if self_ty_matches {
397         debug!("issue33140_self_ty - MATCHES!");
398         Some(self_ty)
399     } else {
400         debug!("issue33140_self_ty - non-matching self type");
401         None
402     }
403 }
404
405 /// Check if a function is async.
406 fn asyncness(tcx: TyCtxt<'_>, def_id: DefId) -> hir::IsAsync {
407     let node = tcx.hir().get_by_def_id(def_id.expect_local());
408     node.fn_sig().map_or(hir::IsAsync::NotAsync, |sig| sig.header.asyncness)
409 }
410
411 pub fn provide(providers: &mut ty::query::Providers) {
412     *providers = ty::query::Providers {
413         asyncness,
414         adt_sized_constraint,
415         param_env,
416         param_env_reveal_all_normalized,
417         instance_def_size_estimate,
418         issue33140_self_ty,
419         impl_defaultness,
420         ..*providers
421     };
422 }