]> git.proxmox.com Git - rustc.git/blame - compiler/rustc_ty_utils/src/instance.rs
New upstream version 1.71.1+dfsg1
[rustc.git] / compiler / rustc_ty_utils / src / instance.rs
CommitLineData
5e7ed085 1use rustc_errors::ErrorGuaranteed;
49aad941 2use rustc_hir::def_id::DefId;
ba9703b0 3use rustc_infer::infer::TyCtxtInferExt;
49aad941 4use rustc_middle::query::Providers;
04454e1e 5use rustc_middle::traits::CodegenObligationError;
ba9703b0 6use rustc_middle::ty::subst::SubstsRef;
9ffffee4 7use rustc_middle::ty::{self, Instance, TyCtxt, TypeVisitableExt};
2b03887a 8use rustc_span::sym;
ba9703b0
XL
9use rustc_trait_selection::traits;
10use traits::{translate_substs, Reveal};
74b04a01 11
353b0b11
FG
12use crate::errors::UnexpectedFnPtrAssociatedItem;
13
f9f354fc 14fn resolve_instance<'tcx>(
74b04a01 15 tcx: TyCtxt<'tcx>,
f9f354fc 16 key: ty::ParamEnvAnd<'tcx, (DefId, SubstsRef<'tcx>)>,
5e7ed085 17) -> Result<Option<Instance<'tcx>>, ErrorGuaranteed> {
3dfed10e
XL
18 let (param_env, (def, substs)) = key.into_parts();
19
49aad941 20 let result = if let Some(trait_def_id) = tcx.trait_of_item(def) {
74b04a01 21 debug!(" => associated item, attempting to find impl in param_env {:#?}", param_env);
9c376795
FG
22 resolve_associated_item(
23 tcx,
49aad941 24 def,
9c376795
FG
25 param_env,
26 trait_def_id,
27 tcx.normalize_erasing_regions(param_env, substs),
28 )
74b04a01 29 } else {
49aad941
FG
30 let ty = tcx.type_of(def);
31 let item_type = tcx.subst_and_normalize_erasing_regions(substs, param_env, ty);
74b04a01 32
1b1a35ee 33 let def = match *item_type.kind() {
923072b8 34 ty::FnDef(def_id, ..) if tcx.is_intrinsic(def_id) => {
74b04a01 35 debug!(" => intrinsic");
49aad941 36 ty::InstanceDef::Intrinsic(def)
74b04a01 37 }
ba9703b0
XL
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) {
3dfed10e 42 debug!(" => nontrivial drop glue");
1b1a35ee 43 match *ty.kind() {
3dfed10e
XL
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),
74b04a01 53 }
ba9703b0 54
ba9703b0 55 ty::InstanceDef::DropGlue(def_id, Some(ty))
74b04a01 56 } else {
ba9703b0
XL
57 debug!(" => trivial drop glue");
58 ty::InstanceDef::DropGlue(def_id, None)
74b04a01
XL
59 }
60 }
ba9703b0
XL
61 _ => {
62 debug!(" => free item");
3dfed10e 63 ty::InstanceDef::Item(def)
ba9703b0 64 }
74b04a01 65 };
f9f354fc 66 Ok(Some(Instance { def, substs }))
74b04a01 67 };
6a06907d 68 debug!("inner_resolve_instance: result={:?}", result);
74b04a01
XL
69 result
70}
71
72fn resolve_associated_item<'tcx>(
73 tcx: TyCtxt<'tcx>,
5099ac24 74 trait_item_id: DefId,
74b04a01
XL
75 param_env: ty::ParamEnv<'tcx>,
76 trait_id: DefId,
77 rcvr_substs: SubstsRef<'tcx>,
5e7ed085 78) -> Result<Option<Instance<'tcx>>, ErrorGuaranteed> {
5099ac24 79 debug!(?trait_item_id, ?param_env, ?trait_id, ?rcvr_substs, "resolve_associated_item");
74b04a01
XL
80
81 let trait_ref = ty::TraitRef::from_method(tcx, trait_id, rcvr_substs);
136023e0 82
f2b60f7d 83 let vtbl = match tcx.codegen_select_candidate((param_env, ty::Binder::dummy(trait_ref))) {
04454e1e
FG
84 Ok(vtbl) => vtbl,
85 Err(CodegenObligationError::Ambiguity) => {
86 let reported = tcx.sess.delay_span_bug(
87 tcx.def_span(trait_item_id),
49aad941 88 format!(
f2b60f7d 89 "encountered ambiguity selecting `{trait_ref:?}` during codegen, presuming due to \
04454e1e 90 overflow or prior type error",
04454e1e
FG
91 ),
92 );
93 return Err(reported);
94 }
95 Err(CodegenObligationError::Unimplemented) => return Ok(None),
96 Err(CodegenObligationError::FulfillmentError) => return Ok(None),
97 };
74b04a01
XL
98
99 // Now that we know which impl is being used, we can dispatch to
100 // the actual function:
f9f354fc 101 Ok(match vtbl {
1b1a35ee 102 traits::ImplSource::UserDefined(impl_data) => {
ba9703b0 103 debug!(
1b1a35ee 104 "resolving ImplSource::UserDefined: {:?}, {:?}, {:?}, {:?}",
5099ac24 105 param_env, trait_item_id, rcvr_substs, impl_data
ba9703b0 106 );
49aad941
FG
107 assert!(!rcvr_substs.has_infer());
108 assert!(!trait_ref.has_infer());
74b04a01 109
ba9703b0
XL
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
f9f354fc 113 .ancestors(tcx, impl_data.impl_def_id)?
5099ac24 114 .leaf_def(tcx, trait_item_id)
ba9703b0 115 .unwrap_or_else(|| {
5099ac24 116 bug!("{:?} not found in {:?}", trait_item_id, impl_data.impl_def_id);
ba9703b0 117 });
2b03887a
FG
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);
74b04a01
XL
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
ba9703b0
XL
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.
74b04a01 136 true
74b04a01 137 } else {
ba9703b0
XL
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.
f035d41b 142 if param_env.reveal() == Reveal::All {
ba9703b0
XL
143 !trait_ref.still_further_specializable()
144 } else {
145 false
146 }
74b04a01
XL
147 };
148
149 if !eligible {
f9f354fc 150 return Ok(None);
74b04a01
XL
151 }
152
2b03887a 153 // Any final impl is required to define all associated items.
064997fb 154 if !leaf_def.item.defaultness(tcx).has_value() {
2b03887a
FG
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);
064997fb
FG
160 }
161
fc512014 162 let substs = tcx.erase_regions(substs);
f9f354fc
XL
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).
5099ac24
FG
168 if leaf_def.item.kind == ty::AssocKind::Const
169 && trait_item_id != leaf_def.item.def_id
2b03887a 170 && let Some(leaf_def_item) = leaf_def.item.def_id.as_local()
f9f354fc 171 {
9c376795 172 tcx.compare_impl_const((
2b03887a
FG
173 leaf_def_item,
174 trait_item_id,
175 ))?;
f9f354fc
XL
176 }
177
178 Some(ty::Instance::new(leaf_def.item.def_id, substs))
74b04a01 179 }
49aad941
FG
180 traits::ImplSource::Generator(generator_data) => {
181 if cfg!(debug_assertions) && tcx.item_name(trait_item_id) != sym::resume {
182 // For compiler developers who'd like to add new items to `Generator`,
183 // you either need to generate a shim body, or perhaps return
184 // `InstanceDef::Item` pointing to a trait default method body if
185 // it is given a default implementation by the trait.
186 span_bug!(
187 tcx.def_span(generator_data.generator_def_id),
188 "no definition for `{trait_ref}::{}` for built-in generator type",
189 tcx.item_name(trait_item_id)
190 )
191 }
192 Some(Instance {
193 def: ty::InstanceDef::Item(generator_data.generator_def_id),
194 substs: generator_data.substs,
195 })
196 }
197 traits::ImplSource::Future(future_data) => {
198 if Some(trait_item_id) == tcx.lang_items().future_poll_fn() {
199 // `Future::poll` is generated by the compiler.
200 Some(Instance {
201 def: ty::InstanceDef::Item(future_data.generator_def_id),
202 substs: future_data.substs,
203 })
204 } else {
205 // All other methods are default methods of the `Future` trait.
206 // (this assumes that `ImplSource::Future` is only used for methods on `Future`)
207 debug_assert!(tcx.impl_defaultness(trait_item_id).has_value());
208 Some(Instance::new(trait_item_id, rcvr_substs))
209 }
210 }
1b1a35ee 211 traits::ImplSource::Closure(closure_data) => {
49aad941
FG
212 if cfg!(debug_assertions)
213 && ![sym::call, sym::call_mut, sym::call_once]
214 .contains(&tcx.item_name(trait_item_id))
215 {
216 // For compiler developers who'd like to add new items to `Fn`/`FnMut`/`FnOnce`,
217 // you either need to generate a shim body, or perhaps return
218 // `InstanceDef::Item` pointing to a trait default method body if
219 // it is given a default implementation by the trait.
220 span_bug!(
221 tcx.def_span(closure_data.closure_def_id),
222 "no definition for `{trait_ref}::{}` for built-in closure type",
223 tcx.item_name(trait_item_id)
224 )
225 }
487cf647 226 let trait_closure_kind = tcx.fn_trait_kind_from_def_id(trait_id).unwrap();
064997fb 227 Instance::resolve_closure(
74b04a01
XL
228 tcx,
229 closure_data.closure_def_id,
230 closure_data.substs,
231 trait_closure_kind,
064997fb 232 )
74b04a01 233 }
1b1a35ee 234 traits::ImplSource::FnPointer(ref data) => match data.fn_ty.kind() {
49aad941
FG
235 ty::FnDef(..) | ty::FnPtr(..) => {
236 if cfg!(debug_assertions)
237 && ![sym::call, sym::call_mut, sym::call_once]
238 .contains(&tcx.item_name(trait_item_id))
239 {
240 // For compiler developers who'd like to add new items to `Fn`/`FnMut`/`FnOnce`,
241 // you either need to generate a shim body, or perhaps return
242 // `InstanceDef::Item` pointing to a trait default method body if
243 // it is given a default implementation by the trait.
244 bug!(
245 "no definition for `{trait_ref}::{}` for built-in fn type",
246 tcx.item_name(trait_item_id)
247 )
248 }
923072b8 249 Some(Instance {
49aad941 250 def: ty::InstanceDef::FnPtrShim(trait_item_id, data.fn_ty),
923072b8
FG
251 substs: rcvr_substs,
252 })
923072b8 253 }
49aad941
FG
254 _ => bug!(
255 "no built-in definition for `{trait_ref}::{}` for non-fn type",
256 tcx.item_name(trait_item_id)
257 ),
258 },
259 traits::ImplSource::Object(ref data) => {
260 traits::get_vtable_index_of_object_method(tcx, data, trait_item_id).map(|index| {
261 Instance {
262 def: ty::InstanceDef::Virtual(trait_item_id, index),
263 substs: rcvr_substs,
264 }
265 })
74b04a01 266 }
1b1a35ee 267 traits::ImplSource::Builtin(..) => {
353b0b11
FG
268 let lang_items = tcx.lang_items();
269 if Some(trait_ref.def_id) == lang_items.clone_trait() {
ba9703b0 270 // FIXME(eddyb) use lang items for methods instead of names.
5099ac24 271 let name = tcx.item_name(trait_item_id);
ba9703b0
XL
272 if name == sym::clone {
273 let self_ty = trait_ref.self_ty();
274
2b03887a 275 let is_copy = self_ty.is_copy_modulo_regions(tcx, param_env);
1b1a35ee 276 match self_ty.kind() {
3dfed10e 277 _ if is_copy => (),
f2b60f7d
FG
278 ty::Generator(..)
279 | ty::GeneratorWitness(..)
280 | ty::Closure(..)
281 | ty::Tuple(..) => {}
3dfed10e
XL
282 _ => return Ok(None),
283 };
ba9703b0
XL
284
285 Some(Instance {
5099ac24 286 def: ty::InstanceDef::CloneShim(trait_item_id, self_ty),
ba9703b0
XL
287 substs: rcvr_substs,
288 })
289 } else {
290 assert_eq!(name, sym::clone_from);
291
292 // Use the default `fn clone_from` from `trait Clone`.
fc512014 293 let substs = tcx.erase_regions(rcvr_substs);
5099ac24 294 Some(ty::Instance::new(trait_item_id, substs))
ba9703b0 295 }
353b0b11
FG
296 } else if Some(trait_ref.def_id) == lang_items.fn_ptr_trait() {
297 if lang_items.fn_ptr_addr() == Some(trait_item_id) {
298 let self_ty = trait_ref.self_ty();
299 if !matches!(self_ty.kind(), ty::FnPtr(..)) {
300 return Ok(None);
301 }
302 Some(Instance {
303 def: ty::InstanceDef::FnPtrAddrShim(trait_item_id, self_ty),
304 substs: rcvr_substs,
305 })
306 } else {
307 tcx.sess.emit_fatal(UnexpectedFnPtrAssociatedItem {
308 span: tcx.def_span(trait_item_id),
309 })
310 }
74b04a01
XL
311 } else {
312 None
313 }
314 }
1b1a35ee
XL
315 traits::ImplSource::AutoImpl(..)
316 | traits::ImplSource::Param(..)
317 | traits::ImplSource::TraitAlias(..)
c295e0f8 318 | traits::ImplSource::TraitUpcasting(_)
2b03887a 319 | traits::ImplSource::ConstDestruct(_) => None,
f9f354fc 320 })
74b04a01 321}
ba9703b0 322
49aad941
FG
323pub fn provide(providers: &mut Providers) {
324 *providers = Providers { resolve_instance, ..*providers };
ba9703b0 325}