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