]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_infer/src/infer/error_reporting/mod.rs
Auto merge of #99223 - saethlin:panicless-split-mut, r=Mark-Simulacrum
[rust.git] / compiler / rustc_infer / src / infer / error_reporting / mod.rs
1 //! Error Reporting Code for the inference engine
2 //!
3 //! Because of the way inference, and in particular region inference,
4 //! works, it often happens that errors are not detected until far after
5 //! the relevant line of code has been type-checked. Therefore, there is
6 //! an elaborate system to track why a particular constraint in the
7 //! inference graph arose so that we can explain to the user what gave
8 //! rise to a particular error.
9 //!
10 //! The system is based around a set of "origin" types. An "origin" is the
11 //! reason that a constraint or inference variable arose. There are
12 //! different "origin" enums for different kinds of constraints/variables
13 //! (e.g., `TypeOrigin`, `RegionVariableOrigin`). An origin always has
14 //! a span, but also more information so that we can generate a meaningful
15 //! error message.
16 //!
17 //! Having a catalog of all the different reasons an error can arise is
18 //! also useful for other reasons, like cross-referencing FAQs etc, though
19 //! we are not really taking advantage of this yet.
20 //!
21 //! # Region Inference
22 //!
23 //! Region inference is particularly tricky because it always succeeds "in
24 //! the moment" and simply registers a constraint. Then, at the end, we
25 //! can compute the full graph and report errors, so we need to be able to
26 //! store and later report what gave rise to the conflicting constraints.
27 //!
28 //! # Subtype Trace
29 //!
30 //! Determining whether `T1 <: T2` often involves a number of subtypes and
31 //! subconstraints along the way. A "TypeTrace" is an extended version
32 //! of an origin that traces the types and other values that were being
33 //! compared. It is not necessarily comprehensive (in fact, at the time of
34 //! this writing it only tracks the root values being compared) but I'd
35 //! like to extend it to include significant "waypoints". For example, if
36 //! you are comparing `(T1, T2) <: (T3, T4)`, and the problem is that `T2
37 //! <: T4` fails, I'd like the trace to include enough information to say
38 //! "in the 2nd element of the tuple". Similarly, failures when comparing
39 //! arguments or return types in fn types should be able to cite the
40 //! specific position, etc.
41 //!
42 //! # Reality vs plan
43 //!
44 //! Of course, there is still a LOT of code in typeck that has yet to be
45 //! ported to this system, and which relies on string concatenation at the
46 //! time of error detection.
47
48 use super::lexical_region_resolve::RegionResolutionError;
49 use super::region_constraints::GenericKind;
50 use super::{InferCtxt, RegionVariableOrigin, SubregionOrigin, TypeTrace, ValuePairs};
51
52 use crate::infer;
53 use crate::infer::error_reporting::nice_region_error::find_anon_type::find_anon_type;
54 use crate::traits::error_reporting::report_object_safety_error;
55 use crate::traits::{
56     IfExpressionCause, MatchExpressionArmCause, ObligationCause, ObligationCauseCode,
57     StatementAsExpression,
58 };
59
60 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
61 use rustc_errors::{pluralize, struct_span_err, Diagnostic, ErrorGuaranteed};
62 use rustc_errors::{Applicability, DiagnosticBuilder, DiagnosticStyledString, MultiSpan};
63 use rustc_hir as hir;
64 use rustc_hir::def_id::{DefId, LocalDefId};
65 use rustc_hir::lang_items::LangItem;
66 use rustc_hir::Node;
67 use rustc_middle::dep_graph::DepContext;
68 use rustc_middle::ty::print::with_no_trimmed_paths;
69 use rustc_middle::ty::{
70     self, error::TypeError, Binder, List, Region, Subst, Ty, TyCtxt, TypeFoldable,
71     TypeSuperVisitable, TypeVisitable,
72 };
73 use rustc_span::{sym, symbol::kw, BytePos, DesugaringKind, Pos, Span};
74 use rustc_target::spec::abi;
75 use std::ops::ControlFlow;
76 use std::{cmp, fmt, iter};
77
78 mod note;
79
80 mod need_type_info;
81 pub use need_type_info::TypeAnnotationNeeded;
82
83 pub mod nice_region_error;
84
85 pub(super) fn note_and_explain_region<'tcx>(
86     tcx: TyCtxt<'tcx>,
87     err: &mut Diagnostic,
88     prefix: &str,
89     region: ty::Region<'tcx>,
90     suffix: &str,
91     alt_span: Option<Span>,
92 ) {
93     let (description, span) = match *region {
94         ty::ReEarlyBound(_) | ty::ReFree(_) | ty::ReStatic => {
95             msg_span_from_free_region(tcx, region, alt_span)
96         }
97
98         ty::ReEmpty(ty::UniverseIndex::ROOT) => ("the empty lifetime".to_owned(), alt_span),
99
100         // uh oh, hope no user ever sees THIS
101         ty::ReEmpty(ui) => (format!("the empty lifetime in universe {:?}", ui), alt_span),
102
103         ty::RePlaceholder(_) => return,
104
105         // FIXME(#13998) RePlaceholder should probably print like
106         // ReFree rather than dumping Debug output on the user.
107         //
108         // We shouldn't really be having unification failures with ReVar
109         // and ReLateBound though.
110         ty::ReVar(_) | ty::ReLateBound(..) | ty::ReErased => {
111             (format!("lifetime {:?}", region), alt_span)
112         }
113     };
114
115     emit_msg_span(err, prefix, description, span, suffix);
116 }
117
118 fn explain_free_region<'tcx>(
119     tcx: TyCtxt<'tcx>,
120     err: &mut Diagnostic,
121     prefix: &str,
122     region: ty::Region<'tcx>,
123     suffix: &str,
124 ) {
125     let (description, span) = msg_span_from_free_region(tcx, region, None);
126
127     label_msg_span(err, prefix, description, span, suffix);
128 }
129
130 fn msg_span_from_free_region<'tcx>(
131     tcx: TyCtxt<'tcx>,
132     region: ty::Region<'tcx>,
133     alt_span: Option<Span>,
134 ) -> (String, Option<Span>) {
135     match *region {
136         ty::ReEarlyBound(_) | ty::ReFree(_) => {
137             let (msg, span) = msg_span_from_early_bound_and_free_regions(tcx, region);
138             (msg, Some(span))
139         }
140         ty::ReStatic => ("the static lifetime".to_owned(), alt_span),
141         ty::ReEmpty(ty::UniverseIndex::ROOT) => ("an empty lifetime".to_owned(), alt_span),
142         ty::ReEmpty(ui) => (format!("an empty lifetime in universe {:?}", ui), alt_span),
143         _ => bug!("{:?}", region),
144     }
145 }
146
147 fn msg_span_from_early_bound_and_free_regions<'tcx>(
148     tcx: TyCtxt<'tcx>,
149     region: ty::Region<'tcx>,
150 ) -> (String, Span) {
151     let scope = region.free_region_binding_scope(tcx).expect_local();
152     match *region {
153         ty::ReEarlyBound(ref br) => {
154             let mut sp = tcx.def_span(scope);
155             if let Some(param) =
156                 tcx.hir().get_generics(scope).and_then(|generics| generics.get_named(br.name))
157             {
158                 sp = param.span;
159             }
160             let text = if br.has_name() {
161                 format!("the lifetime `{}` as defined here", br.name)
162             } else {
163                 format!("the anonymous lifetime as defined here")
164             };
165             (text, sp)
166         }
167         ty::ReFree(ref fr) => {
168             if !fr.bound_region.is_named()
169                 && let Some((ty, _)) = find_anon_type(tcx, region, &fr.bound_region)
170             {
171                 ("the anonymous lifetime defined here".to_string(), ty.span)
172             } else {
173                 match fr.bound_region {
174                     ty::BoundRegionKind::BrNamed(_, name) => {
175                         let mut sp = tcx.def_span(scope);
176                         if let Some(param) =
177                             tcx.hir().get_generics(scope).and_then(|generics| generics.get_named(name))
178                         {
179                             sp = param.span;
180                         }
181                         let text = if name == kw::UnderscoreLifetime {
182                             format!("the anonymous lifetime as defined here")
183                         } else {
184                             format!("the lifetime `{}` as defined here", name)
185                         };
186                         (text, sp)
187                     }
188                     ty::BrAnon(idx) => (
189                         format!("the anonymous lifetime #{} defined here", idx + 1),
190                         tcx.def_span(scope)
191                     ),
192                     _ => (
193                         format!("the lifetime `{}` as defined here", region),
194                         tcx.def_span(scope),
195                     ),
196                 }
197             }
198         }
199         _ => bug!(),
200     }
201 }
202
203 fn emit_msg_span(
204     err: &mut Diagnostic,
205     prefix: &str,
206     description: String,
207     span: Option<Span>,
208     suffix: &str,
209 ) {
210     let message = format!("{}{}{}", prefix, description, suffix);
211
212     if let Some(span) = span {
213         err.span_note(span, &message);
214     } else {
215         err.note(&message);
216     }
217 }
218
219 fn label_msg_span(
220     err: &mut Diagnostic,
221     prefix: &str,
222     description: String,
223     span: Option<Span>,
224     suffix: &str,
225 ) {
226     let message = format!("{}{}{}", prefix, description, suffix);
227
228     if let Some(span) = span {
229         err.span_label(span, &message);
230     } else {
231         err.note(&message);
232     }
233 }
234
235 pub fn unexpected_hidden_region_diagnostic<'tcx>(
236     tcx: TyCtxt<'tcx>,
237     span: Span,
238     hidden_ty: Ty<'tcx>,
239     hidden_region: ty::Region<'tcx>,
240 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
241     let mut err = struct_span_err!(
242         tcx.sess,
243         span,
244         E0700,
245         "hidden type for `impl Trait` captures lifetime that does not appear in bounds",
246     );
247
248     // Explain the region we are capturing.
249     match *hidden_region {
250         ty::ReEmpty(ty::UniverseIndex::ROOT) => {
251             // All lifetimes shorter than the function body are `empty` in
252             // lexical region resolution. The default explanation of "an empty
253             // lifetime" isn't really accurate here.
254             let message = format!(
255                 "hidden type `{}` captures lifetime smaller than the function body",
256                 hidden_ty
257             );
258             err.span_note(span, &message);
259         }
260         ty::ReEarlyBound(_) | ty::ReFree(_) | ty::ReStatic | ty::ReEmpty(_) => {
261             // Assuming regionck succeeded (*), we ought to always be
262             // capturing *some* region from the fn header, and hence it
263             // ought to be free. So under normal circumstances, we will go
264             // down this path which gives a decent human readable
265             // explanation.
266             //
267             // (*) if not, the `tainted_by_errors` field would be set to
268             // `Some(ErrorGuaranteed)` in any case, so we wouldn't be here at all.
269             explain_free_region(
270                 tcx,
271                 &mut err,
272                 &format!("hidden type `{}` captures ", hidden_ty),
273                 hidden_region,
274                 "",
275             );
276             if let Some(reg_info) = tcx.is_suitable_region(hidden_region) {
277                 let fn_returns = tcx.return_type_impl_or_dyn_traits(reg_info.def_id);
278                 nice_region_error::suggest_new_region_bound(
279                     tcx,
280                     &mut err,
281                     fn_returns,
282                     hidden_region.to_string(),
283                     None,
284                     format!("captures `{}`", hidden_region),
285                     None,
286                 )
287             }
288         }
289         _ => {
290             // Ugh. This is a painful case: the hidden region is not one
291             // that we can easily summarize or explain. This can happen
292             // in a case like
293             // `src/test/ui/multiple-lifetimes/ordinary-bounds-unsuited.rs`:
294             //
295             // ```
296             // fn upper_bounds<'a, 'b>(a: Ordinary<'a>, b: Ordinary<'b>) -> impl Trait<'a, 'b> {
297             //   if condition() { a } else { b }
298             // }
299             // ```
300             //
301             // Here the captured lifetime is the intersection of `'a` and
302             // `'b`, which we can't quite express.
303
304             // We can at least report a really cryptic error for now.
305             note_and_explain_region(
306                 tcx,
307                 &mut err,
308                 &format!("hidden type `{}` captures ", hidden_ty),
309                 hidden_region,
310                 "",
311                 None,
312             );
313         }
314     }
315
316     err
317 }
318
319 /// Structurally compares two types, modulo any inference variables.
320 ///
321 /// Returns `true` if two types are equal, or if one type is an inference variable compatible
322 /// with the other type. A TyVar inference type is compatible with any type, and an IntVar or
323 /// FloatVar inference type are compatible with themselves or their concrete types (Int and
324 /// Float types, respectively). When comparing two ADTs, these rules apply recursively.
325 pub fn same_type_modulo_infer<'tcx>(a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
326     match (&a.kind(), &b.kind()) {
327         (&ty::Adt(did_a, substs_a), &ty::Adt(did_b, substs_b)) => {
328             if did_a != did_b {
329                 return false;
330             }
331
332             substs_a.types().zip(substs_b.types()).all(|(a, b)| same_type_modulo_infer(a, b))
333         }
334         (&ty::Int(_), &ty::Infer(ty::InferTy::IntVar(_)))
335         | (&ty::Infer(ty::InferTy::IntVar(_)), &ty::Int(_) | &ty::Infer(ty::InferTy::IntVar(_)))
336         | (&ty::Float(_), &ty::Infer(ty::InferTy::FloatVar(_)))
337         | (
338             &ty::Infer(ty::InferTy::FloatVar(_)),
339             &ty::Float(_) | &ty::Infer(ty::InferTy::FloatVar(_)),
340         )
341         | (&ty::Infer(ty::InferTy::TyVar(_)), _)
342         | (_, &ty::Infer(ty::InferTy::TyVar(_))) => true,
343         (&ty::Ref(_, ty_a, mut_a), &ty::Ref(_, ty_b, mut_b)) => {
344             mut_a == mut_b && same_type_modulo_infer(*ty_a, *ty_b)
345         }
346         _ => a == b,
347     }
348 }
349
350 impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
351     pub fn report_region_errors(
352         &self,
353         generic_param_scope: LocalDefId,
354         errors: &[RegionResolutionError<'tcx>],
355     ) {
356         debug!("report_region_errors(): {} errors to start", errors.len());
357
358         // try to pre-process the errors, which will group some of them
359         // together into a `ProcessedErrors` group:
360         let errors = self.process_errors(errors);
361
362         debug!("report_region_errors: {} errors after preprocessing", errors.len());
363
364         for error in errors {
365             debug!("report_region_errors: error = {:?}", error);
366
367             if !self.try_report_nice_region_error(&error) {
368                 match error.clone() {
369                     // These errors could indicate all manner of different
370                     // problems with many different solutions. Rather
371                     // than generate a "one size fits all" error, what we
372                     // attempt to do is go through a number of specific
373                     // scenarios and try to find the best way to present
374                     // the error. If all of these fails, we fall back to a rather
375                     // general bit of code that displays the error information
376                     RegionResolutionError::ConcreteFailure(origin, sub, sup) => {
377                         if sub.is_placeholder() || sup.is_placeholder() {
378                             self.report_placeholder_failure(origin, sub, sup).emit();
379                         } else {
380                             self.report_concrete_failure(origin, sub, sup).emit();
381                         }
382                     }
383
384                     RegionResolutionError::GenericBoundFailure(origin, param_ty, sub) => {
385                         self.report_generic_bound_failure(
386                             generic_param_scope,
387                             origin.span(),
388                             Some(origin),
389                             param_ty,
390                             sub,
391                         );
392                     }
393
394                     RegionResolutionError::SubSupConflict(
395                         _,
396                         var_origin,
397                         sub_origin,
398                         sub_r,
399                         sup_origin,
400                         sup_r,
401                         _,
402                     ) => {
403                         if sub_r.is_placeholder() {
404                             self.report_placeholder_failure(sub_origin, sub_r, sup_r).emit();
405                         } else if sup_r.is_placeholder() {
406                             self.report_placeholder_failure(sup_origin, sub_r, sup_r).emit();
407                         } else {
408                             self.report_sub_sup_conflict(
409                                 var_origin, sub_origin, sub_r, sup_origin, sup_r,
410                             );
411                         }
412                     }
413
414                     RegionResolutionError::UpperBoundUniverseConflict(
415                         _,
416                         _,
417                         var_universe,
418                         sup_origin,
419                         sup_r,
420                     ) => {
421                         assert!(sup_r.is_placeholder());
422
423                         // Make a dummy value for the "sub region" --
424                         // this is the initial value of the
425                         // placeholder. In practice, we expect more
426                         // tailored errors that don't really use this
427                         // value.
428                         let sub_r = self.tcx.mk_region(ty::ReEmpty(var_universe));
429
430                         self.report_placeholder_failure(sup_origin, sub_r, sup_r).emit();
431                     }
432                 }
433             }
434         }
435     }
436
437     // This method goes through all the errors and try to group certain types
438     // of error together, for the purpose of suggesting explicit lifetime
439     // parameters to the user. This is done so that we can have a more
440     // complete view of what lifetimes should be the same.
441     // If the return value is an empty vector, it means that processing
442     // failed (so the return value of this method should not be used).
443     //
444     // The method also attempts to weed out messages that seem like
445     // duplicates that will be unhelpful to the end-user. But
446     // obviously it never weeds out ALL errors.
447     fn process_errors(
448         &self,
449         errors: &[RegionResolutionError<'tcx>],
450     ) -> Vec<RegionResolutionError<'tcx>> {
451         debug!("process_errors()");
452
453         // We want to avoid reporting generic-bound failures if we can
454         // avoid it: these have a very high rate of being unhelpful in
455         // practice. This is because they are basically secondary
456         // checks that test the state of the region graph after the
457         // rest of inference is done, and the other kinds of errors
458         // indicate that the region constraint graph is internally
459         // inconsistent, so these test results are likely to be
460         // meaningless.
461         //
462         // Therefore, we filter them out of the list unless they are
463         // the only thing in the list.
464
465         let is_bound_failure = |e: &RegionResolutionError<'tcx>| match *e {
466             RegionResolutionError::GenericBoundFailure(..) => true,
467             RegionResolutionError::ConcreteFailure(..)
468             | RegionResolutionError::SubSupConflict(..)
469             | RegionResolutionError::UpperBoundUniverseConflict(..) => false,
470         };
471
472         let mut errors = if errors.iter().all(|e| is_bound_failure(e)) {
473             errors.to_owned()
474         } else {
475             errors.iter().filter(|&e| !is_bound_failure(e)).cloned().collect()
476         };
477
478         // sort the errors by span, for better error message stability.
479         errors.sort_by_key(|u| match *u {
480             RegionResolutionError::ConcreteFailure(ref sro, _, _) => sro.span(),
481             RegionResolutionError::GenericBoundFailure(ref sro, _, _) => sro.span(),
482             RegionResolutionError::SubSupConflict(_, ref rvo, _, _, _, _, _) => rvo.span(),
483             RegionResolutionError::UpperBoundUniverseConflict(_, ref rvo, _, _, _) => rvo.span(),
484         });
485         errors
486     }
487
488     /// Adds a note if the types come from similarly named crates
489     fn check_and_note_conflicting_crates(&self, err: &mut Diagnostic, terr: &TypeError<'tcx>) {
490         use hir::def_id::CrateNum;
491         use rustc_hir::definitions::DisambiguatedDefPathData;
492         use ty::print::Printer;
493         use ty::subst::GenericArg;
494
495         struct AbsolutePathPrinter<'tcx> {
496             tcx: TyCtxt<'tcx>,
497         }
498
499         struct NonTrivialPath;
500
501         impl<'tcx> Printer<'tcx> for AbsolutePathPrinter<'tcx> {
502             type Error = NonTrivialPath;
503
504             type Path = Vec<String>;
505             type Region = !;
506             type Type = !;
507             type DynExistential = !;
508             type Const = !;
509
510             fn tcx<'a>(&'a self) -> TyCtxt<'tcx> {
511                 self.tcx
512             }
513
514             fn print_region(self, _region: ty::Region<'_>) -> Result<Self::Region, Self::Error> {
515                 Err(NonTrivialPath)
516             }
517
518             fn print_type(self, _ty: Ty<'tcx>) -> Result<Self::Type, Self::Error> {
519                 Err(NonTrivialPath)
520             }
521
522             fn print_dyn_existential(
523                 self,
524                 _predicates: &'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>,
525             ) -> Result<Self::DynExistential, Self::Error> {
526                 Err(NonTrivialPath)
527             }
528
529             fn print_const(self, _ct: ty::Const<'tcx>) -> Result<Self::Const, Self::Error> {
530                 Err(NonTrivialPath)
531             }
532
533             fn path_crate(self, cnum: CrateNum) -> Result<Self::Path, Self::Error> {
534                 Ok(vec![self.tcx.crate_name(cnum).to_string()])
535             }
536             fn path_qualified(
537                 self,
538                 _self_ty: Ty<'tcx>,
539                 _trait_ref: Option<ty::TraitRef<'tcx>>,
540             ) -> Result<Self::Path, Self::Error> {
541                 Err(NonTrivialPath)
542             }
543
544             fn path_append_impl(
545                 self,
546                 _print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
547                 _disambiguated_data: &DisambiguatedDefPathData,
548                 _self_ty: Ty<'tcx>,
549                 _trait_ref: Option<ty::TraitRef<'tcx>>,
550             ) -> Result<Self::Path, Self::Error> {
551                 Err(NonTrivialPath)
552             }
553             fn path_append(
554                 self,
555                 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
556                 disambiguated_data: &DisambiguatedDefPathData,
557             ) -> Result<Self::Path, Self::Error> {
558                 let mut path = print_prefix(self)?;
559                 path.push(disambiguated_data.to_string());
560                 Ok(path)
561             }
562             fn path_generic_args(
563                 self,
564                 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
565                 _args: &[GenericArg<'tcx>],
566             ) -> Result<Self::Path, Self::Error> {
567                 print_prefix(self)
568             }
569         }
570
571         let report_path_match = |err: &mut Diagnostic, did1: DefId, did2: DefId| {
572             // Only external crates, if either is from a local
573             // module we could have false positives
574             if !(did1.is_local() || did2.is_local()) && did1.krate != did2.krate {
575                 let abs_path =
576                     |def_id| AbsolutePathPrinter { tcx: self.tcx }.print_def_path(def_id, &[]);
577
578                 // We compare strings because DefPath can be different
579                 // for imported and non-imported crates
580                 let same_path = || -> Result<_, NonTrivialPath> {
581                     Ok(self.tcx.def_path_str(did1) == self.tcx.def_path_str(did2)
582                         || abs_path(did1)? == abs_path(did2)?)
583                 };
584                 if same_path().unwrap_or(false) {
585                     let crate_name = self.tcx.crate_name(did1.krate);
586                     err.note(&format!(
587                         "perhaps two different versions of crate `{}` are being used?",
588                         crate_name
589                     ));
590                 }
591             }
592         };
593         match *terr {
594             TypeError::Sorts(ref exp_found) => {
595                 // if they are both "path types", there's a chance of ambiguity
596                 // due to different versions of the same crate
597                 if let (&ty::Adt(exp_adt, _), &ty::Adt(found_adt, _)) =
598                     (exp_found.expected.kind(), exp_found.found.kind())
599                 {
600                     report_path_match(err, exp_adt.did(), found_adt.did());
601                 }
602             }
603             TypeError::Traits(ref exp_found) => {
604                 report_path_match(err, exp_found.expected, exp_found.found);
605             }
606             _ => (), // FIXME(#22750) handle traits and stuff
607         }
608     }
609
610     fn note_error_origin(
611         &self,
612         err: &mut Diagnostic,
613         cause: &ObligationCause<'tcx>,
614         exp_found: Option<ty::error::ExpectedFound<Ty<'tcx>>>,
615         terr: &TypeError<'tcx>,
616     ) {
617         match *cause.code() {
618             ObligationCauseCode::Pattern { origin_expr: true, span: Some(span), root_ty } => {
619                 let ty = self.resolve_vars_if_possible(root_ty);
620                 if !matches!(ty.kind(), ty::Infer(ty::InferTy::TyVar(_) | ty::InferTy::FreshTy(_)))
621                 {
622                     // don't show type `_`
623                     if span.desugaring_kind() == Some(DesugaringKind::ForLoop)
624                     && let ty::Adt(def, substs) = ty.kind()
625                     && Some(def.did()) == self.tcx.get_diagnostic_item(sym::Option)
626                     {
627                         err.span_label(span, format!("this is an iterator with items of type `{}`", substs.type_at(0)));
628                     } else {
629                         err.span_label(span, format!("this expression has type `{}`", ty));
630                     }
631                 }
632                 if let Some(ty::error::ExpectedFound { found, .. }) = exp_found
633                     && ty.is_box() && ty.boxed_ty() == found
634                     && let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span)
635                 {
636                     err.span_suggestion(
637                         span,
638                         "consider dereferencing the boxed value",
639                         format!("*{}", snippet),
640                         Applicability::MachineApplicable,
641                     );
642                 }
643             }
644             ObligationCauseCode::Pattern { origin_expr: false, span: Some(span), .. } => {
645                 err.span_label(span, "expected due to this");
646             }
647             ObligationCauseCode::MatchExpressionArm(box MatchExpressionArmCause {
648                 semi_span,
649                 source,
650                 ref prior_arms,
651                 last_ty,
652                 scrut_hir_id,
653                 opt_suggest_box_span,
654                 arm_span,
655                 scrut_span,
656                 ..
657             }) => match source {
658                 hir::MatchSource::TryDesugar => {
659                     if let Some(ty::error::ExpectedFound { expected, .. }) = exp_found {
660                         let scrut_expr = self.tcx.hir().expect_expr(scrut_hir_id);
661                         let scrut_ty = if let hir::ExprKind::Call(_, args) = &scrut_expr.kind {
662                             let arg_expr = args.first().expect("try desugaring call w/out arg");
663                             self.in_progress_typeck_results.and_then(|typeck_results| {
664                                 typeck_results.borrow().expr_ty_opt(arg_expr)
665                             })
666                         } else {
667                             bug!("try desugaring w/out call expr as scrutinee");
668                         };
669
670                         match scrut_ty {
671                             Some(ty) if expected == ty => {
672                                 let source_map = self.tcx.sess.source_map();
673                                 err.span_suggestion(
674                                     source_map.end_point(cause.span),
675                                     "try removing this `?`",
676                                     "",
677                                     Applicability::MachineApplicable,
678                                 );
679                             }
680                             _ => {}
681                         }
682                     }
683                 }
684                 _ => {
685                     // `last_ty` can be `!`, `expected` will have better info when present.
686                     let t = self.resolve_vars_if_possible(match exp_found {
687                         Some(ty::error::ExpectedFound { expected, .. }) => expected,
688                         _ => last_ty,
689                     });
690                     let source_map = self.tcx.sess.source_map();
691                     let mut any_multiline_arm = source_map.is_multiline(arm_span);
692                     if prior_arms.len() <= 4 {
693                         for sp in prior_arms {
694                             any_multiline_arm |= source_map.is_multiline(*sp);
695                             err.span_label(*sp, format!("this is found to be of type `{}`", t));
696                         }
697                     } else if let Some(sp) = prior_arms.last() {
698                         any_multiline_arm |= source_map.is_multiline(*sp);
699                         err.span_label(
700                             *sp,
701                             format!("this and all prior arms are found to be of type `{}`", t),
702                         );
703                     }
704                     let outer_error_span = if any_multiline_arm {
705                         // Cover just `match` and the scrutinee expression, not
706                         // the entire match body, to reduce diagram noise.
707                         cause.span.shrink_to_lo().to(scrut_span)
708                     } else {
709                         cause.span
710                     };
711                     let msg = "`match` arms have incompatible types";
712                     err.span_label(outer_error_span, msg);
713                     if let Some((sp, boxed)) = semi_span {
714                         if let (StatementAsExpression::NeedsBoxing, [.., prior_arm]) =
715                             (boxed, &prior_arms[..])
716                         {
717                             err.multipart_suggestion(
718                                 "consider removing this semicolon and boxing the expressions",
719                                 vec![
720                                     (prior_arm.shrink_to_lo(), "Box::new(".to_string()),
721                                     (prior_arm.shrink_to_hi(), ")".to_string()),
722                                     (arm_span.shrink_to_lo(), "Box::new(".to_string()),
723                                     (arm_span.shrink_to_hi(), ")".to_string()),
724                                     (sp, String::new()),
725                                 ],
726                                 Applicability::HasPlaceholders,
727                             );
728                         } else if matches!(boxed, StatementAsExpression::NeedsBoxing) {
729                             err.span_suggestion_short(
730                                 sp,
731                                 "consider removing this semicolon and boxing the expressions",
732                                 "",
733                                 Applicability::MachineApplicable,
734                             );
735                         } else {
736                             err.span_suggestion_short(
737                                 sp,
738                                 "consider removing this semicolon",
739                                 "",
740                                 Applicability::MachineApplicable,
741                             );
742                         }
743                     }
744                     if let Some(ret_sp) = opt_suggest_box_span {
745                         // Get return type span and point to it.
746                         self.suggest_boxing_for_return_impl_trait(
747                             err,
748                             ret_sp,
749                             prior_arms.iter().chain(std::iter::once(&arm_span)).map(|s| *s),
750                         );
751                     }
752                 }
753             },
754             ObligationCauseCode::IfExpression(box IfExpressionCause {
755                 then,
756                 else_sp,
757                 outer,
758                 semicolon,
759                 opt_suggest_box_span,
760             }) => {
761                 err.span_label(then, "expected because of this");
762                 if let Some(sp) = outer {
763                     err.span_label(sp, "`if` and `else` have incompatible types");
764                 }
765                 if let Some((sp, boxed)) = semicolon {
766                     if matches!(boxed, StatementAsExpression::NeedsBoxing) {
767                         err.multipart_suggestion(
768                             "consider removing this semicolon and boxing the expression",
769                             vec![
770                                 (then.shrink_to_lo(), "Box::new(".to_string()),
771                                 (then.shrink_to_hi(), ")".to_string()),
772                                 (else_sp.shrink_to_lo(), "Box::new(".to_string()),
773                                 (else_sp.shrink_to_hi(), ")".to_string()),
774                                 (sp, String::new()),
775                             ],
776                             Applicability::MachineApplicable,
777                         );
778                     } else {
779                         err.span_suggestion_short(
780                             sp,
781                             "consider removing this semicolon",
782                             "",
783                             Applicability::MachineApplicable,
784                         );
785                     }
786                 }
787                 if let Some(ret_sp) = opt_suggest_box_span {
788                     self.suggest_boxing_for_return_impl_trait(
789                         err,
790                         ret_sp,
791                         [then, else_sp].into_iter(),
792                     );
793                 }
794             }
795             ObligationCauseCode::LetElse => {
796                 err.help("try adding a diverging expression, such as `return` or `panic!(..)`");
797                 err.help("...or use `match` instead of `let...else`");
798             }
799             _ => {
800                 if let ObligationCauseCode::BindingObligation(_, binding_span) =
801                     cause.code().peel_derives()
802                 {
803                     if matches!(terr, TypeError::RegionsPlaceholderMismatch) {
804                         err.span_note(*binding_span, "the lifetime requirement is introduced here");
805                     }
806                 }
807             }
808         }
809     }
810
811     fn suggest_boxing_for_return_impl_trait(
812         &self,
813         err: &mut Diagnostic,
814         return_sp: Span,
815         arm_spans: impl Iterator<Item = Span>,
816     ) {
817         err.multipart_suggestion(
818             "you could change the return type to be a boxed trait object",
819             vec![
820                 (return_sp.with_hi(return_sp.lo() + BytePos(4)), "Box<dyn".to_string()),
821                 (return_sp.shrink_to_hi(), ">".to_string()),
822             ],
823             Applicability::MaybeIncorrect,
824         );
825         let sugg = arm_spans
826             .flat_map(|sp| {
827                 [(sp.shrink_to_lo(), "Box::new(".to_string()), (sp.shrink_to_hi(), ")".to_string())]
828                     .into_iter()
829             })
830             .collect::<Vec<_>>();
831         err.multipart_suggestion(
832             "if you change the return type to expect trait objects, box the returned expressions",
833             sugg,
834             Applicability::MaybeIncorrect,
835         );
836     }
837
838     /// Given that `other_ty` is the same as a type argument for `name` in `sub`, populate `value`
839     /// highlighting `name` and every type argument that isn't at `pos` (which is `other_ty`), and
840     /// populate `other_value` with `other_ty`.
841     ///
842     /// ```text
843     /// Foo<Bar<Qux>>
844     /// ^^^^--------^ this is highlighted
845     /// |   |
846     /// |   this type argument is exactly the same as the other type, not highlighted
847     /// this is highlighted
848     /// Bar<Qux>
849     /// -------- this type is the same as a type argument in the other type, not highlighted
850     /// ```
851     fn highlight_outer(
852         &self,
853         value: &mut DiagnosticStyledString,
854         other_value: &mut DiagnosticStyledString,
855         name: String,
856         sub: ty::subst::SubstsRef<'tcx>,
857         pos: usize,
858         other_ty: Ty<'tcx>,
859     ) {
860         // `value` and `other_value` hold two incomplete type representation for display.
861         // `name` is the path of both types being compared. `sub`
862         value.push_highlighted(name);
863         let len = sub.len();
864         if len > 0 {
865             value.push_highlighted("<");
866         }
867
868         // Output the lifetimes for the first type
869         let lifetimes = sub
870             .regions()
871             .map(|lifetime| {
872                 let s = lifetime.to_string();
873                 if s.is_empty() { "'_".to_string() } else { s }
874             })
875             .collect::<Vec<_>>()
876             .join(", ");
877         if !lifetimes.is_empty() {
878             if sub.regions().count() < len {
879                 value.push_normal(lifetimes + ", ");
880             } else {
881                 value.push_normal(lifetimes);
882             }
883         }
884
885         // Highlight all the type arguments that aren't at `pos` and compare the type argument at
886         // `pos` and `other_ty`.
887         for (i, type_arg) in sub.types().enumerate() {
888             if i == pos {
889                 let values = self.cmp(type_arg, other_ty);
890                 value.0.extend((values.0).0);
891                 other_value.0.extend((values.1).0);
892             } else {
893                 value.push_highlighted(type_arg.to_string());
894             }
895
896             if len > 0 && i != len - 1 {
897                 value.push_normal(", ");
898             }
899         }
900         if len > 0 {
901             value.push_highlighted(">");
902         }
903     }
904
905     /// If `other_ty` is the same as a type argument present in `sub`, highlight `path` in `t1_out`,
906     /// as that is the difference to the other type.
907     ///
908     /// For the following code:
909     ///
910     /// ```ignore (illustrative)
911     /// let x: Foo<Bar<Qux>> = foo::<Bar<Qux>>();
912     /// ```
913     ///
914     /// The type error output will behave in the following way:
915     ///
916     /// ```text
917     /// Foo<Bar<Qux>>
918     /// ^^^^--------^ this is highlighted
919     /// |   |
920     /// |   this type argument is exactly the same as the other type, not highlighted
921     /// this is highlighted
922     /// Bar<Qux>
923     /// -------- this type is the same as a type argument in the other type, not highlighted
924     /// ```
925     fn cmp_type_arg(
926         &self,
927         mut t1_out: &mut DiagnosticStyledString,
928         mut t2_out: &mut DiagnosticStyledString,
929         path: String,
930         sub: &'tcx [ty::GenericArg<'tcx>],
931         other_path: String,
932         other_ty: Ty<'tcx>,
933     ) -> Option<()> {
934         // FIXME/HACK: Go back to `SubstsRef` to use its inherent methods,
935         // ideally that shouldn't be necessary.
936         let sub = self.tcx.intern_substs(sub);
937         for (i, ta) in sub.types().enumerate() {
938             if ta == other_ty {
939                 self.highlight_outer(&mut t1_out, &mut t2_out, path, sub, i, other_ty);
940                 return Some(());
941             }
942             if let ty::Adt(def, _) = ta.kind() {
943                 let path_ = self.tcx.def_path_str(def.did());
944                 if path_ == other_path {
945                     self.highlight_outer(&mut t1_out, &mut t2_out, path, sub, i, other_ty);
946                     return Some(());
947                 }
948             }
949         }
950         None
951     }
952
953     /// Adds a `,` to the type representation only if it is appropriate.
954     fn push_comma(
955         &self,
956         value: &mut DiagnosticStyledString,
957         other_value: &mut DiagnosticStyledString,
958         len: usize,
959         pos: usize,
960     ) {
961         if len > 0 && pos != len - 1 {
962             value.push_normal(", ");
963             other_value.push_normal(", ");
964         }
965     }
966
967     /// Given two `fn` signatures highlight only sub-parts that are different.
968     fn cmp_fn_sig(
969         &self,
970         sig1: &ty::PolyFnSig<'tcx>,
971         sig2: &ty::PolyFnSig<'tcx>,
972     ) -> (DiagnosticStyledString, DiagnosticStyledString) {
973         let get_lifetimes = |sig| {
974             use rustc_hir::def::Namespace;
975             let (_, sig, reg) = ty::print::FmtPrinter::new(self.tcx, Namespace::TypeNS)
976                 .name_all_regions(sig)
977                 .unwrap();
978             let lts: Vec<String> = reg.into_iter().map(|(_, kind)| kind.to_string()).collect();
979             (if lts.is_empty() { String::new() } else { format!("for<{}> ", lts.join(", ")) }, sig)
980         };
981
982         let (lt1, sig1) = get_lifetimes(sig1);
983         let (lt2, sig2) = get_lifetimes(sig2);
984
985         // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
986         let mut values = (
987             DiagnosticStyledString::normal("".to_string()),
988             DiagnosticStyledString::normal("".to_string()),
989         );
990
991         // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
992         // ^^^^^^
993         values.0.push(sig1.unsafety.prefix_str(), sig1.unsafety != sig2.unsafety);
994         values.1.push(sig2.unsafety.prefix_str(), sig1.unsafety != sig2.unsafety);
995
996         // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
997         //        ^^^^^^^^^^
998         if sig1.abi != abi::Abi::Rust {
999             values.0.push(format!("extern {} ", sig1.abi), sig1.abi != sig2.abi);
1000         }
1001         if sig2.abi != abi::Abi::Rust {
1002             values.1.push(format!("extern {} ", sig2.abi), sig1.abi != sig2.abi);
1003         }
1004
1005         // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
1006         //                   ^^^^^^^^
1007         let lifetime_diff = lt1 != lt2;
1008         values.0.push(lt1, lifetime_diff);
1009         values.1.push(lt2, lifetime_diff);
1010
1011         // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
1012         //                           ^^^
1013         values.0.push_normal("fn(");
1014         values.1.push_normal("fn(");
1015
1016         // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
1017         //                              ^^^^^
1018         let len1 = sig1.inputs().len();
1019         let len2 = sig2.inputs().len();
1020         if len1 == len2 {
1021             for (i, (l, r)) in iter::zip(sig1.inputs(), sig2.inputs()).enumerate() {
1022                 let (x1, x2) = self.cmp(*l, *r);
1023                 (values.0).0.extend(x1.0);
1024                 (values.1).0.extend(x2.0);
1025                 self.push_comma(&mut values.0, &mut values.1, len1, i);
1026             }
1027         } else {
1028             for (i, l) in sig1.inputs().iter().enumerate() {
1029                 values.0.push_highlighted(l.to_string());
1030                 if i != len1 - 1 {
1031                     values.0.push_highlighted(", ");
1032                 }
1033             }
1034             for (i, r) in sig2.inputs().iter().enumerate() {
1035                 values.1.push_highlighted(r.to_string());
1036                 if i != len2 - 1 {
1037                     values.1.push_highlighted(", ");
1038                 }
1039             }
1040         }
1041
1042         if sig1.c_variadic {
1043             if len1 > 0 {
1044                 values.0.push_normal(", ");
1045             }
1046             values.0.push("...", !sig2.c_variadic);
1047         }
1048         if sig2.c_variadic {
1049             if len2 > 0 {
1050                 values.1.push_normal(", ");
1051             }
1052             values.1.push("...", !sig1.c_variadic);
1053         }
1054
1055         // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
1056         //                                   ^
1057         values.0.push_normal(")");
1058         values.1.push_normal(")");
1059
1060         // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
1061         //                                     ^^^^^^^^
1062         let output1 = sig1.output();
1063         let output2 = sig2.output();
1064         let (x1, x2) = self.cmp(output1, output2);
1065         if !output1.is_unit() {
1066             values.0.push_normal(" -> ");
1067             (values.0).0.extend(x1.0);
1068         }
1069         if !output2.is_unit() {
1070             values.1.push_normal(" -> ");
1071             (values.1).0.extend(x2.0);
1072         }
1073         values
1074     }
1075
1076     /// Compares two given types, eliding parts that are the same between them and highlighting
1077     /// relevant differences, and return two representation of those types for highlighted printing.
1078     pub fn cmp(
1079         &self,
1080         t1: Ty<'tcx>,
1081         t2: Ty<'tcx>,
1082     ) -> (DiagnosticStyledString, DiagnosticStyledString) {
1083         debug!("cmp(t1={}, t1.kind={:?}, t2={}, t2.kind={:?})", t1, t1.kind(), t2, t2.kind());
1084
1085         // helper functions
1086         fn equals<'tcx>(a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
1087             match (a.kind(), b.kind()) {
1088                 (a, b) if *a == *b => true,
1089                 (&ty::Int(_), &ty::Infer(ty::InferTy::IntVar(_)))
1090                 | (
1091                     &ty::Infer(ty::InferTy::IntVar(_)),
1092                     &ty::Int(_) | &ty::Infer(ty::InferTy::IntVar(_)),
1093                 )
1094                 | (&ty::Float(_), &ty::Infer(ty::InferTy::FloatVar(_)))
1095                 | (
1096                     &ty::Infer(ty::InferTy::FloatVar(_)),
1097                     &ty::Float(_) | &ty::Infer(ty::InferTy::FloatVar(_)),
1098                 ) => true,
1099                 _ => false,
1100             }
1101         }
1102
1103         fn push_ty_ref<'tcx>(
1104             region: ty::Region<'tcx>,
1105             ty: Ty<'tcx>,
1106             mutbl: hir::Mutability,
1107             s: &mut DiagnosticStyledString,
1108         ) {
1109             let mut r = region.to_string();
1110             if r == "'_" {
1111                 r.clear();
1112             } else {
1113                 r.push(' ');
1114             }
1115             s.push_highlighted(format!("&{}{}", r, mutbl.prefix_str()));
1116             s.push_normal(ty.to_string());
1117         }
1118
1119         // process starts here
1120         match (t1.kind(), t2.kind()) {
1121             (&ty::Adt(def1, sub1), &ty::Adt(def2, sub2)) => {
1122                 let did1 = def1.did();
1123                 let did2 = def2.did();
1124                 let sub_no_defaults_1 =
1125                     self.tcx.generics_of(did1).own_substs_no_defaults(self.tcx, sub1);
1126                 let sub_no_defaults_2 =
1127                     self.tcx.generics_of(did2).own_substs_no_defaults(self.tcx, sub2);
1128                 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
1129                 let path1 = self.tcx.def_path_str(did1);
1130                 let path2 = self.tcx.def_path_str(did2);
1131                 if did1 == did2 {
1132                     // Easy case. Replace same types with `_` to shorten the output and highlight
1133                     // the differing ones.
1134                     //     let x: Foo<Bar, Qux> = y::<Foo<Quz, Qux>>();
1135                     //     Foo<Bar, _>
1136                     //     Foo<Quz, _>
1137                     //         ---  ^ type argument elided
1138                     //         |
1139                     //         highlighted in output
1140                     values.0.push_normal(path1);
1141                     values.1.push_normal(path2);
1142
1143                     // Avoid printing out default generic parameters that are common to both
1144                     // types.
1145                     let len1 = sub_no_defaults_1.len();
1146                     let len2 = sub_no_defaults_2.len();
1147                     let common_len = cmp::min(len1, len2);
1148                     let remainder1: Vec<_> = sub1.types().skip(common_len).collect();
1149                     let remainder2: Vec<_> = sub2.types().skip(common_len).collect();
1150                     let common_default_params =
1151                         iter::zip(remainder1.iter().rev(), remainder2.iter().rev())
1152                             .filter(|(a, b)| a == b)
1153                             .count();
1154                     let len = sub1.len() - common_default_params;
1155                     let consts_offset = len - sub1.consts().count();
1156
1157                     // Only draw `<...>` if there are lifetime/type arguments.
1158                     if len > 0 {
1159                         values.0.push_normal("<");
1160                         values.1.push_normal("<");
1161                     }
1162
1163                     fn lifetime_display(lifetime: Region<'_>) -> String {
1164                         let s = lifetime.to_string();
1165                         if s.is_empty() { "'_".to_string() } else { s }
1166                     }
1167                     // At one point we'd like to elide all lifetimes here, they are irrelevant for
1168                     // all diagnostics that use this output
1169                     //
1170                     //     Foo<'x, '_, Bar>
1171                     //     Foo<'y, '_, Qux>
1172                     //         ^^  ^^  --- type arguments are not elided
1173                     //         |   |
1174                     //         |   elided as they were the same
1175                     //         not elided, they were different, but irrelevant
1176                     //
1177                     // For bound lifetimes, keep the names of the lifetimes,
1178                     // even if they are the same so that it's clear what's happening
1179                     // if we have something like
1180                     //
1181                     // for<'r, 's> fn(Inv<'r>, Inv<'s>)
1182                     // for<'r> fn(Inv<'r>, Inv<'r>)
1183                     let lifetimes = sub1.regions().zip(sub2.regions());
1184                     for (i, lifetimes) in lifetimes.enumerate() {
1185                         let l1 = lifetime_display(lifetimes.0);
1186                         let l2 = lifetime_display(lifetimes.1);
1187                         if lifetimes.0 != lifetimes.1 {
1188                             values.0.push_highlighted(l1);
1189                             values.1.push_highlighted(l2);
1190                         } else if lifetimes.0.is_late_bound() {
1191                             values.0.push_normal(l1);
1192                             values.1.push_normal(l2);
1193                         } else {
1194                             values.0.push_normal("'_");
1195                             values.1.push_normal("'_");
1196                         }
1197                         self.push_comma(&mut values.0, &mut values.1, len, i);
1198                     }
1199
1200                     // We're comparing two types with the same path, so we compare the type
1201                     // arguments for both. If they are the same, do not highlight and elide from the
1202                     // output.
1203                     //     Foo<_, Bar>
1204                     //     Foo<_, Qux>
1205                     //         ^ elided type as this type argument was the same in both sides
1206                     let type_arguments = sub1.types().zip(sub2.types());
1207                     let regions_len = sub1.regions().count();
1208                     let num_display_types = consts_offset - regions_len;
1209                     for (i, (ta1, ta2)) in type_arguments.take(num_display_types).enumerate() {
1210                         let i = i + regions_len;
1211                         if ta1 == ta2 {
1212                             values.0.push_normal("_");
1213                             values.1.push_normal("_");
1214                         } else {
1215                             let (x1, x2) = self.cmp(ta1, ta2);
1216                             (values.0).0.extend(x1.0);
1217                             (values.1).0.extend(x2.0);
1218                         }
1219                         self.push_comma(&mut values.0, &mut values.1, len, i);
1220                     }
1221
1222                     // Do the same for const arguments, if they are equal, do not highlight and
1223                     // elide them from the output.
1224                     let const_arguments = sub1.consts().zip(sub2.consts());
1225                     for (i, (ca1, ca2)) in const_arguments.enumerate() {
1226                         let i = i + consts_offset;
1227                         if ca1 == ca2 {
1228                             values.0.push_normal("_");
1229                             values.1.push_normal("_");
1230                         } else {
1231                             values.0.push_highlighted(ca1.to_string());
1232                             values.1.push_highlighted(ca2.to_string());
1233                         }
1234                         self.push_comma(&mut values.0, &mut values.1, len, i);
1235                     }
1236
1237                     // Close the type argument bracket.
1238                     // Only draw `<...>` if there are lifetime/type arguments.
1239                     if len > 0 {
1240                         values.0.push_normal(">");
1241                         values.1.push_normal(">");
1242                     }
1243                     values
1244                 } else {
1245                     // Check for case:
1246                     //     let x: Foo<Bar<Qux> = foo::<Bar<Qux>>();
1247                     //     Foo<Bar<Qux>
1248                     //         ------- this type argument is exactly the same as the other type
1249                     //     Bar<Qux>
1250                     if self
1251                         .cmp_type_arg(
1252                             &mut values.0,
1253                             &mut values.1,
1254                             path1.clone(),
1255                             sub_no_defaults_1,
1256                             path2.clone(),
1257                             t2,
1258                         )
1259                         .is_some()
1260                     {
1261                         return values;
1262                     }
1263                     // Check for case:
1264                     //     let x: Bar<Qux> = y:<Foo<Bar<Qux>>>();
1265                     //     Bar<Qux>
1266                     //     Foo<Bar<Qux>>
1267                     //         ------- this type argument is exactly the same as the other type
1268                     if self
1269                         .cmp_type_arg(
1270                             &mut values.1,
1271                             &mut values.0,
1272                             path2,
1273                             sub_no_defaults_2,
1274                             path1,
1275                             t1,
1276                         )
1277                         .is_some()
1278                     {
1279                         return values;
1280                     }
1281
1282                     // We can't find anything in common, highlight relevant part of type path.
1283                     //     let x: foo::bar::Baz<Qux> = y:<foo::bar::Bar<Zar>>();
1284                     //     foo::bar::Baz<Qux>
1285                     //     foo::bar::Bar<Zar>
1286                     //               -------- this part of the path is different
1287
1288                     let t1_str = t1.to_string();
1289                     let t2_str = t2.to_string();
1290                     let min_len = t1_str.len().min(t2_str.len());
1291
1292                     const SEPARATOR: &str = "::";
1293                     let separator_len = SEPARATOR.len();
1294                     let split_idx: usize =
1295                         iter::zip(t1_str.split(SEPARATOR), t2_str.split(SEPARATOR))
1296                             .take_while(|(mod1_str, mod2_str)| mod1_str == mod2_str)
1297                             .map(|(mod_str, _)| mod_str.len() + separator_len)
1298                             .sum();
1299
1300                     debug!(
1301                         "cmp: separator_len={}, split_idx={}, min_len={}",
1302                         separator_len, split_idx, min_len
1303                     );
1304
1305                     if split_idx >= min_len {
1306                         // paths are identical, highlight everything
1307                         (
1308                             DiagnosticStyledString::highlighted(t1_str),
1309                             DiagnosticStyledString::highlighted(t2_str),
1310                         )
1311                     } else {
1312                         let (common, uniq1) = t1_str.split_at(split_idx);
1313                         let (_, uniq2) = t2_str.split_at(split_idx);
1314                         debug!("cmp: common={}, uniq1={}, uniq2={}", common, uniq1, uniq2);
1315
1316                         values.0.push_normal(common);
1317                         values.0.push_highlighted(uniq1);
1318                         values.1.push_normal(common);
1319                         values.1.push_highlighted(uniq2);
1320
1321                         values
1322                     }
1323                 }
1324             }
1325
1326             // When finding T != &T, highlight only the borrow
1327             (&ty::Ref(r1, ref_ty1, mutbl1), _) if equals(ref_ty1, t2) => {
1328                 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
1329                 push_ty_ref(r1, ref_ty1, mutbl1, &mut values.0);
1330                 values.1.push_normal(t2.to_string());
1331                 values
1332             }
1333             (_, &ty::Ref(r2, ref_ty2, mutbl2)) if equals(t1, ref_ty2) => {
1334                 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
1335                 values.0.push_normal(t1.to_string());
1336                 push_ty_ref(r2, ref_ty2, mutbl2, &mut values.1);
1337                 values
1338             }
1339
1340             // When encountering &T != &mut T, highlight only the borrow
1341             (&ty::Ref(r1, ref_ty1, mutbl1), &ty::Ref(r2, ref_ty2, mutbl2))
1342                 if equals(ref_ty1, ref_ty2) =>
1343             {
1344                 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
1345                 push_ty_ref(r1, ref_ty1, mutbl1, &mut values.0);
1346                 push_ty_ref(r2, ref_ty2, mutbl2, &mut values.1);
1347                 values
1348             }
1349
1350             // When encountering tuples of the same size, highlight only the differing types
1351             (&ty::Tuple(substs1), &ty::Tuple(substs2)) if substs1.len() == substs2.len() => {
1352                 let mut values =
1353                     (DiagnosticStyledString::normal("("), DiagnosticStyledString::normal("("));
1354                 let len = substs1.len();
1355                 for (i, (left, right)) in substs1.iter().zip(substs2).enumerate() {
1356                     let (x1, x2) = self.cmp(left, right);
1357                     (values.0).0.extend(x1.0);
1358                     (values.1).0.extend(x2.0);
1359                     self.push_comma(&mut values.0, &mut values.1, len, i);
1360                 }
1361                 if len == 1 {
1362                     // Keep the output for single element tuples as `(ty,)`.
1363                     values.0.push_normal(",");
1364                     values.1.push_normal(",");
1365                 }
1366                 values.0.push_normal(")");
1367                 values.1.push_normal(")");
1368                 values
1369             }
1370
1371             (ty::FnDef(did1, substs1), ty::FnDef(did2, substs2)) => {
1372                 let sig1 = self.tcx.bound_fn_sig(*did1).subst(self.tcx, substs1);
1373                 let sig2 = self.tcx.bound_fn_sig(*did2).subst(self.tcx, substs2);
1374                 let mut values = self.cmp_fn_sig(&sig1, &sig2);
1375                 let path1 = format!(" {{{}}}", self.tcx.def_path_str_with_substs(*did1, substs1));
1376                 let path2 = format!(" {{{}}}", self.tcx.def_path_str_with_substs(*did2, substs2));
1377                 let same_path = path1 == path2;
1378                 values.0.push(path1, !same_path);
1379                 values.1.push(path2, !same_path);
1380                 values
1381             }
1382
1383             (ty::FnDef(did1, substs1), ty::FnPtr(sig2)) => {
1384                 let sig1 = self.tcx.bound_fn_sig(*did1).subst(self.tcx, substs1);
1385                 let mut values = self.cmp_fn_sig(&sig1, sig2);
1386                 values.0.push_highlighted(format!(
1387                     " {{{}}}",
1388                     self.tcx.def_path_str_with_substs(*did1, substs1)
1389                 ));
1390                 values
1391             }
1392
1393             (ty::FnPtr(sig1), ty::FnDef(did2, substs2)) => {
1394                 let sig2 = self.tcx.bound_fn_sig(*did2).subst(self.tcx, substs2);
1395                 let mut values = self.cmp_fn_sig(sig1, &sig2);
1396                 values.1.push_normal(format!(
1397                     " {{{}}}",
1398                     self.tcx.def_path_str_with_substs(*did2, substs2)
1399                 ));
1400                 values
1401             }
1402
1403             (ty::FnPtr(sig1), ty::FnPtr(sig2)) => self.cmp_fn_sig(sig1, sig2),
1404
1405             _ => {
1406                 if t1 == t2 {
1407                     // The two types are the same, elide and don't highlight.
1408                     (DiagnosticStyledString::normal("_"), DiagnosticStyledString::normal("_"))
1409                 } else {
1410                     // We couldn't find anything in common, highlight everything.
1411                     (
1412                         DiagnosticStyledString::highlighted(t1.to_string()),
1413                         DiagnosticStyledString::highlighted(t2.to_string()),
1414                     )
1415                 }
1416             }
1417         }
1418     }
1419
1420     /// Extend a type error with extra labels pointing at "non-trivial" types, like closures and
1421     /// the return type of `async fn`s.
1422     ///
1423     /// `secondary_span` gives the caller the opportunity to expand `diag` with a `span_label`.
1424     ///
1425     /// `swap_secondary_and_primary` is used to make projection errors in particular nicer by using
1426     /// the message in `secondary_span` as the primary label, and apply the message that would
1427     /// otherwise be used for the primary label on the `secondary_span` `Span`. This applies on
1428     /// E0271, like `src/test/ui/issues/issue-39970.stderr`.
1429     #[tracing::instrument(
1430         level = "debug",
1431         skip(self, diag, secondary_span, swap_secondary_and_primary, force_label)
1432     )]
1433     pub fn note_type_err(
1434         &self,
1435         diag: &mut Diagnostic,
1436         cause: &ObligationCause<'tcx>,
1437         secondary_span: Option<(Span, String)>,
1438         mut values: Option<ValuePairs<'tcx>>,
1439         terr: &TypeError<'tcx>,
1440         swap_secondary_and_primary: bool,
1441         force_label: bool,
1442     ) {
1443         let span = cause.span();
1444
1445         // For some types of errors, expected-found does not make
1446         // sense, so just ignore the values we were given.
1447         if let TypeError::CyclicTy(_) = terr {
1448             values = None;
1449         }
1450         struct OpaqueTypesVisitor<'tcx> {
1451             types: FxHashMap<TyCategory, FxHashSet<Span>>,
1452             expected: FxHashMap<TyCategory, FxHashSet<Span>>,
1453             found: FxHashMap<TyCategory, FxHashSet<Span>>,
1454             ignore_span: Span,
1455             tcx: TyCtxt<'tcx>,
1456         }
1457
1458         impl<'tcx> OpaqueTypesVisitor<'tcx> {
1459             fn visit_expected_found(
1460                 tcx: TyCtxt<'tcx>,
1461                 expected: Ty<'tcx>,
1462                 found: Ty<'tcx>,
1463                 ignore_span: Span,
1464             ) -> Self {
1465                 let mut types_visitor = OpaqueTypesVisitor {
1466                     types: Default::default(),
1467                     expected: Default::default(),
1468                     found: Default::default(),
1469                     ignore_span,
1470                     tcx,
1471                 };
1472                 // The visitor puts all the relevant encountered types in `self.types`, but in
1473                 // here we want to visit two separate types with no relation to each other, so we
1474                 // move the results from `types` to `expected` or `found` as appropriate.
1475                 expected.visit_with(&mut types_visitor);
1476                 std::mem::swap(&mut types_visitor.expected, &mut types_visitor.types);
1477                 found.visit_with(&mut types_visitor);
1478                 std::mem::swap(&mut types_visitor.found, &mut types_visitor.types);
1479                 types_visitor
1480             }
1481
1482             fn report(&self, err: &mut Diagnostic) {
1483                 self.add_labels_for_types(err, "expected", &self.expected);
1484                 self.add_labels_for_types(err, "found", &self.found);
1485             }
1486
1487             fn add_labels_for_types(
1488                 &self,
1489                 err: &mut Diagnostic,
1490                 target: &str,
1491                 types: &FxHashMap<TyCategory, FxHashSet<Span>>,
1492             ) {
1493                 for (key, values) in types.iter() {
1494                     let count = values.len();
1495                     let kind = key.descr();
1496                     let mut returned_async_output_error = false;
1497                     for &sp in values {
1498                         if sp.is_desugaring(DesugaringKind::Async) && !returned_async_output_error {
1499                             if [sp] != err.span.primary_spans() {
1500                                 let mut span: MultiSpan = sp.into();
1501                                 span.push_span_label(
1502                                     sp,
1503                                     format!(
1504                                         "checked the `Output` of this `async fn`, {}{} {}{}",
1505                                         if count > 1 { "one of the " } else { "" },
1506                                         target,
1507                                         kind,
1508                                         pluralize!(count),
1509                                     ),
1510                                 );
1511                                 err.span_note(
1512                                     span,
1513                                     "while checking the return type of the `async fn`",
1514                                 );
1515                             } else {
1516                                 err.span_label(
1517                                     sp,
1518                                     format!(
1519                                         "checked the `Output` of this `async fn`, {}{} {}{}",
1520                                         if count > 1 { "one of the " } else { "" },
1521                                         target,
1522                                         kind,
1523                                         pluralize!(count),
1524                                     ),
1525                                 );
1526                                 err.note("while checking the return type of the `async fn`");
1527                             }
1528                             returned_async_output_error = true;
1529                         } else {
1530                             err.span_label(
1531                                 sp,
1532                                 format!(
1533                                     "{}{} {}{}",
1534                                     if count == 1 { "the " } else { "one of the " },
1535                                     target,
1536                                     kind,
1537                                     pluralize!(count),
1538                                 ),
1539                             );
1540                         }
1541                     }
1542                 }
1543             }
1544         }
1545
1546         impl<'tcx> ty::visit::TypeVisitor<'tcx> for OpaqueTypesVisitor<'tcx> {
1547             fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
1548                 if let Some((kind, def_id)) = TyCategory::from_ty(self.tcx, t) {
1549                     let span = self.tcx.def_span(def_id);
1550                     // Avoid cluttering the output when the "found" and error span overlap:
1551                     //
1552                     // error[E0308]: mismatched types
1553                     //   --> $DIR/issue-20862.rs:2:5
1554                     //    |
1555                     // LL |     |y| x + y
1556                     //    |     ^^^^^^^^^
1557                     //    |     |
1558                     //    |     the found closure
1559                     //    |     expected `()`, found closure
1560                     //    |
1561                     //    = note: expected unit type `()`
1562                     //                 found closure `[closure@$DIR/issue-20862.rs:2:5: 2:14 x:_]`
1563                     if !self.ignore_span.overlaps(span) {
1564                         self.types.entry(kind).or_default().insert(span);
1565                     }
1566                 }
1567                 t.super_visit_with(self)
1568             }
1569         }
1570
1571         debug!("note_type_err(diag={:?})", diag);
1572         enum Mismatch<'a> {
1573             Variable(ty::error::ExpectedFound<Ty<'a>>),
1574             Fixed(&'static str),
1575         }
1576         let (expected_found, exp_found, is_simple_error, values) = match values {
1577             None => (None, Mismatch::Fixed("type"), false, None),
1578             Some(values) => {
1579                 let values = self.resolve_vars_if_possible(values);
1580                 let (is_simple_error, exp_found) = match values {
1581                     ValuePairs::Terms(infer::ExpectedFound {
1582                         expected: ty::Term::Ty(expected),
1583                         found: ty::Term::Ty(found),
1584                     }) => {
1585                         let is_simple_err = expected.is_simple_text() && found.is_simple_text();
1586                         OpaqueTypesVisitor::visit_expected_found(self.tcx, expected, found, span)
1587                             .report(diag);
1588
1589                         (
1590                             is_simple_err,
1591                             Mismatch::Variable(infer::ExpectedFound { expected, found }),
1592                         )
1593                     }
1594                     ValuePairs::TraitRefs(_) | ValuePairs::PolyTraitRefs(_) => {
1595                         (false, Mismatch::Fixed("trait"))
1596                     }
1597                     _ => (false, Mismatch::Fixed("type")),
1598                 };
1599                 let vals = match self.values_str(values) {
1600                     Some((expected, found)) => Some((expected, found)),
1601                     None => {
1602                         // Derived error. Cancel the emitter.
1603                         // NOTE(eddyb) this was `.cancel()`, but `diag`
1604                         // is borrowed, so we can't fully defuse it.
1605                         diag.downgrade_to_delayed_bug();
1606                         return;
1607                     }
1608                 };
1609                 (vals, exp_found, is_simple_error, Some(values))
1610             }
1611         };
1612
1613         match terr {
1614             // Ignore msg for object safe coercion
1615             // since E0038 message will be printed
1616             TypeError::ObjectUnsafeCoercion(_) => {}
1617             _ => {
1618                 let mut label_or_note = |span: Span, msg: &str| {
1619                     if force_label || &[span] == diag.span.primary_spans() {
1620                         diag.span_label(span, msg);
1621                     } else {
1622                         diag.span_note(span, msg);
1623                     }
1624                 };
1625                 if let Some((sp, msg)) = secondary_span {
1626                     if swap_secondary_and_primary {
1627                         let terr = if let Some(infer::ValuePairs::Terms(infer::ExpectedFound {
1628                             expected,
1629                             ..
1630                         })) = values
1631                         {
1632                             format!("expected this to be `{}`", expected)
1633                         } else {
1634                             terr.to_string()
1635                         };
1636                         label_or_note(sp, &terr);
1637                         label_or_note(span, &msg);
1638                     } else {
1639                         label_or_note(span, &terr.to_string());
1640                         label_or_note(sp, &msg);
1641                     }
1642                 } else {
1643                     label_or_note(span, &terr.to_string());
1644                 }
1645             }
1646         };
1647         if let Some((expected, found)) = expected_found {
1648             let (expected_label, found_label, exp_found) = match exp_found {
1649                 Mismatch::Variable(ef) => (
1650                     ef.expected.prefix_string(self.tcx),
1651                     ef.found.prefix_string(self.tcx),
1652                     Some(ef),
1653                 ),
1654                 Mismatch::Fixed(s) => (s.into(), s.into(), None),
1655             };
1656             match (&terr, expected == found) {
1657                 (TypeError::Sorts(values), extra) => {
1658                     let sort_string = |ty: Ty<'tcx>| match (extra, ty.kind()) {
1659                         (true, ty::Opaque(def_id, _)) => {
1660                             let sm = self.tcx.sess.source_map();
1661                             let pos = sm.lookup_char_pos(self.tcx.def_span(*def_id).lo());
1662                             format!(
1663                                 " (opaque type at <{}:{}:{}>)",
1664                                 sm.filename_for_diagnostics(&pos.file.name),
1665                                 pos.line,
1666                                 pos.col.to_usize() + 1,
1667                             )
1668                         }
1669                         (true, _) => format!(" ({})", ty.sort_string(self.tcx)),
1670                         (false, _) => "".to_string(),
1671                     };
1672                     if !(values.expected.is_simple_text() && values.found.is_simple_text())
1673                         || (exp_found.map_or(false, |ef| {
1674                             // This happens when the type error is a subset of the expectation,
1675                             // like when you have two references but one is `usize` and the other
1676                             // is `f32`. In those cases we still want to show the `note`. If the
1677                             // value from `ef` is `Infer(_)`, then we ignore it.
1678                             if !ef.expected.is_ty_infer() {
1679                                 ef.expected != values.expected
1680                             } else if !ef.found.is_ty_infer() {
1681                                 ef.found != values.found
1682                             } else {
1683                                 false
1684                             }
1685                         }))
1686                     {
1687                         diag.note_expected_found_extra(
1688                             &expected_label,
1689                             expected,
1690                             &found_label,
1691                             found,
1692                             &sort_string(values.expected),
1693                             &sort_string(values.found),
1694                         );
1695                     }
1696                 }
1697                 (TypeError::ObjectUnsafeCoercion(_), _) => {
1698                     diag.note_unsuccessful_coercion(found, expected);
1699                 }
1700                 (_, _) => {
1701                     debug!(
1702                         "note_type_err: exp_found={:?}, expected={:?} found={:?}",
1703                         exp_found, expected, found
1704                     );
1705                     if !is_simple_error || terr.must_include_note() {
1706                         diag.note_expected_found(&expected_label, expected, &found_label, found);
1707                     }
1708                 }
1709             }
1710         }
1711         let exp_found = match exp_found {
1712             Mismatch::Variable(exp_found) => Some(exp_found),
1713             Mismatch::Fixed(_) => None,
1714         };
1715         let exp_found = match terr {
1716             // `terr` has more accurate type information than `exp_found` in match expressions.
1717             ty::error::TypeError::Sorts(terr)
1718                 if exp_found.map_or(false, |ef| terr.found == ef.found) =>
1719             {
1720                 Some(*terr)
1721             }
1722             _ => exp_found,
1723         };
1724         debug!("exp_found {:?} terr {:?} cause.code {:?}", exp_found, terr, cause.code());
1725         if let Some(exp_found) = exp_found {
1726             let should_suggest_fixes = if let ObligationCauseCode::Pattern { root_ty, .. } =
1727                 cause.code()
1728             {
1729                 // Skip if the root_ty of the pattern is not the same as the expected_ty.
1730                 // If these types aren't equal then we've probably peeled off a layer of arrays.
1731                 same_type_modulo_infer(self.resolve_vars_if_possible(*root_ty), exp_found.expected)
1732             } else {
1733                 true
1734             };
1735
1736             if should_suggest_fixes {
1737                 self.suggest_tuple_pattern(cause, &exp_found, diag);
1738                 self.suggest_as_ref_where_appropriate(span, &exp_found, diag);
1739                 self.suggest_accessing_field_where_appropriate(cause, &exp_found, diag);
1740                 self.suggest_await_on_expect_found(cause, span, &exp_found, diag);
1741             }
1742         }
1743
1744         // In some (most?) cases cause.body_id points to actual body, but in some cases
1745         // it's an actual definition. According to the comments (e.g. in
1746         // librustc_typeck/check/compare_method.rs:compare_predicate_entailment) the latter
1747         // is relied upon by some other code. This might (or might not) need cleanup.
1748         let body_owner_def_id =
1749             self.tcx.hir().opt_local_def_id(cause.body_id).unwrap_or_else(|| {
1750                 self.tcx.hir().body_owner_def_id(hir::BodyId { hir_id: cause.body_id })
1751             });
1752         self.check_and_note_conflicting_crates(diag, terr);
1753         self.tcx.note_and_explain_type_err(diag, terr, cause, span, body_owner_def_id.to_def_id());
1754
1755         if let Some(ValuePairs::PolyTraitRefs(exp_found)) = values
1756             && let ty::Closure(def_id, _) = exp_found.expected.skip_binder().self_ty().kind()
1757             && let Some(def_id) = def_id.as_local()
1758         {
1759             let span = self.tcx.def_span(def_id);
1760             diag.span_note(span, "this closure does not fulfill the lifetime requirements");
1761         }
1762
1763         // It reads better to have the error origin as the final
1764         // thing.
1765         self.note_error_origin(diag, cause, exp_found, terr);
1766
1767         debug!(?diag);
1768     }
1769
1770     fn suggest_tuple_pattern(
1771         &self,
1772         cause: &ObligationCause<'tcx>,
1773         exp_found: &ty::error::ExpectedFound<Ty<'tcx>>,
1774         diag: &mut Diagnostic,
1775     ) {
1776         // Heavily inspired by `FnCtxt::suggest_compatible_variants`, with
1777         // some modifications due to that being in typeck and this being in infer.
1778         if let ObligationCauseCode::Pattern { .. } = cause.code() {
1779             if let ty::Adt(expected_adt, substs) = exp_found.expected.kind() {
1780                 let compatible_variants: Vec<_> = expected_adt
1781                     .variants()
1782                     .iter()
1783                     .filter(|variant| {
1784                         variant.fields.len() == 1 && variant.ctor_kind == hir::def::CtorKind::Fn
1785                     })
1786                     .filter_map(|variant| {
1787                         let sole_field = &variant.fields[0];
1788                         let sole_field_ty = sole_field.ty(self.tcx, substs);
1789                         if same_type_modulo_infer(sole_field_ty, exp_found.found) {
1790                             let variant_path =
1791                                 with_no_trimmed_paths!(self.tcx.def_path_str(variant.def_id));
1792                             // FIXME #56861: DRYer prelude filtering
1793                             if let Some(path) = variant_path.strip_prefix("std::prelude::") {
1794                                 if let Some((_, path)) = path.split_once("::") {
1795                                     return Some(path.to_string());
1796                                 }
1797                             }
1798                             Some(variant_path)
1799                         } else {
1800                             None
1801                         }
1802                     })
1803                     .collect();
1804                 match &compatible_variants[..] {
1805                     [] => {}
1806                     [variant] => {
1807                         diag.multipart_suggestion_verbose(
1808                             &format!("try wrapping the pattern in `{}`", variant),
1809                             vec![
1810                                 (cause.span.shrink_to_lo(), format!("{}(", variant)),
1811                                 (cause.span.shrink_to_hi(), ")".to_string()),
1812                             ],
1813                             Applicability::MaybeIncorrect,
1814                         );
1815                     }
1816                     _ => {
1817                         // More than one matching variant.
1818                         diag.multipart_suggestions(
1819                             &format!(
1820                                 "try wrapping the pattern in a variant of `{}`",
1821                                 self.tcx.def_path_str(expected_adt.did())
1822                             ),
1823                             compatible_variants.into_iter().map(|variant| {
1824                                 vec![
1825                                     (cause.span.shrink_to_lo(), format!("{}(", variant)),
1826                                     (cause.span.shrink_to_hi(), ")".to_string()),
1827                                 ]
1828                             }),
1829                             Applicability::MaybeIncorrect,
1830                         );
1831                     }
1832                 }
1833             }
1834         }
1835     }
1836
1837     pub fn get_impl_future_output_ty(&self, ty: Ty<'tcx>) -> Option<Binder<'tcx, Ty<'tcx>>> {
1838         if let ty::Opaque(def_id, substs) = ty.kind() {
1839             let future_trait = self.tcx.require_lang_item(LangItem::Future, None);
1840             // Future::Output
1841             let item_def_id = self.tcx.associated_item_def_ids(future_trait)[0];
1842
1843             let bounds = self.tcx.bound_explicit_item_bounds(*def_id);
1844
1845             for predicate in bounds.transpose_iter().map(|e| e.map_bound(|(p, _)| *p)) {
1846                 let predicate = predicate.subst(self.tcx, substs);
1847                 let output = predicate
1848                     .kind()
1849                     .map_bound(|kind| match kind {
1850                         ty::PredicateKind::Projection(projection_predicate)
1851                             if projection_predicate.projection_ty.item_def_id == item_def_id =>
1852                         {
1853                             projection_predicate.term.ty()
1854                         }
1855                         _ => None,
1856                     })
1857                     .transpose();
1858                 if output.is_some() {
1859                     // We don't account for multiple `Future::Output = Ty` constraints.
1860                     return output;
1861                 }
1862             }
1863         }
1864         None
1865     }
1866
1867     /// A possible error is to forget to add `.await` when using futures:
1868     ///
1869     /// ```compile_fail,E0308
1870     /// async fn make_u32() -> u32 {
1871     ///     22
1872     /// }
1873     ///
1874     /// fn take_u32(x: u32) {}
1875     ///
1876     /// async fn foo() {
1877     ///     let x = make_u32();
1878     ///     take_u32(x);
1879     /// }
1880     /// ```
1881     ///
1882     /// This routine checks if the found type `T` implements `Future<Output=U>` where `U` is the
1883     /// expected type. If this is the case, and we are inside of an async body, it suggests adding
1884     /// `.await` to the tail of the expression.
1885     fn suggest_await_on_expect_found(
1886         &self,
1887         cause: &ObligationCause<'tcx>,
1888         exp_span: Span,
1889         exp_found: &ty::error::ExpectedFound<Ty<'tcx>>,
1890         diag: &mut Diagnostic,
1891     ) {
1892         debug!(
1893             "suggest_await_on_expect_found: exp_span={:?}, expected_ty={:?}, found_ty={:?}",
1894             exp_span, exp_found.expected, exp_found.found,
1895         );
1896
1897         if let ObligationCauseCode::CompareImplMethodObligation { .. } = cause.code() {
1898             return;
1899         }
1900
1901         match (
1902             self.get_impl_future_output_ty(exp_found.expected).map(Binder::skip_binder),
1903             self.get_impl_future_output_ty(exp_found.found).map(Binder::skip_binder),
1904         ) {
1905             (Some(exp), Some(found)) if same_type_modulo_infer(exp, found) => match cause.code() {
1906                 ObligationCauseCode::IfExpression(box IfExpressionCause { then, .. }) => {
1907                     diag.multipart_suggestion(
1908                         "consider `await`ing on both `Future`s",
1909                         vec![
1910                             (then.shrink_to_hi(), ".await".to_string()),
1911                             (exp_span.shrink_to_hi(), ".await".to_string()),
1912                         ],
1913                         Applicability::MaybeIncorrect,
1914                     );
1915                 }
1916                 ObligationCauseCode::MatchExpressionArm(box MatchExpressionArmCause {
1917                     prior_arms,
1918                     ..
1919                 }) => {
1920                     if let [.., arm_span] = &prior_arms[..] {
1921                         diag.multipart_suggestion(
1922                             "consider `await`ing on both `Future`s",
1923                             vec![
1924                                 (arm_span.shrink_to_hi(), ".await".to_string()),
1925                                 (exp_span.shrink_to_hi(), ".await".to_string()),
1926                             ],
1927                             Applicability::MaybeIncorrect,
1928                         );
1929                     } else {
1930                         diag.help("consider `await`ing on both `Future`s");
1931                     }
1932                 }
1933                 _ => {
1934                     diag.help("consider `await`ing on both `Future`s");
1935                 }
1936             },
1937             (_, Some(ty)) if same_type_modulo_infer(exp_found.expected, ty) => {
1938                 diag.span_suggestion_verbose(
1939                     exp_span.shrink_to_hi(),
1940                     "consider `await`ing on the `Future`",
1941                     ".await",
1942                     Applicability::MaybeIncorrect,
1943                 );
1944             }
1945             (Some(ty), _) if same_type_modulo_infer(ty, exp_found.found) => match cause.code() {
1946                 ObligationCauseCode::Pattern { span: Some(span), .. }
1947                 | ObligationCauseCode::IfExpression(box IfExpressionCause { then: span, .. }) => {
1948                     diag.span_suggestion_verbose(
1949                         span.shrink_to_hi(),
1950                         "consider `await`ing on the `Future`",
1951                         ".await",
1952                         Applicability::MaybeIncorrect,
1953                     );
1954                 }
1955                 ObligationCauseCode::MatchExpressionArm(box MatchExpressionArmCause {
1956                     ref prior_arms,
1957                     ..
1958                 }) => {
1959                     diag.multipart_suggestion_verbose(
1960                         "consider `await`ing on the `Future`",
1961                         prior_arms
1962                             .iter()
1963                             .map(|arm| (arm.shrink_to_hi(), ".await".to_string()))
1964                             .collect(),
1965                         Applicability::MaybeIncorrect,
1966                     );
1967                 }
1968                 _ => {}
1969             },
1970             _ => {}
1971         }
1972     }
1973
1974     fn suggest_accessing_field_where_appropriate(
1975         &self,
1976         cause: &ObligationCause<'tcx>,
1977         exp_found: &ty::error::ExpectedFound<Ty<'tcx>>,
1978         diag: &mut Diagnostic,
1979     ) {
1980         debug!(
1981             "suggest_accessing_field_where_appropriate(cause={:?}, exp_found={:?})",
1982             cause, exp_found
1983         );
1984         if let ty::Adt(expected_def, expected_substs) = exp_found.expected.kind() {
1985             if expected_def.is_enum() {
1986                 return;
1987             }
1988
1989             if let Some((name, ty)) = expected_def
1990                 .non_enum_variant()
1991                 .fields
1992                 .iter()
1993                 .filter(|field| field.vis.is_accessible_from(field.did, self.tcx))
1994                 .map(|field| (field.name, field.ty(self.tcx, expected_substs)))
1995                 .find(|(_, ty)| same_type_modulo_infer(*ty, exp_found.found))
1996             {
1997                 if let ObligationCauseCode::Pattern { span: Some(span), .. } = *cause.code() {
1998                     if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
1999                         let suggestion = if expected_def.is_struct() {
2000                             format!("{}.{}", snippet, name)
2001                         } else if expected_def.is_union() {
2002                             format!("unsafe {{ {}.{} }}", snippet, name)
2003                         } else {
2004                             return;
2005                         };
2006                         diag.span_suggestion(
2007                             span,
2008                             &format!(
2009                                 "you might have meant to use field `{}` whose type is `{}`",
2010                                 name, ty
2011                             ),
2012                             suggestion,
2013                             Applicability::MaybeIncorrect,
2014                         );
2015                     }
2016                 }
2017             }
2018         }
2019     }
2020
2021     /// When encountering a case where `.as_ref()` on a `Result` or `Option` would be appropriate,
2022     /// suggests it.
2023     fn suggest_as_ref_where_appropriate(
2024         &self,
2025         span: Span,
2026         exp_found: &ty::error::ExpectedFound<Ty<'tcx>>,
2027         diag: &mut Diagnostic,
2028     ) {
2029         if let (ty::Adt(exp_def, exp_substs), ty::Ref(_, found_ty, _)) =
2030             (exp_found.expected.kind(), exp_found.found.kind())
2031         {
2032             if let ty::Adt(found_def, found_substs) = *found_ty.kind() {
2033                 let path_str = format!("{:?}", exp_def);
2034                 if exp_def == &found_def {
2035                     let opt_msg = "you can convert from `&Option<T>` to `Option<&T>` using \
2036                                        `.as_ref()`";
2037                     let result_msg = "you can convert from `&Result<T, E>` to \
2038                                           `Result<&T, &E>` using `.as_ref()`";
2039                     let have_as_ref = &[
2040                         ("std::option::Option", opt_msg),
2041                         ("core::option::Option", opt_msg),
2042                         ("std::result::Result", result_msg),
2043                         ("core::result::Result", result_msg),
2044                     ];
2045                     if let Some(msg) = have_as_ref
2046                         .iter()
2047                         .find_map(|(path, msg)| (&path_str == path).then_some(msg))
2048                     {
2049                         let mut show_suggestion = true;
2050                         for (exp_ty, found_ty) in
2051                             iter::zip(exp_substs.types(), found_substs.types())
2052                         {
2053                             match *exp_ty.kind() {
2054                                 ty::Ref(_, exp_ty, _) => {
2055                                     match (exp_ty.kind(), found_ty.kind()) {
2056                                         (_, ty::Param(_))
2057                                         | (_, ty::Infer(_))
2058                                         | (ty::Param(_), _)
2059                                         | (ty::Infer(_), _) => {}
2060                                         _ if same_type_modulo_infer(exp_ty, found_ty) => {}
2061                                         _ => show_suggestion = false,
2062                                     };
2063                                 }
2064                                 ty::Param(_) | ty::Infer(_) => {}
2065                                 _ => show_suggestion = false,
2066                             }
2067                         }
2068                         if let (Ok(snippet), true) =
2069                             (self.tcx.sess.source_map().span_to_snippet(span), show_suggestion)
2070                         {
2071                             diag.span_suggestion(
2072                                 span,
2073                                 *msg,
2074                                 format!("{}.as_ref()", snippet),
2075                                 Applicability::MachineApplicable,
2076                             );
2077                         }
2078                     }
2079                 }
2080             }
2081         }
2082     }
2083
2084     pub fn report_and_explain_type_error(
2085         &self,
2086         trace: TypeTrace<'tcx>,
2087         terr: &TypeError<'tcx>,
2088     ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
2089         use crate::traits::ObligationCauseCode::MatchExpressionArm;
2090
2091         debug!("report_and_explain_type_error(trace={:?}, terr={:?})", trace, terr);
2092
2093         let span = trace.cause.span();
2094         let failure_code = trace.cause.as_failure_code(terr);
2095         let mut diag = match failure_code {
2096             FailureCode::Error0038(did) => {
2097                 let violations = self.tcx.object_safety_violations(did);
2098                 report_object_safety_error(self.tcx, span, did, violations)
2099             }
2100             FailureCode::Error0317(failure_str) => {
2101                 struct_span_err!(self.tcx.sess, span, E0317, "{}", failure_str)
2102             }
2103             FailureCode::Error0580(failure_str) => {
2104                 struct_span_err!(self.tcx.sess, span, E0580, "{}", failure_str)
2105             }
2106             FailureCode::Error0308(failure_str) => {
2107                 let mut err = struct_span_err!(self.tcx.sess, span, E0308, "{}", failure_str);
2108                 if let Some((expected, found)) = trace.values.ty() {
2109                     match (expected.kind(), found.kind()) {
2110                         (ty::Tuple(_), ty::Tuple(_)) => {}
2111                         // If a tuple of length one was expected and the found expression has
2112                         // parentheses around it, perhaps the user meant to write `(expr,)` to
2113                         // build a tuple (issue #86100)
2114                         (ty::Tuple(fields), _) => {
2115                             self.emit_tuple_wrap_err(&mut err, span, found, fields)
2116                         }
2117                         // If a character was expected and the found expression is a string literal
2118                         // containing a single character, perhaps the user meant to write `'c'` to
2119                         // specify a character literal (issue #92479)
2120                         (ty::Char, ty::Ref(_, r, _)) if r.is_str() => {
2121                             if let Ok(code) = self.tcx.sess().source_map().span_to_snippet(span)
2122                                 && let Some(code) = code.strip_prefix('"').and_then(|s| s.strip_suffix('"'))
2123                                 && code.chars().count() == 1
2124                             {
2125                                 err.span_suggestion(
2126                                     span,
2127                                     "if you meant to write a `char` literal, use single quotes",
2128                                     format!("'{}'", code),
2129                                     Applicability::MachineApplicable,
2130                                 );
2131                             }
2132                         }
2133                         // If a string was expected and the found expression is a character literal,
2134                         // perhaps the user meant to write `"s"` to specify a string literal.
2135                         (ty::Ref(_, r, _), ty::Char) if r.is_str() => {
2136                             if let Ok(code) = self.tcx.sess().source_map().span_to_snippet(span) {
2137                                 if let Some(code) =
2138                                     code.strip_prefix('\'').and_then(|s| s.strip_suffix('\''))
2139                                 {
2140                                     err.span_suggestion(
2141                                         span,
2142                                         "if you meant to write a `str` literal, use double quotes",
2143                                         format!("\"{}\"", code),
2144                                         Applicability::MachineApplicable,
2145                                     );
2146                                 }
2147                             }
2148                         }
2149                         _ => {}
2150                     }
2151                 }
2152                 let code = trace.cause.code();
2153                 if let &MatchExpressionArm(box MatchExpressionArmCause { source, .. }) = code
2154                     && let hir::MatchSource::TryDesugar = source
2155                     && let Some((expected_ty, found_ty)) = self.values_str(trace.values)
2156                 {
2157                     err.note(&format!(
2158                         "`?` operator cannot convert from `{}` to `{}`",
2159                         found_ty.content(),
2160                         expected_ty.content(),
2161                     ));
2162                 }
2163                 err
2164             }
2165             FailureCode::Error0644(failure_str) => {
2166                 struct_span_err!(self.tcx.sess, span, E0644, "{}", failure_str)
2167             }
2168         };
2169         self.note_type_err(&mut diag, &trace.cause, None, Some(trace.values), terr, false, false);
2170         diag
2171     }
2172
2173     fn emit_tuple_wrap_err(
2174         &self,
2175         err: &mut Diagnostic,
2176         span: Span,
2177         found: Ty<'tcx>,
2178         expected_fields: &List<Ty<'tcx>>,
2179     ) {
2180         let [expected_tup_elem] = expected_fields[..] else { return };
2181
2182         if !same_type_modulo_infer(expected_tup_elem, found) {
2183             return;
2184         }
2185
2186         let Ok(code) = self.tcx.sess().source_map().span_to_snippet(span)
2187             else { return };
2188
2189         let msg = "use a trailing comma to create a tuple with one element";
2190         if code.starts_with('(') && code.ends_with(')') {
2191             let before_close = span.hi() - BytePos::from_u32(1);
2192             err.span_suggestion(
2193                 span.with_hi(before_close).shrink_to_hi(),
2194                 msg,
2195                 ",",
2196                 Applicability::MachineApplicable,
2197             );
2198         } else {
2199             err.multipart_suggestion(
2200                 msg,
2201                 vec![(span.shrink_to_lo(), "(".into()), (span.shrink_to_hi(), ",)".into())],
2202                 Applicability::MachineApplicable,
2203             );
2204         }
2205     }
2206
2207     fn values_str(
2208         &self,
2209         values: ValuePairs<'tcx>,
2210     ) -> Option<(DiagnosticStyledString, DiagnosticStyledString)> {
2211         match values {
2212             infer::Regions(exp_found) => self.expected_found_str(exp_found),
2213             infer::Terms(exp_found) => self.expected_found_str_term(exp_found),
2214             infer::TraitRefs(exp_found) => {
2215                 let pretty_exp_found = ty::error::ExpectedFound {
2216                     expected: exp_found.expected.print_only_trait_path(),
2217                     found: exp_found.found.print_only_trait_path(),
2218                 };
2219                 match self.expected_found_str(pretty_exp_found) {
2220                     Some((expected, found)) if expected == found => {
2221                         self.expected_found_str(exp_found)
2222                     }
2223                     ret => ret,
2224                 }
2225             }
2226             infer::PolyTraitRefs(exp_found) => {
2227                 let pretty_exp_found = ty::error::ExpectedFound {
2228                     expected: exp_found.expected.print_only_trait_path(),
2229                     found: exp_found.found.print_only_trait_path(),
2230                 };
2231                 match self.expected_found_str(pretty_exp_found) {
2232                     Some((expected, found)) if expected == found => {
2233                         self.expected_found_str(exp_found)
2234                     }
2235                     ret => ret,
2236                 }
2237             }
2238         }
2239     }
2240
2241     fn expected_found_str_term(
2242         &self,
2243         exp_found: ty::error::ExpectedFound<ty::Term<'tcx>>,
2244     ) -> Option<(DiagnosticStyledString, DiagnosticStyledString)> {
2245         let exp_found = self.resolve_vars_if_possible(exp_found);
2246         if exp_found.references_error() {
2247             return None;
2248         }
2249
2250         Some(match (exp_found.expected, exp_found.found) {
2251             (ty::Term::Ty(expected), ty::Term::Ty(found)) => self.cmp(expected, found),
2252             (expected, found) => (
2253                 DiagnosticStyledString::highlighted(expected.to_string()),
2254                 DiagnosticStyledString::highlighted(found.to_string()),
2255             ),
2256         })
2257     }
2258
2259     /// Returns a string of the form "expected `{}`, found `{}`".
2260     fn expected_found_str<T: fmt::Display + TypeFoldable<'tcx>>(
2261         &self,
2262         exp_found: ty::error::ExpectedFound<T>,
2263     ) -> Option<(DiagnosticStyledString, DiagnosticStyledString)> {
2264         let exp_found = self.resolve_vars_if_possible(exp_found);
2265         if exp_found.references_error() {
2266             return None;
2267         }
2268
2269         Some((
2270             DiagnosticStyledString::highlighted(exp_found.expected.to_string()),
2271             DiagnosticStyledString::highlighted(exp_found.found.to_string()),
2272         ))
2273     }
2274
2275     pub fn report_generic_bound_failure(
2276         &self,
2277         generic_param_scope: LocalDefId,
2278         span: Span,
2279         origin: Option<SubregionOrigin<'tcx>>,
2280         bound_kind: GenericKind<'tcx>,
2281         sub: Region<'tcx>,
2282     ) {
2283         self.construct_generic_bound_failure(generic_param_scope, span, origin, bound_kind, sub)
2284             .emit();
2285     }
2286
2287     pub fn construct_generic_bound_failure(
2288         &self,
2289         generic_param_scope: LocalDefId,
2290         span: Span,
2291         origin: Option<SubregionOrigin<'tcx>>,
2292         bound_kind: GenericKind<'tcx>,
2293         sub: Region<'tcx>,
2294     ) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
2295         // Attempt to obtain the span of the parameter so we can
2296         // suggest adding an explicit lifetime bound to it.
2297         let generics = self.tcx.generics_of(generic_param_scope);
2298         // type_param_span is (span, has_bounds)
2299         let type_param_span = match bound_kind {
2300             GenericKind::Param(ref param) => {
2301                 // Account for the case where `param` corresponds to `Self`,
2302                 // which doesn't have the expected type argument.
2303                 if !(generics.has_self && param.index == 0) {
2304                     let type_param = generics.type_param(param, self.tcx);
2305                     type_param.def_id.as_local().map(|def_id| {
2306                         // Get the `hir::Param` to verify whether it already has any bounds.
2307                         // We do this to avoid suggesting code that ends up as `T: 'a'b`,
2308                         // instead we suggest `T: 'a + 'b` in that case.
2309                         let hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id);
2310                         let ast_generics = self.tcx.hir().get_generics(hir_id.owner);
2311                         let bounds =
2312                             ast_generics.and_then(|g| g.bounds_span_for_suggestions(def_id));
2313                         // `sp` only covers `T`, change it so that it covers
2314                         // `T:` when appropriate
2315                         if let Some(span) = bounds {
2316                             (span, true)
2317                         } else {
2318                             let sp = self.tcx.def_span(def_id);
2319                             (sp.shrink_to_hi(), false)
2320                         }
2321                     })
2322                 } else {
2323                     None
2324                 }
2325             }
2326             _ => None,
2327         };
2328
2329         let new_lt = {
2330             let mut possible = (b'a'..=b'z').map(|c| format!("'{}", c as char));
2331             let lts_names =
2332                 iter::successors(Some(generics), |g| g.parent.map(|p| self.tcx.generics_of(p)))
2333                     .flat_map(|g| &g.params)
2334                     .filter(|p| matches!(p.kind, ty::GenericParamDefKind::Lifetime))
2335                     .map(|p| p.name.as_str())
2336                     .collect::<Vec<_>>();
2337             possible
2338                 .find(|candidate| !lts_names.contains(&&candidate[..]))
2339                 .unwrap_or("'lt".to_string())
2340         };
2341
2342         let add_lt_sugg = generics
2343             .params
2344             .first()
2345             .and_then(|param| param.def_id.as_local())
2346             .map(|def_id| (self.tcx.def_span(def_id).shrink_to_lo(), format!("{}, ", new_lt)));
2347
2348         let labeled_user_string = match bound_kind {
2349             GenericKind::Param(ref p) => format!("the parameter type `{}`", p),
2350             GenericKind::Projection(ref p) => format!("the associated type `{}`", p),
2351         };
2352
2353         if let Some(SubregionOrigin::CompareImplMethodObligation {
2354             span,
2355             impl_item_def_id,
2356             trait_item_def_id,
2357         }) = origin
2358         {
2359             return self.report_extra_impl_obligation(
2360                 span,
2361                 impl_item_def_id,
2362                 trait_item_def_id,
2363                 &format!("`{}: {}`", bound_kind, sub),
2364             );
2365         }
2366
2367         fn binding_suggestion<'tcx, S: fmt::Display>(
2368             err: &mut Diagnostic,
2369             type_param_span: Option<(Span, bool)>,
2370             bound_kind: GenericKind<'tcx>,
2371             sub: S,
2372         ) {
2373             let msg = "consider adding an explicit lifetime bound";
2374             if let Some((sp, has_lifetimes)) = type_param_span {
2375                 let suggestion =
2376                     if has_lifetimes { format!(" + {}", sub) } else { format!(": {}", sub) };
2377                 err.span_suggestion_verbose(
2378                     sp,
2379                     &format!("{}...", msg),
2380                     suggestion,
2381                     Applicability::MaybeIncorrect, // Issue #41966
2382                 );
2383             } else {
2384                 let consider = format!("{} `{}: {}`...", msg, bound_kind, sub,);
2385                 err.help(&consider);
2386             }
2387         }
2388
2389         let new_binding_suggestion =
2390             |err: &mut Diagnostic, type_param_span: Option<(Span, bool)>| {
2391                 let msg = "consider introducing an explicit lifetime bound";
2392                 if let Some((sp, has_lifetimes)) = type_param_span {
2393                     let suggestion = if has_lifetimes {
2394                         format!(" + {}", new_lt)
2395                     } else {
2396                         format!(": {}", new_lt)
2397                     };
2398                     let mut sugg =
2399                         vec![(sp, suggestion), (span.shrink_to_hi(), format!(" + {}", new_lt))];
2400                     if let Some(lt) = add_lt_sugg {
2401                         sugg.push(lt);
2402                         sugg.rotate_right(1);
2403                     }
2404                     // `MaybeIncorrect` due to issue #41966.
2405                     err.multipart_suggestion(msg, sugg, Applicability::MaybeIncorrect);
2406                 }
2407             };
2408
2409         #[derive(Debug)]
2410         enum SubOrigin<'hir> {
2411             GAT(&'hir hir::Generics<'hir>),
2412             Impl(&'hir hir::Generics<'hir>),
2413             Trait(&'hir hir::Generics<'hir>),
2414             Fn(&'hir hir::Generics<'hir>),
2415             Unknown,
2416         }
2417         let sub_origin = 'origin: {
2418             match *sub {
2419                 ty::ReEarlyBound(ty::EarlyBoundRegion { def_id, .. }) => {
2420                     let node = self.tcx.hir().get_if_local(def_id).unwrap();
2421                     match node {
2422                         Node::GenericParam(param) => {
2423                             for h in self.tcx.hir().parent_iter(param.hir_id) {
2424                                 break 'origin match h.1 {
2425                                     Node::ImplItem(hir::ImplItem {
2426                                         kind: hir::ImplItemKind::TyAlias(..),
2427                                         generics,
2428                                         ..
2429                                     }) => SubOrigin::GAT(generics),
2430                                     Node::ImplItem(hir::ImplItem {
2431                                         kind: hir::ImplItemKind::Fn(..),
2432                                         generics,
2433                                         ..
2434                                     }) => SubOrigin::Fn(generics),
2435                                     Node::TraitItem(hir::TraitItem {
2436                                         kind: hir::TraitItemKind::Type(..),
2437                                         generics,
2438                                         ..
2439                                     }) => SubOrigin::GAT(generics),
2440                                     Node::TraitItem(hir::TraitItem {
2441                                         kind: hir::TraitItemKind::Fn(..),
2442                                         generics,
2443                                         ..
2444                                     }) => SubOrigin::Fn(generics),
2445                                     Node::Item(hir::Item {
2446                                         kind: hir::ItemKind::Trait(_, _, generics, _, _),
2447                                         ..
2448                                     }) => SubOrigin::Trait(generics),
2449                                     Node::Item(hir::Item {
2450                                         kind: hir::ItemKind::Impl(hir::Impl { generics, .. }),
2451                                         ..
2452                                     }) => SubOrigin::Impl(generics),
2453                                     Node::Item(hir::Item {
2454                                         kind: hir::ItemKind::Fn(_, generics, _),
2455                                         ..
2456                                     }) => SubOrigin::Fn(generics),
2457                                     _ => continue,
2458                                 };
2459                             }
2460                         }
2461                         _ => {}
2462                     }
2463                 }
2464                 _ => {}
2465             }
2466             SubOrigin::Unknown
2467         };
2468         debug!(?sub_origin);
2469
2470         let mut err = match (*sub, sub_origin) {
2471             // In the case of GATs, we have to be careful. If we a type parameter `T` on an impl,
2472             // but a lifetime `'a` on an associated type, then we might need to suggest adding
2473             // `where T: 'a`. Importantly, this is on the GAT span, not on the `T` declaration.
2474             (ty::ReEarlyBound(ty::EarlyBoundRegion { name: _, .. }), SubOrigin::GAT(generics)) => {
2475                 // Does the required lifetime have a nice name we can print?
2476                 let mut err = struct_span_err!(
2477                     self.tcx.sess,
2478                     span,
2479                     E0309,
2480                     "{} may not live long enough",
2481                     labeled_user_string
2482                 );
2483                 let pred = format!("{}: {}", bound_kind, sub);
2484                 let suggestion = format!("{} {}", generics.add_where_or_trailing_comma(), pred,);
2485                 err.span_suggestion(
2486                     generics.tail_span_for_predicate_suggestion(),
2487                     "consider adding a where clause",
2488                     suggestion,
2489                     Applicability::MaybeIncorrect,
2490                 );
2491                 err
2492             }
2493             (
2494                 ty::ReEarlyBound(ty::EarlyBoundRegion { name, .. })
2495                 | ty::ReFree(ty::FreeRegion { bound_region: ty::BrNamed(_, name), .. }),
2496                 _,
2497             ) if name != kw::UnderscoreLifetime => {
2498                 // Does the required lifetime have a nice name we can print?
2499                 let mut err = struct_span_err!(
2500                     self.tcx.sess,
2501                     span,
2502                     E0309,
2503                     "{} may not live long enough",
2504                     labeled_user_string
2505                 );
2506                 // Explicitly use the name instead of `sub`'s `Display` impl. The `Display` impl
2507                 // for the bound is not suitable for suggestions when `-Zverbose` is set because it
2508                 // uses `Debug` output, so we handle it specially here so that suggestions are
2509                 // always correct.
2510                 binding_suggestion(&mut err, type_param_span, bound_kind, name);
2511                 err
2512             }
2513
2514             (ty::ReStatic, _) => {
2515                 // Does the required lifetime have a nice name we can print?
2516                 let mut err = struct_span_err!(
2517                     self.tcx.sess,
2518                     span,
2519                     E0310,
2520                     "{} may not live long enough",
2521                     labeled_user_string
2522                 );
2523                 binding_suggestion(&mut err, type_param_span, bound_kind, "'static");
2524                 err
2525             }
2526
2527             _ => {
2528                 // If not, be less specific.
2529                 let mut err = struct_span_err!(
2530                     self.tcx.sess,
2531                     span,
2532                     E0311,
2533                     "{} may not live long enough",
2534                     labeled_user_string
2535                 );
2536                 note_and_explain_region(
2537                     self.tcx,
2538                     &mut err,
2539                     &format!("{} must be valid for ", labeled_user_string),
2540                     sub,
2541                     "...",
2542                     None,
2543                 );
2544                 if let Some(infer::RelateParamBound(_, t, _)) = origin {
2545                     let return_impl_trait =
2546                         self.tcx.return_type_impl_trait(generic_param_scope).is_some();
2547                     let t = self.resolve_vars_if_possible(t);
2548                     match t.kind() {
2549                         // We've got:
2550                         // fn get_later<G, T>(g: G, dest: &mut T) -> impl FnOnce() + '_
2551                         // suggest:
2552                         // fn get_later<'a, G: 'a, T>(g: G, dest: &mut T) -> impl FnOnce() + '_ + 'a
2553                         ty::Closure(_, _substs) | ty::Opaque(_, _substs) if return_impl_trait => {
2554                             new_binding_suggestion(&mut err, type_param_span);
2555                         }
2556                         _ => {
2557                             binding_suggestion(&mut err, type_param_span, bound_kind, new_lt);
2558                         }
2559                     }
2560                 }
2561                 err
2562             }
2563         };
2564
2565         if let Some(origin) = origin {
2566             self.note_region_origin(&mut err, &origin);
2567         }
2568         err
2569     }
2570
2571     fn report_sub_sup_conflict(
2572         &self,
2573         var_origin: RegionVariableOrigin,
2574         sub_origin: SubregionOrigin<'tcx>,
2575         sub_region: Region<'tcx>,
2576         sup_origin: SubregionOrigin<'tcx>,
2577         sup_region: Region<'tcx>,
2578     ) {
2579         let mut err = self.report_inference_failure(var_origin);
2580
2581         note_and_explain_region(
2582             self.tcx,
2583             &mut err,
2584             "first, the lifetime cannot outlive ",
2585             sup_region,
2586             "...",
2587             None,
2588         );
2589
2590         debug!("report_sub_sup_conflict: var_origin={:?}", var_origin);
2591         debug!("report_sub_sup_conflict: sub_region={:?}", sub_region);
2592         debug!("report_sub_sup_conflict: sub_origin={:?}", sub_origin);
2593         debug!("report_sub_sup_conflict: sup_region={:?}", sup_region);
2594         debug!("report_sub_sup_conflict: sup_origin={:?}", sup_origin);
2595
2596         if let (&infer::Subtype(ref sup_trace), &infer::Subtype(ref sub_trace)) =
2597             (&sup_origin, &sub_origin)
2598         {
2599             debug!("report_sub_sup_conflict: sup_trace={:?}", sup_trace);
2600             debug!("report_sub_sup_conflict: sub_trace={:?}", sub_trace);
2601             debug!("report_sub_sup_conflict: sup_trace.values={:?}", sup_trace.values);
2602             debug!("report_sub_sup_conflict: sub_trace.values={:?}", sub_trace.values);
2603
2604             if let (Some((sup_expected, sup_found)), Some((sub_expected, sub_found))) =
2605                 (self.values_str(sup_trace.values), self.values_str(sub_trace.values))
2606             {
2607                 if sub_expected == sup_expected && sub_found == sup_found {
2608                     note_and_explain_region(
2609                         self.tcx,
2610                         &mut err,
2611                         "...but the lifetime must also be valid for ",
2612                         sub_region,
2613                         "...",
2614                         None,
2615                     );
2616                     err.span_note(
2617                         sup_trace.cause.span,
2618                         &format!("...so that the {}", sup_trace.cause.as_requirement_str()),
2619                     );
2620
2621                     err.note_expected_found(&"", sup_expected, &"", sup_found);
2622                     err.emit();
2623                     return;
2624                 }
2625             }
2626         }
2627
2628         self.note_region_origin(&mut err, &sup_origin);
2629
2630         note_and_explain_region(
2631             self.tcx,
2632             &mut err,
2633             "but, the lifetime must be valid for ",
2634             sub_region,
2635             "...",
2636             None,
2637         );
2638
2639         self.note_region_origin(&mut err, &sub_origin);
2640         err.emit();
2641     }
2642
2643     /// Determine whether an error associated with the given span and definition
2644     /// should be treated as being caused by the implicit `From` conversion
2645     /// within `?` desugaring.
2646     pub fn is_try_conversion(&self, span: Span, trait_def_id: DefId) -> bool {
2647         span.is_desugaring(DesugaringKind::QuestionMark)
2648             && self.tcx.is_diagnostic_item(sym::From, trait_def_id)
2649     }
2650 }
2651
2652 impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
2653     fn report_inference_failure(
2654         &self,
2655         var_origin: RegionVariableOrigin,
2656     ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
2657         let br_string = |br: ty::BoundRegionKind| {
2658             let mut s = match br {
2659                 ty::BrNamed(_, name) => name.to_string(),
2660                 _ => String::new(),
2661             };
2662             if !s.is_empty() {
2663                 s.push(' ');
2664             }
2665             s
2666         };
2667         let var_description = match var_origin {
2668             infer::MiscVariable(_) => String::new(),
2669             infer::PatternRegion(_) => " for pattern".to_string(),
2670             infer::AddrOfRegion(_) => " for borrow expression".to_string(),
2671             infer::Autoref(_) => " for autoref".to_string(),
2672             infer::Coercion(_) => " for automatic coercion".to_string(),
2673             infer::LateBoundRegion(_, br, infer::FnCall) => {
2674                 format!(" for lifetime parameter {}in function call", br_string(br))
2675             }
2676             infer::LateBoundRegion(_, br, infer::HigherRankedType) => {
2677                 format!(" for lifetime parameter {}in generic type", br_string(br))
2678             }
2679             infer::LateBoundRegion(_, br, infer::AssocTypeProjection(def_id)) => format!(
2680                 " for lifetime parameter {}in trait containing associated type `{}`",
2681                 br_string(br),
2682                 self.tcx.associated_item(def_id).name
2683             ),
2684             infer::EarlyBoundRegion(_, name) => format!(" for lifetime parameter `{}`", name),
2685             infer::UpvarRegion(ref upvar_id, _) => {
2686                 let var_name = self.tcx.hir().name(upvar_id.var_path.hir_id);
2687                 format!(" for capture of `{}` by closure", var_name)
2688             }
2689             infer::Nll(..) => bug!("NLL variable found in lexical phase"),
2690         };
2691
2692         struct_span_err!(
2693             self.tcx.sess,
2694             var_origin.span(),
2695             E0495,
2696             "cannot infer an appropriate lifetime{} due to conflicting requirements",
2697             var_description
2698         )
2699     }
2700 }
2701
2702 pub enum FailureCode {
2703     Error0038(DefId),
2704     Error0317(&'static str),
2705     Error0580(&'static str),
2706     Error0308(&'static str),
2707     Error0644(&'static str),
2708 }
2709
2710 pub trait ObligationCauseExt<'tcx> {
2711     fn as_failure_code(&self, terr: &TypeError<'tcx>) -> FailureCode;
2712     fn as_requirement_str(&self) -> &'static str;
2713 }
2714
2715 impl<'tcx> ObligationCauseExt<'tcx> for ObligationCause<'tcx> {
2716     fn as_failure_code(&self, terr: &TypeError<'tcx>) -> FailureCode {
2717         use self::FailureCode::*;
2718         use crate::traits::ObligationCauseCode::*;
2719         match self.code() {
2720             CompareImplMethodObligation { .. } => Error0308("method not compatible with trait"),
2721             CompareImplTypeObligation { .. } => Error0308("type not compatible with trait"),
2722             MatchExpressionArm(box MatchExpressionArmCause { source, .. }) => {
2723                 Error0308(match source {
2724                     hir::MatchSource::TryDesugar => "`?` operator has incompatible types",
2725                     _ => "`match` arms have incompatible types",
2726                 })
2727             }
2728             IfExpression { .. } => Error0308("`if` and `else` have incompatible types"),
2729             IfExpressionWithNoElse => Error0317("`if` may be missing an `else` clause"),
2730             LetElse => Error0308("`else` clause of `let...else` does not diverge"),
2731             MainFunctionType => Error0580("`main` function has wrong type"),
2732             StartFunctionType => Error0308("`#[start]` function has wrong type"),
2733             IntrinsicType => Error0308("intrinsic has wrong type"),
2734             MethodReceiver => Error0308("mismatched `self` parameter type"),
2735
2736             // In the case where we have no more specific thing to
2737             // say, also take a look at the error code, maybe we can
2738             // tailor to that.
2739             _ => match terr {
2740                 TypeError::CyclicTy(ty) if ty.is_closure() || ty.is_generator() => {
2741                     Error0644("closure/generator type that references itself")
2742                 }
2743                 TypeError::IntrinsicCast => {
2744                     Error0308("cannot coerce intrinsics to function pointers")
2745                 }
2746                 TypeError::ObjectUnsafeCoercion(did) => Error0038(*did),
2747                 _ => Error0308("mismatched types"),
2748             },
2749         }
2750     }
2751
2752     fn as_requirement_str(&self) -> &'static str {
2753         use crate::traits::ObligationCauseCode::*;
2754         match self.code() {
2755             CompareImplMethodObligation { .. } => "method type is compatible with trait",
2756             CompareImplTypeObligation { .. } => "associated type is compatible with trait",
2757             ExprAssignable => "expression is assignable",
2758             IfExpression { .. } => "`if` and `else` have incompatible types",
2759             IfExpressionWithNoElse => "`if` missing an `else` returns `()`",
2760             MainFunctionType => "`main` function has the correct type",
2761             StartFunctionType => "`#[start]` function has the correct type",
2762             IntrinsicType => "intrinsic has the correct type",
2763             MethodReceiver => "method receiver has the correct type",
2764             _ => "types are compatible",
2765         }
2766     }
2767 }
2768
2769 /// This is a bare signal of what kind of type we're dealing with. `ty::TyKind` tracks
2770 /// extra information about each type, but we only care about the category.
2771 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
2772 pub enum TyCategory {
2773     Closure,
2774     Opaque,
2775     Generator(hir::GeneratorKind),
2776     Foreign,
2777 }
2778
2779 impl TyCategory {
2780     fn descr(&self) -> &'static str {
2781         match self {
2782             Self::Closure => "closure",
2783             Self::Opaque => "opaque type",
2784             Self::Generator(gk) => gk.descr(),
2785             Self::Foreign => "foreign type",
2786         }
2787     }
2788
2789     pub fn from_ty(tcx: TyCtxt<'_>, ty: Ty<'_>) -> Option<(Self, DefId)> {
2790         match *ty.kind() {
2791             ty::Closure(def_id, _) => Some((Self::Closure, def_id)),
2792             ty::Opaque(def_id, _) => Some((Self::Opaque, def_id)),
2793             ty::Generator(def_id, ..) => {
2794                 Some((Self::Generator(tcx.generator_kind(def_id).unwrap()), def_id))
2795             }
2796             ty::Foreign(def_id) => Some((Self::Foreign, def_id)),
2797             _ => None,
2798         }
2799     }
2800 }