]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_ty_utils/src/ty.rs
Rollup merge of #107700 - jyn514:tools-builder, r=Mark-Simulacrum
[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_index::bit_set::BitSet;
4 use rustc_middle::ty::{self, Binder, Predicate, PredicateKind, ToPredicate, Ty, TyCtxt};
5 use rustc_session::config::TraitSolver;
6 use rustc_span::def_id::{DefId, CRATE_DEF_ID};
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 rustc_type_ir::sty::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
21         | Dynamic(..)
22         | Slice(_)
23         | Foreign(..)
24         | Error(_)
25         | GeneratorWitness(..)
26         | GeneratorWitnessMIR(..) => {
27             // these are never sized - return the target type
28             vec![ty]
29         }
30
31         Tuple(ref tys) => match tys.last() {
32             None => vec![],
33             Some(&ty) => sized_constraint_for_ty(tcx, adtdef, ty),
34         },
35
36         Adt(adt, substs) => {
37             // recursive case
38             let adt_tys = adt.sized_constraint(tcx);
39             debug!("sized_constraint_for_ty({:?}) intermediate = {:?}", ty, adt_tys);
40             adt_tys
41                 .0
42                 .iter()
43                 .map(|ty| adt_tys.rebind(*ty).subst(tcx, substs))
44                 .flat_map(|ty| sized_constraint_for_ty(tcx, adtdef, ty))
45                 .collect()
46         }
47
48         Alias(..) => {
49             // must calculate explicitly.
50             // FIXME: consider special-casing always-Sized projections
51             vec![ty]
52         }
53
54         Param(..) => {
55             // perf hack: if there is a `T: Sized` bound, then
56             // we know that `T` is Sized and do not need to check
57             // it on the impl.
58
59             let Some(sized_trait) = tcx.lang_items().sized_trait() else { return vec![ty] };
60             let sized_predicate = ty::Binder::dummy(tcx.mk_trait_ref(sized_trait, [ty]))
61                 .without_const()
62                 .to_predicate(tcx);
63             let predicates = tcx.predicates_of(adtdef.did()).predicates;
64             if predicates.iter().any(|(p, _)| *p == sized_predicate) { vec![] } else { vec![ty] }
65         }
66
67         Placeholder(..) | Bound(..) | Infer(..) => {
68             bug!("unexpected type `{:?}` in sized_constraint_for_ty", ty)
69         }
70     };
71     debug!("sized_constraint_for_ty({:?}) = {:?}", ty, result);
72     result
73 }
74
75 fn impl_defaultness(tcx: TyCtxt<'_>, def_id: DefId) -> hir::Defaultness {
76     match tcx.hir().get_by_def_id(def_id.expect_local()) {
77         hir::Node::Item(hir::Item { kind: hir::ItemKind::Impl(impl_), .. }) => impl_.defaultness,
78         hir::Node::ImplItem(hir::ImplItem { defaultness, .. })
79         | hir::Node::TraitItem(hir::TraitItem { defaultness, .. }) => *defaultness,
80         node => {
81             bug!("`impl_defaultness` called on {:?}", node);
82         }
83     }
84 }
85
86 /// Calculates the `Sized` constraint.
87 ///
88 /// In fact, there are only a few options for the types in the constraint:
89 ///     - an obviously-unsized type
90 ///     - a type parameter or projection whose Sizedness can't be known
91 ///     - a tuple of type parameters or projections, if there are multiple
92 ///       such.
93 ///     - an Error, if a type is infinitely sized
94 fn adt_sized_constraint(tcx: TyCtxt<'_>, def_id: DefId) -> &[Ty<'_>] {
95     if let Some(def_id) = def_id.as_local() {
96         if matches!(tcx.representability(def_id), ty::Representability::Infinite) {
97             return tcx.intern_type_list(&[tcx.ty_error()]);
98         }
99     }
100     let def = tcx.adt_def(def_id);
101
102     let result = tcx.mk_type_list(
103         def.variants()
104             .iter()
105             .flat_map(|v| v.fields.last())
106             .flat_map(|f| sized_constraint_for_ty(tcx, def, tcx.type_of(f.did))),
107     );
108
109     debug!("adt_sized_constraint: {:?} => {:?}", def, result);
110
111     result
112 }
113
114 /// See `ParamEnv` struct definition for details.
115 fn param_env(tcx: TyCtxt<'_>, def_id: DefId) -> ty::ParamEnv<'_> {
116     // Compute the bounds on Self and the type parameters.
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.trait_solver == TraitSolver::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     // FIXME(consts): This is not exactly in line with the constness query.
141     let constness = match hir_id {
142         Some(hir_id) => match tcx.hir().get(hir_id) {
143             hir::Node::TraitItem(hir::TraitItem { kind: hir::TraitItemKind::Fn(..), .. })
144                 if tcx.is_const_default_method(def_id) =>
145             {
146                 hir::Constness::Const
147             }
148
149             hir::Node::Item(hir::Item { kind: hir::ItemKind::Const(..), .. })
150             | hir::Node::Item(hir::Item { kind: hir::ItemKind::Static(..), .. })
151             | hir::Node::TraitItem(hir::TraitItem {
152                 kind: hir::TraitItemKind::Const(..), ..
153             })
154             | hir::Node::AnonConst(_)
155             | hir::Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Const(..), .. })
156             | hir::Node::ImplItem(hir::ImplItem {
157                 kind:
158                     hir::ImplItemKind::Fn(
159                         hir::FnSig {
160                             header: hir::FnHeader { constness: hir::Constness::Const, .. },
161                             ..
162                         },
163                         ..,
164                     ),
165                 ..
166             }) => hir::Constness::Const,
167
168             hir::Node::ImplItem(hir::ImplItem {
169                 kind: hir::ImplItemKind::Type(..) | hir::ImplItemKind::Fn(..),
170                 ..
171             }) => {
172                 let parent_hir_id = tcx.hir().parent_id(hir_id);
173                 match tcx.hir().get(parent_hir_id) {
174                     hir::Node::Item(hir::Item {
175                         kind: hir::ItemKind::Impl(hir::Impl { constness, .. }),
176                         ..
177                     }) => *constness,
178                     _ => span_bug!(
179                         tcx.def_span(parent_hir_id.owner),
180                         "impl item's parent node is not an impl",
181                     ),
182                 }
183             }
184
185             hir::Node::Item(hir::Item {
186                 kind:
187                     hir::ItemKind::Fn(hir::FnSig { header: hir::FnHeader { constness, .. }, .. }, ..),
188                 ..
189             })
190             | hir::Node::TraitItem(hir::TraitItem {
191                 kind:
192                     hir::TraitItemKind::Fn(
193                         hir::FnSig { header: hir::FnHeader { constness, .. }, .. },
194                         ..,
195                     ),
196                 ..
197             })
198             | hir::Node::Item(hir::Item {
199                 kind: hir::ItemKind::Impl(hir::Impl { constness, .. }),
200                 ..
201             }) => *constness,
202
203             _ => hir::Constness::NotConst,
204         },
205         // FIXME(consts): It's suspicious that a param-env for a foreign item
206         // will always have NotConst param-env, though we don't typically use
207         // that param-env for anything meaningful right now, so it's likely
208         // not an issue.
209         None => hir::Constness::NotConst,
210     };
211
212     let unnormalized_env = ty::ParamEnv::new(
213         tcx.intern_predicates(&predicates),
214         traits::Reveal::UserFacing,
215         constness,
216     );
217
218     let body_id = local_did.unwrap_or(CRATE_DEF_ID);
219     let cause = traits::ObligationCause::misc(tcx.def_span(def_id), body_id);
220     traits::normalize_param_env_or_error(tcx, unnormalized_env, cause)
221 }
222
223 /// Elaborate the environment.
224 ///
225 /// Collect a list of `Predicate`'s used for building the `ParamEnv`. Adds `TypeWellFormedFromEnv`'s
226 /// that are assumed to be well-formed (because they come from the environment).
227 ///
228 /// Used only in chalk mode.
229 fn well_formed_types_in_env(tcx: TyCtxt<'_>, def_id: DefId) -> &ty::List<Predicate<'_>> {
230     use rustc_hir::{ForeignItemKind, ImplItemKind, ItemKind, Node, TraitItemKind};
231     use rustc_middle::ty::subst::GenericArgKind;
232
233     debug!("environment(def_id = {:?})", def_id);
234
235     // The environment of an impl Trait type is its defining function's environment.
236     if let Some(parent) = ty::is_impl_trait_defn(tcx, def_id) {
237         return well_formed_types_in_env(tcx, parent.to_def_id());
238     }
239
240     // Compute the bounds on `Self` and the type parameters.
241     let ty::InstantiatedPredicates { predicates, .. } =
242         tcx.predicates_of(def_id).instantiate_identity(tcx);
243
244     let clauses = predicates.into_iter();
245
246     if !def_id.is_local() {
247         return ty::List::empty();
248     }
249     let node = tcx.hir().get_by_def_id(def_id.expect_local());
250
251     enum NodeKind {
252         TraitImpl,
253         InherentImpl,
254         Fn,
255         Other,
256     }
257
258     let node_kind = match node {
259         Node::TraitItem(item) => match item.kind {
260             TraitItemKind::Fn(..) => NodeKind::Fn,
261             _ => NodeKind::Other,
262         },
263
264         Node::ImplItem(item) => match item.kind {
265             ImplItemKind::Fn(..) => NodeKind::Fn,
266             _ => NodeKind::Other,
267         },
268
269         Node::Item(item) => match item.kind {
270             ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }) => NodeKind::TraitImpl,
271             ItemKind::Impl(hir::Impl { of_trait: None, .. }) => NodeKind::InherentImpl,
272             ItemKind::Fn(..) => NodeKind::Fn,
273             _ => NodeKind::Other,
274         },
275
276         Node::ForeignItem(item) => match item.kind {
277             ForeignItemKind::Fn(..) => NodeKind::Fn,
278             _ => NodeKind::Other,
279         },
280
281         // FIXME: closures?
282         _ => NodeKind::Other,
283     };
284
285     // FIXME(eddyb) isn't the unordered nature of this a hazard?
286     let mut inputs = FxIndexSet::default();
287
288     match node_kind {
289         // In a trait impl, we assume that the header trait ref and all its
290         // constituents are well-formed.
291         NodeKind::TraitImpl => {
292             let trait_ref = tcx.impl_trait_ref(def_id).expect("not an impl").subst_identity();
293
294             // FIXME(chalk): this has problems because of late-bound regions
295             //inputs.extend(trait_ref.substs.iter().flat_map(|arg| arg.walk()));
296             inputs.extend(trait_ref.substs.iter());
297         }
298
299         // In an inherent impl, we assume that the receiver type and all its
300         // constituents are well-formed.
301         NodeKind::InherentImpl => {
302             let self_ty = tcx.type_of(def_id);
303             inputs.extend(self_ty.walk());
304         }
305
306         // In an fn, we assume that the arguments and all their constituents are
307         // well-formed.
308         NodeKind::Fn => {
309             let fn_sig = tcx.fn_sig(def_id).subst_identity();
310             let fn_sig = tcx.liberate_late_bound_regions(def_id, fn_sig);
311
312             inputs.extend(fn_sig.inputs().iter().flat_map(|ty| ty.walk()));
313         }
314
315         NodeKind::Other => (),
316     }
317     let input_clauses = inputs.into_iter().filter_map(|arg| {
318         match arg.unpack() {
319             GenericArgKind::Type(ty) => {
320                 let binder = Binder::dummy(PredicateKind::TypeWellFormedFromEnv(ty));
321                 Some(tcx.mk_predicate(binder))
322             }
323
324             // FIXME(eddyb) no WF conditions from lifetimes?
325             GenericArgKind::Lifetime(_) => None,
326
327             // FIXME(eddyb) support const generics in Chalk
328             GenericArgKind::Const(_) => None,
329         }
330     });
331
332     tcx.mk_predicates(clauses.chain(input_clauses))
333 }
334
335 fn param_env_reveal_all_normalized(tcx: TyCtxt<'_>, def_id: DefId) -> ty::ParamEnv<'_> {
336     tcx.param_env(def_id).with_reveal_all_normalized(tcx)
337 }
338
339 fn instance_def_size_estimate<'tcx>(
340     tcx: TyCtxt<'tcx>,
341     instance_def: ty::InstanceDef<'tcx>,
342 ) -> usize {
343     use ty::InstanceDef;
344
345     match instance_def {
346         InstanceDef::Item(..) | InstanceDef::DropGlue(..) => {
347             let mir = tcx.instance_mir(instance_def);
348             mir.basic_blocks.iter().map(|bb| bb.statements.len() + 1).sum()
349         }
350         // Estimate the size of other compiler-generated shims to be 1.
351         _ => 1,
352     }
353 }
354
355 /// If `def_id` is an issue 33140 hack impl, returns its self type; otherwise, returns `None`.
356 ///
357 /// See [`ty::ImplOverlapKind::Issue33140`] for more details.
358 fn issue33140_self_ty(tcx: TyCtxt<'_>, def_id: DefId) -> Option<Ty<'_>> {
359     debug!("issue33140_self_ty({:?})", def_id);
360
361     let trait_ref = tcx
362         .impl_trait_ref(def_id)
363         .unwrap_or_else(|| bug!("issue33140_self_ty called on inherent impl {:?}", def_id))
364         .skip_binder();
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     node.fn_sig().map_or(hir::IsAsync::NotAsync, |sig| sig.header.asyncness)
408 }
409
410 fn unsizing_params_for_adt<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> BitSet<u32> {
411     let def = tcx.adt_def(def_id);
412     let num_params = tcx.generics_of(def_id).count();
413
414     let maybe_unsizing_param_idx = |arg: ty::GenericArg<'tcx>| match arg.unpack() {
415         ty::GenericArgKind::Type(ty) => match ty.kind() {
416             ty::Param(p) => Some(p.index),
417             _ => None,
418         },
419
420         // We can't unsize a lifetime
421         ty::GenericArgKind::Lifetime(_) => None,
422
423         ty::GenericArgKind::Const(ct) => match ct.kind() {
424             ty::ConstKind::Param(p) => Some(p.index),
425             _ => None,
426         },
427     };
428
429     // The last field of the structure has to exist and contain type/const parameters.
430     let Some((tail_field, prefix_fields)) =
431         def.non_enum_variant().fields.split_last() else
432     {
433         return BitSet::new_empty(num_params);
434     };
435
436     let mut unsizing_params = BitSet::new_empty(num_params);
437     for arg in tcx.bound_type_of(tail_field.did).subst_identity().walk() {
438         if let Some(i) = maybe_unsizing_param_idx(arg) {
439             unsizing_params.insert(i);
440         }
441     }
442
443     // Ensure none of the other fields mention the parameters used
444     // in unsizing.
445     for field in prefix_fields {
446         for arg in tcx.bound_type_of(field.did).subst_identity().walk() {
447             if let Some(i) = maybe_unsizing_param_idx(arg) {
448                 unsizing_params.remove(i);
449             }
450         }
451     }
452
453     unsizing_params
454 }
455
456 pub fn provide(providers: &mut ty::query::Providers) {
457     *providers = ty::query::Providers {
458         asyncness,
459         adt_sized_constraint,
460         param_env,
461         param_env_reveal_all_normalized,
462         instance_def_size_estimate,
463         issue33140_self_ty,
464         impl_defaultness,
465         unsizing_params_for_adt,
466         ..*providers
467     };
468 }