]> git.proxmox.com Git - rustc.git/blame - compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs
New upstream version 1.63.0+dfsg1
[rustc.git] / compiler / rustc_trait_selection / src / traits / select / candidate_assembly.rs
CommitLineData
f035d41b
XL
1//! Candidate assembly.
2//!
3//! The selection process begins by examining all in-scope impls,
4//! caller obligations, and so forth and assembling a list of
5//! candidates. See the [rustc dev guide] for more details.
6//!
7//! [rustc dev guide]:https://rustc-dev-guide.rust-lang.org/traits/resolution.html#candidate-assembly
5e7ed085 8use hir::LangItem;
f035d41b 9use rustc_hir as hir;
c295e0f8
XL
10use rustc_hir::def_id::DefId;
11use rustc_infer::traits::TraitEngine;
f035d41b 12use rustc_infer::traits::{Obligation, SelectionError, TraitObligation};
c295e0f8 13use rustc_lint_defs::builtin::DEREF_INTO_DYN_SUPERTRAIT;
1b1a35ee 14use rustc_middle::ty::print::with_no_trimmed_paths;
a2a8927a 15use rustc_middle::ty::{self, ToPredicate, Ty, TypeFoldable};
f035d41b
XL
16use rustc_target::spec::abi::Abi;
17
c295e0f8 18use crate::traits;
1b1a35ee 19use crate::traits::coherence::Conflict;
c295e0f8 20use crate::traits::query::evaluate_obligation::InferCtxtExt;
f035d41b 21use crate::traits::{util, SelectionResult};
3c0e092e 22use crate::traits::{Ambiguous, ErrorReporting, Overflow, Unimplemented};
f035d41b
XL
23
24use super::BuiltinImplConditions;
1b1a35ee
XL
25use super::IntercrateAmbiguityCause;
26use super::OverflowError;
f035d41b 27use super::SelectionCandidate::{self, *};
1b1a35ee 28use super::{EvaluatedCandidate, SelectionCandidateSet, SelectionContext, TraitObligationStack};
f035d41b
XL
29
30impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
29967ef6 31 #[instrument(level = "debug", skip(self))]
f035d41b
XL
32 pub(super) fn candidate_from_obligation<'o>(
33 &mut self,
34 stack: &TraitObligationStack<'o, 'tcx>,
35 ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
36 // Watch out for overflow. This intentionally bypasses (and does
37 // not update) the cache.
38 self.check_recursion_limit(&stack.obligation, &stack.obligation)?;
39
40 // Check the cache. Note that we freshen the trait-ref
41 // separately rather than using `stack.fresh_trait_ref` --
42 // this is because we want the unbound variables to be
43 // replaced with fresh types starting from index 0.
44 let cache_fresh_trait_pred = self.infcx.freshen(stack.obligation.predicate);
29967ef6 45 debug!(?cache_fresh_trait_pred);
f035d41b
XL
46 debug_assert!(!stack.obligation.predicate.has_escaping_bound_vars());
47
48 if let Some(c) =
49 self.check_candidate_cache(stack.obligation.param_env, cache_fresh_trait_pred)
50 {
29967ef6 51 debug!(candidate = ?c, "CACHE HIT");
f035d41b
XL
52 return c;
53 }
54
55 // If no match, compute result and insert into cache.
56 //
57 // FIXME(nikomatsakis) -- this cache is not taking into
58 // account cycles that may have occurred in forming the
59 // candidate. I don't know of any specific problems that
60 // result but it seems awfully suspicious.
61 let (candidate, dep_node) =
62 self.in_task(|this| this.candidate_from_obligation_no_cache(stack));
63
29967ef6 64 debug!(?candidate, "CACHE MISS");
f035d41b
XL
65 self.insert_candidate_cache(
66 stack.obligation.param_env,
67 cache_fresh_trait_pred,
68 dep_node,
69 candidate.clone(),
70 );
71 candidate
72 }
73
1b1a35ee
XL
74 fn candidate_from_obligation_no_cache<'o>(
75 &mut self,
76 stack: &TraitObligationStack<'o, 'tcx>,
77 ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
78 if let Some(conflict) = self.is_knowable(stack) {
79 debug!("coherence stage: not knowable");
80 if self.intercrate_ambiguity_causes.is_some() {
81 debug!("evaluate_stack: intercrate_ambiguity_causes is some");
82 // Heuristics: show the diagnostics when there are no candidates in crate.
83 if let Ok(candidate_set) = self.assemble_candidates(stack) {
84 let mut no_candidates_apply = true;
85
86 for c in candidate_set.vec.iter() {
87 if self.evaluate_candidate(stack, &c)?.may_apply() {
88 no_candidates_apply = false;
89 break;
90 }
91 }
92
93 if !candidate_set.ambiguous && no_candidates_apply {
94 let trait_ref = stack.obligation.predicate.skip_binder().trait_ref;
95 let self_ty = trait_ref.self_ty();
5e7ed085 96 let (trait_desc, self_desc) = with_no_trimmed_paths!({
1b1a35ee
XL
97 let trait_desc = trait_ref.print_only_trait_path().to_string();
98 let self_desc = if self_ty.has_concrete_skeleton() {
99 Some(self_ty.to_string())
100 } else {
101 None
102 };
103 (trait_desc, self_desc)
104 });
105 let cause = if let Conflict::Upstream = conflict {
106 IntercrateAmbiguityCause::UpstreamCrateUpdate { trait_desc, self_desc }
107 } else {
108 IntercrateAmbiguityCause::DownstreamCrate { trait_desc, self_desc }
109 };
29967ef6 110 debug!(?cause, "evaluate_stack: pushing cause");
1b1a35ee
XL
111 self.intercrate_ambiguity_causes.as_mut().unwrap().push(cause);
112 }
113 }
114 }
115 return Ok(None);
116 }
117
118 let candidate_set = self.assemble_candidates(stack)?;
119
120 if candidate_set.ambiguous {
121 debug!("candidate set contains ambig");
122 return Ok(None);
123 }
124
3c0e092e 125 let candidates = candidate_set.vec;
1b1a35ee 126
29967ef6 127 debug!(?stack, ?candidates, "assembled {} candidates", candidates.len());
1b1a35ee
XL
128
129 // At this point, we know that each of the entries in the
130 // candidate set is *individually* applicable. Now we have to
131 // figure out if they contain mutual incompatibilities. This
132 // frequently arises if we have an unconstrained input type --
133 // for example, we are looking for `$0: Eq` where `$0` is some
134 // unconstrained type variable. In that case, we'll get a
135 // candidate which assumes $0 == int, one that assumes `$0 ==
136 // usize`, etc. This spells an ambiguity.
137
3c0e092e
XL
138 let mut candidates = self.filter_impls(candidates, stack.obligation);
139
1b1a35ee
XL
140 // If there is more than one candidate, first winnow them down
141 // by considering extra conditions (nested obligations and so
142 // forth). We don't winnow if there is exactly one
143 // candidate. This is a relatively minor distinction but it
144 // can lead to better inference and error-reporting. An
145 // example would be if there was an impl:
146 //
147 // impl<T:Clone> Vec<T> { fn push_clone(...) { ... } }
148 //
149 // and we were to see some code `foo.push_clone()` where `boo`
150 // is a `Vec<Bar>` and `Bar` does not implement `Clone`. If
151 // we were to winnow, we'd wind up with zero candidates.
152 // Instead, we select the right impl now but report "`Bar` does
153 // not implement `Clone`".
154 if candidates.len() == 1 {
3c0e092e 155 return self.filter_reservation_impls(candidates.pop().unwrap(), stack.obligation);
1b1a35ee
XL
156 }
157
158 // Winnow, but record the exact outcome of evaluation, which
159 // is needed for specialization. Propagate overflow if it occurs.
160 let mut candidates = candidates
161 .into_iter()
162 .map(|c| match self.evaluate_candidate(stack, &c) {
163 Ok(eval) if eval.may_apply() => {
164 Ok(Some(EvaluatedCandidate { candidate: c, evaluation: eval }))
165 }
166 Ok(_) => Ok(None),
5e7ed085 167 Err(OverflowError::Canonical) => Err(Overflow(OverflowError::Canonical)),
c295e0f8 168 Err(OverflowError::ErrorReporting) => Err(ErrorReporting),
5e7ed085 169 Err(OverflowError::Error(e)) => Err(Overflow(OverflowError::Error(e))),
1b1a35ee
XL
170 })
171 .flat_map(Result::transpose)
172 .collect::<Result<Vec<_>, _>>()?;
173
29967ef6 174 debug!(?stack, ?candidates, "winnowed to {} candidates", candidates.len());
1b1a35ee 175
29967ef6 176 let needs_infer = stack.obligation.predicate.has_infer_types_or_consts();
1b1a35ee
XL
177
178 // If there are STILL multiple candidates, we can further
179 // reduce the list by dropping duplicates -- including
180 // resolving specializations.
181 if candidates.len() > 1 {
182 let mut i = 0;
183 while i < candidates.len() {
184 let is_dup = (0..candidates.len()).filter(|&j| i != j).any(|j| {
185 self.candidate_should_be_dropped_in_favor_of(
186 &candidates[i],
187 &candidates[j],
188 needs_infer,
189 )
190 });
191 if is_dup {
29967ef6 192 debug!(candidate = ?candidates[i], "Dropping candidate #{}/{}", i, candidates.len());
1b1a35ee
XL
193 candidates.swap_remove(i);
194 } else {
29967ef6 195 debug!(candidate = ?candidates[i], "Retaining candidate #{}/{}", i, candidates.len());
1b1a35ee
XL
196 i += 1;
197
198 // If there are *STILL* multiple candidates, give up
199 // and report ambiguity.
200 if i > 1 {
201 debug!("multiple matches, ambig");
3c0e092e
XL
202 return Err(Ambiguous(
203 candidates
204 .into_iter()
205 .filter_map(|c| match c.candidate {
206 SelectionCandidate::ImplCandidate(def_id) => Some(def_id),
207 _ => None,
208 })
209 .collect(),
210 ));
1b1a35ee
XL
211 }
212 }
213 }
214 }
215
216 // If there are *NO* candidates, then there are no impls --
217 // that we know of, anyway. Note that in the case where there
218 // are unbound type variables within the obligation, it might
219 // be the case that you could still satisfy the obligation
220 // from another crate by instantiating the type variables with
221 // a type from another crate that does have an impl. This case
222 // is checked for in `evaluate_stack` (and hence users
223 // who might care about this case, like coherence, should use
224 // that function).
225 if candidates.is_empty() {
226 // If there's an error type, 'downgrade' our result from
227 // `Err(Unimplemented)` to `Ok(None)`. This helps us avoid
228 // emitting additional spurious errors, since we're guaranteed
229 // to have emitted at least one.
04454e1e
FG
230 if stack.obligation.predicate.references_error() {
231 debug!(?stack.obligation.predicate, "found error type in predicate, treating as ambiguous");
1b1a35ee
XL
232 return Ok(None);
233 }
234 return Err(Unimplemented);
235 }
236
237 // Just one candidate left.
3c0e092e 238 self.filter_reservation_impls(candidates.pop().unwrap().candidate, stack.obligation)
1b1a35ee
XL
239 }
240
c295e0f8 241 #[instrument(skip(self, stack), level = "debug")]
f035d41b
XL
242 pub(super) fn assemble_candidates<'o>(
243 &mut self,
244 stack: &TraitObligationStack<'o, 'tcx>,
245 ) -> Result<SelectionCandidateSet<'tcx>, SelectionError<'tcx>> {
246 let TraitObligationStack { obligation, .. } = *stack;
247 let obligation = &Obligation {
248 param_env: obligation.param_env,
249 cause: obligation.cause.clone(),
250 recursion_depth: obligation.recursion_depth,
fc512014 251 predicate: self.infcx().resolve_vars_if_possible(obligation.predicate),
f035d41b
XL
252 };
253
254 if obligation.predicate.skip_binder().self_ty().is_ty_var() {
5e7ed085 255 debug!(ty = ?obligation.predicate.skip_binder().self_ty(), "ambiguous inference var or opaque type");
f035d41b
XL
256 // Self is a type variable (e.g., `_: AsRef<str>`).
257 //
258 // This is somewhat problematic, as the current scheme can't really
259 // handle it turning to be a projection. This does end up as truly
260 // ambiguous in most cases anyway.
261 //
262 // Take the fast path out - this also improves
263 // performance by preventing assemble_candidates_from_impls from
264 // matching every impl for this trait.
265 return Ok(SelectionCandidateSet { vec: vec![], ambiguous: true });
266 }
267
268 let mut candidates = SelectionCandidateSet { vec: Vec::new(), ambiguous: false };
269
3c0e092e
XL
270 // The only way to prove a NotImplemented(T: Foo) predicate is via a negative impl.
271 // There are no compiler built-in rules for this.
272 if obligation.polarity() == ty::ImplPolarity::Negative {
273 self.assemble_candidates_for_trait_alias(obligation, &mut candidates);
5869c6ff 274 self.assemble_candidates_from_impls(obligation, &mut candidates);
f035d41b 275 } else {
3c0e092e
XL
276 self.assemble_candidates_for_trait_alias(obligation, &mut candidates);
277
278 // Other bounds. Consider both in-scope bounds from fn decl
279 // and applicable impls. There is a certain set of precedence rules here.
280 let def_id = obligation.predicate.def_id();
281 let lang_items = self.tcx().lang_items();
282
283 if lang_items.copy_trait() == Some(def_id) {
284 debug!(obligation_self_ty = ?obligation.predicate.skip_binder().self_ty());
285
286 // User-defined copy impls are permitted, but only for
287 // structs and enums.
288 self.assemble_candidates_from_impls(obligation, &mut candidates);
289
290 // For other types, we'll use the builtin rules.
291 let copy_conditions = self.copy_clone_conditions(obligation);
292 self.assemble_builtin_bound_candidates(copy_conditions, &mut candidates);
293 } else if lang_items.discriminant_kind_trait() == Some(def_id) {
294 // `DiscriminantKind` is automatically implemented for every type.
295 candidates.vec.push(DiscriminantKindCandidate);
296 } else if lang_items.pointee_trait() == Some(def_id) {
297 // `Pointee` is automatically implemented for every type.
298 candidates.vec.push(PointeeCandidate);
299 } else if lang_items.sized_trait() == Some(def_id) {
300 // Sized is never implementable by end-users, it is
301 // always automatically computed.
302 let sized_conditions = self.sized_conditions(obligation);
303 self.assemble_builtin_bound_candidates(sized_conditions, &mut candidates);
304 } else if lang_items.unsize_trait() == Some(def_id) {
305 self.assemble_candidates_for_unsizing(obligation, &mut candidates);
5e7ed085
FG
306 } else if lang_items.destruct_trait() == Some(def_id) {
307 self.assemble_const_destruct_candidates(obligation, &mut candidates);
3c0e092e
XL
308 } else {
309 if lang_items.clone_trait() == Some(def_id) {
310 // Same builtin conditions as `Copy`, i.e., every type which has builtin support
311 // for `Copy` also has builtin support for `Clone`, and tuples/arrays of `Clone`
312 // types have builtin support for `Clone`.
313 let clone_conditions = self.copy_clone_conditions(obligation);
314 self.assemble_builtin_bound_candidates(clone_conditions, &mut candidates);
315 }
f035d41b 316
3c0e092e
XL
317 self.assemble_generator_candidates(obligation, &mut candidates);
318 self.assemble_closure_candidates(obligation, &mut candidates);
319 self.assemble_fn_pointer_candidates(obligation, &mut candidates);
320 self.assemble_candidates_from_impls(obligation, &mut candidates);
321 self.assemble_candidates_from_object_ty(obligation, &mut candidates);
322 }
f035d41b 323
3c0e092e
XL
324 self.assemble_candidates_from_projected_tys(obligation, &mut candidates);
325 self.assemble_candidates_from_caller_bounds(stack, &mut candidates)?;
326 // Auto implementations have lower priority, so we only
327 // consider triggering a default if there is no other impl that can apply.
328 if candidates.vec.is_empty() {
329 self.assemble_candidates_from_auto_impls(obligation, &mut candidates);
330 }
f035d41b
XL
331 }
332 debug!("candidate list size: {}", candidates.vec.len());
333 Ok(candidates)
334 }
335
5099ac24 336 #[tracing::instrument(level = "debug", skip(self, candidates))]
f035d41b
XL
337 fn assemble_candidates_from_projected_tys(
338 &mut self,
339 obligation: &TraitObligation<'tcx>,
340 candidates: &mut SelectionCandidateSet<'tcx>,
341 ) {
f035d41b
XL
342 // Before we go into the whole placeholder thing, just
343 // quickly check if the self-type is a projection at all.
1b1a35ee 344 match obligation.predicate.skip_binder().trait_ref.self_ty().kind() {
f035d41b
XL
345 ty::Projection(_) | ty::Opaque(..) => {}
346 ty::Infer(ty::TyVar(_)) => {
347 span_bug!(
348 obligation.cause.span,
349 "Self=_ should have been handled by assemble_candidates"
350 );
351 }
352 _ => return,
353 }
354
355 let result = self
356 .infcx
357 .probe(|_| self.match_projection_obligation_against_definition_bounds(obligation));
358
a2a8927a 359 candidates.vec.extend(result.into_iter().map(ProjectionCandidate));
f035d41b
XL
360 }
361
362 /// Given an obligation like `<SomeTrait for T>`, searches the obligations that the caller
363 /// supplied to find out whether it is listed among them.
364 ///
365 /// Never affects the inference environment.
5099ac24 366 #[tracing::instrument(level = "debug", skip(self, stack, candidates))]
f035d41b
XL
367 fn assemble_candidates_from_caller_bounds<'o>(
368 &mut self,
369 stack: &TraitObligationStack<'o, 'tcx>,
370 candidates: &mut SelectionCandidateSet<'tcx>,
371 ) -> Result<(), SelectionError<'tcx>> {
5099ac24 372 debug!(?stack.obligation);
f035d41b
XL
373
374 let all_bounds = stack
375 .obligation
376 .param_env
377 .caller_bounds()
378 .iter()
a2a8927a 379 .filter_map(|o| o.to_opt_poly_trait_pred());
f035d41b
XL
380
381 // Micro-optimization: filter out predicates relating to different traits.
382 let matching_bounds =
a2a8927a 383 all_bounds.filter(|p| p.def_id() == stack.obligation.predicate.def_id());
f035d41b
XL
384
385 // Keep only those bounds which may apply, and propagate overflow if it occurs.
f035d41b 386 for bound in matching_bounds {
a2a8927a
XL
387 // FIXME(oli-obk): it is suspicious that we are dropping the constness and
388 // polarity here.
5e7ed085 389 let wc = self.where_clause_may_apply(stack, bound.map_bound(|t| t.trait_ref))?;
f035d41b 390 if wc.may_apply() {
a2a8927a 391 candidates.vec.push(ParamCandidate(bound));
f035d41b
XL
392 }
393 }
394
f035d41b
XL
395 Ok(())
396 }
397
398 fn assemble_generator_candidates(
399 &mut self,
400 obligation: &TraitObligation<'tcx>,
401 candidates: &mut SelectionCandidateSet<'tcx>,
5869c6ff 402 ) {
f035d41b 403 if self.tcx().lang_items().gen_trait() != Some(obligation.predicate.def_id()) {
5869c6ff 404 return;
f035d41b
XL
405 }
406
407 // Okay to skip binder because the substs on generator types never
408 // touch bound regions, they just capture the in-scope
409 // type/region parameters.
410 let self_ty = obligation.self_ty().skip_binder();
1b1a35ee 411 match self_ty.kind() {
f035d41b 412 ty::Generator(..) => {
29967ef6 413 debug!(?self_ty, ?obligation, "assemble_generator_candidates",);
f035d41b
XL
414
415 candidates.vec.push(GeneratorCandidate);
416 }
417 ty::Infer(ty::TyVar(_)) => {
418 debug!("assemble_generator_candidates: ambiguous self-type");
419 candidates.ambiguous = true;
420 }
421 _ => {}
422 }
f035d41b
XL
423 }
424
425 /// Checks for the artificial impl that the compiler will create for an obligation like `X :
426 /// FnMut<..>` where `X` is a closure type.
427 ///
428 /// Note: the type parameters on a closure candidate are modeled as *output* type
429 /// parameters and hence do not affect whether this trait is a match or not. They will be
430 /// unified during the confirmation step.
431 fn assemble_closure_candidates(
432 &mut self,
433 obligation: &TraitObligation<'tcx>,
434 candidates: &mut SelectionCandidateSet<'tcx>,
5869c6ff 435 ) {
5e7ed085
FG
436 let Some(kind) = self.tcx().fn_trait_kind_from_lang_item(obligation.predicate.def_id()) else {
437 return;
f035d41b
XL
438 };
439
440 // Okay to skip binder because the substs on closure types never
441 // touch bound regions, they just capture the in-scope
442 // type/region parameters
1b1a35ee 443 match *obligation.self_ty().skip_binder().kind() {
f035d41b 444 ty::Closure(_, closure_substs) => {
29967ef6 445 debug!(?kind, ?obligation, "assemble_unboxed_candidates");
f035d41b
XL
446 match self.infcx.closure_kind(closure_substs) {
447 Some(closure_kind) => {
29967ef6 448 debug!(?closure_kind, "assemble_unboxed_candidates");
f035d41b
XL
449 if closure_kind.extends(kind) {
450 candidates.vec.push(ClosureCandidate);
451 }
452 }
453 None => {
454 debug!("assemble_unboxed_candidates: closure_kind not yet known");
455 candidates.vec.push(ClosureCandidate);
456 }
457 }
458 }
459 ty::Infer(ty::TyVar(_)) => {
460 debug!("assemble_unboxed_closure_candidates: ambiguous self-type");
461 candidates.ambiguous = true;
462 }
463 _ => {}
464 }
f035d41b
XL
465 }
466
467 /// Implements one of the `Fn()` family for a fn pointer.
468 fn assemble_fn_pointer_candidates(
469 &mut self,
470 obligation: &TraitObligation<'tcx>,
471 candidates: &mut SelectionCandidateSet<'tcx>,
5869c6ff 472 ) {
f035d41b
XL
473 // We provide impl of all fn traits for fn pointers.
474 if self.tcx().fn_trait_kind_from_lang_item(obligation.predicate.def_id()).is_none() {
5869c6ff 475 return;
f035d41b
XL
476 }
477
478 // Okay to skip binder because what we are inspecting doesn't involve bound regions.
479 let self_ty = obligation.self_ty().skip_binder();
1b1a35ee 480 match *self_ty.kind() {
f035d41b
XL
481 ty::Infer(ty::TyVar(_)) => {
482 debug!("assemble_fn_pointer_candidates: ambiguous self-type");
483 candidates.ambiguous = true; // Could wind up being a fn() type.
484 }
485 // Provide an impl, but only for suitable `fn` pointers.
486 ty::FnPtr(_) => {
487 if let ty::FnSig {
488 unsafety: hir::Unsafety::Normal,
489 abi: Abi::Rust,
490 c_variadic: false,
491 ..
492 } = self_ty.fn_sig(self.tcx()).skip_binder()
493 {
c295e0f8 494 candidates.vec.push(FnPointerCandidate { is_const: false });
f035d41b
XL
495 }
496 }
497 // Provide an impl for suitable functions, rejecting `#[target_feature]` functions (RFC 2396).
498 ty::FnDef(def_id, _) => {
499 if let ty::FnSig {
500 unsafety: hir::Unsafety::Normal,
501 abi: Abi::Rust,
502 c_variadic: false,
503 ..
504 } = self_ty.fn_sig(self.tcx()).skip_binder()
505 {
506 if self.tcx().codegen_fn_attrs(def_id).target_features.is_empty() {
c295e0f8
XL
507 candidates
508 .vec
509 .push(FnPointerCandidate { is_const: self.tcx().is_const_fn(def_id) });
f035d41b
XL
510 }
511 }
512 }
513 _ => {}
514 }
f035d41b
XL
515 }
516
517 /// Searches for impls that might apply to `obligation`.
518 fn assemble_candidates_from_impls(
519 &mut self,
520 obligation: &TraitObligation<'tcx>,
521 candidates: &mut SelectionCandidateSet<'tcx>,
5869c6ff 522 ) {
29967ef6 523 debug!(?obligation, "assemble_candidates_from_impls");
f035d41b
XL
524
525 // Essentially any user-written impl will match with an error type,
526 // so creating `ImplCandidates` isn't useful. However, we might
527 // end up finding a candidate elsewhere (e.g. a `BuiltinCandidate` for `Sized)
528 // This helps us avoid overflow: see issue #72839
529 // Since compilation is already guaranteed to fail, this is just
530 // to try to show the 'nicest' possible errors to the user.
3c0e092e
XL
531 // We don't check for errors in the `ParamEnv` - in practice,
532 // it seems to cause us to be overly aggressive in deciding
533 // to give up searching for candidates, leading to spurious errors.
534 if obligation.predicate.references_error() {
5869c6ff 535 return;
f035d41b
XL
536 }
537
538 self.tcx().for_each_relevant_impl(
539 obligation.predicate.def_id(),
540 obligation.predicate.skip_binder().trait_ref.self_ty(),
541 |impl_def_id| {
923072b8
FG
542 // Before we create the substitutions and everything, first
543 // consider a "quick reject". This avoids creating more types
544 // and so forth that we need to.
545 let impl_trait_ref = self.tcx().bound_impl_trait_ref(impl_def_id).unwrap();
546 if self.fast_reject_trait_refs(obligation, &impl_trait_ref.0) {
547 return;
548 }
549
f035d41b 550 self.infcx.probe(|_| {
923072b8 551 if let Ok(_substs) = self.match_impl(impl_def_id, impl_trait_ref, obligation) {
f035d41b
XL
552 candidates.vec.push(ImplCandidate(impl_def_id));
553 }
554 });
555 },
556 );
f035d41b
XL
557 }
558
559 fn assemble_candidates_from_auto_impls(
560 &mut self,
561 obligation: &TraitObligation<'tcx>,
562 candidates: &mut SelectionCandidateSet<'tcx>,
5869c6ff 563 ) {
f035d41b
XL
564 // Okay to skip binder here because the tests we do below do not involve bound regions.
565 let self_ty = obligation.self_ty().skip_binder();
29967ef6 566 debug!(?self_ty, "assemble_candidates_from_auto_impls");
f035d41b
XL
567
568 let def_id = obligation.predicate.def_id();
569
570 if self.tcx().trait_is_auto(def_id) {
1b1a35ee 571 match self_ty.kind() {
f035d41b
XL
572 ty::Dynamic(..) => {
573 // For object types, we don't know what the closed
574 // over types are. This means we conservatively
575 // say nothing; a candidate may be added by
576 // `assemble_candidates_from_object_ty`.
577 }
578 ty::Foreign(..) => {
579 // Since the contents of foreign types is unknown,
580 // we don't add any `..` impl. Default traits could
581 // still be provided by a manual implementation for
582 // this trait and type.
583 }
584 ty::Param(..) | ty::Projection(..) => {
585 // In these cases, we don't know what the actual
586 // type is. Therefore, we cannot break it down
587 // into its constituent types. So we don't
588 // consider the `..` impl but instead just add no
589 // candidates: this means that typeck will only
590 // succeed if there is another reason to believe
591 // that this obligation holds. That could be a
592 // where-clause or, in the case of an object type,
593 // it could be that the object type lists the
594 // trait (e.g., `Foo+Send : Send`). See
5869c6ff 595 // `ui/typeck/typeck-default-trait-impl-send-param.rs`
f035d41b
XL
596 // for an example of a test case that exercises
597 // this path.
598 }
599 ty::Infer(ty::TyVar(_)) => {
600 // The auto impl might apply; we don't know.
601 candidates.ambiguous = true;
602 }
603 ty::Generator(_, _, movability)
604 if self.tcx().lang_items().unpin_trait() == Some(def_id) =>
605 {
606 match movability {
607 hir::Movability::Static => {
608 // Immovable generators are never `Unpin`, so
609 // suppress the normal auto-impl candidate for it.
610 }
611 hir::Movability::Movable => {
612 // Movable generators are always `Unpin`, so add an
613 // unconditional builtin candidate.
614 candidates.vec.push(BuiltinCandidate { has_nested: false });
615 }
616 }
617 }
618
619 _ => candidates.vec.push(AutoImplCandidate(def_id)),
620 }
621 }
f035d41b
XL
622 }
623
624 /// Searches for impls that might apply to `obligation`.
625 fn assemble_candidates_from_object_ty(
626 &mut self,
627 obligation: &TraitObligation<'tcx>,
628 candidates: &mut SelectionCandidateSet<'tcx>,
629 ) {
630 debug!(
29967ef6
XL
631 self_ty = ?obligation.self_ty().skip_binder(),
632 "assemble_candidates_from_object_ty",
f035d41b
XL
633 );
634
635 self.infcx.probe(|_snapshot| {
636 // The code below doesn't care about regions, and the
637 // self-ty here doesn't escape this probe, so just erase
638 // any LBR.
fc512014 639 let self_ty = self.tcx().erase_late_bound_regions(obligation.self_ty());
1b1a35ee 640 let poly_trait_ref = match self_ty.kind() {
f035d41b
XL
641 ty::Dynamic(ref data, ..) => {
642 if data.auto_traits().any(|did| did == obligation.predicate.def_id()) {
643 debug!(
644 "assemble_candidates_from_object_ty: matched builtin bound, \
645 pushing candidate"
646 );
647 candidates.vec.push(BuiltinObjectCandidate);
648 return;
649 }
650
651 if let Some(principal) = data.principal() {
652 if !self.infcx.tcx.features().object_safe_for_dispatch {
653 principal.with_self_ty(self.tcx(), self_ty)
654 } else if self.tcx().is_object_safe(principal.def_id()) {
655 principal.with_self_ty(self.tcx(), self_ty)
656 } else {
657 return;
658 }
659 } else {
660 // Only auto trait bounds exist.
661 return;
662 }
663 }
664 ty::Infer(ty::TyVar(_)) => {
665 debug!("assemble_candidates_from_object_ty: ambiguous");
666 candidates.ambiguous = true; // could wind up being an object type
667 return;
668 }
669 _ => return,
670 };
671
29967ef6
XL
672 debug!(?poly_trait_ref, "assemble_candidates_from_object_ty");
673
fc512014 674 let poly_trait_predicate = self.infcx().resolve_vars_if_possible(obligation.predicate);
29967ef6 675 let placeholder_trait_predicate =
fc512014 676 self.infcx().replace_bound_vars_with_placeholders(poly_trait_predicate);
f035d41b
XL
677
678 // Count only those upcast versions that match the trait-ref
679 // we are looking for. Specifically, do not only check for the
680 // correct trait, but also the correct type parameters.
681 // For example, we may be trying to upcast `Foo` to `Bar<i32>`,
682 // but `Foo` is declared as `trait Foo: Bar<u32>`.
29967ef6
XL
683 let candidate_supertraits = util::supertraits(self.tcx(), poly_trait_ref)
684 .enumerate()
685 .filter(|&(_, upcast_trait_ref)| {
686 self.infcx.probe(|_| {
687 self.match_normalize_trait_ref(
688 obligation,
689 upcast_trait_ref,
690 placeholder_trait_predicate.trait_ref,
691 )
692 .is_ok()
693 })
f035d41b 694 })
29967ef6 695 .map(|(idx, _)| ObjectCandidate(idx));
f035d41b 696
29967ef6 697 candidates.vec.extend(candidate_supertraits);
f035d41b
XL
698 })
699 }
700
c295e0f8
XL
701 /// Temporary migration for #89190
702 fn need_migrate_deref_output_trait_object(
703 &mut self,
704 ty: Ty<'tcx>,
705 cause: &traits::ObligationCause<'tcx>,
706 param_env: ty::ParamEnv<'tcx>,
707 ) -> Option<(Ty<'tcx>, DefId)> {
708 let tcx = self.tcx();
709 if tcx.features().trait_upcasting {
710 return None;
711 }
712
713 // <ty as Deref>
714 let trait_ref = ty::TraitRef {
715 def_id: tcx.lang_items().deref_trait()?,
716 substs: tcx.mk_substs_trait(ty, &[]),
717 };
718
719 let obligation = traits::Obligation::new(
720 cause.clone(),
721 param_env,
722 ty::Binder::dummy(trait_ref).without_const().to_predicate(tcx),
723 );
724 if !self.infcx.predicate_may_hold(&obligation) {
725 return None;
726 }
727
728 let mut fulfillcx = traits::FulfillmentContext::new_in_snapshot();
729 let normalized_ty = fulfillcx.normalize_projection_type(
730 &self.infcx,
731 param_env,
732 ty::ProjectionTy {
733 item_def_id: tcx.lang_items().deref_target()?,
734 substs: trait_ref.substs,
735 },
736 cause.clone(),
737 );
738
3c0e092e 739 let ty::Dynamic(data, ..) = normalized_ty.kind() else {
c295e0f8
XL
740 return None;
741 };
742
743 let def_id = data.principal_def_id()?;
744
745 return Some((normalized_ty, def_id));
746 }
747
f035d41b
XL
748 /// Searches for unsizing that might apply to `obligation`.
749 fn assemble_candidates_for_unsizing(
750 &mut self,
751 obligation: &TraitObligation<'tcx>,
752 candidates: &mut SelectionCandidateSet<'tcx>,
753 ) {
754 // We currently never consider higher-ranked obligations e.g.
755 // `for<'a> &'a T: Unsize<Trait+'a>` to be implemented. This is not
756 // because they are a priori invalid, and we could potentially add support
757 // for them later, it's just that there isn't really a strong need for it.
758 // A `T: Unsize<U>` obligation is always used as part of a `T: CoerceUnsize<U>`
759 // impl, and those are generally applied to concrete types.
760 //
761 // That said, one might try to write a fn with a where clause like
762 // for<'a> Foo<'a, T>: Unsize<Foo<'a, Trait>>
763 // where the `'a` is kind of orthogonal to the relevant part of the `Unsize`.
764 // Still, you'd be more likely to write that where clause as
765 // T: Trait
766 // so it seems ok if we (conservatively) fail to accept that `Unsize`
767 // obligation above. Should be possible to extend this in the future.
5e7ed085
FG
768 let Some(source) = obligation.self_ty().no_bound_vars() else {
769 // Don't add any candidates if there are bound regions.
770 return;
f035d41b
XL
771 };
772 let target = obligation.predicate.skip_binder().trait_ref.substs.type_at(1);
773
29967ef6 774 debug!(?source, ?target, "assemble_candidates_for_unsizing");
f035d41b 775
94222f64 776 match (source.kind(), target.kind()) {
f035d41b
XL
777 // Trait+Kx+'a -> Trait+Ky+'b (upcasts).
778 (&ty::Dynamic(ref data_a, ..), &ty::Dynamic(ref data_b, ..)) => {
94222f64 779 // Upcast coercions permit several things:
f035d41b
XL
780 //
781 // 1. Dropping auto traits, e.g., `Foo + Send` to `Foo`
782 // 2. Tightening the region bound, e.g., `Foo + 'a` to `Foo + 'b` if `'a: 'b`
94222f64 783 // 3. Tightening trait to its super traits, eg. `Foo` to `Bar` if `Foo: Bar`
f035d41b 784 //
94222f64
XL
785 // Note that neither of the first two of these changes requires any
786 // change at runtime. The third needs to change pointer metadata at runtime.
f035d41b 787 //
94222f64 788 // We always perform upcasting coercions when we can because of reason
f035d41b 789 // #2 (region bounds).
94222f64
XL
790 let auto_traits_compatible = data_b
791 .auto_traits()
792 // All of a's auto traits need to be in b's auto traits.
793 .all(|b| data_a.auto_traits().any(|a| a == b));
794 if auto_traits_compatible {
795 let principal_def_id_a = data_a.principal_def_id();
796 let principal_def_id_b = data_b.principal_def_id();
797 if principal_def_id_a == principal_def_id_b {
798 // no cyclic
799 candidates.vec.push(BuiltinUnsizeCandidate);
800 } else if principal_def_id_a.is_some() && principal_def_id_b.is_some() {
801 // not casual unsizing, now check whether this is trait upcasting coercion.
802 let principal_a = data_a.principal().unwrap();
803 let target_trait_did = principal_def_id_b.unwrap();
804 let source_trait_ref = principal_a.with_self_ty(self.tcx(), source);
c295e0f8
XL
805 if let Some((deref_output_ty, deref_output_trait_did)) = self
806 .need_migrate_deref_output_trait_object(
807 source,
808 &obligation.cause,
809 obligation.param_env,
810 )
811 {
812 if deref_output_trait_did == target_trait_did {
813 self.tcx().struct_span_lint_hir(
814 DEREF_INTO_DYN_SUPERTRAIT,
815 obligation.cause.body_id,
816 obligation.cause.span,
817 |lint| {
818 lint.build(&format!(
819 "`{}` implements `Deref` with supertrait `{}` as output",
820 source,
821 deref_output_ty
822 )).emit();
823 },
824 );
825 return;
826 }
827 }
828
94222f64
XL
829 for (idx, upcast_trait_ref) in
830 util::supertraits(self.tcx(), source_trait_ref).enumerate()
831 {
832 if upcast_trait_ref.def_id() == target_trait_did {
833 candidates.vec.push(TraitUpcastingUnsizeCandidate(idx));
834 }
835 }
836 }
837 }
f035d41b
XL
838 }
839
840 // `T` -> `Trait`
94222f64
XL
841 (_, &ty::Dynamic(..)) => {
842 candidates.vec.push(BuiltinUnsizeCandidate);
843 }
f035d41b
XL
844
845 // Ambiguous handling is below `T` -> `Trait`, because inference
846 // variables can still implement `Unsize<Trait>` and nested
847 // obligations will have the final say (likely deferred).
848 (&ty::Infer(ty::TyVar(_)), _) | (_, &ty::Infer(ty::TyVar(_))) => {
849 debug!("assemble_candidates_for_unsizing: ambiguous");
850 candidates.ambiguous = true;
f035d41b
XL
851 }
852
853 // `[T; n]` -> `[T]`
94222f64
XL
854 (&ty::Array(..), &ty::Slice(_)) => {
855 candidates.vec.push(BuiltinUnsizeCandidate);
856 }
f035d41b
XL
857
858 // `Struct<T>` -> `Struct<U>`
859 (&ty::Adt(def_id_a, _), &ty::Adt(def_id_b, _)) if def_id_a.is_struct() => {
94222f64
XL
860 if def_id_a == def_id_b {
861 candidates.vec.push(BuiltinUnsizeCandidate);
862 }
f035d41b
XL
863 }
864
865 // `(.., T)` -> `(.., U)`
94222f64
XL
866 (&ty::Tuple(tys_a), &ty::Tuple(tys_b)) => {
867 if tys_a.len() == tys_b.len() {
868 candidates.vec.push(BuiltinUnsizeCandidate);
869 }
870 }
f035d41b 871
94222f64 872 _ => {}
f035d41b 873 };
f035d41b
XL
874 }
875
5099ac24 876 #[tracing::instrument(level = "debug", skip(self, obligation, candidates))]
f035d41b
XL
877 fn assemble_candidates_for_trait_alias(
878 &mut self,
879 obligation: &TraitObligation<'tcx>,
880 candidates: &mut SelectionCandidateSet<'tcx>,
5869c6ff 881 ) {
f035d41b
XL
882 // Okay to skip binder here because the tests we do below do not involve bound regions.
883 let self_ty = obligation.self_ty().skip_binder();
5099ac24 884 debug!(?self_ty);
f035d41b
XL
885
886 let def_id = obligation.predicate.def_id();
887
888 if self.tcx().is_trait_alias(def_id) {
889 candidates.vec.push(TraitAliasCandidate(def_id));
890 }
f035d41b
XL
891 }
892
893 /// Assembles the trait which are built-in to the language itself:
894 /// `Copy`, `Clone` and `Sized`.
5099ac24 895 #[tracing::instrument(level = "debug", skip(self, candidates))]
f035d41b
XL
896 fn assemble_builtin_bound_candidates(
897 &mut self,
898 conditions: BuiltinImplConditions<'tcx>,
899 candidates: &mut SelectionCandidateSet<'tcx>,
5869c6ff 900 ) {
f035d41b
XL
901 match conditions {
902 BuiltinImplConditions::Where(nested) => {
f035d41b
XL
903 candidates
904 .vec
905 .push(BuiltinCandidate { has_nested: !nested.skip_binder().is_empty() });
906 }
907 BuiltinImplConditions::None => {}
908 BuiltinImplConditions::Ambiguous => {
f035d41b
XL
909 candidates.ambiguous = true;
910 }
911 }
f035d41b 912 }
c295e0f8 913
5e7ed085 914 fn assemble_const_destruct_candidates(
c295e0f8
XL
915 &mut self,
916 obligation: &TraitObligation<'tcx>,
917 candidates: &mut SelectionCandidateSet<'tcx>,
5099ac24 918 ) {
5e7ed085 919 // If the predicate is `~const Destruct` in a non-const environment, we don't actually need
5099ac24 920 // to check anything. We'll short-circuit checking any obligations in confirmation, too.
5e7ed085
FG
921 if !obligation.is_const() {
922 candidates.vec.push(ConstDestructCandidate(None));
5099ac24
FG
923 return;
924 }
c295e0f8 925
5099ac24
FG
926 let self_ty = self.infcx().shallow_resolve(obligation.self_ty());
927 match self_ty.skip_binder().kind() {
928 ty::Opaque(..)
929 | ty::Dynamic(..)
930 | ty::Error(_)
931 | ty::Bound(..)
932 | ty::Param(_)
933 | ty::Placeholder(_)
934 | ty::Projection(_) => {
5e7ed085 935 // We don't know if these are `~const Destruct`, at least
5099ac24
FG
936 // not structurally... so don't push a candidate.
937 }
c295e0f8 938
5099ac24
FG
939 ty::Bool
940 | ty::Char
941 | ty::Int(_)
942 | ty::Uint(_)
943 | ty::Float(_)
944 | ty::Infer(ty::IntVar(_))
945 | ty::Infer(ty::FloatVar(_))
946 | ty::Str
947 | ty::RawPtr(_)
948 | ty::Ref(..)
949 | ty::FnDef(..)
950 | ty::FnPtr(_)
951 | ty::Never
952 | ty::Foreign(_)
953 | ty::Array(..)
954 | ty::Slice(_)
955 | ty::Closure(..)
956 | ty::Generator(..)
957 | ty::Tuple(_)
958 | ty::GeneratorWitness(_) => {
5e7ed085
FG
959 // These are built-in, and cannot have a custom `impl const Destruct`.
960 candidates.vec.push(ConstDestructCandidate(None));
5099ac24 961 }
c295e0f8 962
5099ac24
FG
963 ty::Adt(..) => {
964 // Find a custom `impl Drop` impl, if it exists
965 let relevant_impl = self.tcx().find_map_relevant_impl(
5e7ed085 966 self.tcx().require_lang_item(LangItem::Drop, None),
5099ac24
FG
967 obligation.predicate.skip_binder().trait_ref.self_ty(),
968 Some,
969 );
c295e0f8 970
5099ac24
FG
971 if let Some(impl_def_id) = relevant_impl {
972 // Check that `impl Drop` is actually const, if there is a custom impl
923072b8 973 if self.tcx().constness(impl_def_id) == hir::Constness::Const {
5e7ed085 974 candidates.vec.push(ConstDestructCandidate(Some(impl_def_id)));
c295e0f8 975 }
5099ac24
FG
976 } else {
977 // Otherwise check the ADT like a built-in type (structurally)
5e7ed085 978 candidates.vec.push(ConstDestructCandidate(None));
c295e0f8
XL
979 }
980 }
c295e0f8 981
5099ac24
FG
982 ty::Infer(_) => {
983 candidates.ambiguous = true;
984 }
985 }
c295e0f8 986 }
f035d41b 987}