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