]> git.lizzy.rs Git - rust.git/blob - src/librustc_ty/instance.rs
pin docs: add some forward references
[rust.git] / src / librustc_ty / 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, Instance, TyCtxt, TypeFoldable};
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 log::debug;
12
13 fn resolve_instance<'tcx>(
14     tcx: TyCtxt<'tcx>,
15     key: ty::ParamEnvAnd<'tcx, (DefId, SubstsRef<'tcx>)>,
16 ) -> Result<Option<Instance<'tcx>>, ErrorReported> {
17     let (param_env, (did, substs)) = key.into_parts();
18     if let Some(did) = did.as_local() {
19         if let Some(param_did) = tcx.opt_const_param_of(did) {
20             return tcx.resolve_instance_of_const_arg(param_env.and((did, param_did, substs)));
21         }
22     }
23
24     inner_resolve_instance(tcx, param_env.and((ty::WithOptConstParam::unknown(did), substs)))
25 }
26
27 fn resolve_instance_of_const_arg<'tcx>(
28     tcx: TyCtxt<'tcx>,
29     key: ty::ParamEnvAnd<'tcx, (LocalDefId, DefId, SubstsRef<'tcx>)>,
30 ) -> Result<Option<Instance<'tcx>>, ErrorReported> {
31     let (param_env, (did, const_param_did, substs)) = key.into_parts();
32     inner_resolve_instance(
33         tcx,
34         param_env.and((
35             ty::WithOptConstParam { did: did.to_def_id(), const_param_did: Some(const_param_did) },
36             substs,
37         )),
38     )
39 }
40
41 fn inner_resolve_instance<'tcx>(
42     tcx: TyCtxt<'tcx>,
43     key: ty::ParamEnvAnd<'tcx, (ty::WithOptConstParam<DefId>, SubstsRef<'tcx>)>,
44 ) -> Result<Option<Instance<'tcx>>, ErrorReported> {
45     let (param_env, (def, substs)) = key.into_parts();
46
47     debug!("resolve(def={:?}, substs={:?})", def.did, substs);
48     let result = if let Some(trait_def_id) = tcx.trait_of_item(def.did) {
49         debug!(" => associated item, attempting to find impl in param_env {:#?}", param_env);
50         let item = tcx.associated_item(def.did);
51         resolve_associated_item(tcx, &item, param_env, trait_def_id, substs)
52     } else {
53         let ty = tcx.type_of(def.def_id_for_type_of());
54         let item_type = tcx.subst_and_normalize_erasing_regions(substs, param_env, &ty);
55
56         let def = match item_type.kind {
57             ty::FnDef(..)
58                 if {
59                     let f = item_type.fn_sig(tcx);
60                     f.abi() == Abi::RustIntrinsic || f.abi() == Abi::PlatformIntrinsic
61                 } =>
62             {
63                 debug!(" => intrinsic");
64                 ty::InstanceDef::Intrinsic(def.did)
65             }
66             ty::FnDef(def_id, substs) if Some(def_id) == tcx.lang_items().drop_in_place_fn() => {
67                 let ty = substs.type_at(0);
68
69                 if ty.needs_drop(tcx, param_env) {
70                     debug!(" => nontrivial drop glue");
71                     match ty.kind {
72                         ty::Closure(..)
73                         | ty::Generator(..)
74                         | ty::Tuple(..)
75                         | ty::Adt(..)
76                         | ty::Dynamic(..)
77                         | ty::Array(..)
78                         | ty::Slice(..) => {}
79                         // Drop shims can only be built from ADTs.
80                         _ => return Ok(None),
81                     }
82
83                     ty::InstanceDef::DropGlue(def_id, Some(ty))
84                 } else {
85                     debug!(" => trivial drop glue");
86                     ty::InstanceDef::DropGlue(def_id, None)
87                 }
88             }
89             _ => {
90                 debug!(" => free item");
91                 ty::InstanceDef::Item(def)
92             }
93         };
94         Ok(Some(Instance { def, substs }))
95     };
96     debug!("resolve(def.did={:?}, substs={:?}) = {:?}", def.did, substs, result);
97     result
98 }
99
100 fn resolve_associated_item<'tcx>(
101     tcx: TyCtxt<'tcx>,
102     trait_item: &ty::AssocItem,
103     param_env: ty::ParamEnv<'tcx>,
104     trait_id: DefId,
105     rcvr_substs: SubstsRef<'tcx>,
106 ) -> Result<Option<Instance<'tcx>>, ErrorReported> {
107     let def_id = trait_item.def_id;
108     debug!(
109         "resolve_associated_item(trait_item={:?}, \
110             param_env={:?}, \
111             trait_id={:?}, \
112             rcvr_substs={:?})",
113         def_id, param_env, trait_id, rcvr_substs
114     );
115
116     let trait_ref = ty::TraitRef::from_method(tcx, trait_id, rcvr_substs);
117     let vtbl = tcx.codegen_fulfill_obligation((param_env, ty::Binder::bind(trait_ref)))?;
118
119     // Now that we know which impl is being used, we can dispatch to
120     // the actual function:
121     Ok(match vtbl {
122         traits::ImplSourceUserDefined(impl_data) => {
123             debug!(
124                 "resolving ImplSourceUserDefined: {:?}, {:?}, {:?}, {:?}",
125                 param_env, trait_item, rcvr_substs, impl_data
126             );
127             assert!(!rcvr_substs.needs_infer());
128             assert!(!trait_ref.needs_infer());
129
130             let trait_def_id = tcx.trait_id_of_impl(impl_data.impl_def_id).unwrap();
131             let trait_def = tcx.trait_def(trait_def_id);
132             let leaf_def = trait_def
133                 .ancestors(tcx, impl_data.impl_def_id)?
134                 .leaf_def(tcx, trait_item.ident, trait_item.kind)
135                 .unwrap_or_else(|| {
136                     bug!("{:?} not found in {:?}", trait_item, impl_data.impl_def_id);
137                 });
138
139             let substs = tcx.infer_ctxt().enter(|infcx| {
140                 let param_env = param_env.with_reveal_all_normalized(tcx);
141                 let substs = rcvr_substs.rebase_onto(tcx, trait_def_id, impl_data.substs);
142                 let substs = translate_substs(
143                     &infcx,
144                     param_env,
145                     impl_data.impl_def_id,
146                     substs,
147                     leaf_def.defining_node,
148                 );
149                 infcx.tcx.erase_regions(&substs)
150             });
151
152             // Since this is a trait item, we need to see if the item is either a trait default item
153             // or a specialization because we can't resolve those unless we can `Reveal::All`.
154             // NOTE: This should be kept in sync with the similar code in
155             // `rustc_trait_selection::traits::project::assemble_candidates_from_impls()`.
156             let eligible = if leaf_def.is_final() {
157                 // Non-specializable items are always projectable.
158                 true
159             } else {
160                 // Only reveal a specializable default if we're past type-checking
161                 // and the obligation is monomorphic, otherwise passes such as
162                 // transmute checking and polymorphic MIR optimizations could
163                 // get a result which isn't correct for all monomorphizations.
164                 if param_env.reveal() == Reveal::All {
165                     !trait_ref.still_further_specializable()
166                 } else {
167                     false
168                 }
169             };
170
171             if !eligible {
172                 return Ok(None);
173             }
174
175             let substs = tcx.erase_regions(&substs);
176
177             // Check if we just resolved an associated `const` declaration from
178             // a `trait` to an associated `const` definition in an `impl`, where
179             // the definition in the `impl` has the wrong type (for which an
180             // error has already been/will be emitted elsewhere).
181             //
182             // NB: this may be expensive, we try to skip it in all the cases where
183             // we know the error would've been caught (e.g. in an upstream crate).
184             //
185             // A better approach might be to just introduce a query (returning
186             // `Result<(), ErrorReported>`) for the check that `rustc_typeck`
187             // performs (i.e. that the definition's type in the `impl` matches
188             // the declaration in the `trait`), so that we can cheaply check
189             // here if it failed, instead of approximating it.
190             if trait_item.kind == ty::AssocKind::Const
191                 && trait_item.def_id != leaf_def.item.def_id
192                 && leaf_def.item.def_id.is_local()
193             {
194                 let normalized_type_of = |def_id, substs| {
195                     tcx.subst_and_normalize_erasing_regions(substs, param_env, &tcx.type_of(def_id))
196                 };
197
198                 let original_ty = normalized_type_of(trait_item.def_id, rcvr_substs);
199                 let resolved_ty = normalized_type_of(leaf_def.item.def_id, substs);
200
201                 if original_ty != resolved_ty {
202                     let msg = format!(
203                         "Instance::resolve: inconsistent associated `const` type: \
204                          was `{}: {}` but resolved to `{}: {}`",
205                         tcx.def_path_str_with_substs(trait_item.def_id, rcvr_substs),
206                         original_ty,
207                         tcx.def_path_str_with_substs(leaf_def.item.def_id, substs),
208                         resolved_ty,
209                     );
210                     let span = tcx.def_span(leaf_def.item.def_id);
211                     tcx.sess.delay_span_bug(span, &msg);
212
213                     return Err(ErrorReported);
214                 }
215             }
216
217             Some(ty::Instance::new(leaf_def.item.def_id, substs))
218         }
219         traits::ImplSourceGenerator(generator_data) => Some(Instance {
220             def: ty::InstanceDef::Item(ty::WithOptConstParam::unknown(
221                 generator_data.generator_def_id,
222             )),
223             substs: generator_data.substs,
224         }),
225         traits::ImplSourceClosure(closure_data) => {
226             let trait_closure_kind = tcx.fn_trait_kind_from_lang_item(trait_id).unwrap();
227             Some(Instance::resolve_closure(
228                 tcx,
229                 closure_data.closure_def_id,
230                 closure_data.substs,
231                 trait_closure_kind,
232             ))
233         }
234         traits::ImplSourceFnPointer(ref data) => match data.fn_ty.kind {
235             ty::FnDef(..) | ty::FnPtr(..) => Some(Instance {
236                 def: ty::InstanceDef::FnPtrShim(trait_item.def_id, data.fn_ty),
237                 substs: rcvr_substs,
238             }),
239             _ => None,
240         },
241         traits::ImplSourceObject(ref data) => {
242             let index = traits::get_vtable_index_of_object_method(tcx, data, def_id);
243             Some(Instance { def: ty::InstanceDef::Virtual(def_id, index), substs: rcvr_substs })
244         }
245         traits::ImplSourceBuiltin(..) => {
246             if Some(trait_ref.def_id) == tcx.lang_items().clone_trait() {
247                 // FIXME(eddyb) use lang items for methods instead of names.
248                 let name = tcx.item_name(def_id);
249                 if name == sym::clone {
250                     let self_ty = trait_ref.self_ty();
251
252                     let is_copy = self_ty.is_copy_modulo_regions(tcx.at(DUMMY_SP), param_env);
253                     match self_ty.kind {
254                         _ if is_copy => (),
255                         ty::Array(..) | ty::Closure(..) | ty::Tuple(..) => {}
256                         _ => return Ok(None),
257                     };
258
259                     Some(Instance {
260                         def: ty::InstanceDef::CloneShim(def_id, self_ty),
261                         substs: rcvr_substs,
262                     })
263                 } else {
264                     assert_eq!(name, sym::clone_from);
265
266                     // Use the default `fn clone_from` from `trait Clone`.
267                     let substs = tcx.erase_regions(&rcvr_substs);
268                     Some(ty::Instance::new(def_id, substs))
269                 }
270             } else {
271                 None
272             }
273         }
274         traits::ImplSourceAutoImpl(..)
275         | traits::ImplSourceParam(..)
276         | traits::ImplSourceTraitAlias(..)
277         | traits::ImplSourceDiscriminantKind(..) => None,
278     })
279 }
280
281 pub fn provide(providers: &mut ty::query::Providers) {
282     *providers =
283         ty::query::Providers { resolve_instance, resolve_instance_of_const_arg, ..*providers };
284 }