]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_ty_utils/src/instance.rs
552db5406df8d3ac6c0c33f2c6dda3a71b8cf065
[rust.git] / compiler / rustc_ty_utils / src / instance.rs
1 use rustc_errors::ErrorGuaranteed;
2 use rustc_hir::def_id::{DefId, LocalDefId};
3 use rustc_infer::infer::TyCtxtInferExt;
4 use rustc_middle::traits::CodegenObligationError;
5 use rustc_middle::ty::subst::SubstsRef;
6 use rustc_middle::ty::{
7     self, Binder, Instance, Ty, TyCtxt, TypeFoldable, TypeSuperFoldable, TypeVisitor,
8 };
9 use rustc_span::{sym, DUMMY_SP};
10 use rustc_trait_selection::traits;
11 use traits::{translate_substs, Reveal};
12
13 use rustc_data_structures::sso::SsoHashSet;
14 use std::collections::btree_map::Entry;
15 use std::collections::BTreeMap;
16 use std::ops::ControlFlow;
17
18 use tracing::debug;
19
20 // FIXME(#86795): `BoundVarsCollector` here should **NOT** be used
21 // outside of `resolve_associated_item`. It's just to address #64494,
22 // #83765, and #85848 which are creating bound types/regions that lose
23 // their `Binder` *unintentionally*.
24 // It's ideal to remove `BoundVarsCollector` and just use
25 // `ty::Binder::*` methods but we use this stopgap until we figure out
26 // the "real" fix.
27 struct BoundVarsCollector<'tcx> {
28     binder_index: ty::DebruijnIndex,
29     vars: BTreeMap<u32, ty::BoundVariableKind>,
30     // We may encounter the same variable at different levels of binding, so
31     // this can't just be `Ty`
32     visited: SsoHashSet<(ty::DebruijnIndex, Ty<'tcx>)>,
33 }
34
35 impl<'tcx> BoundVarsCollector<'tcx> {
36     fn new() -> Self {
37         BoundVarsCollector {
38             binder_index: ty::INNERMOST,
39             vars: BTreeMap::new(),
40             visited: SsoHashSet::default(),
41         }
42     }
43
44     fn into_vars(self, tcx: TyCtxt<'tcx>) -> &'tcx ty::List<ty::BoundVariableKind> {
45         let max = self.vars.iter().map(|(k, _)| *k).max().unwrap_or(0);
46         for i in 0..max {
47             if let None = self.vars.get(&i) {
48                 panic!("Unknown variable: {:?}", i);
49             }
50         }
51
52         tcx.mk_bound_variable_kinds(self.vars.into_iter().map(|(_, v)| v))
53     }
54 }
55
56 impl<'tcx> TypeVisitor<'tcx> for BoundVarsCollector<'tcx> {
57     type BreakTy = ();
58
59     fn visit_binder<T: TypeFoldable<'tcx>>(
60         &mut self,
61         t: &Binder<'tcx, T>,
62     ) -> ControlFlow<Self::BreakTy> {
63         self.binder_index.shift_in(1);
64         let result = t.super_visit_with(self);
65         self.binder_index.shift_out(1);
66         result
67     }
68
69     fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
70         if t.outer_exclusive_binder() < self.binder_index
71             || !self.visited.insert((self.binder_index, t))
72         {
73             return ControlFlow::CONTINUE;
74         }
75         match *t.kind() {
76             ty::Bound(debruijn, bound_ty) if debruijn == self.binder_index => {
77                 match self.vars.entry(bound_ty.var.as_u32()) {
78                     Entry::Vacant(entry) => {
79                         entry.insert(ty::BoundVariableKind::Ty(bound_ty.kind));
80                     }
81                     Entry::Occupied(entry) => match entry.get() {
82                         ty::BoundVariableKind::Ty(_) => {}
83                         _ => bug!("Conflicting bound vars"),
84                     },
85                 }
86             }
87
88             _ => (),
89         };
90
91         t.super_visit_with(self)
92     }
93
94     fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
95         match *r {
96             ty::ReLateBound(index, br) if index == self.binder_index => {
97                 match self.vars.entry(br.var.as_u32()) {
98                     Entry::Vacant(entry) => {
99                         entry.insert(ty::BoundVariableKind::Region(br.kind));
100                     }
101                     Entry::Occupied(entry) => match entry.get() {
102                         ty::BoundVariableKind::Region(_) => {}
103                         _ => bug!("Conflicting bound vars"),
104                     },
105                 }
106             }
107
108             _ => (),
109         };
110
111         r.super_visit_with(self)
112     }
113 }
114
115 fn resolve_instance<'tcx>(
116     tcx: TyCtxt<'tcx>,
117     key: ty::ParamEnvAnd<'tcx, (DefId, SubstsRef<'tcx>)>,
118 ) -> Result<Option<Instance<'tcx>>, ErrorGuaranteed> {
119     let (param_env, (did, substs)) = key.into_parts();
120     if let Some(did) = did.as_local() {
121         if let Some(param_did) = tcx.opt_const_param_of(did) {
122             return tcx.resolve_instance_of_const_arg(param_env.and((did, param_did, substs)));
123         }
124     }
125
126     inner_resolve_instance(tcx, param_env.and((ty::WithOptConstParam::unknown(did), substs)))
127 }
128
129 fn resolve_instance_of_const_arg<'tcx>(
130     tcx: TyCtxt<'tcx>,
131     key: ty::ParamEnvAnd<'tcx, (LocalDefId, DefId, SubstsRef<'tcx>)>,
132 ) -> Result<Option<Instance<'tcx>>, ErrorGuaranteed> {
133     let (param_env, (did, const_param_did, substs)) = key.into_parts();
134     inner_resolve_instance(
135         tcx,
136         param_env.and((
137             ty::WithOptConstParam { did: did.to_def_id(), const_param_did: Some(const_param_did) },
138             substs,
139         )),
140     )
141 }
142
143 fn inner_resolve_instance<'tcx>(
144     tcx: TyCtxt<'tcx>,
145     key: ty::ParamEnvAnd<'tcx, (ty::WithOptConstParam<DefId>, SubstsRef<'tcx>)>,
146 ) -> Result<Option<Instance<'tcx>>, ErrorGuaranteed> {
147     let (param_env, (def, substs)) = key.into_parts();
148
149     let result = if let Some(trait_def_id) = tcx.trait_of_item(def.did) {
150         debug!(" => associated item, attempting to find impl in param_env {:#?}", param_env);
151         resolve_associated_item(tcx, def.did, param_env, trait_def_id, substs)
152     } else {
153         let ty = tcx.type_of(def.def_id_for_type_of());
154         let item_type = tcx.subst_and_normalize_erasing_regions(substs, param_env, ty);
155
156         let def = match *item_type.kind() {
157             ty::FnDef(def_id, ..) if tcx.is_intrinsic(def_id) => {
158                 debug!(" => intrinsic");
159                 ty::InstanceDef::Intrinsic(def.did)
160             }
161             ty::FnDef(def_id, substs) if Some(def_id) == tcx.lang_items().drop_in_place_fn() => {
162                 let ty = substs.type_at(0);
163
164                 if ty.needs_drop(tcx, param_env) {
165                     debug!(" => nontrivial drop glue");
166                     match *ty.kind() {
167                         ty::Closure(..)
168                         | ty::Generator(..)
169                         | ty::Tuple(..)
170                         | ty::Adt(..)
171                         | ty::Dynamic(..)
172                         | ty::Array(..)
173                         | ty::Slice(..) => {}
174                         // Drop shims can only be built from ADTs.
175                         _ => return Ok(None),
176                     }
177
178                     ty::InstanceDef::DropGlue(def_id, Some(ty))
179                 } else {
180                     debug!(" => trivial drop glue");
181                     ty::InstanceDef::DropGlue(def_id, None)
182                 }
183             }
184             _ => {
185                 debug!(" => free item");
186                 ty::InstanceDef::Item(def)
187             }
188         };
189         Ok(Some(Instance { def, substs }))
190     };
191     debug!("inner_resolve_instance: result={:?}", result);
192     result
193 }
194
195 fn resolve_associated_item<'tcx>(
196     tcx: TyCtxt<'tcx>,
197     trait_item_id: DefId,
198     param_env: ty::ParamEnv<'tcx>,
199     trait_id: DefId,
200     rcvr_substs: SubstsRef<'tcx>,
201 ) -> Result<Option<Instance<'tcx>>, ErrorGuaranteed> {
202     debug!(?trait_item_id, ?param_env, ?trait_id, ?rcvr_substs, "resolve_associated_item");
203
204     let trait_ref = ty::TraitRef::from_method(tcx, trait_id, rcvr_substs);
205
206     // See FIXME on `BoundVarsCollector`.
207     let mut bound_vars_collector = BoundVarsCollector::new();
208     trait_ref.visit_with(&mut bound_vars_collector);
209     let trait_binder = ty::Binder::bind_with_vars(trait_ref, bound_vars_collector.into_vars(tcx));
210     let vtbl = match tcx.codegen_fulfill_obligation((param_env, trait_binder)) {
211         Ok(vtbl) => vtbl,
212         Err(CodegenObligationError::Ambiguity) => {
213             let reported = tcx.sess.delay_span_bug(
214                 tcx.def_span(trait_item_id),
215                 &format!(
216                     "encountered ambiguity selecting `{:?}` during codegen, presuming due to \
217                      overflow or prior type error",
218                     trait_binder
219                 ),
220             );
221             return Err(reported);
222         }
223         Err(CodegenObligationError::Unimplemented) => return Ok(None),
224         Err(CodegenObligationError::FulfillmentError) => return Ok(None),
225     };
226
227     // Now that we know which impl is being used, we can dispatch to
228     // the actual function:
229     Ok(match vtbl {
230         traits::ImplSource::UserDefined(impl_data) => {
231             debug!(
232                 "resolving ImplSource::UserDefined: {:?}, {:?}, {:?}, {:?}",
233                 param_env, trait_item_id, rcvr_substs, impl_data
234             );
235             assert!(!rcvr_substs.needs_infer());
236             assert!(!trait_ref.needs_infer());
237
238             let trait_def_id = tcx.trait_id_of_impl(impl_data.impl_def_id).unwrap();
239             let trait_def = tcx.trait_def(trait_def_id);
240             let leaf_def = trait_def
241                 .ancestors(tcx, impl_data.impl_def_id)?
242                 .leaf_def(tcx, trait_item_id)
243                 .unwrap_or_else(|| {
244                     bug!("{:?} not found in {:?}", trait_item_id, impl_data.impl_def_id);
245                 });
246
247             let substs = tcx.infer_ctxt().enter(|infcx| {
248                 let param_env = param_env.with_reveal_all_normalized(tcx);
249                 let substs = rcvr_substs.rebase_onto(tcx, trait_def_id, impl_data.substs);
250                 let substs = translate_substs(
251                     &infcx,
252                     param_env,
253                     impl_data.impl_def_id,
254                     substs,
255                     leaf_def.defining_node,
256                 );
257                 infcx.tcx.erase_regions(substs)
258             });
259
260             // Since this is a trait item, we need to see if the item is either a trait default item
261             // or a specialization because we can't resolve those unless we can `Reveal::All`.
262             // NOTE: This should be kept in sync with the similar code in
263             // `rustc_trait_selection::traits::project::assemble_candidates_from_impls()`.
264             let eligible = if leaf_def.is_final() {
265                 // Non-specializable items are always projectable.
266                 true
267             } else {
268                 // Only reveal a specializable default if we're past type-checking
269                 // and the obligation is monomorphic, otherwise passes such as
270                 // transmute checking and polymorphic MIR optimizations could
271                 // get a result which isn't correct for all monomorphizations.
272                 if param_env.reveal() == Reveal::All {
273                     !trait_ref.still_further_specializable()
274                 } else {
275                     false
276                 }
277             };
278
279             if !eligible {
280                 return Ok(None);
281             }
282
283             let substs = tcx.erase_regions(substs);
284
285             // Check if we just resolved an associated `const` declaration from
286             // a `trait` to an associated `const` definition in an `impl`, where
287             // the definition in the `impl` has the wrong type (for which an
288             // error has already been/will be emitted elsewhere).
289             //
290             // NB: this may be expensive, we try to skip it in all the cases where
291             // we know the error would've been caught (e.g. in an upstream crate).
292             //
293             // A better approach might be to just introduce a query (returning
294             // `Result<(), ErrorGuaranteed>`) for the check that `rustc_typeck`
295             // performs (i.e. that the definition's type in the `impl` matches
296             // the declaration in the `trait`), so that we can cheaply check
297             // here if it failed, instead of approximating it.
298             if leaf_def.item.kind == ty::AssocKind::Const
299                 && trait_item_id != leaf_def.item.def_id
300                 && leaf_def.item.def_id.is_local()
301             {
302                 let normalized_type_of = |def_id, substs| {
303                     tcx.subst_and_normalize_erasing_regions(substs, param_env, tcx.type_of(def_id))
304                 };
305
306                 let original_ty = normalized_type_of(trait_item_id, rcvr_substs);
307                 let resolved_ty = normalized_type_of(leaf_def.item.def_id, substs);
308
309                 if original_ty != resolved_ty {
310                     let msg = format!(
311                         "Instance::resolve: inconsistent associated `const` type: \
312                          was `{}: {}` but resolved to `{}: {}`",
313                         tcx.def_path_str_with_substs(trait_item_id, rcvr_substs),
314                         original_ty,
315                         tcx.def_path_str_with_substs(leaf_def.item.def_id, substs),
316                         resolved_ty,
317                     );
318                     let span = tcx.def_span(leaf_def.item.def_id);
319                     let reported = tcx.sess.delay_span_bug(span, &msg);
320
321                     return Err(reported);
322                 }
323             }
324
325             Some(ty::Instance::new(leaf_def.item.def_id, substs))
326         }
327         traits::ImplSource::Generator(generator_data) => Some(Instance {
328             def: ty::InstanceDef::Item(ty::WithOptConstParam::unknown(
329                 generator_data.generator_def_id,
330             )),
331             substs: generator_data.substs,
332         }),
333         traits::ImplSource::Closure(closure_data) => {
334             let trait_closure_kind = tcx.fn_trait_kind_from_lang_item(trait_id).unwrap();
335             Some(Instance::resolve_closure(
336                 tcx,
337                 closure_data.closure_def_id,
338                 closure_data.substs,
339                 trait_closure_kind,
340             ))
341         }
342         traits::ImplSource::FnPointer(ref data) => match data.fn_ty.kind() {
343             ty::FnDef(..) | ty::FnPtr(..) => Some(Instance {
344                 def: ty::InstanceDef::FnPtrShim(trait_item_id, data.fn_ty),
345                 substs: rcvr_substs,
346             }),
347             _ => None,
348         },
349         traits::ImplSource::Object(ref data) => {
350             if let Some(index) = traits::get_vtable_index_of_object_method(tcx, data, trait_item_id)
351             {
352                 Some(Instance {
353                     def: ty::InstanceDef::Virtual(trait_item_id, index),
354                     substs: rcvr_substs,
355                 })
356             } else {
357                 None
358             }
359         }
360         traits::ImplSource::Builtin(..) => {
361             if Some(trait_ref.def_id) == tcx.lang_items().clone_trait() {
362                 // FIXME(eddyb) use lang items for methods instead of names.
363                 let name = tcx.item_name(trait_item_id);
364                 if name == sym::clone {
365                     let self_ty = trait_ref.self_ty();
366
367                     let is_copy = self_ty.is_copy_modulo_regions(tcx.at(DUMMY_SP), param_env);
368                     match self_ty.kind() {
369                         _ if is_copy => (),
370                         ty::Closure(..) | ty::Tuple(..) => {}
371                         _ => return Ok(None),
372                     };
373
374                     Some(Instance {
375                         def: ty::InstanceDef::CloneShim(trait_item_id, self_ty),
376                         substs: rcvr_substs,
377                     })
378                 } else {
379                     assert_eq!(name, sym::clone_from);
380
381                     // Use the default `fn clone_from` from `trait Clone`.
382                     let substs = tcx.erase_regions(rcvr_substs);
383                     Some(ty::Instance::new(trait_item_id, substs))
384                 }
385             } else {
386                 None
387             }
388         }
389         traits::ImplSource::AutoImpl(..)
390         | traits::ImplSource::Param(..)
391         | traits::ImplSource::TraitAlias(..)
392         | traits::ImplSource::DiscriminantKind(..)
393         | traits::ImplSource::Pointee(..)
394         | traits::ImplSource::TraitUpcasting(_)
395         | traits::ImplSource::ConstDestruct(_) => None,
396     })
397 }
398
399 pub fn provide(providers: &mut ty::query::Providers) {
400     *providers =
401         ty::query::Providers { resolve_instance, resolve_instance_of_const_arg, ..*providers };
402 }