1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
use rustc_errors::ErrorGuaranteed;
use rustc_hir::def::DefKind;
use rustc_hir::def_id::DefId;
use rustc_infer::infer::TyCtxtInferExt;
use rustc_middle::query::Providers;
use rustc_middle::traits::{BuiltinImplSource, CodegenObligationError};
use rustc_middle::ty::GenericArgsRef;
use rustc_middle::ty::{self, Instance, TyCtxt, TypeVisitableExt};
use rustc_span::sym;
use rustc_trait_selection::traits;
use traits::{translate_args, Reveal};

use crate::errors::UnexpectedFnPtrAssociatedItem;

fn resolve_instance<'tcx>(
    tcx: TyCtxt<'tcx>,
    key: ty::ParamEnvAnd<'tcx, (DefId, GenericArgsRef<'tcx>)>,
) -> Result<Option<Instance<'tcx>>, ErrorGuaranteed> {
    let (param_env, (def_id, args)) = key.into_parts();

    let result = if let Some(trait_def_id) = tcx.trait_of_item(def_id) {
        debug!(" => associated item, attempting to find impl in param_env {:#?}", param_env);
        resolve_associated_item(
            tcx,
            def_id,
            param_env,
            trait_def_id,
            tcx.normalize_erasing_regions(param_env, args),
        )
    } else {
        let def = if matches!(tcx.def_kind(def_id), DefKind::Fn) && tcx.is_intrinsic(def_id) {
            debug!(" => intrinsic");
            ty::InstanceDef::Intrinsic(def_id)
        } else if Some(def_id) == tcx.lang_items().drop_in_place_fn() {
            let ty = args.type_at(0);

            if ty.needs_drop(tcx, param_env) {
                debug!(" => nontrivial drop glue");
                match *ty.kind() {
                    ty::Closure(..)
                    | ty::Generator(..)
                    | ty::Tuple(..)
                    | ty::Adt(..)
                    | ty::Dynamic(..)
                    | ty::Array(..)
                    | ty::Slice(..) => {}
                    // Drop shims can only be built from ADTs.
                    _ => return Ok(None),
                }

                ty::InstanceDef::DropGlue(def_id, Some(ty))
            } else {
                debug!(" => trivial drop glue");
                ty::InstanceDef::DropGlue(def_id, None)
            }
        } else {
            debug!(" => free item");
            // FIXME(effects): we may want to erase the effect param if that is present on this item.
            ty::InstanceDef::Item(def_id)
        };

        Ok(Some(Instance { def, args }))
    };
    debug!("inner_resolve_instance: result={:?}", result);
    result
}

fn resolve_associated_item<'tcx>(
    tcx: TyCtxt<'tcx>,
    trait_item_id: DefId,
    param_env: ty::ParamEnv<'tcx>,
    trait_id: DefId,
    rcvr_args: GenericArgsRef<'tcx>,
) -> Result<Option<Instance<'tcx>>, ErrorGuaranteed> {
    debug!(?trait_item_id, ?param_env, ?trait_id, ?rcvr_args, "resolve_associated_item");

    let trait_ref = ty::TraitRef::from_method(tcx, trait_id, rcvr_args);

    let vtbl = match tcx.codegen_select_candidate((param_env, trait_ref)) {
        Ok(vtbl) => vtbl,
        Err(CodegenObligationError::Ambiguity) => {
            let reported = tcx.sess.delay_span_bug(
                tcx.def_span(trait_item_id),
                format!(
                    "encountered ambiguity selecting `{trait_ref:?}` during codegen, presuming due to \
                     overflow or prior type error",
                ),
            );
            return Err(reported);
        }
        Err(CodegenObligationError::Unimplemented) => return Ok(None),
        Err(CodegenObligationError::FulfillmentError) => return Ok(None),
    };

    // Now that we know which impl is being used, we can dispatch to
    // the actual function:
    Ok(match vtbl {
        traits::ImplSource::UserDefined(impl_data) => {
            debug!(
                "resolving ImplSource::UserDefined: {:?}, {:?}, {:?}, {:?}",
                param_env, trait_item_id, rcvr_args, impl_data
            );
            assert!(!rcvr_args.has_infer());
            assert!(!trait_ref.has_infer());

            let trait_def_id = tcx.trait_id_of_impl(impl_data.impl_def_id).unwrap();
            let trait_def = tcx.trait_def(trait_def_id);
            let leaf_def = trait_def
                .ancestors(tcx, impl_data.impl_def_id)?
                .leaf_def(tcx, trait_item_id)
                .unwrap_or_else(|| {
                    bug!("{:?} not found in {:?}", trait_item_id, impl_data.impl_def_id);
                });
            let infcx = tcx.infer_ctxt().build();
            let param_env = param_env.with_reveal_all_normalized(tcx);
            let args = rcvr_args.rebase_onto(tcx, trait_def_id, impl_data.args);
            let args = translate_args(
                &infcx,
                param_env,
                impl_data.impl_def_id,
                args,
                leaf_def.defining_node,
            );
            let args = infcx.tcx.erase_regions(args);

            // Since this is a trait item, we need to see if the item is either a trait default item
            // or a specialization because we can't resolve those unless we can `Reveal::All`.
            // NOTE: This should be kept in sync with the similar code in
            // `rustc_trait_selection::traits::project::assemble_candidates_from_impls()`.
            let eligible = if leaf_def.is_final() {
                // Non-specializable items are always projectable.
                true
            } else {
                // Only reveal a specializable default if we're past type-checking
                // and the obligation is monomorphic, otherwise passes such as
                // transmute checking and polymorphic MIR optimizations could
                // get a result which isn't correct for all monomorphizations.
                if param_env.reveal() == Reveal::All {
                    !trait_ref.still_further_specializable()
                } else {
                    false
                }
            };
            if !eligible {
                return Ok(None);
            }

            // HACK: We may have overlapping `dyn Trait` built-in impls and
            // user-provided blanket impls. Detect that case here, and return
            // ambiguity.
            //
            // This should not affect totally monomorphized contexts, only
            // resolve calls that happen polymorphically, such as the mir-inliner
            // and const-prop (and also some lints).
            let self_ty = rcvr_args.type_at(0);
            if !self_ty.is_known_rigid() {
                let predicates = tcx
                    .predicates_of(impl_data.impl_def_id)
                    .instantiate(tcx, impl_data.args)
                    .predicates;
                let sized_def_id = tcx.lang_items().sized_trait();
                // If we find a `Self: Sized` bound on the item, then we know
                // that `dyn Trait` can certainly never apply here.
                if !predicates.into_iter().filter_map(ty::Clause::as_trait_clause).any(|clause| {
                    Some(clause.def_id()) == sized_def_id
                        && clause.skip_binder().self_ty() == self_ty
                }) {
                    return Ok(None);
                }
            }

            // Any final impl is required to define all associated items.
            if !leaf_def.item.defaultness(tcx).has_value() {
                let guard = tcx.sess.delay_span_bug(
                    tcx.def_span(leaf_def.item.def_id),
                    "missing value for assoc item in impl",
                );
                return Err(guard);
            }

            let args = tcx.erase_regions(args);

            // Check if we just resolved an associated `const` declaration from
            // a `trait` to an associated `const` definition in an `impl`, where
            // the definition in the `impl` has the wrong type (for which an
            // error has already been/will be emitted elsewhere).
            if leaf_def.item.kind == ty::AssocKind::Const
                && trait_item_id != leaf_def.item.def_id
                && let Some(leaf_def_item) = leaf_def.item.def_id.as_local()
            {
                tcx.compare_impl_const((
                    leaf_def_item,
                    trait_item_id,
                ))?;
            }

            Some(ty::Instance::new(leaf_def.item.def_id, args))
        }
        traits::ImplSource::Builtin(BuiltinImplSource::Object { vtable_base }, _) => {
            traits::get_vtable_index_of_object_method(tcx, *vtable_base, trait_item_id).map(
                |index| Instance {
                    def: ty::InstanceDef::Virtual(trait_item_id, index),
                    args: rcvr_args,
                },
            )
        }
        traits::ImplSource::Builtin(BuiltinImplSource::Misc, _) => {
            let lang_items = tcx.lang_items();
            if Some(trait_ref.def_id) == lang_items.clone_trait() {
                // FIXME(eddyb) use lang items for methods instead of names.
                let name = tcx.item_name(trait_item_id);
                if name == sym::clone {
                    let self_ty = trait_ref.self_ty();

                    let is_copy = self_ty.is_copy_modulo_regions(tcx, param_env);
                    match self_ty.kind() {
                        _ if is_copy => (),
                        ty::Generator(..)
                        | ty::GeneratorWitness(..)
                        | ty::Closure(..)
                        | ty::Tuple(..) => {}
                        _ => return Ok(None),
                    };

                    Some(Instance {
                        def: ty::InstanceDef::CloneShim(trait_item_id, self_ty),
                        args: rcvr_args,
                    })
                } else {
                    assert_eq!(name, sym::clone_from);

                    // Use the default `fn clone_from` from `trait Clone`.
                    let args = tcx.erase_regions(rcvr_args);
                    Some(ty::Instance::new(trait_item_id, args))
                }
            } else if Some(trait_ref.def_id) == lang_items.fn_ptr_trait() {
                if lang_items.fn_ptr_addr() == Some(trait_item_id) {
                    let self_ty = trait_ref.self_ty();
                    if !matches!(self_ty.kind(), ty::FnPtr(..)) {
                        return Ok(None);
                    }
                    Some(Instance {
                        def: ty::InstanceDef::FnPtrAddrShim(trait_item_id, self_ty),
                        args: rcvr_args,
                    })
                } else {
                    tcx.sess.emit_fatal(UnexpectedFnPtrAssociatedItem {
                        span: tcx.def_span(trait_item_id),
                    })
                }
            } else if Some(trait_ref.def_id) == lang_items.future_trait() {
                let ty::Generator(generator_def_id, args, _) = *rcvr_args.type_at(0).kind() else {
                    bug!()
                };
                if Some(trait_item_id) == tcx.lang_items().future_poll_fn() {
                    // `Future::poll` is generated by the compiler.
                    Some(Instance { def: ty::InstanceDef::Item(generator_def_id), args: args })
                } else {
                    // All other methods are default methods of the `Future` trait.
                    // (this assumes that `ImplSource::Builtin` is only used for methods on `Future`)
                    debug_assert!(tcx.defaultness(trait_item_id).has_value());
                    Some(Instance::new(trait_item_id, rcvr_args))
                }
            } else if Some(trait_ref.def_id) == lang_items.gen_trait() {
                let ty::Generator(generator_def_id, args, _) = *rcvr_args.type_at(0).kind() else {
                    bug!()
                };
                if cfg!(debug_assertions) && tcx.item_name(trait_item_id) != sym::resume {
                    // For compiler developers who'd like to add new items to `Generator`,
                    // you either need to generate a shim body, or perhaps return
                    // `InstanceDef::Item` pointing to a trait default method body if
                    // it is given a default implementation by the trait.
                    span_bug!(
                        tcx.def_span(generator_def_id),
                        "no definition for `{trait_ref}::{}` for built-in generator type",
                        tcx.item_name(trait_item_id)
                    )
                }
                Some(Instance { def: ty::InstanceDef::Item(generator_def_id), args })
            } else if tcx.fn_trait_kind_from_def_id(trait_ref.def_id).is_some() {
                // FIXME: This doesn't check for malformed libcore that defines, e.g.,
                // `trait Fn { fn call_once(&self) { .. } }`. This is mostly for extension
                // methods.
                if cfg!(debug_assertions)
                    && ![sym::call, sym::call_mut, sym::call_once]
                        .contains(&tcx.item_name(trait_item_id))
                {
                    // For compiler developers who'd like to add new items to `Fn`/`FnMut`/`FnOnce`,
                    // you either need to generate a shim body, or perhaps return
                    // `InstanceDef::Item` pointing to a trait default method body if
                    // it is given a default implementation by the trait.
                    bug!(
                        "no definition for `{trait_ref}::{}` for built-in callable type",
                        tcx.item_name(trait_item_id)
                    )
                }
                match *rcvr_args.type_at(0).kind() {
                    ty::Closure(closure_def_id, args) => {
                        let trait_closure_kind = tcx.fn_trait_kind_from_def_id(trait_id).unwrap();
                        Instance::resolve_closure(tcx, closure_def_id, args, trait_closure_kind)
                    }
                    ty::FnDef(..) | ty::FnPtr(..) => Some(Instance {
                        def: ty::InstanceDef::FnPtrShim(trait_item_id, rcvr_args.type_at(0)),
                        args: rcvr_args,
                    }),
                    _ => bug!(
                        "no built-in definition for `{trait_ref}::{}` for non-fn type",
                        tcx.item_name(trait_item_id)
                    ),
                }
            } else {
                None
            }
        }
        traits::ImplSource::Param(..)
        | traits::ImplSource::Builtin(BuiltinImplSource::TraitUpcasting { .. }, _)
        | traits::ImplSource::Builtin(BuiltinImplSource::TupleUnsizing, _) => None,
    })
}

pub fn provide(providers: &mut Providers) {
    *providers = Providers { resolve_instance, ..*providers };
}