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