]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_ty_utils/src/ty.rs
Test drop_tracking_mir before querying generator.
[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_middle::ty::{self, Binder, Predicate, PredicateKind, ToPredicate, Ty, TyCtxt};
4 use rustc_session::config::TraitSolver;
5 use rustc_span::def_id::{DefId, CRATE_DEF_ID};
6 use rustc_trait_selection::traits;
7
8 fn sized_constraint_for_ty<'tcx>(
9     tcx: TyCtxt<'tcx>,
10     adtdef: ty::AdtDef<'tcx>,
11     ty: Ty<'tcx>,
12 ) -> Vec<Ty<'tcx>> {
13     use rustc_type_ir::sty::TyKind::*;
14
15     let result = match ty.kind() {
16         Bool | Char | Int(..) | Uint(..) | Float(..) | RawPtr(..) | Ref(..) | FnDef(..)
17         | FnPtr(_) | Array(..) | Closure(..) | Generator(..) | Never => vec![],
18
19         Str
20         | Dynamic(..)
21         | Slice(_)
22         | Foreign(..)
23         | Error(_)
24         | GeneratorWitness(..)
25         | GeneratorWitnessMIR(..) => {
26             // these are never sized - return the target type
27             vec![ty]
28         }
29
30         Tuple(ref tys) => match tys.last() {
31             None => vec![],
32             Some(&ty) => sized_constraint_for_ty(tcx, adtdef, ty),
33         },
34
35         Adt(adt, substs) => {
36             // recursive case
37             let adt_tys = adt.sized_constraint(tcx);
38             debug!("sized_constraint_for_ty({:?}) intermediate = {:?}", ty, adt_tys);
39             adt_tys
40                 .0
41                 .iter()
42                 .map(|ty| adt_tys.rebind(*ty).subst(tcx, substs))
43                 .flat_map(|ty| sized_constraint_for_ty(tcx, adtdef, ty))
44                 .collect()
45         }
46
47         Alias(..) => {
48             // must calculate explicitly.
49             // FIXME: consider special-casing always-Sized projections
50             vec![ty]
51         }
52
53         Param(..) => {
54             // perf hack: if there is a `T: Sized` bound, then
55             // we know that `T` is Sized and do not need to check
56             // it on the impl.
57
58             let Some(sized_trait) = tcx.lang_items().sized_trait() else { return vec![ty] };
59             let sized_predicate = ty::Binder::dummy(tcx.mk_trait_ref(sized_trait, [ty]))
60                 .without_const()
61                 .to_predicate(tcx);
62             let predicates = tcx.predicates_of(adtdef.did()).predicates;
63             if predicates.iter().any(|(p, _)| *p == sized_predicate) { vec![] } else { vec![ty] }
64         }
65
66         Placeholder(..) | Bound(..) | Infer(..) => {
67             bug!("unexpected type `{:?}` in sized_constraint_for_ty", ty)
68         }
69     };
70     debug!("sized_constraint_for_ty({:?}) = {:?}", ty, result);
71     result
72 }
73
74 fn impl_defaultness(tcx: TyCtxt<'_>, def_id: DefId) -> hir::Defaultness {
75     match tcx.hir().get_by_def_id(def_id.expect_local()) {
76         hir::Node::Item(hir::Item { kind: hir::ItemKind::Impl(impl_), .. }) => impl_.defaultness,
77         hir::Node::ImplItem(hir::ImplItem { defaultness, .. })
78         | hir::Node::TraitItem(hir::TraitItem { defaultness, .. }) => *defaultness,
79         node => {
80             bug!("`impl_defaultness` called on {:?}", node);
81         }
82     }
83 }
84
85 /// Calculates the `Sized` constraint.
86 ///
87 /// In fact, there are only a few options for the types in the constraint:
88 ///     - an obviously-unsized type
89 ///     - a type parameter or projection whose Sizedness can't be known
90 ///     - a tuple of type parameters or projections, if there are multiple
91 ///       such.
92 ///     - an Error, if a type is infinitely sized
93 fn adt_sized_constraint(tcx: TyCtxt<'_>, def_id: DefId) -> &[Ty<'_>] {
94     if let Some(def_id) = def_id.as_local() {
95         if matches!(tcx.representability(def_id), ty::Representability::Infinite) {
96             return tcx.intern_type_list(&[tcx.ty_error()]);
97         }
98     }
99     let def = tcx.adt_def(def_id);
100
101     let result = tcx.mk_type_list(
102         def.variants()
103             .iter()
104             .flat_map(|v| v.fields.last())
105             .flat_map(|f| sized_constraint_for_ty(tcx, def, tcx.type_of(f.did))),
106     );
107
108     debug!("adt_sized_constraint: {:?} => {:?}", def, result);
109
110     result
111 }
112
113 /// See `ParamEnv` struct definition for details.
114 fn param_env(tcx: TyCtxt<'_>, def_id: DefId) -> ty::ParamEnv<'_> {
115     // Compute the bounds on Self and the type parameters.
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.trait_solver == TraitSolver::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     // FIXME(consts): This is not exactly in line with the constness query.
140     let constness = match hir_id {
141         Some(hir_id) => match tcx.hir().get(hir_id) {
142             hir::Node::TraitItem(hir::TraitItem { kind: hir::TraitItemKind::Fn(..), .. })
143                 if tcx.is_const_default_method(def_id) =>
144             {
145                 hir::Constness::Const
146             }
147
148             hir::Node::Item(hir::Item { kind: hir::ItemKind::Const(..), .. })
149             | hir::Node::Item(hir::Item { kind: hir::ItemKind::Static(..), .. })
150             | hir::Node::TraitItem(hir::TraitItem {
151                 kind: hir::TraitItemKind::Const(..), ..
152             })
153             | hir::Node::AnonConst(_)
154             | hir::Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Const(..), .. })
155             | hir::Node::ImplItem(hir::ImplItem {
156                 kind:
157                     hir::ImplItemKind::Fn(
158                         hir::FnSig {
159                             header: hir::FnHeader { constness: hir::Constness::Const, .. },
160                             ..
161                         },
162                         ..,
163                     ),
164                 ..
165             }) => hir::Constness::Const,
166
167             hir::Node::ImplItem(hir::ImplItem {
168                 kind: hir::ImplItemKind::Type(..) | hir::ImplItemKind::Fn(..),
169                 ..
170             }) => {
171                 let parent_hir_id = tcx.hir().parent_id(hir_id);
172                 match tcx.hir().get(parent_hir_id) {
173                     hir::Node::Item(hir::Item {
174                         kind: hir::ItemKind::Impl(hir::Impl { constness, .. }),
175                         ..
176                     }) => *constness,
177                     _ => span_bug!(
178                         tcx.def_span(parent_hir_id.owner),
179                         "impl item's parent node is not an impl",
180                     ),
181                 }
182             }
183
184             hir::Node::Item(hir::Item {
185                 kind:
186                     hir::ItemKind::Fn(hir::FnSig { header: hir::FnHeader { constness, .. }, .. }, ..),
187                 ..
188             })
189             | hir::Node::TraitItem(hir::TraitItem {
190                 kind:
191                     hir::TraitItemKind::Fn(
192                         hir::FnSig { header: hir::FnHeader { constness, .. }, .. },
193                         ..,
194                     ),
195                 ..
196             })
197             | hir::Node::Item(hir::Item {
198                 kind: hir::ItemKind::Impl(hir::Impl { constness, .. }),
199                 ..
200             }) => *constness,
201
202             _ => hir::Constness::NotConst,
203         },
204         // FIXME(consts): It's suspicious that a param-env for a foreign item
205         // will always have NotConst param-env, though we don't typically use
206         // that param-env for anything meaningful right now, so it's likely
207         // not an issue.
208         None => hir::Constness::NotConst,
209     };
210
211     let unnormalized_env = ty::ParamEnv::new(
212         tcx.intern_predicates(&predicates),
213         traits::Reveal::UserFacing,
214         constness,
215     );
216
217     let body_id = local_did.unwrap_or(CRATE_DEF_ID);
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: TyCtxt<'_>, def_id: DefId) -> &ty::List<Predicate<'_>> {
229     use rustc_hir::{ForeignItemKind, ImplItemKind, ItemKind, Node, TraitItemKind};
230     use rustc_middle::ty::subst::GenericArgKind;
231
232     debug!("environment(def_id = {:?})", def_id);
233
234     // The environment of an impl Trait type is its defining function's environment.
235     if let Some(parent) = ty::is_impl_trait_defn(tcx, def_id) {
236         return well_formed_types_in_env(tcx, parent.to_def_id());
237     }
238
239     // Compute the bounds on `Self` and the type parameters.
240     let ty::InstantiatedPredicates { predicates, .. } =
241         tcx.predicates_of(def_id).instantiate_identity(tcx);
242
243     let clauses = predicates.into_iter();
244
245     if !def_id.is_local() {
246         return ty::List::empty();
247     }
248     let node = tcx.hir().get_by_def_id(def_id.expect_local());
249
250     enum NodeKind {
251         TraitImpl,
252         InherentImpl,
253         Fn,
254         Other,
255     }
256
257     let node_kind = match node {
258         Node::TraitItem(item) => match item.kind {
259             TraitItemKind::Fn(..) => NodeKind::Fn,
260             _ => NodeKind::Other,
261         },
262
263         Node::ImplItem(item) => match item.kind {
264             ImplItemKind::Fn(..) => NodeKind::Fn,
265             _ => NodeKind::Other,
266         },
267
268         Node::Item(item) => match item.kind {
269             ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }) => NodeKind::TraitImpl,
270             ItemKind::Impl(hir::Impl { of_trait: None, .. }) => NodeKind::InherentImpl,
271             ItemKind::Fn(..) => NodeKind::Fn,
272             _ => NodeKind::Other,
273         },
274
275         Node::ForeignItem(item) => match item.kind {
276             ForeignItemKind::Fn(..) => NodeKind::Fn,
277             _ => NodeKind::Other,
278         },
279
280         // FIXME: closures?
281         _ => NodeKind::Other,
282     };
283
284     // FIXME(eddyb) isn't the unordered nature of this a hazard?
285     let mut inputs = FxIndexSet::default();
286
287     match node_kind {
288         // In a trait impl, we assume that the header trait ref and all its
289         // constituents are well-formed.
290         NodeKind::TraitImpl => {
291             let trait_ref = tcx.impl_trait_ref(def_id).expect("not an impl").subst_identity();
292
293             // FIXME(chalk): this has problems because of late-bound regions
294             //inputs.extend(trait_ref.substs.iter().flat_map(|arg| arg.walk()));
295             inputs.extend(trait_ref.substs.iter());
296         }
297
298         // In an inherent impl, we assume that the receiver type and all its
299         // constituents are well-formed.
300         NodeKind::InherentImpl => {
301             let self_ty = tcx.type_of(def_id);
302             inputs.extend(self_ty.walk());
303         }
304
305         // In an fn, we assume that the arguments and all their constituents are
306         // well-formed.
307         NodeKind::Fn => {
308             let fn_sig = tcx.fn_sig(def_id).subst_identity();
309             let fn_sig = tcx.liberate_late_bound_regions(def_id, fn_sig);
310
311             inputs.extend(fn_sig.inputs().iter().flat_map(|ty| ty.walk()));
312         }
313
314         NodeKind::Other => (),
315     }
316     let input_clauses = inputs.into_iter().filter_map(|arg| {
317         match arg.unpack() {
318             GenericArgKind::Type(ty) => {
319                 let binder = Binder::dummy(PredicateKind::TypeWellFormedFromEnv(ty));
320                 Some(tcx.mk_predicate(binder))
321             }
322
323             // FIXME(eddyb) no WF conditions from lifetimes?
324             GenericArgKind::Lifetime(_) => None,
325
326             // FIXME(eddyb) support const generics in Chalk
327             GenericArgKind::Const(_) => None,
328         }
329     });
330
331     tcx.mk_predicates(clauses.chain(input_clauses))
332 }
333
334 fn param_env_reveal_all_normalized(tcx: TyCtxt<'_>, def_id: DefId) -> ty::ParamEnv<'_> {
335     tcx.param_env(def_id).with_reveal_all_normalized(tcx)
336 }
337
338 fn instance_def_size_estimate<'tcx>(
339     tcx: TyCtxt<'tcx>,
340     instance_def: ty::InstanceDef<'tcx>,
341 ) -> usize {
342     use ty::InstanceDef;
343
344     match instance_def {
345         InstanceDef::Item(..) | InstanceDef::DropGlue(..) => {
346             let mir = tcx.instance_mir(instance_def);
347             mir.basic_blocks.iter().map(|bb| bb.statements.len() + 1).sum()
348         }
349         // Estimate the size of other compiler-generated shims to be 1.
350         _ => 1,
351     }
352 }
353
354 /// If `def_id` is an issue 33140 hack impl, returns its self type; otherwise, returns `None`.
355 ///
356 /// See [`ty::ImplOverlapKind::Issue33140`] for more details.
357 fn issue33140_self_ty(tcx: TyCtxt<'_>, def_id: DefId) -> Option<Ty<'_>> {
358     debug!("issue33140_self_ty({:?})", def_id);
359
360     let trait_ref = tcx
361         .impl_trait_ref(def_id)
362         .unwrap_or_else(|| bug!("issue33140_self_ty called on inherent impl {:?}", def_id))
363         .skip_binder();
364
365     debug!("issue33140_self_ty({:?}), trait-ref={:?}", def_id, trait_ref);
366
367     let is_marker_like = tcx.impl_polarity(def_id) == ty::ImplPolarity::Positive
368         && tcx.associated_item_def_ids(trait_ref.def_id).is_empty();
369
370     // Check whether these impls would be ok for a marker trait.
371     if !is_marker_like {
372         debug!("issue33140_self_ty - not marker-like!");
373         return None;
374     }
375
376     // impl must be `impl Trait for dyn Marker1 + Marker2 + ...`
377     if trait_ref.substs.len() != 1 {
378         debug!("issue33140_self_ty - impl has substs!");
379         return None;
380     }
381
382     let predicates = tcx.predicates_of(def_id);
383     if predicates.parent.is_some() || !predicates.predicates.is_empty() {
384         debug!("issue33140_self_ty - impl has predicates {:?}!", predicates);
385         return None;
386     }
387
388     let self_ty = trait_ref.self_ty();
389     let self_ty_matches = match self_ty.kind() {
390         ty::Dynamic(ref data, re, _) if re.is_static() => data.principal().is_none(),
391         _ => false,
392     };
393
394     if self_ty_matches {
395         debug!("issue33140_self_ty - MATCHES!");
396         Some(self_ty)
397     } else {
398         debug!("issue33140_self_ty - non-matching self type");
399         None
400     }
401 }
402
403 /// Check if a function is async.
404 fn asyncness(tcx: TyCtxt<'_>, def_id: DefId) -> hir::IsAsync {
405     let node = tcx.hir().get_by_def_id(def_id.expect_local());
406     node.fn_sig().map_or(hir::IsAsync::NotAsync, |sig| sig.header.asyncness)
407 }
408
409 pub fn provide(providers: &mut ty::query::Providers) {
410     *providers = ty::query::Providers {
411         asyncness,
412         adt_sized_constraint,
413         param_env,
414         param_env_reveal_all_normalized,
415         instance_def_size_estimate,
416         issue33140_self_ty,
417         impl_defaultness,
418         ..*providers
419     };
420 }