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