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