1 use rustc_errors::ErrorGuaranteed;
2 use rustc_hir::def_id::DefId;
3 use rustc_infer::infer::TyCtxtInferExt;
4 use rustc_middle::query::Providers;
5 use rustc_middle::traits::CodegenObligationError;
6 use rustc_middle::ty::subst::SubstsRef;
7 use rustc_middle::ty::{self, Instance, TyCtxt, TypeVisitableExt};
8 use rustc_span::sym;
9 use rustc_trait_selection::traits;
10 use traits::{translate_substs, Reveal};
11
12 use crate::errors::UnexpectedFnPtrAssociatedItem;
13
resolve_instance<'tcx>( tcx: TyCtxt<'tcx>, key: ty::ParamEnvAnd<'tcx, (DefId, SubstsRef<'tcx>)>, ) -> Result<Option<Instance<'tcx>>, ErrorGuaranteed>14 fn resolve_instance<'tcx>(
15 tcx: TyCtxt<'tcx>,
16 key: ty::ParamEnvAnd<'tcx, (DefId, SubstsRef<'tcx>)>,
17 ) -> Result<Option<Instance<'tcx>>, ErrorGuaranteed> {
18 let (param_env, (def, substs)) = key.into_parts();
19
20 let result = if let Some(trait_def_id) = tcx.trait_of_item(def) {
21 debug!(" => associated item, attempting to find impl in param_env {:#?}", param_env);
22 resolve_associated_item(
23 tcx,
24 def,
25 param_env,
26 trait_def_id,
27 tcx.normalize_erasing_regions(param_env, substs),
28 )
29 } else {
30 let ty = tcx.type_of(def);
31 let item_type = tcx.subst_and_normalize_erasing_regions(substs, param_env, ty);
32
33 let def = match *item_type.kind() {
34 ty::FnDef(def_id, ..) if tcx.is_intrinsic(def_id) => {
35 debug!(" => intrinsic");
36 ty::InstanceDef::Intrinsic(def)
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 debug!(" => nontrivial drop glue");
43 match *ty.kind() {
44 ty::Closure(..)
45 | ty::Generator(..)
46 | ty::Tuple(..)
47 | ty::Adt(..)
48 | ty::Dynamic(..)
49 | ty::Array(..)
50 | ty::Slice(..) => {}
51 // Drop shims can only be built from ADTs.
52 _ => return Ok(None),
53 }
54
55 ty::InstanceDef::DropGlue(def_id, Some(ty))
56 } else {
57 debug!(" => trivial drop glue");
58 ty::InstanceDef::DropGlue(def_id, None)
59 }
60 }
61 _ => {
62 debug!(" => free item");
63 ty::InstanceDef::Item(def)
64 }
65 };
66 Ok(Some(Instance { def, substs }))
67 };
68 debug!("inner_resolve_instance: result={:?}", result);
69 result
70 }
71
resolve_associated_item<'tcx>( tcx: TyCtxt<'tcx>, trait_item_id: DefId, param_env: ty::ParamEnv<'tcx>, trait_id: DefId, rcvr_substs: SubstsRef<'tcx>, ) -> Result<Option<Instance<'tcx>>, ErrorGuaranteed>72 fn resolve_associated_item<'tcx>(
73 tcx: TyCtxt<'tcx>,
74 trait_item_id: DefId,
75 param_env: ty::ParamEnv<'tcx>,
76 trait_id: DefId,
77 rcvr_substs: SubstsRef<'tcx>,
78 ) -> Result<Option<Instance<'tcx>>, ErrorGuaranteed> {
79 debug!(?trait_item_id, ?param_env, ?trait_id, ?rcvr_substs, "resolve_associated_item");
80
81 let trait_ref = ty::TraitRef::from_method(tcx, trait_id, rcvr_substs);
82
83 let vtbl = match tcx.codegen_select_candidate((param_env, trait_ref)) {
84 Ok(vtbl) => vtbl,
85 Err(CodegenObligationError::Ambiguity) => {
86 let reported = tcx.sess.delay_span_bug(
87 tcx.def_span(trait_item_id),
88 format!(
89 "encountered ambiguity selecting `{trait_ref:?}` during codegen, presuming due to \
90 overflow or prior type error",
91 ),
92 );
93 return Err(reported);
94 }
95 Err(CodegenObligationError::Unimplemented) => return Ok(None),
96 Err(CodegenObligationError::FulfillmentError) => return Ok(None),
97 };
98
99 // Now that we know which impl is being used, we can dispatch to
100 // the actual function:
101 Ok(match vtbl {
102 traits::ImplSource::UserDefined(impl_data) => {
103 debug!(
104 "resolving ImplSource::UserDefined: {:?}, {:?}, {:?}, {:?}",
105 param_env, trait_item_id, rcvr_substs, impl_data
106 );
107 assert!(!rcvr_substs.has_infer());
108 assert!(!trait_ref.has_infer());
109
110 let trait_def_id = tcx.trait_id_of_impl(impl_data.impl_def_id).unwrap();
111 let trait_def = tcx.trait_def(trait_def_id);
112 let leaf_def = trait_def
113 .ancestors(tcx, impl_data.impl_def_id)?
114 .leaf_def(tcx, trait_item_id)
115 .unwrap_or_else(|| {
116 bug!("{:?} not found in {:?}", trait_item_id, impl_data.impl_def_id);
117 });
118 let infcx = tcx.infer_ctxt().build();
119 let param_env = param_env.with_reveal_all_normalized(tcx);
120 let substs = rcvr_substs.rebase_onto(tcx, trait_def_id, impl_data.substs);
121 let substs = translate_substs(
122 &infcx,
123 param_env,
124 impl_data.impl_def_id,
125 substs,
126 leaf_def.defining_node,
127 );
128 let substs = infcx.tcx.erase_regions(substs);
129
130 // Since this is a trait item, we need to see if the item is either a trait default item
131 // or a specialization because we can't resolve those unless we can `Reveal::All`.
132 // NOTE: This should be kept in sync with the similar code in
133 // `rustc_trait_selection::traits::project::assemble_candidates_from_impls()`.
134 let eligible = if leaf_def.is_final() {
135 // Non-specializable items are always projectable.
136 true
137 } else {
138 // Only reveal a specializable default if we're past type-checking
139 // and the obligation is monomorphic, otherwise passes such as
140 // transmute checking and polymorphic MIR optimizations could
141 // get a result which isn't correct for all monomorphizations.
142 if param_env.reveal() == Reveal::All {
143 !trait_ref.still_further_specializable()
144 } else {
145 false
146 }
147 };
148
149 if !eligible {
150 return Ok(None);
151 }
152
153 // Any final impl is required to define all associated items.
154 if !leaf_def.item.defaultness(tcx).has_value() {
155 let guard = tcx.sess.delay_span_bug(
156 tcx.def_span(leaf_def.item.def_id),
157 "missing value for assoc item in impl",
158 );
159 return Err(guard);
160 }
161
162 let substs = tcx.erase_regions(substs);
163
164 // Check if we just resolved an associated `const` declaration from
165 // a `trait` to an associated `const` definition in an `impl`, where
166 // the definition in the `impl` has the wrong type (for which an
167 // error has already been/will be emitted elsewhere).
168 if leaf_def.item.kind == ty::AssocKind::Const
169 && trait_item_id != leaf_def.item.def_id
170 && let Some(leaf_def_item) = leaf_def.item.def_id.as_local()
171 {
172 tcx.compare_impl_const((
173 leaf_def_item,
174 trait_item_id,
175 ))?;
176 }
177
178 Some(ty::Instance::new(leaf_def.item.def_id, substs))
179 }
180 traits::ImplSource::Object(ref data) => {
181 traits::get_vtable_index_of_object_method(tcx, data, trait_item_id).map(|index| {
182 Instance {
183 def: ty::InstanceDef::Virtual(trait_item_id, index),
184 substs: rcvr_substs,
185 }
186 })
187 }
188 traits::ImplSource::Builtin(..) => {
189 let lang_items = tcx.lang_items();
190 if Some(trait_ref.def_id) == lang_items.clone_trait() {
191 // FIXME(eddyb) use lang items for methods instead of names.
192 let name = tcx.item_name(trait_item_id);
193 if name == sym::clone {
194 let self_ty = trait_ref.self_ty();
195
196 let is_copy = self_ty.is_copy_modulo_regions(tcx, param_env);
197 match self_ty.kind() {
198 _ if is_copy => (),
199 ty::Generator(..)
200 | ty::GeneratorWitness(..)
201 | ty::Closure(..)
202 | ty::Tuple(..) => {}
203 _ => return Ok(None),
204 };
205
206 Some(Instance {
207 def: ty::InstanceDef::CloneShim(trait_item_id, self_ty),
208 substs: rcvr_substs,
209 })
210 } else {
211 assert_eq!(name, sym::clone_from);
212
213 // Use the default `fn clone_from` from `trait Clone`.
214 let substs = tcx.erase_regions(rcvr_substs);
215 Some(ty::Instance::new(trait_item_id, substs))
216 }
217 } else if Some(trait_ref.def_id) == lang_items.fn_ptr_trait() {
218 if lang_items.fn_ptr_addr() == Some(trait_item_id) {
219 let self_ty = trait_ref.self_ty();
220 if !matches!(self_ty.kind(), ty::FnPtr(..)) {
221 return Ok(None);
222 }
223 Some(Instance {
224 def: ty::InstanceDef::FnPtrAddrShim(trait_item_id, self_ty),
225 substs: rcvr_substs,
226 })
227 } else {
228 tcx.sess.emit_fatal(UnexpectedFnPtrAssociatedItem {
229 span: tcx.def_span(trait_item_id),
230 })
231 }
232 } else if Some(trait_ref.def_id) == lang_items.future_trait() {
233 let ty::Generator(generator_def_id, substs, _) = *rcvr_substs.type_at(0).kind() else {
234 bug!()
235 };
236 if Some(trait_item_id) == tcx.lang_items().future_poll_fn() {
237 // `Future::poll` is generated by the compiler.
238 Some(Instance { def: ty::InstanceDef::Item(generator_def_id), substs: substs })
239 } else {
240 // All other methods are default methods of the `Future` trait.
241 // (this assumes that `ImplSource::Builtin` is only used for methods on `Future`)
242 debug_assert!(tcx.defaultness(trait_item_id).has_value());
243 Some(Instance::new(trait_item_id, rcvr_substs))
244 }
245 } else if Some(trait_ref.def_id) == lang_items.gen_trait() {
246 let ty::Generator(generator_def_id, substs, _) = *rcvr_substs.type_at(0).kind() else {
247 bug!()
248 };
249 if cfg!(debug_assertions) && tcx.item_name(trait_item_id) != sym::resume {
250 // For compiler developers who'd like to add new items to `Generator`,
251 // you either need to generate a shim body, or perhaps return
252 // `InstanceDef::Item` pointing to a trait default method body if
253 // it is given a default implementation by the trait.
254 span_bug!(
255 tcx.def_span(generator_def_id),
256 "no definition for `{trait_ref}::{}` for built-in generator type",
257 tcx.item_name(trait_item_id)
258 )
259 }
260 Some(Instance { def: ty::InstanceDef::Item(generator_def_id), substs })
261 } else if tcx.fn_trait_kind_from_def_id(trait_ref.def_id).is_some() {
262 // FIXME: This doesn't check for malformed libcore that defines, e.g.,
263 // `trait Fn { fn call_once(&self) { .. } }`. This is mostly for extension
264 // methods.
265 if cfg!(debug_assertions)
266 && ![sym::call, sym::call_mut, sym::call_once]
267 .contains(&tcx.item_name(trait_item_id))
268 {
269 // For compiler developers who'd like to add new items to `Fn`/`FnMut`/`FnOnce`,
270 // you either need to generate a shim body, or perhaps return
271 // `InstanceDef::Item` pointing to a trait default method body if
272 // it is given a default implementation by the trait.
273 bug!(
274 "no definition for `{trait_ref}::{}` for built-in callable type",
275 tcx.item_name(trait_item_id)
276 )
277 }
278 match *rcvr_substs.type_at(0).kind() {
279 ty::Closure(closure_def_id, substs) => {
280 let trait_closure_kind = tcx.fn_trait_kind_from_def_id(trait_id).unwrap();
281 Instance::resolve_closure(tcx, closure_def_id, substs, trait_closure_kind)
282 }
283 ty::FnDef(..) | ty::FnPtr(..) => Some(Instance {
284 def: ty::InstanceDef::FnPtrShim(trait_item_id, rcvr_substs.type_at(0)),
285 substs: rcvr_substs,
286 }),
287 _ => bug!(
288 "no built-in definition for `{trait_ref}::{}` for non-fn type",
289 tcx.item_name(trait_item_id)
290 ),
291 }
292 } else {
293 None
294 }
295 }
296 traits::ImplSource::Param(..) | traits::ImplSource::TraitUpcasting(_) => None,
297 })
298 }
299
provide(providers: &mut Providers)300 pub fn provide(providers: &mut Providers) {
301 *providers = Providers { resolve_instance, ..*providers };
302 }
303