]> git.lizzy.rs Git - rust.git/blob - src/librustc_ty/ty.rs
Auto merge of #67290 - jonas-schievink:leak-audit, r=KodrAus
[rust.git] / src / librustc_ty / ty.rs
1 use rustc::hir::map as hir_map;
2 use rustc::session::CrateDisambiguator;
3 use rustc::ty::subst::Subst;
4 use rustc::ty::{self, ToPredicate, Ty, TyCtxt, WithConstness};
5 use rustc_data_structures::svh::Svh;
6 use rustc_hir as hir;
7 use rustc_hir::def_id::{CrateNum, DefId, LOCAL_CRATE};
8 use rustc_infer::traits;
9 use rustc_span::symbol::Symbol;
10 use rustc_span::Span;
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::Method { has_self } => (ty::AssocKind::Method, 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         method_has_self_argument: 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::Method { has_self } => (ty::AssocKind::Method, 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         method_has_self_argument: 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 /// Calculates the `Sized` constraint.
169 ///
170 /// In fact, there are only a few options for the types in the constraint:
171 ///     - an obviously-unsized type
172 ///     - a type parameter or projection whose Sizedness can't be known
173 ///     - a tuple of type parameters or projections, if there are multiple
174 ///       such.
175 ///     - a Error, if a type contained itself. The representability
176 ///       check should catch this case.
177 fn adt_sized_constraint(tcx: TyCtxt<'_>, def_id: DefId) -> ty::AdtSizedConstraint<'_> {
178     let def = tcx.adt_def(def_id);
179
180     let result = tcx.mk_type_list(
181         def.variants
182             .iter()
183             .flat_map(|v| v.fields.last())
184             .flat_map(|f| sized_constraint_for_ty(tcx, def, tcx.type_of(f.did))),
185     );
186
187     debug!("adt_sized_constraint: {:?} => {:?}", def, result);
188
189     ty::AdtSizedConstraint(result)
190 }
191
192 fn associated_item_def_ids(tcx: TyCtxt<'_>, def_id: DefId) -> &[DefId] {
193     let id = tcx.hir().as_local_hir_id(def_id).unwrap();
194     let item = tcx.hir().expect_item(id);
195     match item.kind {
196         hir::ItemKind::Trait(.., ref trait_item_refs) => tcx.arena.alloc_from_iter(
197             trait_item_refs
198                 .iter()
199                 .map(|trait_item_ref| trait_item_ref.id)
200                 .map(|id| tcx.hir().local_def_id(id.hir_id)),
201         ),
202         hir::ItemKind::Impl { ref items, .. } => tcx.arena.alloc_from_iter(
203             items
204                 .iter()
205                 .map(|impl_item_ref| impl_item_ref.id)
206                 .map(|id| tcx.hir().local_def_id(id.hir_id)),
207         ),
208         hir::ItemKind::TraitAlias(..) => &[],
209         _ => span_bug!(item.span, "associated_item_def_ids: not impl or trait"),
210     }
211 }
212
213 fn associated_items<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> &'tcx ty::AssociatedItems {
214     let items = tcx.associated_item_def_ids(def_id).iter().map(|did| tcx.associated_item(*did));
215     tcx.arena.alloc(ty::AssociatedItems::new(items))
216 }
217
218 fn def_span(tcx: TyCtxt<'_>, def_id: DefId) -> Span {
219     tcx.hir().span_if_local(def_id).unwrap()
220 }
221
222 /// If the given `DefId` describes an item belonging to a trait,
223 /// returns the `DefId` of the trait that the trait item belongs to;
224 /// otherwise, returns `None`.
225 fn trait_of_item(tcx: TyCtxt<'_>, def_id: DefId) -> Option<DefId> {
226     tcx.opt_associated_item(def_id).and_then(|associated_item| match associated_item.container {
227         ty::TraitContainer(def_id) => Some(def_id),
228         ty::ImplContainer(_) => None,
229     })
230 }
231
232 /// See `ParamEnv` struct definition for details.
233 fn param_env(tcx: TyCtxt<'_>, def_id: DefId) -> ty::ParamEnv<'_> {
234     // The param_env of an impl Trait type is its defining function's param_env
235     if let Some(parent) = ty::is_impl_trait_defn(tcx, def_id) {
236         return param_env(tcx, parent);
237     }
238     // Compute the bounds on Self and the type parameters.
239
240     let ty::InstantiatedPredicates { predicates, .. } =
241         tcx.predicates_of(def_id).instantiate_identity(tcx);
242
243     // Finally, we have to normalize the bounds in the environment, in
244     // case they contain any associated type projections. This process
245     // can yield errors if the put in illegal associated types, like
246     // `<i32 as Foo>::Bar` where `i32` does not implement `Foo`. We
247     // report these errors right here; this doesn't actually feel
248     // right to me, because constructing the environment feels like a
249     // kind of a "idempotent" action, but I'm not sure where would be
250     // a better place. In practice, we construct environments for
251     // every fn once during type checking, and we'll abort if there
252     // are any errors at that point, so after type checking you can be
253     // sure that this will succeed without errors anyway.
254
255     let unnormalized_env = ty::ParamEnv::new(
256         tcx.intern_predicates(&predicates),
257         traits::Reveal::UserFacing,
258         tcx.sess.opts.debugging_opts.chalk.then_some(def_id),
259     );
260
261     let body_id = tcx.hir().as_local_hir_id(def_id).map_or(hir::DUMMY_HIR_ID, |id| {
262         tcx.hir().maybe_body_owned_by(id).map_or(id, |body| body.hir_id)
263     });
264     let cause = traits::ObligationCause::misc(tcx.def_span(def_id), body_id);
265     traits::normalize_param_env_or_error(tcx, def_id, unnormalized_env, cause)
266 }
267
268 fn crate_disambiguator(tcx: TyCtxt<'_>, crate_num: CrateNum) -> CrateDisambiguator {
269     assert_eq!(crate_num, LOCAL_CRATE);
270     tcx.sess.local_crate_disambiguator()
271 }
272
273 fn original_crate_name(tcx: TyCtxt<'_>, crate_num: CrateNum) -> Symbol {
274     assert_eq!(crate_num, LOCAL_CRATE);
275     tcx.crate_name
276 }
277
278 fn crate_hash(tcx: TyCtxt<'_>, crate_num: CrateNum) -> Svh {
279     assert_eq!(crate_num, LOCAL_CRATE);
280     tcx.hir().crate_hash
281 }
282
283 fn instance_def_size_estimate<'tcx>(
284     tcx: TyCtxt<'tcx>,
285     instance_def: ty::InstanceDef<'tcx>,
286 ) -> usize {
287     use ty::InstanceDef;
288
289     match instance_def {
290         InstanceDef::Item(..) | InstanceDef::DropGlue(..) => {
291             let mir = tcx.instance_mir(instance_def);
292             mir.basic_blocks().iter().map(|bb| bb.statements.len()).sum()
293         }
294         // Estimate the size of other compiler-generated shims to be 1.
295         _ => 1,
296     }
297 }
298
299 /// If `def_id` is an issue 33140 hack impl, returns its self type; otherwise, returns `None`.
300 ///
301 /// See [`ImplOverlapKind::Issue33140`] for more details.
302 fn issue33140_self_ty(tcx: TyCtxt<'_>, def_id: DefId) -> Option<Ty<'_>> {
303     debug!("issue33140_self_ty({:?})", def_id);
304
305     let trait_ref = tcx
306         .impl_trait_ref(def_id)
307         .unwrap_or_else(|| bug!("issue33140_self_ty called on inherent impl {:?}", def_id));
308
309     debug!("issue33140_self_ty({:?}), trait-ref={:?}", def_id, trait_ref);
310
311     let is_marker_like = tcx.impl_polarity(def_id) == ty::ImplPolarity::Positive
312         && tcx.associated_item_def_ids(trait_ref.def_id).is_empty();
313
314     // Check whether these impls would be ok for a marker trait.
315     if !is_marker_like {
316         debug!("issue33140_self_ty - not marker-like!");
317         return None;
318     }
319
320     // impl must be `impl Trait for dyn Marker1 + Marker2 + ...`
321     if trait_ref.substs.len() != 1 {
322         debug!("issue33140_self_ty - impl has substs!");
323         return None;
324     }
325
326     let predicates = tcx.predicates_of(def_id);
327     if predicates.parent.is_some() || !predicates.predicates.is_empty() {
328         debug!("issue33140_self_ty - impl has predicates {:?}!", predicates);
329         return None;
330     }
331
332     let self_ty = trait_ref.self_ty();
333     let self_ty_matches = match self_ty.kind {
334         ty::Dynamic(ref data, ty::ReStatic) => data.principal().is_none(),
335         _ => false,
336     };
337
338     if self_ty_matches {
339         debug!("issue33140_self_ty - MATCHES!");
340         Some(self_ty)
341     } else {
342         debug!("issue33140_self_ty - non-matching self type");
343         None
344     }
345 }
346
347 /// Check if a function is async.
348 fn asyncness(tcx: TyCtxt<'_>, def_id: DefId) -> hir::IsAsync {
349     let hir_id = tcx
350         .hir()
351         .as_local_hir_id(def_id)
352         .unwrap_or_else(|| bug!("asyncness: expected local `DefId`, got `{:?}`", def_id));
353
354     let node = tcx.hir().get(hir_id);
355
356     let fn_like = hir_map::blocks::FnLikeNode::from_node(node).unwrap_or_else(|| {
357         bug!("asyncness: expected fn-like node but got `{:?}`", def_id);
358     });
359
360     fn_like.asyncness()
361 }
362
363 pub fn provide(providers: &mut ty::query::Providers<'_>) {
364     *providers = ty::query::Providers {
365         asyncness,
366         associated_item,
367         associated_item_def_ids,
368         associated_items,
369         adt_sized_constraint,
370         def_span,
371         param_env,
372         trait_of_item,
373         crate_disambiguator,
374         original_crate_name,
375         crate_hash,
376         instance_def_size_estimate,
377         issue33140_self_ty,
378         ..*providers
379     };
380 }