]> git.lizzy.rs Git - rust.git/blob - src/librustc_ty/ty.rs
Rollup merge of #71063 - LeSeulArtichaut:document-unsafe, r=Mark-Simulacrum
[rust.git] / src / librustc_ty / ty.rs
1 use rustc_data_structures::svh::Svh;
2 use rustc_hir as hir;
3 use rustc_hir::def_id::{CrateNum, DefId, LOCAL_CRATE};
4 use rustc_middle::hir::map as hir_map;
5 use rustc_middle::ty::subst::Subst;
6 use rustc_middle::ty::{self, ToPredicate, Ty, TyCtxt, WithConstness};
7 use rustc_session::CrateDisambiguator;
8 use rustc_span::symbol::Symbol;
9 use rustc_span::Span;
10 use rustc_trait_selection::traits;
11
12 fn sized_constraint_for_ty<'tcx>(
13     tcx: TyCtxt<'tcx>,
14     adtdef: &ty::AdtDef,
15     ty: Ty<'tcx>,
16 ) -> Vec<Ty<'tcx>> {
17     use ty::TyKind::*;
18
19     let result = match ty.kind {
20         Bool | Char | Int(..) | Uint(..) | Float(..) | RawPtr(..) | Ref(..) | FnDef(..)
21         | FnPtr(_) | Array(..) | Closure(..) | Generator(..) | Never => vec![],
22
23         Str | Dynamic(..) | Slice(_) | Foreign(..) | Error | GeneratorWitness(..) => {
24             // these are never sized - return the target type
25             vec![ty]
26         }
27
28         Tuple(ref tys) => match tys.last() {
29             None => vec![],
30             Some(ty) => sized_constraint_for_ty(tcx, adtdef, ty.expect_ty()),
31         },
32
33         Adt(adt, substs) => {
34             // recursive case
35             let adt_tys = adt.sized_constraint(tcx);
36             debug!("sized_constraint_for_ty({:?}) intermediate = {:?}", ty, adt_tys);
37             adt_tys
38                 .iter()
39                 .map(|ty| ty.subst(tcx, substs))
40                 .flat_map(|ty| sized_constraint_for_ty(tcx, adtdef, ty))
41                 .collect()
42         }
43
44         Projection(..) | Opaque(..) => {
45             // must calculate explicitly.
46             // FIXME: consider special-casing always-Sized projections
47             vec![ty]
48         }
49
50         UnnormalizedProjection(..) => bug!("only used with chalk-engine"),
51
52         Param(..) => {
53             // perf hack: if there is a `T: Sized` bound, then
54             // we know that `T` is Sized and do not need to check
55             // it on the impl.
56
57             let sized_trait = match tcx.lang_items().sized_trait() {
58                 Some(x) => x,
59                 _ => return vec![ty],
60             };
61             let sized_predicate = ty::Binder::dummy(ty::TraitRef {
62                 def_id: sized_trait,
63                 substs: tcx.mk_substs_trait(ty, &[]),
64             })
65             .without_const()
66             .to_predicate();
67             let predicates = tcx.predicates_of(adtdef.did).predicates;
68             if predicates.iter().any(|(p, _)| *p == sized_predicate) { vec![] } else { vec![ty] }
69         }
70
71         Placeholder(..) | Bound(..) | Infer(..) => {
72             bug!("unexpected type `{:?}` in sized_constraint_for_ty", ty)
73         }
74     };
75     debug!("sized_constraint_for_ty({:?}) = {:?}", ty, result);
76     result
77 }
78
79 fn associated_item_from_trait_item_ref(
80     tcx: TyCtxt<'_>,
81     parent_def_id: DefId,
82     parent_vis: &hir::Visibility<'_>,
83     trait_item_ref: &hir::TraitItemRef,
84 ) -> ty::AssocItem {
85     let def_id = tcx.hir().local_def_id(trait_item_ref.id.hir_id);
86     let (kind, has_self) = match trait_item_ref.kind {
87         hir::AssocItemKind::Const => (ty::AssocKind::Const, false),
88         hir::AssocItemKind::Fn { has_self } => (ty::AssocKind::Fn, has_self),
89         hir::AssocItemKind::Type => (ty::AssocKind::Type, false),
90         hir::AssocItemKind::OpaqueTy => bug!("only impls can have opaque types"),
91     };
92
93     ty::AssocItem {
94         ident: trait_item_ref.ident,
95         kind,
96         // Visibility of trait items is inherited from their traits.
97         vis: ty::Visibility::from_hir(parent_vis, trait_item_ref.id.hir_id, tcx),
98         defaultness: trait_item_ref.defaultness,
99         def_id,
100         container: ty::TraitContainer(parent_def_id),
101         fn_has_self_parameter: has_self,
102     }
103 }
104
105 fn associated_item_from_impl_item_ref(
106     tcx: TyCtxt<'_>,
107     parent_def_id: DefId,
108     impl_item_ref: &hir::ImplItemRef<'_>,
109 ) -> ty::AssocItem {
110     let def_id = tcx.hir().local_def_id(impl_item_ref.id.hir_id);
111     let (kind, has_self) = match impl_item_ref.kind {
112         hir::AssocItemKind::Const => (ty::AssocKind::Const, false),
113         hir::AssocItemKind::Fn { has_self } => (ty::AssocKind::Fn, has_self),
114         hir::AssocItemKind::Type => (ty::AssocKind::Type, false),
115         hir::AssocItemKind::OpaqueTy => (ty::AssocKind::OpaqueTy, false),
116     };
117
118     ty::AssocItem {
119         ident: impl_item_ref.ident,
120         kind,
121         // Visibility of trait impl items doesn't matter.
122         vis: ty::Visibility::from_hir(&impl_item_ref.vis, impl_item_ref.id.hir_id, tcx),
123         defaultness: impl_item_ref.defaultness,
124         def_id,
125         container: ty::ImplContainer(parent_def_id),
126         fn_has_self_parameter: has_self,
127     }
128 }
129
130 fn associated_item(tcx: TyCtxt<'_>, def_id: DefId) -> ty::AssocItem {
131     let id = tcx.hir().as_local_hir_id(def_id).unwrap();
132     let parent_id = tcx.hir().get_parent_item(id);
133     let parent_def_id = tcx.hir().local_def_id(parent_id);
134     let parent_item = tcx.hir().expect_item(parent_id);
135     match parent_item.kind {
136         hir::ItemKind::Impl { ref items, .. } => {
137             if let Some(impl_item_ref) = items.iter().find(|i| i.id.hir_id == id) {
138                 let assoc_item =
139                     associated_item_from_impl_item_ref(tcx, parent_def_id, impl_item_ref);
140                 debug_assert_eq!(assoc_item.def_id, def_id);
141                 return assoc_item;
142             }
143         }
144
145         hir::ItemKind::Trait(.., ref trait_item_refs) => {
146             if let Some(trait_item_ref) = trait_item_refs.iter().find(|i| i.id.hir_id == id) {
147                 let assoc_item = associated_item_from_trait_item_ref(
148                     tcx,
149                     parent_def_id,
150                     &parent_item.vis,
151                     trait_item_ref,
152                 );
153                 debug_assert_eq!(assoc_item.def_id, def_id);
154                 return assoc_item;
155             }
156         }
157
158         _ => {}
159     }
160
161     span_bug!(
162         parent_item.span,
163         "unexpected parent of trait or impl item or item not found: {:?}",
164         parent_item.kind
165     )
166 }
167
168 fn impl_defaultness(tcx: TyCtxt<'_>, def_id: DefId) -> hir::Defaultness {
169     let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
170     let item = tcx.hir().expect_item(hir_id);
171     if let hir::ItemKind::Impl { defaultness, .. } = item.kind {
172         defaultness
173     } else {
174         bug!("`impl_defaultness` called on {:?}", item);
175     }
176 }
177
178 /// Calculates the `Sized` constraint.
179 ///
180 /// In fact, there are only a few options for the types in the constraint:
181 ///     - an obviously-unsized type
182 ///     - a type parameter or projection whose Sizedness can't be known
183 ///     - a tuple of type parameters or projections, if there are multiple
184 ///       such.
185 ///     - a Error, if a type contained itself. The representability
186 ///       check should catch this case.
187 fn adt_sized_constraint(tcx: TyCtxt<'_>, def_id: DefId) -> ty::AdtSizedConstraint<'_> {
188     let def = tcx.adt_def(def_id);
189
190     let result = tcx.mk_type_list(
191         def.variants
192             .iter()
193             .flat_map(|v| v.fields.last())
194             .flat_map(|f| sized_constraint_for_ty(tcx, def, tcx.type_of(f.did))),
195     );
196
197     debug!("adt_sized_constraint: {:?} => {:?}", def, result);
198
199     ty::AdtSizedConstraint(result)
200 }
201
202 fn associated_item_def_ids(tcx: TyCtxt<'_>, def_id: DefId) -> &[DefId] {
203     let id = tcx.hir().as_local_hir_id(def_id).unwrap();
204     let item = tcx.hir().expect_item(id);
205     match item.kind {
206         hir::ItemKind::Trait(.., ref trait_item_refs) => tcx.arena.alloc_from_iter(
207             trait_item_refs
208                 .iter()
209                 .map(|trait_item_ref| trait_item_ref.id)
210                 .map(|id| tcx.hir().local_def_id(id.hir_id)),
211         ),
212         hir::ItemKind::Impl { ref items, .. } => tcx.arena.alloc_from_iter(
213             items
214                 .iter()
215                 .map(|impl_item_ref| impl_item_ref.id)
216                 .map(|id| tcx.hir().local_def_id(id.hir_id)),
217         ),
218         hir::ItemKind::TraitAlias(..) => &[],
219         _ => span_bug!(item.span, "associated_item_def_ids: not impl or trait"),
220     }
221 }
222
223 fn associated_items(tcx: TyCtxt<'_>, def_id: DefId) -> &ty::AssociatedItems {
224     let items = tcx.associated_item_def_ids(def_id).iter().map(|did| tcx.associated_item(*did));
225     tcx.arena.alloc(ty::AssociatedItems::new(items))
226 }
227
228 fn def_span(tcx: TyCtxt<'_>, def_id: DefId) -> Span {
229     tcx.hir().span_if_local(def_id).unwrap()
230 }
231
232 /// If the given `DefId` describes an item belonging to a trait,
233 /// returns the `DefId` of the trait that the trait item belongs to;
234 /// otherwise, returns `None`.
235 fn trait_of_item(tcx: TyCtxt<'_>, def_id: DefId) -> Option<DefId> {
236     tcx.opt_associated_item(def_id).and_then(|associated_item| match associated_item.container {
237         ty::TraitContainer(def_id) => Some(def_id),
238         ty::ImplContainer(_) => None,
239     })
240 }
241
242 /// See `ParamEnv` struct definition for details.
243 fn param_env(tcx: TyCtxt<'_>, def_id: DefId) -> ty::ParamEnv<'_> {
244     // The param_env of an impl Trait type is its defining function's param_env
245     if let Some(parent) = ty::is_impl_trait_defn(tcx, def_id) {
246         return param_env(tcx, parent);
247     }
248     // Compute the bounds on Self and the type parameters.
249
250     let ty::InstantiatedPredicates { predicates, .. } =
251         tcx.predicates_of(def_id).instantiate_identity(tcx);
252
253     // Finally, we have to normalize the bounds in the environment, in
254     // case they contain any associated type projections. This process
255     // can yield errors if the put in illegal associated types, like
256     // `<i32 as Foo>::Bar` where `i32` does not implement `Foo`. We
257     // report these errors right here; this doesn't actually feel
258     // right to me, because constructing the environment feels like a
259     // kind of a "idempotent" action, but I'm not sure where would be
260     // a better place. In practice, we construct environments for
261     // every fn once during type checking, and we'll abort if there
262     // are any errors at that point, so after type checking you can be
263     // sure that this will succeed without errors anyway.
264
265     let unnormalized_env =
266         ty::ParamEnv::new(tcx.intern_predicates(&predicates), traits::Reveal::UserFacing, None);
267
268     let body_id = tcx.hir().as_local_hir_id(def_id).map_or(hir::CRATE_HIR_ID, |id| {
269         tcx.hir().maybe_body_owned_by(id).map_or(id, |body| body.hir_id)
270     });
271     let cause = traits::ObligationCause::misc(tcx.def_span(def_id), body_id);
272     traits::normalize_param_env_or_error(tcx, def_id, unnormalized_env, cause)
273 }
274
275 fn crate_disambiguator(tcx: TyCtxt<'_>, crate_num: CrateNum) -> CrateDisambiguator {
276     assert_eq!(crate_num, LOCAL_CRATE);
277     tcx.sess.local_crate_disambiguator()
278 }
279
280 fn original_crate_name(tcx: TyCtxt<'_>, crate_num: CrateNum) -> Symbol {
281     assert_eq!(crate_num, LOCAL_CRATE);
282     tcx.crate_name
283 }
284
285 fn crate_hash(tcx: TyCtxt<'_>, crate_num: CrateNum) -> Svh {
286     tcx.index_hir(crate_num).crate_hash
287 }
288
289 fn instance_def_size_estimate<'tcx>(
290     tcx: TyCtxt<'tcx>,
291     instance_def: ty::InstanceDef<'tcx>,
292 ) -> usize {
293     use ty::InstanceDef;
294
295     match instance_def {
296         InstanceDef::Item(..) | InstanceDef::DropGlue(..) => {
297             let mir = tcx.instance_mir(instance_def);
298             mir.basic_blocks().iter().map(|bb| bb.statements.len()).sum()
299         }
300         // Estimate the size of other compiler-generated shims to be 1.
301         _ => 1,
302     }
303 }
304
305 /// If `def_id` is an issue 33140 hack impl, returns its self type; otherwise, returns `None`.
306 ///
307 /// See [`ImplOverlapKind::Issue33140`] for more details.
308 fn issue33140_self_ty(tcx: TyCtxt<'_>, def_id: DefId) -> Option<Ty<'_>> {
309     debug!("issue33140_self_ty({:?})", def_id);
310
311     let trait_ref = tcx
312         .impl_trait_ref(def_id)
313         .unwrap_or_else(|| bug!("issue33140_self_ty called on inherent impl {:?}", def_id));
314
315     debug!("issue33140_self_ty({:?}), trait-ref={:?}", def_id, trait_ref);
316
317     let is_marker_like = tcx.impl_polarity(def_id) == ty::ImplPolarity::Positive
318         && tcx.associated_item_def_ids(trait_ref.def_id).is_empty();
319
320     // Check whether these impls would be ok for a marker trait.
321     if !is_marker_like {
322         debug!("issue33140_self_ty - not marker-like!");
323         return None;
324     }
325
326     // impl must be `impl Trait for dyn Marker1 + Marker2 + ...`
327     if trait_ref.substs.len() != 1 {
328         debug!("issue33140_self_ty - impl has substs!");
329         return None;
330     }
331
332     let predicates = tcx.predicates_of(def_id);
333     if predicates.parent.is_some() || !predicates.predicates.is_empty() {
334         debug!("issue33140_self_ty - impl has predicates {:?}!", predicates);
335         return None;
336     }
337
338     let self_ty = trait_ref.self_ty();
339     let self_ty_matches = match self_ty.kind {
340         ty::Dynamic(ref data, ty::ReStatic) => data.principal().is_none(),
341         _ => false,
342     };
343
344     if self_ty_matches {
345         debug!("issue33140_self_ty - MATCHES!");
346         Some(self_ty)
347     } else {
348         debug!("issue33140_self_ty - non-matching self type");
349         None
350     }
351 }
352
353 /// Check if a function is async.
354 fn asyncness(tcx: TyCtxt<'_>, def_id: DefId) -> hir::IsAsync {
355     let hir_id = tcx
356         .hir()
357         .as_local_hir_id(def_id)
358         .unwrap_or_else(|| bug!("asyncness: expected local `DefId`, got `{:?}`", def_id));
359
360     let node = tcx.hir().get(hir_id);
361
362     let fn_like = hir_map::blocks::FnLikeNode::from_node(node).unwrap_or_else(|| {
363         bug!("asyncness: expected fn-like node but got `{:?}`", def_id);
364     });
365
366     fn_like.asyncness()
367 }
368
369 pub fn provide(providers: &mut ty::query::Providers<'_>) {
370     *providers = ty::query::Providers {
371         asyncness,
372         associated_item,
373         associated_item_def_ids,
374         associated_items,
375         adt_sized_constraint,
376         def_span,
377         param_env,
378         trait_of_item,
379         crate_disambiguator,
380         original_crate_name,
381         crate_hash,
382         instance_def_size_estimate,
383         issue33140_self_ty,
384         impl_defaultness,
385         ..*providers
386     };
387 }