2 ActualImplExpectedKind, ActualImplExpectedLifetimeKind, ActualImplExplNotes,
3 TraitPlaceholderMismatch,
5 use crate::infer::error_reporting::nice_region_error::NiceRegionError;
6 use crate::infer::lexical_region_resolve::RegionResolutionError;
7 use crate::infer::ValuePairs;
8 use crate::infer::{SubregionOrigin, TypeTrace};
9 use crate::traits::{ObligationCause, ObligationCauseCode};
10 use rustc_data_structures::intern::Interned;
11 use rustc_errors::{DiagnosticBuilder, ErrorGuaranteed};
12 use rustc_hir::def::Namespace;
13 use rustc_hir::def_id::DefId;
14 use rustc_middle::ty::error::ExpectedFound;
15 use rustc_middle::ty::print::{FmtPrinter, Print, RegionHighlightMode};
16 use rustc_middle::ty::subst::SubstsRef;
17 use rustc_middle::ty::{self, RePlaceholder, ReVar, Region, TyCtxt};
21 impl<'tcx> NiceRegionError<'_, 'tcx> {
22 /// When given a `ConcreteFailure` for a function with arguments containing a named region and
23 /// an anonymous region, emit a descriptive diagnostic error.
24 pub(super) fn try_report_placeholder_conflict(
26 ) -> Option<DiagnosticBuilder<'tcx, ErrorGuaranteed>> {
28 ///////////////////////////////////////////////////////////////////////////
29 // NB. The ordering of cases in this match is very
30 // sensitive, because we are often matching against
31 // specific cases and then using an `_` to match all
34 ///////////////////////////////////////////////////////////////////////////
35 // Check for errors from comparing trait failures -- first
36 // with two placeholders, then with one.
37 Some(RegionResolutionError::SubSupConflict(
40 SubregionOrigin::Subtype(box TypeTrace { cause, values }),
41 sub_placeholder @ Region(Interned(RePlaceholder(_), _)),
43 sup_placeholder @ Region(Interned(RePlaceholder(_), _)),
45 )) => self.try_report_trait_placeholder_mismatch(
46 Some(self.tcx().mk_region(ReVar(*vid))),
48 Some(*sub_placeholder),
49 Some(*sup_placeholder),
53 Some(RegionResolutionError::SubSupConflict(
56 SubregionOrigin::Subtype(box TypeTrace { cause, values }),
57 sub_placeholder @ Region(Interned(RePlaceholder(_), _)),
61 )) => self.try_report_trait_placeholder_mismatch(
62 Some(self.tcx().mk_region(ReVar(*vid))),
64 Some(*sub_placeholder),
69 Some(RegionResolutionError::SubSupConflict(
72 SubregionOrigin::Subtype(box TypeTrace { cause, values }),
75 sup_placeholder @ Region(Interned(RePlaceholder(_), _)),
77 )) => self.try_report_trait_placeholder_mismatch(
78 Some(self.tcx().mk_region(ReVar(*vid))),
81 Some(*sup_placeholder),
85 Some(RegionResolutionError::SubSupConflict(
90 SubregionOrigin::Subtype(box TypeTrace { cause, values }),
91 sup_placeholder @ Region(Interned(RePlaceholder(_), _)),
93 )) => self.try_report_trait_placeholder_mismatch(
94 Some(self.tcx().mk_region(ReVar(*vid))),
97 Some(*sup_placeholder),
101 Some(RegionResolutionError::UpperBoundUniverseConflict(
105 SubregionOrigin::Subtype(box TypeTrace { cause, values }),
106 sup_placeholder @ Region(Interned(RePlaceholder(_), _)),
107 )) => self.try_report_trait_placeholder_mismatch(
108 Some(self.tcx().mk_region(ReVar(*vid))),
111 Some(*sup_placeholder),
115 Some(RegionResolutionError::ConcreteFailure(
116 SubregionOrigin::Subtype(box TypeTrace { cause, values }),
117 sub_region @ Region(Interned(RePlaceholder(_), _)),
118 sup_region @ Region(Interned(RePlaceholder(_), _)),
119 )) => self.try_report_trait_placeholder_mismatch(
127 Some(RegionResolutionError::ConcreteFailure(
128 SubregionOrigin::Subtype(box TypeTrace { cause, values }),
129 sub_region @ Region(Interned(RePlaceholder(_), _)),
131 )) => self.try_report_trait_placeholder_mismatch(
132 (!sup_region.has_name()).then_some(*sup_region),
139 Some(RegionResolutionError::ConcreteFailure(
140 SubregionOrigin::Subtype(box TypeTrace { cause, values }),
142 sup_region @ Region(Interned(RePlaceholder(_), _)),
143 )) => self.try_report_trait_placeholder_mismatch(
144 (!sub_region.has_name()).then_some(*sub_region),
155 fn try_report_trait_placeholder_mismatch(
157 vid: Option<Region<'tcx>>,
158 cause: &ObligationCause<'tcx>,
159 sub_placeholder: Option<Region<'tcx>>,
160 sup_placeholder: Option<Region<'tcx>>,
161 value_pairs: &ValuePairs<'tcx>,
162 ) -> Option<DiagnosticBuilder<'tcx, ErrorGuaranteed>> {
163 let (expected_substs, found_substs, trait_def_id) = match value_pairs {
164 ValuePairs::TraitRefs(ExpectedFound { expected, found })
165 if expected.def_id == found.def_id =>
167 (expected.substs, found.substs, expected.def_id)
169 ValuePairs::PolyTraitRefs(ExpectedFound { expected, found })
170 if expected.def_id() == found.def_id() =>
172 // It's possible that the placeholders come from a binder
173 // outside of this value pair. Use `no_bound_vars` as a
174 // simple heuristic for that.
175 (expected.no_bound_vars()?.substs, found.no_bound_vars()?.substs, expected.def_id())
180 Some(self.report_trait_placeholder_mismatch(
191 // error[E0308]: implementation of `Foo` does not apply to enough lifetimes
192 // --> /home/nmatsakis/tmp/foo.rs:12:5
194 // 12 | all::<&'static u32>();
195 // | ^^^^^^^^^^^^^^^^^^^ lifetime mismatch
197 // = note: Due to a where-clause on the function `all`,
198 // = note: `T` must implement `...` for any two lifetimes `'1` and `'2`.
199 // = note: However, the type `T` only implements `...` for some specific lifetime `'2`.
200 #[instrument(level = "debug", skip(self))]
201 fn report_trait_placeholder_mismatch(
203 vid: Option<Region<'tcx>>,
204 cause: &ObligationCause<'tcx>,
205 sub_placeholder: Option<Region<'tcx>>,
206 sup_placeholder: Option<Region<'tcx>>,
208 expected_substs: SubstsRef<'tcx>,
209 actual_substs: SubstsRef<'tcx>,
210 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
211 let span = cause.span();
213 let (leading_ellipsis, satisfy_span, where_span, dup_span, def_id) =
214 if let ObligationCauseCode::ItemObligation(def_id)
215 | ObligationCauseCode::ExprItemObligation(def_id, ..) = *cause.code()
220 Some(self.tcx().def_span(def_id)),
222 self.tcx().def_path_str(def_id),
225 (false, None, None, Some(span), String::new())
228 let expected_trait_ref = self
230 .resolve_vars_if_possible(self.cx.tcx.mk_trait_ref(trait_def_id, expected_substs));
231 let actual_trait_ref =
232 self.cx.resolve_vars_if_possible(self.cx.tcx.mk_trait_ref(trait_def_id, actual_substs));
234 // Search the expected and actual trait references to see (a)
235 // whether the sub/sup placeholders appear in them (sometimes
236 // you have a trait ref like `T: Foo<fn(&u8)>`, where the
237 // placeholder was created as part of an inner type) and (b)
238 // whether the inference variable appears. In each case,
239 // assign a counter value in each case if so.
241 let mut has_sub = None;
242 let mut has_sup = None;
244 let mut actual_has_vid = None;
245 let mut expected_has_vid = None;
247 self.tcx().for_each_free_region(&expected_trait_ref, |r| {
248 if Some(r) == sub_placeholder && has_sub.is_none() {
249 has_sub = Some(counter);
251 } else if Some(r) == sup_placeholder && has_sup.is_none() {
252 has_sup = Some(counter);
256 if Some(r) == vid && expected_has_vid.is_none() {
257 expected_has_vid = Some(counter);
262 self.tcx().for_each_free_region(&actual_trait_ref, |r| {
263 if Some(r) == vid && actual_has_vid.is_none() {
264 actual_has_vid = Some(counter);
269 let actual_self_ty_has_vid =
270 self.tcx().any_free_region_meets(&actual_trait_ref.self_ty(), |r| Some(r) == vid);
272 let expected_self_ty_has_vid =
273 self.tcx().any_free_region_meets(&expected_trait_ref.self_ty(), |r| Some(r) == vid);
275 let any_self_ty_has_vid = actual_self_ty_has_vid || expected_self_ty_has_vid;
282 ?actual_self_ty_has_vid,
283 ?expected_self_ty_has_vid,
286 let actual_impl_expl_notes = self.explain_actual_impl_that_was_found(
300 let diag = TraitPlaceholderMismatch {
306 trait_def_id: self.tcx().def_path_str(trait_def_id),
307 actual_impl_expl_notes,
310 self.tcx().sess.create_err(diag)
313 /// Add notes with details about the expected and actual trait refs, with attention to cases
314 /// when placeholder regions are involved: either the trait or the self type containing
315 /// them needs to be mentioned the closest to the placeholders.
316 /// This makes the error messages read better, however at the cost of some complexity
317 /// due to the number of combinations we have to deal with.
318 fn explain_actual_impl_that_was_found(
320 sub_placeholder: Option<Region<'tcx>>,
321 sup_placeholder: Option<Region<'tcx>>,
322 has_sub: Option<usize>,
323 has_sup: Option<usize>,
324 expected_trait_ref: ty::TraitRef<'tcx>,
325 actual_trait_ref: ty::TraitRef<'tcx>,
326 vid: Option<Region<'tcx>>,
327 expected_has_vid: Option<usize>,
328 actual_has_vid: Option<usize>,
329 any_self_ty_has_vid: bool,
330 leading_ellipsis: bool,
331 ) -> Vec<ActualImplExplNotes> {
332 // HACK(eddyb) maybe move this in a more central location.
333 #[derive(Copy, Clone)]
334 struct Highlighted<'tcx, T> {
336 highlight: RegionHighlightMode<'tcx>,
340 impl<'tcx, T> Highlighted<'tcx, T> {
341 fn map<U>(self, f: impl FnOnce(T) -> U) -> Highlighted<'tcx, U> {
342 Highlighted { tcx: self.tcx, highlight: self.highlight, value: f(self.value) }
346 impl<'tcx, T> fmt::Display for Highlighted<'tcx, T>
350 FmtPrinter<'a, 'tcx>,
352 Output = FmtPrinter<'a, 'tcx>,
355 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
356 let mut printer = ty::print::FmtPrinter::new(self.tcx, Namespace::TypeNS);
357 printer.region_highlight_mode = self.highlight;
359 let s = self.value.print(printer)?.into_buffer();
364 // The weird thing here with the `maybe_highlighting_region` calls and the
365 // the match inside is meant to be like this:
367 // - The match checks whether the given things (placeholders, etc) appear
368 // in the types are about to print
369 // - Meanwhile, the `maybe_highlighting_region` calls set up
370 // highlights so that, if they do appear, we will replace
371 // them `'0` and whatever. (This replacement takes place
372 // inside the closure given to `maybe_highlighting_region`.)
374 // There is some duplication between the calls -- i.e., the
375 // `maybe_highlighting_region` checks if (e.g.) `has_sub` is
376 // None, an then we check again inside the closure, but this
377 // setup sort of minimized the number of calls and so form.
379 let highlight_trait_ref = |trait_ref| Highlighted {
381 highlight: RegionHighlightMode::new(self.tcx()),
385 let same_self_type = actual_trait_ref.self_ty() == expected_trait_ref.self_ty();
387 let mut expected_trait_ref = highlight_trait_ref(expected_trait_ref);
388 expected_trait_ref.highlight.maybe_highlighting_region(sub_placeholder, has_sub);
389 expected_trait_ref.highlight.maybe_highlighting_region(sup_placeholder, has_sup);
391 let passive_voice = match (has_sub, has_sup) {
392 (Some(_), _) | (_, Some(_)) => any_self_ty_has_vid,
394 expected_trait_ref.highlight.maybe_highlighting_region(vid, expected_has_vid);
395 match expected_has_vid {
397 None => any_self_ty_has_vid,
402 let (kind, ty_or_sig, trait_path) = if same_self_type {
403 let mut self_ty = expected_trait_ref.map(|tr| tr.self_ty());
404 self_ty.highlight.maybe_highlighting_region(vid, actual_has_vid);
406 if self_ty.value.is_closure()
407 && self.tcx().is_fn_trait(expected_trait_ref.value.def_id)
409 let closure_sig = self_ty.map(|closure| {
410 if let ty::Closure(_, substs) = closure.kind() {
411 self.tcx().signature_unclosure(
412 substs.as_closure().sig(),
413 rustc_hir::Unsafety::Normal,
416 bug!("type is not longer closure");
420 ActualImplExpectedKind::Signature,
421 closure_sig.to_string(),
422 expected_trait_ref.map(|tr| tr.print_only_trait_path()).to_string(),
426 ActualImplExpectedKind::Other,
428 expected_trait_ref.map(|tr| tr.print_only_trait_path()).to_string(),
431 } else if passive_voice {
433 ActualImplExpectedKind::Passive,
434 expected_trait_ref.map(|tr| tr.self_ty()).to_string(),
435 expected_trait_ref.map(|tr| tr.print_only_trait_path()).to_string(),
439 ActualImplExpectedKind::Other,
440 expected_trait_ref.map(|tr| tr.self_ty()).to_string(),
441 expected_trait_ref.map(|tr| tr.print_only_trait_path()).to_string(),
445 let (lt_kind, lifetime_1, lifetime_2) = match (has_sub, has_sup) {
446 (Some(n1), Some(n2)) => {
447 (ActualImplExpectedLifetimeKind::Two, std::cmp::min(n1, n2), std::cmp::max(n1, n2))
449 (Some(n), _) | (_, Some(n)) => (ActualImplExpectedLifetimeKind::Any, n, 0),
451 if let Some(n) = expected_has_vid {
452 (ActualImplExpectedLifetimeKind::Some, n, 0)
454 (ActualImplExpectedLifetimeKind::Nothing, 0, 0)
459 let note_1 = ActualImplExplNotes::new_expected(
469 let mut actual_trait_ref = highlight_trait_ref(actual_trait_ref);
470 actual_trait_ref.highlight.maybe_highlighting_region(vid, actual_has_vid);
472 let passive_voice = match actual_has_vid {
473 Some(_) => any_self_ty_has_vid,
477 let trait_path = actual_trait_ref.map(|tr| tr.print_only_trait_path()).to_string();
478 let ty = actual_trait_ref.map(|tr| tr.self_ty()).to_string();
479 let has_lifetime = actual_has_vid.is_some();
480 let lifetime = actual_has_vid.unwrap_or_default();
482 let note_2 = if same_self_type {
483 ActualImplExplNotes::ButActuallyImplementsTrait { trait_path, has_lifetime, lifetime }
484 } else if passive_voice {
485 ActualImplExplNotes::ButActuallyImplementedForTy {
492 ActualImplExplNotes::ButActuallyTyImplements { trait_path, ty, has_lifetime, lifetime }