rustc_ty_utils/
instance.rs

1use rustc_errors::ErrorGuaranteed;
2use rustc_hir::LangItem;
3use rustc_hir::def_id::DefId;
4use rustc_infer::infer::TyCtxtInferExt;
5use rustc_middle::bug;
6use rustc_middle::query::Providers;
7use rustc_middle::traits::{BuiltinImplSource, CodegenObligationError};
8use rustc_middle::ty::util::AsyncDropGlueMorphology;
9use rustc_middle::ty::{
10    self, GenericArgsRef, Instance, PseudoCanonicalInput, TyCtxt, TypeVisitableExt,
11};
12use rustc_span::sym;
13use rustc_trait_selection::traits;
14use rustc_type_ir::ClosureKind;
15use tracing::debug;
16use traits::translate_args;
17
18use crate::errors::UnexpectedFnPtrAssociatedItem;
19
20fn resolve_instance_raw<'tcx>(
21    tcx: TyCtxt<'tcx>,
22    key: ty::PseudoCanonicalInput<'tcx, (DefId, GenericArgsRef<'tcx>)>,
23) -> Result<Option<Instance<'tcx>>, ErrorGuaranteed> {
24    let PseudoCanonicalInput { typing_env, value: (def_id, args) } = key;
25
26    let result = if let Some(trait_def_id) = tcx.trait_of_item(def_id) {
27        debug!(" => associated item, attempting to find impl in typing_env {:#?}", typing_env);
28        resolve_associated_item(
29            tcx,
30            def_id,
31            typing_env,
32            trait_def_id,
33            tcx.normalize_erasing_regions(typing_env, args),
34        )
35    } else {
36        let def = if tcx.intrinsic(def_id).is_some() {
37            debug!(" => intrinsic");
38            ty::InstanceKind::Intrinsic(def_id)
39        } else if tcx.is_lang_item(def_id, LangItem::DropInPlace) {
40            let ty = args.type_at(0);
41
42            if ty.needs_drop(tcx, typing_env) {
43                debug!(" => nontrivial drop glue");
44                match *ty.kind() {
45                    ty::Closure(..)
46                    | ty::CoroutineClosure(..)
47                    | ty::Coroutine(..)
48                    | ty::Tuple(..)
49                    | ty::Adt(..)
50                    | ty::Dynamic(..)
51                    | ty::Array(..)
52                    | ty::Slice(..)
53                    | ty::UnsafeBinder(..) => {}
54                    // Drop shims can only be built from ADTs.
55                    _ => return Ok(None),
56                }
57
58                ty::InstanceKind::DropGlue(def_id, Some(ty))
59            } else {
60                debug!(" => trivial drop glue");
61                ty::InstanceKind::DropGlue(def_id, None)
62            }
63        } else if tcx.is_lang_item(def_id, LangItem::AsyncDropInPlace) {
64            let ty = args.type_at(0);
65
66            if ty.async_drop_glue_morphology(tcx) != AsyncDropGlueMorphology::Noop {
67                match *ty.kind() {
68                    ty::Closure(..)
69                    | ty::CoroutineClosure(..)
70                    | ty::Coroutine(..)
71                    | ty::Tuple(..)
72                    | ty::Adt(..)
73                    | ty::Dynamic(..)
74                    | ty::Array(..)
75                    | ty::Slice(..) => {}
76                    // Async destructor ctor shims can only be built from ADTs.
77                    _ => return Ok(None),
78                }
79                debug!(" => nontrivial async drop glue ctor");
80                ty::InstanceKind::AsyncDropGlueCtorShim(def_id, Some(ty))
81            } else {
82                debug!(" => trivial async drop glue ctor");
83                ty::InstanceKind::AsyncDropGlueCtorShim(def_id, None)
84            }
85        } else {
86            debug!(" => free item");
87            ty::InstanceKind::Item(def_id)
88        };
89
90        Ok(Some(Instance { def, args }))
91    };
92    debug!("resolve_instance: result={:?}", result);
93    result
94}
95
96fn resolve_associated_item<'tcx>(
97    tcx: TyCtxt<'tcx>,
98    trait_item_id: DefId,
99    typing_env: ty::TypingEnv<'tcx>,
100    trait_id: DefId,
101    rcvr_args: GenericArgsRef<'tcx>,
102) -> Result<Option<Instance<'tcx>>, ErrorGuaranteed> {
103    debug!(?trait_item_id, ?typing_env, ?trait_id, ?rcvr_args, "resolve_associated_item");
104
105    let trait_ref = ty::TraitRef::from_method(tcx, trait_id, rcvr_args);
106
107    let input = typing_env.as_query_input(trait_ref);
108    let vtbl = match tcx.codegen_select_candidate(input) {
109        Ok(vtbl) => vtbl,
110        Err(
111            CodegenObligationError::Ambiguity
112            | CodegenObligationError::Unimplemented
113            | CodegenObligationError::FulfillmentError,
114        ) => return Ok(None),
115    };
116
117    // Now that we know which impl is being used, we can dispatch to
118    // the actual function:
119    Ok(match vtbl {
120        traits::ImplSource::UserDefined(impl_data) => {
121            debug!(
122                "resolving ImplSource::UserDefined: {:?}, {:?}, {:?}, {:?}",
123                typing_env, trait_item_id, rcvr_args, impl_data
124            );
125            assert!(!rcvr_args.has_infer());
126            assert!(!trait_ref.has_infer());
127
128            let trait_def_id = tcx.trait_id_of_impl(impl_data.impl_def_id).unwrap();
129            let trait_def = tcx.trait_def(trait_def_id);
130            let leaf_def = trait_def
131                .ancestors(tcx, impl_data.impl_def_id)?
132                .leaf_def(tcx, trait_item_id)
133                .unwrap_or_else(|| {
134                    bug!("{:?} not found in {:?}", trait_item_id, impl_data.impl_def_id);
135                });
136
137            // Since this is a trait item, we need to see if the item is either a trait
138            // default item or a specialization because we can't resolve those until we're
139            // in `TypingMode::PostAnalysis`.
140            //
141            // NOTE: This should be kept in sync with the similar code in
142            // `rustc_trait_selection::traits::project::assemble_candidates_from_impls()`.
143            let eligible = if leaf_def.is_final() {
144                // Non-specializable items are always projectable.
145                true
146            } else {
147                // Only reveal a specializable default if we're past type-checking
148                // and the obligation is monomorphic, otherwise passes such as
149                // transmute checking and polymorphic MIR optimizations could
150                // get a result which isn't correct for all monomorphizations.
151                match typing_env.typing_mode {
152                    ty::TypingMode::Coherence
153                    | ty::TypingMode::Analysis { .. }
154                    | ty::TypingMode::PostBorrowckAnalysis { .. } => false,
155                    ty::TypingMode::PostAnalysis => !trait_ref.still_further_specializable(),
156                }
157            };
158            if !eligible {
159                return Ok(None);
160            }
161
162            let typing_env = typing_env.with_post_analysis_normalized(tcx);
163            let (infcx, param_env) = tcx.infer_ctxt().build_with_typing_env(typing_env);
164            let args = rcvr_args.rebase_onto(tcx, trait_def_id, impl_data.args);
165            let args = translate_args(
166                &infcx,
167                param_env,
168                impl_data.impl_def_id,
169                args,
170                leaf_def.defining_node,
171            );
172            let args = infcx.tcx.erase_regions(args);
173
174            // HACK: We may have overlapping `dyn Trait` built-in impls and
175            // user-provided blanket impls. Detect that case here, and return
176            // ambiguity.
177            //
178            // This should not affect totally monomorphized contexts, only
179            // resolve calls that happen polymorphically, such as the mir-inliner
180            // and const-prop (and also some lints).
181            let self_ty = rcvr_args.type_at(0);
182            if !self_ty.is_known_rigid() {
183                let predicates = tcx
184                    .predicates_of(impl_data.impl_def_id)
185                    .instantiate(tcx, impl_data.args)
186                    .predicates;
187                let sized_def_id = tcx.lang_items().sized_trait();
188                // If we find a `Self: Sized` bound on the item, then we know
189                // that `dyn Trait` can certainly never apply here.
190                if !predicates.into_iter().filter_map(ty::Clause::as_trait_clause).any(|clause| {
191                    Some(clause.def_id()) == sized_def_id
192                        && clause.skip_binder().self_ty() == self_ty
193                }) {
194                    return Ok(None);
195                }
196            }
197
198            // Any final impl is required to define all associated items.
199            if !leaf_def.item.defaultness(tcx).has_value() {
200                let guar = tcx.dcx().span_delayed_bug(
201                    tcx.def_span(leaf_def.item.def_id),
202                    "missing value for assoc item in impl",
203                );
204                return Err(guar);
205            }
206
207            // Make sure that we're projecting to an item that has compatible args.
208            // This may happen if we are resolving an instance before codegen, such
209            // as during inlining. This check is also done in projection.
210            if !tcx.check_args_compatible(leaf_def.item.def_id, args) {
211                let guar = tcx.dcx().span_delayed_bug(
212                    tcx.def_span(leaf_def.item.def_id),
213                    "missing value for assoc item in impl",
214                );
215                return Err(guar);
216            }
217
218            let args = tcx.erase_regions(args);
219
220            // We check that the impl item is compatible with the trait item
221            // because otherwise we may ICE in const eval due to type mismatches,
222            // signature incompatibilities, etc.
223            // NOTE: We could also only enforce this in `PostAnalysis`, which
224            // is what CTFE and MIR inlining would care about anyways.
225            if trait_item_id != leaf_def.item.def_id
226                && let Some(leaf_def_item) = leaf_def.item.def_id.as_local()
227            {
228                tcx.ensure_ok().compare_impl_item(leaf_def_item)?;
229            }
230
231            Some(ty::Instance::new(leaf_def.item.def_id, args))
232        }
233        traits::ImplSource::Builtin(BuiltinImplSource::Object(_), _) => {
234            let trait_ref = ty::TraitRef::from_method(tcx, trait_id, rcvr_args);
235            if trait_ref.has_non_region_infer() || trait_ref.has_non_region_param() {
236                // We only resolve totally substituted vtable entries.
237                None
238            } else {
239                let vtable_base = tcx.first_method_vtable_slot(trait_ref);
240                let offset = tcx
241                    .own_existential_vtable_entries(trait_id)
242                    .iter()
243                    .copied()
244                    .position(|def_id| def_id == trait_item_id);
245                offset.map(|offset| Instance {
246                    def: ty::InstanceKind::Virtual(trait_item_id, vtable_base + offset),
247                    args: rcvr_args,
248                })
249            }
250        }
251        traits::ImplSource::Builtin(BuiltinImplSource::Misc | BuiltinImplSource::Trivial, _) => {
252            if tcx.is_lang_item(trait_ref.def_id, LangItem::Clone) {
253                // FIXME(eddyb) use lang items for methods instead of names.
254                let name = tcx.item_name(trait_item_id);
255                if name == sym::clone {
256                    let self_ty = trait_ref.self_ty();
257                    match self_ty.kind() {
258                        ty::FnDef(..) | ty::FnPtr(..) => (),
259                        ty::Coroutine(..)
260                        | ty::CoroutineWitness(..)
261                        | ty::Closure(..)
262                        | ty::CoroutineClosure(..)
263                        | ty::Tuple(..) => {}
264                        _ => return Ok(None),
265                    };
266
267                    Some(Instance {
268                        def: ty::InstanceKind::CloneShim(trait_item_id, self_ty),
269                        args: rcvr_args,
270                    })
271                } else {
272                    assert_eq!(name, sym::clone_from);
273
274                    // Use the default `fn clone_from` from `trait Clone`.
275                    let args = tcx.erase_regions(rcvr_args);
276                    Some(ty::Instance::new(trait_item_id, args))
277                }
278            } else if tcx.is_lang_item(trait_ref.def_id, LangItem::FnPtrTrait) {
279                if tcx.is_lang_item(trait_item_id, LangItem::FnPtrAddr) {
280                    let self_ty = trait_ref.self_ty();
281                    if !matches!(self_ty.kind(), ty::FnPtr(..)) {
282                        return Ok(None);
283                    }
284                    Some(Instance {
285                        def: ty::InstanceKind::FnPtrAddrShim(trait_item_id, self_ty),
286                        args: rcvr_args,
287                    })
288                } else {
289                    tcx.dcx().emit_fatal(UnexpectedFnPtrAssociatedItem {
290                        span: tcx.def_span(trait_item_id),
291                    })
292                }
293            } else if let Some(target_kind) = tcx.fn_trait_kind_from_def_id(trait_ref.def_id) {
294                // FIXME: This doesn't check for malformed libcore that defines, e.g.,
295                // `trait Fn { fn call_once(&self) { .. } }`. This is mostly for extension
296                // methods.
297                if cfg!(debug_assertions)
298                    && ![sym::call, sym::call_mut, sym::call_once]
299                        .contains(&tcx.item_name(trait_item_id))
300                {
301                    // For compiler developers who'd like to add new items to `Fn`/`FnMut`/`FnOnce`,
302                    // you either need to generate a shim body, or perhaps return
303                    // `InstanceKind::Item` pointing to a trait default method body if
304                    // it is given a default implementation by the trait.
305                    bug!(
306                        "no definition for `{trait_ref}::{}` for built-in callable type",
307                        tcx.item_name(trait_item_id)
308                    )
309                }
310                match *rcvr_args.type_at(0).kind() {
311                    ty::Closure(closure_def_id, args) => {
312                        Some(Instance::resolve_closure(tcx, closure_def_id, args, target_kind))
313                    }
314                    ty::FnDef(..) | ty::FnPtr(..) => Some(Instance {
315                        def: ty::InstanceKind::FnPtrShim(trait_item_id, rcvr_args.type_at(0)),
316                        args: rcvr_args,
317                    }),
318                    ty::CoroutineClosure(coroutine_closure_def_id, args) => {
319                        // When a coroutine-closure implements the `Fn` traits, then it
320                        // always dispatches to the `FnOnce` implementation. This is to
321                        // ensure that the `closure_kind` of the resulting closure is in
322                        // sync with the built-in trait implementations (since all of the
323                        // implementations return `FnOnce::Output`).
324                        if ty::ClosureKind::FnOnce == args.as_coroutine_closure().kind() {
325                            Some(Instance::new(coroutine_closure_def_id, args))
326                        } else {
327                            Some(Instance {
328                                def: ty::InstanceKind::ConstructCoroutineInClosureShim {
329                                    coroutine_closure_def_id,
330                                    receiver_by_ref: target_kind != ty::ClosureKind::FnOnce,
331                                },
332                                args,
333                            })
334                        }
335                    }
336                    _ => bug!(
337                        "no built-in definition for `{trait_ref}::{}` for non-fn type",
338                        tcx.item_name(trait_item_id)
339                    ),
340                }
341            } else if let Some(target_kind) = tcx.async_fn_trait_kind_from_def_id(trait_ref.def_id)
342            {
343                match *rcvr_args.type_at(0).kind() {
344                    ty::CoroutineClosure(coroutine_closure_def_id, args) => {
345                        if target_kind == ClosureKind::FnOnce
346                            && args.as_coroutine_closure().kind() != ClosureKind::FnOnce
347                        {
348                            // If we're computing `AsyncFnOnce` for a by-ref closure then
349                            // construct a new body that has the right return types.
350                            Some(Instance {
351                                def: ty::InstanceKind::ConstructCoroutineInClosureShim {
352                                    coroutine_closure_def_id,
353                                    receiver_by_ref: false,
354                                },
355                                args,
356                            })
357                        } else {
358                            Some(Instance::new(coroutine_closure_def_id, args))
359                        }
360                    }
361                    ty::Closure(closure_def_id, args) => {
362                        Some(Instance::resolve_closure(tcx, closure_def_id, args, target_kind))
363                    }
364                    ty::FnDef(..) | ty::FnPtr(..) => Some(Instance {
365                        def: ty::InstanceKind::FnPtrShim(trait_item_id, rcvr_args.type_at(0)),
366                        args: rcvr_args,
367                    }),
368                    _ => bug!(
369                        "no built-in definition for `{trait_ref}::{}` for non-lending-closure type",
370                        tcx.item_name(trait_item_id)
371                    ),
372                }
373            } else if tcx.is_lang_item(trait_ref.def_id, LangItem::TransmuteTrait) {
374                let name = tcx.item_name(trait_item_id);
375                assert_eq!(name, sym::transmute);
376                let args = tcx.erase_regions(rcvr_args);
377                Some(ty::Instance::new(trait_item_id, args))
378            } else {
379                Instance::try_resolve_item_for_coroutine(tcx, trait_item_id, trait_id, rcvr_args)
380            }
381        }
382        traits::ImplSource::Param(..)
383        | traits::ImplSource::Builtin(BuiltinImplSource::TraitUpcasting { .. }, _)
384        | traits::ImplSource::Builtin(BuiltinImplSource::TupleUnsizing, _) => None,
385    })
386}
387
388pub(crate) fn provide(providers: &mut Providers) {
389    *providers = Providers { resolve_instance_raw, ..*providers };
390}