]> git.lizzy.rs Git - rust.git/blob - src/librustc_infer/infer/error_reporting/mod.rs
Unconfuse Unpin docs a bit
[rust.git] / src / librustc_infer / 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 basis of the system are the "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::traits::error_reporting::report_object_safety_error;
54 use crate::traits::{
55     IfExpressionCause, MatchExpressionArmCause, ObligationCause, ObligationCauseCode,
56 };
57
58 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
59 use rustc_errors::{pluralize, struct_span_err};
60 use rustc_errors::{Applicability, DiagnosticBuilder, DiagnosticStyledString};
61 use rustc_hir as hir;
62 use rustc_hir::def_id::DefId;
63 use rustc_hir::{Item, ItemKind, Node};
64 use rustc_middle::ty::error::TypeError;
65 use rustc_middle::ty::{
66     self,
67     subst::{Subst, SubstsRef},
68     Region, Ty, TyCtxt, TypeFoldable,
69 };
70 use rustc_span::{DesugaringKind, Pos, Span};
71 use rustc_target::spec::abi;
72 use std::{cmp, fmt};
73
74 mod note;
75
76 mod need_type_info;
77 pub use need_type_info::TypeAnnotationNeeded;
78
79 pub mod nice_region_error;
80
81 pub(super) fn note_and_explain_region(
82     tcx: TyCtxt<'tcx>,
83     err: &mut DiagnosticBuilder<'_>,
84     prefix: &str,
85     region: ty::Region<'tcx>,
86     suffix: &str,
87 ) {
88     let (description, span) = match *region {
89         ty::ReEarlyBound(_) | ty::ReFree(_) | ty::ReStatic => {
90             msg_span_from_free_region(tcx, region)
91         }
92
93         ty::ReEmpty(ty::UniverseIndex::ROOT) => ("the empty lifetime".to_owned(), None),
94
95         // uh oh, hope no user ever sees THIS
96         ty::ReEmpty(ui) => (format!("the empty lifetime in universe {:?}", ui), None),
97
98         ty::RePlaceholder(_) => ("any other region".to_string(), None),
99
100         // FIXME(#13998) RePlaceholder should probably print like
101         // ReFree rather than dumping Debug output on the user.
102         //
103         // We shouldn't really be having unification failures with ReVar
104         // and ReLateBound though.
105         ty::ReVar(_) | ty::ReLateBound(..) | ty::ReErased => {
106             (format!("lifetime {:?}", region), None)
107         }
108     };
109
110     emit_msg_span(err, prefix, description, span, suffix);
111 }
112
113 pub(super) fn note_and_explain_free_region(
114     tcx: TyCtxt<'tcx>,
115     err: &mut DiagnosticBuilder<'_>,
116     prefix: &str,
117     region: ty::Region<'tcx>,
118     suffix: &str,
119 ) {
120     let (description, span) = msg_span_from_free_region(tcx, region);
121
122     emit_msg_span(err, prefix, description, span, suffix);
123 }
124
125 fn msg_span_from_free_region(
126     tcx: TyCtxt<'tcx>,
127     region: ty::Region<'tcx>,
128 ) -> (String, Option<Span>) {
129     match *region {
130         ty::ReEarlyBound(_) | ty::ReFree(_) => {
131             msg_span_from_early_bound_and_free_regions(tcx, region)
132         }
133         ty::ReStatic => ("the static lifetime".to_owned(), None),
134         ty::ReEmpty(ty::UniverseIndex::ROOT) => ("an empty lifetime".to_owned(), None),
135         ty::ReEmpty(ui) => (format!("an empty lifetime in universe {:?}", ui), None),
136         _ => bug!("{:?}", region),
137     }
138 }
139
140 fn msg_span_from_early_bound_and_free_regions(
141     tcx: TyCtxt<'tcx>,
142     region: ty::Region<'tcx>,
143 ) -> (String, Option<Span>) {
144     let sm = tcx.sess.source_map();
145
146     let scope = region.free_region_binding_scope(tcx);
147     let node = tcx.hir().local_def_id_to_hir_id(scope.expect_local());
148     let tag = match tcx.hir().find(node) {
149         Some(Node::Block(_) | Node::Expr(_)) => "body",
150         Some(Node::Item(it)) => item_scope_tag(&it),
151         Some(Node::TraitItem(it)) => trait_item_scope_tag(&it),
152         Some(Node::ImplItem(it)) => impl_item_scope_tag(&it),
153         _ => unreachable!(),
154     };
155     let (prefix, span) = match *region {
156         ty::ReEarlyBound(ref br) => {
157             let mut sp = sm.guess_head_span(tcx.hir().span(node));
158             if let Some(param) =
159                 tcx.hir().get_generics(scope).and_then(|generics| generics.get_named(br.name))
160             {
161                 sp = param.span;
162             }
163             (format!("the lifetime `{}` as defined on", br.name), sp)
164         }
165         ty::ReFree(ty::FreeRegion { bound_region: ty::BoundRegion::BrNamed(_, name), .. }) => {
166             let mut sp = sm.guess_head_span(tcx.hir().span(node));
167             if let Some(param) =
168                 tcx.hir().get_generics(scope).and_then(|generics| generics.get_named(name))
169             {
170                 sp = param.span;
171             }
172             (format!("the lifetime `{}` as defined on", name), sp)
173         }
174         ty::ReFree(ref fr) => match fr.bound_region {
175             ty::BrAnon(idx) => {
176                 (format!("the anonymous lifetime #{} defined on", idx + 1), tcx.hir().span(node))
177             }
178             _ => (
179                 format!("the lifetime `{}` as defined on", region),
180                 sm.guess_head_span(tcx.hir().span(node)),
181             ),
182         },
183         _ => bug!(),
184     };
185     let (msg, opt_span) = explain_span(tcx, tag, span);
186     (format!("{} {}", prefix, msg), opt_span)
187 }
188
189 fn emit_msg_span(
190     err: &mut DiagnosticBuilder<'_>,
191     prefix: &str,
192     description: String,
193     span: Option<Span>,
194     suffix: &str,
195 ) {
196     let message = format!("{}{}{}", prefix, description, suffix);
197
198     if let Some(span) = span {
199         err.span_note(span, &message);
200     } else {
201         err.note(&message);
202     }
203 }
204
205 fn item_scope_tag(item: &hir::Item<'_>) -> &'static str {
206     match item.kind {
207         hir::ItemKind::Impl { .. } => "impl",
208         hir::ItemKind::Struct(..) => "struct",
209         hir::ItemKind::Union(..) => "union",
210         hir::ItemKind::Enum(..) => "enum",
211         hir::ItemKind::Trait(..) => "trait",
212         hir::ItemKind::Fn(..) => "function body",
213         _ => "item",
214     }
215 }
216
217 fn trait_item_scope_tag(item: &hir::TraitItem<'_>) -> &'static str {
218     match item.kind {
219         hir::TraitItemKind::Fn(..) => "method body",
220         hir::TraitItemKind::Const(..) | hir::TraitItemKind::Type(..) => "associated item",
221     }
222 }
223
224 fn impl_item_scope_tag(item: &hir::ImplItem<'_>) -> &'static str {
225     match item.kind {
226         hir::ImplItemKind::Fn(..) => "method body",
227         hir::ImplItemKind::Const(..) | hir::ImplItemKind::TyAlias(..) => "associated item",
228     }
229 }
230
231 fn explain_span(tcx: TyCtxt<'tcx>, heading: &str, span: Span) -> (String, Option<Span>) {
232     let lo = tcx.sess.source_map().lookup_char_pos(span.lo());
233     (format!("the {} at {}:{}", heading, lo.line, lo.col.to_usize() + 1), Some(span))
234 }
235
236 pub fn unexpected_hidden_region_diagnostic(
237     tcx: TyCtxt<'tcx>,
238     span: Span,
239     hidden_ty: Ty<'tcx>,
240     hidden_region: ty::Region<'tcx>,
241 ) -> DiagnosticBuilder<'tcx> {
242     let mut err = struct_span_err!(
243         tcx.sess,
244         span,
245         E0700,
246         "hidden type for `impl Trait` captures lifetime that does not appear in bounds",
247     );
248
249     // Explain the region we are capturing.
250     match hidden_region {
251         ty::ReEmpty(ty::UniverseIndex::ROOT) => {
252             // All lifetimes shorter than the function body are `empty` in
253             // lexical region resolution. The default explanation of "an empty
254             // lifetime" isn't really accurate here.
255             let message = format!(
256                 "hidden type `{}` captures lifetime smaller than the function body",
257                 hidden_ty
258             );
259             err.span_note(span, &message);
260         }
261         ty::ReEarlyBound(_) | ty::ReFree(_) | ty::ReStatic | ty::ReEmpty(_) => {
262             // Assuming regionck succeeded (*), we ought to always be
263             // capturing *some* region from the fn header, and hence it
264             // ought to be free. So under normal circumstances, we will go
265             // down this path which gives a decent human readable
266             // explanation.
267             //
268             // (*) if not, the `tainted_by_errors` field would be set to
269             // `Some(ErrorReported)` in any case, so we wouldn't be here at all.
270             note_and_explain_free_region(
271                 tcx,
272                 &mut err,
273                 &format!("hidden type `{}` captures ", hidden_ty),
274                 hidden_region,
275                 "",
276             );
277         }
278         _ => {
279             // Ugh. This is a painful case: the hidden region is not one
280             // that we can easily summarize or explain. This can happen
281             // in a case like
282             // `src/test/ui/multiple-lifetimes/ordinary-bounds-unsuited.rs`:
283             //
284             // ```
285             // fn upper_bounds<'a, 'b>(a: Ordinary<'a>, b: Ordinary<'b>) -> impl Trait<'a, 'b> {
286             //   if condition() { a } else { b }
287             // }
288             // ```
289             //
290             // Here the captured lifetime is the intersection of `'a` and
291             // `'b`, which we can't quite express.
292
293             // We can at least report a really cryptic error for now.
294             note_and_explain_region(
295                 tcx,
296                 &mut err,
297                 &format!("hidden type `{}` captures ", hidden_ty),
298                 hidden_region,
299                 "",
300             );
301         }
302     }
303
304     err
305 }
306
307 impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
308     pub fn report_region_errors(&self, errors: &Vec<RegionResolutionError<'tcx>>) {
309         debug!("report_region_errors(): {} errors to start", errors.len());
310
311         // try to pre-process the errors, which will group some of them
312         // together into a `ProcessedErrors` group:
313         let errors = self.process_errors(errors);
314
315         debug!("report_region_errors: {} errors after preprocessing", errors.len());
316
317         for error in errors {
318             debug!("report_region_errors: error = {:?}", error);
319
320             if !self.try_report_nice_region_error(&error) {
321                 match error.clone() {
322                     // These errors could indicate all manner of different
323                     // problems with many different solutions. Rather
324                     // than generate a "one size fits all" error, what we
325                     // attempt to do is go through a number of specific
326                     // scenarios and try to find the best way to present
327                     // the error. If all of these fails, we fall back to a rather
328                     // general bit of code that displays the error information
329                     RegionResolutionError::ConcreteFailure(origin, sub, sup) => {
330                         if sub.is_placeholder() || sup.is_placeholder() {
331                             self.report_placeholder_failure(origin, sub, sup).emit();
332                         } else {
333                             self.report_concrete_failure(origin, sub, sup).emit();
334                         }
335                     }
336
337                     RegionResolutionError::GenericBoundFailure(origin, param_ty, sub) => {
338                         self.report_generic_bound_failure(
339                             origin.span(),
340                             Some(origin),
341                             param_ty,
342                             sub,
343                         );
344                     }
345
346                     RegionResolutionError::SubSupConflict(
347                         _,
348                         var_origin,
349                         sub_origin,
350                         sub_r,
351                         sup_origin,
352                         sup_r,
353                     ) => {
354                         if sub_r.is_placeholder() {
355                             self.report_placeholder_failure(sub_origin, sub_r, sup_r).emit();
356                         } else if sup_r.is_placeholder() {
357                             self.report_placeholder_failure(sup_origin, sub_r, sup_r).emit();
358                         } else {
359                             self.report_sub_sup_conflict(
360                                 var_origin, sub_origin, sub_r, sup_origin, sup_r,
361                             );
362                         }
363                     }
364
365                     RegionResolutionError::UpperBoundUniverseConflict(
366                         _,
367                         _,
368                         var_universe,
369                         sup_origin,
370                         sup_r,
371                     ) => {
372                         assert!(sup_r.is_placeholder());
373
374                         // Make a dummy value for the "sub region" --
375                         // this is the initial value of the
376                         // placeholder. In practice, we expect more
377                         // tailored errors that don't really use this
378                         // value.
379                         let sub_r = self.tcx.mk_region(ty::ReEmpty(var_universe));
380
381                         self.report_placeholder_failure(sup_origin, sub_r, sup_r).emit();
382                     }
383
384                     RegionResolutionError::MemberConstraintFailure {
385                         hidden_ty,
386                         member_region,
387                         span,
388                     } => {
389                         let hidden_ty = self.resolve_vars_if_possible(&hidden_ty);
390                         unexpected_hidden_region_diagnostic(
391                             self.tcx,
392                             span,
393                             hidden_ty,
394                             member_region,
395                         )
396                         .emit();
397                     }
398                 }
399             }
400         }
401     }
402
403     // This method goes through all the errors and try to group certain types
404     // of error together, for the purpose of suggesting explicit lifetime
405     // parameters to the user. This is done so that we can have a more
406     // complete view of what lifetimes should be the same.
407     // If the return value is an empty vector, it means that processing
408     // failed (so the return value of this method should not be used).
409     //
410     // The method also attempts to weed out messages that seem like
411     // duplicates that will be unhelpful to the end-user. But
412     // obviously it never weeds out ALL errors.
413     fn process_errors(
414         &self,
415         errors: &Vec<RegionResolutionError<'tcx>>,
416     ) -> Vec<RegionResolutionError<'tcx>> {
417         debug!("process_errors()");
418
419         // We want to avoid reporting generic-bound failures if we can
420         // avoid it: these have a very high rate of being unhelpful in
421         // practice. This is because they are basically secondary
422         // checks that test the state of the region graph after the
423         // rest of inference is done, and the other kinds of errors
424         // indicate that the region constraint graph is internally
425         // inconsistent, so these test results are likely to be
426         // meaningless.
427         //
428         // Therefore, we filter them out of the list unless they are
429         // the only thing in the list.
430
431         let is_bound_failure = |e: &RegionResolutionError<'tcx>| match *e {
432             RegionResolutionError::GenericBoundFailure(..) => true,
433             RegionResolutionError::ConcreteFailure(..)
434             | RegionResolutionError::SubSupConflict(..)
435             | RegionResolutionError::UpperBoundUniverseConflict(..)
436             | RegionResolutionError::MemberConstraintFailure { .. } => false,
437         };
438
439         let mut errors = if errors.iter().all(|e| is_bound_failure(e)) {
440             errors.clone()
441         } else {
442             errors.iter().filter(|&e| !is_bound_failure(e)).cloned().collect()
443         };
444
445         // sort the errors by span, for better error message stability.
446         errors.sort_by_key(|u| match *u {
447             RegionResolutionError::ConcreteFailure(ref sro, _, _) => sro.span(),
448             RegionResolutionError::GenericBoundFailure(ref sro, _, _) => sro.span(),
449             RegionResolutionError::SubSupConflict(_, ref rvo, _, _, _, _) => rvo.span(),
450             RegionResolutionError::UpperBoundUniverseConflict(_, ref rvo, _, _, _) => rvo.span(),
451             RegionResolutionError::MemberConstraintFailure { span, .. } => span,
452         });
453         errors
454     }
455
456     /// Adds a note if the types come from similarly named crates
457     fn check_and_note_conflicting_crates(
458         &self,
459         err: &mut DiagnosticBuilder<'_>,
460         terr: &TypeError<'tcx>,
461     ) {
462         use hir::def_id::CrateNum;
463         use rustc_hir::definitions::DisambiguatedDefPathData;
464         use ty::print::Printer;
465         use ty::subst::GenericArg;
466
467         struct AbsolutePathPrinter<'tcx> {
468             tcx: TyCtxt<'tcx>,
469         }
470
471         struct NonTrivialPath;
472
473         impl<'tcx> Printer<'tcx> for AbsolutePathPrinter<'tcx> {
474             type Error = NonTrivialPath;
475
476             type Path = Vec<String>;
477             type Region = !;
478             type Type = !;
479             type DynExistential = !;
480             type Const = !;
481
482             fn tcx<'a>(&'a self) -> TyCtxt<'tcx> {
483                 self.tcx
484             }
485
486             fn print_region(self, _region: ty::Region<'_>) -> Result<Self::Region, Self::Error> {
487                 Err(NonTrivialPath)
488             }
489
490             fn print_type(self, _ty: Ty<'tcx>) -> Result<Self::Type, Self::Error> {
491                 Err(NonTrivialPath)
492             }
493
494             fn print_dyn_existential(
495                 self,
496                 _predicates: &'tcx ty::List<ty::ExistentialPredicate<'tcx>>,
497             ) -> Result<Self::DynExistential, Self::Error> {
498                 Err(NonTrivialPath)
499             }
500
501             fn print_const(self, _ct: &'tcx ty::Const<'tcx>) -> Result<Self::Const, Self::Error> {
502                 Err(NonTrivialPath)
503             }
504
505             fn path_crate(self, cnum: CrateNum) -> Result<Self::Path, Self::Error> {
506                 Ok(vec![self.tcx.original_crate_name(cnum).to_string()])
507             }
508             fn path_qualified(
509                 self,
510                 _self_ty: Ty<'tcx>,
511                 _trait_ref: Option<ty::TraitRef<'tcx>>,
512             ) -> Result<Self::Path, Self::Error> {
513                 Err(NonTrivialPath)
514             }
515
516             fn path_append_impl(
517                 self,
518                 _print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
519                 _disambiguated_data: &DisambiguatedDefPathData,
520                 _self_ty: Ty<'tcx>,
521                 _trait_ref: Option<ty::TraitRef<'tcx>>,
522             ) -> Result<Self::Path, Self::Error> {
523                 Err(NonTrivialPath)
524             }
525             fn path_append(
526                 self,
527                 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
528                 disambiguated_data: &DisambiguatedDefPathData,
529             ) -> Result<Self::Path, Self::Error> {
530                 let mut path = print_prefix(self)?;
531                 path.push(disambiguated_data.data.as_symbol().to_string());
532                 Ok(path)
533             }
534             fn path_generic_args(
535                 self,
536                 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
537                 _args: &[GenericArg<'tcx>],
538             ) -> Result<Self::Path, Self::Error> {
539                 print_prefix(self)
540             }
541         }
542
543         let report_path_match = |err: &mut DiagnosticBuilder<'_>, did1: DefId, did2: DefId| {
544             // Only external crates, if either is from a local
545             // module we could have false positives
546             if !(did1.is_local() || did2.is_local()) && did1.krate != did2.krate {
547                 let abs_path =
548                     |def_id| AbsolutePathPrinter { tcx: self.tcx }.print_def_path(def_id, &[]);
549
550                 // We compare strings because DefPath can be different
551                 // for imported and non-imported crates
552                 let same_path = || -> Result<_, NonTrivialPath> {
553                     Ok(self.tcx.def_path_str(did1) == self.tcx.def_path_str(did2)
554                         || abs_path(did1)? == abs_path(did2)?)
555                 };
556                 if same_path().unwrap_or(false) {
557                     let crate_name = self.tcx.crate_name(did1.krate);
558                     err.note(&format!(
559                         "perhaps two different versions of crate `{}` are being used?",
560                         crate_name
561                     ));
562                 }
563             }
564         };
565         match *terr {
566             TypeError::Sorts(ref exp_found) => {
567                 // if they are both "path types", there's a chance of ambiguity
568                 // due to different versions of the same crate
569                 if let (&ty::Adt(exp_adt, _), &ty::Adt(found_adt, _)) =
570                     (&exp_found.expected.kind, &exp_found.found.kind)
571                 {
572                     report_path_match(err, exp_adt.did, found_adt.did);
573                 }
574             }
575             TypeError::Traits(ref exp_found) => {
576                 report_path_match(err, exp_found.expected, exp_found.found);
577             }
578             _ => (), // FIXME(#22750) handle traits and stuff
579         }
580     }
581
582     fn note_error_origin(
583         &self,
584         err: &mut DiagnosticBuilder<'tcx>,
585         cause: &ObligationCause<'tcx>,
586         exp_found: Option<ty::error::ExpectedFound<Ty<'tcx>>>,
587     ) {
588         match cause.code {
589             ObligationCauseCode::Pattern { origin_expr: true, span: Some(span), root_ty } => {
590                 let ty = self.resolve_vars_if_possible(&root_ty);
591                 if ty.is_suggestable() {
592                     // don't show type `_`
593                     err.span_label(span, format!("this expression has type `{}`", ty));
594                 }
595                 if let Some(ty::error::ExpectedFound { found, .. }) = exp_found {
596                     if ty.is_box() && ty.boxed_ty() == found {
597                         if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
598                             err.span_suggestion(
599                                 span,
600                                 "consider dereferencing the boxed value",
601                                 format!("*{}", snippet),
602                                 Applicability::MachineApplicable,
603                             );
604                         }
605                     }
606                 }
607             }
608             ObligationCauseCode::Pattern { origin_expr: false, span: Some(span), .. } => {
609                 err.span_label(span, "expected due to this");
610             }
611             ObligationCauseCode::MatchExpressionArm(box MatchExpressionArmCause {
612                 source,
613                 ref prior_arms,
614                 last_ty,
615                 scrut_hir_id,
616                 ..
617             }) => match source {
618                 hir::MatchSource::IfLetDesugar { .. } => {
619                     let msg = "`if let` arms have incompatible types";
620                     err.span_label(cause.span, msg);
621                 }
622                 hir::MatchSource::TryDesugar => {
623                     if let Some(ty::error::ExpectedFound { expected, .. }) = exp_found {
624                         let scrut_expr = self.tcx.hir().expect_expr(scrut_hir_id);
625                         let scrut_ty = if let hir::ExprKind::Call(_, args) = &scrut_expr.kind {
626                             let arg_expr = args.first().expect("try desugaring call w/out arg");
627                             self.in_progress_typeck_results.and_then(|typeck_results| {
628                                 typeck_results.borrow().expr_ty_opt(arg_expr)
629                             })
630                         } else {
631                             bug!("try desugaring w/out call expr as scrutinee");
632                         };
633
634                         match scrut_ty {
635                             Some(ty) if expected == ty => {
636                                 let source_map = self.tcx.sess.source_map();
637                                 err.span_suggestion(
638                                     source_map.end_point(cause.span),
639                                     "try removing this `?`",
640                                     "".to_string(),
641                                     Applicability::MachineApplicable,
642                                 );
643                             }
644                             _ => {}
645                         }
646                     }
647                 }
648                 _ => {
649                     // `last_ty` can be `!`, `expected` will have better info when present.
650                     let t = self.resolve_vars_if_possible(&match exp_found {
651                         Some(ty::error::ExpectedFound { expected, .. }) => expected,
652                         _ => last_ty,
653                     });
654                     let msg = "`match` arms have incompatible types";
655                     err.span_label(cause.span, msg);
656                     if prior_arms.len() <= 4 {
657                         for sp in prior_arms {
658                             err.span_label(*sp, format!("this is found to be of type `{}`", t));
659                         }
660                     } else if let Some(sp) = prior_arms.last() {
661                         err.span_label(
662                             *sp,
663                             format!("this and all prior arms are found to be of type `{}`", t),
664                         );
665                     }
666                 }
667             },
668             ObligationCauseCode::IfExpression(box IfExpressionCause { then, outer, semicolon }) => {
669                 err.span_label(then, "expected because of this");
670                 if let Some(sp) = outer {
671                     err.span_label(sp, "`if` and `else` have incompatible types");
672                 }
673                 if let Some(sp) = semicolon {
674                     err.span_suggestion_short(
675                         sp,
676                         "consider removing this semicolon",
677                         String::new(),
678                         Applicability::MachineApplicable,
679                     );
680                 }
681             }
682             _ => (),
683         }
684     }
685
686     /// Given that `other_ty` is the same as a type argument for `name` in `sub`, populate `value`
687     /// highlighting `name` and every type argument that isn't at `pos` (which is `other_ty`), and
688     /// populate `other_value` with `other_ty`.
689     ///
690     /// ```text
691     /// Foo<Bar<Qux>>
692     /// ^^^^--------^ this is highlighted
693     /// |   |
694     /// |   this type argument is exactly the same as the other type, not highlighted
695     /// this is highlighted
696     /// Bar<Qux>
697     /// -------- this type is the same as a type argument in the other type, not highlighted
698     /// ```
699     fn highlight_outer(
700         &self,
701         value: &mut DiagnosticStyledString,
702         other_value: &mut DiagnosticStyledString,
703         name: String,
704         sub: ty::subst::SubstsRef<'tcx>,
705         pos: usize,
706         other_ty: Ty<'tcx>,
707     ) {
708         // `value` and `other_value` hold two incomplete type representation for display.
709         // `name` is the path of both types being compared. `sub`
710         value.push_highlighted(name);
711         let len = sub.len();
712         if len > 0 {
713             value.push_highlighted("<");
714         }
715
716         // Output the lifetimes for the first type
717         let lifetimes = sub
718             .regions()
719             .map(|lifetime| {
720                 let s = lifetime.to_string();
721                 if s.is_empty() { "'_".to_string() } else { s }
722             })
723             .collect::<Vec<_>>()
724             .join(", ");
725         if !lifetimes.is_empty() {
726             if sub.regions().count() < len {
727                 value.push_normal(lifetimes + ", ");
728             } else {
729                 value.push_normal(lifetimes);
730             }
731         }
732
733         // Highlight all the type arguments that aren't at `pos` and compare the type argument at
734         // `pos` and `other_ty`.
735         for (i, type_arg) in sub.types().enumerate() {
736             if i == pos {
737                 let values = self.cmp(type_arg, other_ty);
738                 value.0.extend((values.0).0);
739                 other_value.0.extend((values.1).0);
740             } else {
741                 value.push_highlighted(type_arg.to_string());
742             }
743
744             if len > 0 && i != len - 1 {
745                 value.push_normal(", ");
746             }
747         }
748         if len > 0 {
749             value.push_highlighted(">");
750         }
751     }
752
753     /// If `other_ty` is the same as a type argument present in `sub`, highlight `path` in `t1_out`,
754     /// as that is the difference to the other type.
755     ///
756     /// For the following code:
757     ///
758     /// ```no_run
759     /// let x: Foo<Bar<Qux>> = foo::<Bar<Qux>>();
760     /// ```
761     ///
762     /// The type error output will behave in the following way:
763     ///
764     /// ```text
765     /// Foo<Bar<Qux>>
766     /// ^^^^--------^ this is highlighted
767     /// |   |
768     /// |   this type argument is exactly the same as the other type, not highlighted
769     /// this is highlighted
770     /// Bar<Qux>
771     /// -------- this type is the same as a type argument in the other type, not highlighted
772     /// ```
773     fn cmp_type_arg(
774         &self,
775         mut t1_out: &mut DiagnosticStyledString,
776         mut t2_out: &mut DiagnosticStyledString,
777         path: String,
778         sub: ty::subst::SubstsRef<'tcx>,
779         other_path: String,
780         other_ty: Ty<'tcx>,
781     ) -> Option<()> {
782         for (i, ta) in sub.types().enumerate() {
783             if ta == other_ty {
784                 self.highlight_outer(&mut t1_out, &mut t2_out, path, sub, i, &other_ty);
785                 return Some(());
786             }
787             if let &ty::Adt(def, _) = &ta.kind {
788                 let path_ = self.tcx.def_path_str(def.did);
789                 if path_ == other_path {
790                     self.highlight_outer(&mut t1_out, &mut t2_out, path, sub, i, &other_ty);
791                     return Some(());
792                 }
793             }
794         }
795         None
796     }
797
798     /// Adds a `,` to the type representation only if it is appropriate.
799     fn push_comma(
800         &self,
801         value: &mut DiagnosticStyledString,
802         other_value: &mut DiagnosticStyledString,
803         len: usize,
804         pos: usize,
805     ) {
806         if len > 0 && pos != len - 1 {
807             value.push_normal(", ");
808             other_value.push_normal(", ");
809         }
810     }
811
812     /// For generic types with parameters with defaults, remove the parameters corresponding to
813     /// the defaults. This repeats a lot of the logic found in `ty::print::pretty`.
814     fn strip_generic_default_params(
815         &self,
816         def_id: DefId,
817         substs: ty::subst::SubstsRef<'tcx>,
818     ) -> SubstsRef<'tcx> {
819         let generics = self.tcx.generics_of(def_id);
820         let mut num_supplied_defaults = 0;
821         let mut type_params = generics
822             .params
823             .iter()
824             .rev()
825             .filter_map(|param| match param.kind {
826                 ty::GenericParamDefKind::Lifetime => None,
827                 ty::GenericParamDefKind::Type { has_default, .. } => {
828                     Some((param.def_id, has_default))
829                 }
830                 ty::GenericParamDefKind::Const => None, // FIXME(const_generics:defaults)
831             })
832             .peekable();
833         let has_default = {
834             let has_default = type_params.peek().map(|(_, has_default)| has_default);
835             *has_default.unwrap_or(&false)
836         };
837         if has_default {
838             let types = substs.types().rev();
839             for ((def_id, has_default), actual) in type_params.zip(types) {
840                 if !has_default {
841                     break;
842                 }
843                 if self.tcx.type_of(def_id).subst(self.tcx, substs) != actual {
844                     break;
845                 }
846                 num_supplied_defaults += 1;
847             }
848         }
849         let len = generics.params.len();
850         let mut generics = generics.clone();
851         generics.params.truncate(len - num_supplied_defaults);
852         substs.truncate_to(self.tcx, &generics)
853     }
854
855     /// Given two `fn` signatures highlight only sub-parts that are different.
856     fn cmp_fn_sig(
857         &self,
858         sig1: &ty::PolyFnSig<'tcx>,
859         sig2: &ty::PolyFnSig<'tcx>,
860     ) -> (DiagnosticStyledString, DiagnosticStyledString) {
861         let get_lifetimes = |sig| {
862             use rustc_hir::def::Namespace;
863             let mut s = String::new();
864             let (_, (sig, reg)) = ty::print::FmtPrinter::new(self.tcx, &mut s, Namespace::TypeNS)
865                 .name_all_regions(sig)
866                 .unwrap();
867             let lts: Vec<String> = reg.into_iter().map(|(_, kind)| kind.to_string()).collect();
868             (if lts.is_empty() { String::new() } else { format!("for<{}> ", lts.join(", ")) }, sig)
869         };
870
871         let (lt1, sig1) = get_lifetimes(sig1);
872         let (lt2, sig2) = get_lifetimes(sig2);
873
874         // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
875         let mut values = (
876             DiagnosticStyledString::normal("".to_string()),
877             DiagnosticStyledString::normal("".to_string()),
878         );
879
880         // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
881         // ^^^^^^
882         values.0.push(sig1.unsafety.prefix_str(), sig1.unsafety != sig2.unsafety);
883         values.1.push(sig2.unsafety.prefix_str(), sig1.unsafety != sig2.unsafety);
884
885         // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
886         //        ^^^^^^^^^^
887         if sig1.abi != abi::Abi::Rust {
888             values.0.push(format!("extern {} ", sig1.abi), sig1.abi != sig2.abi);
889         }
890         if sig2.abi != abi::Abi::Rust {
891             values.1.push(format!("extern {} ", sig2.abi), sig1.abi != sig2.abi);
892         }
893
894         // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
895         //                   ^^^^^^^^
896         let lifetime_diff = lt1 != lt2;
897         values.0.push(lt1, lifetime_diff);
898         values.1.push(lt2, lifetime_diff);
899
900         // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
901         //                           ^^^
902         values.0.push_normal("fn(");
903         values.1.push_normal("fn(");
904
905         // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
906         //                              ^^^^^
907         let len1 = sig1.inputs().len();
908         let len2 = sig2.inputs().len();
909         if len1 == len2 {
910             for (i, (l, r)) in sig1.inputs().iter().zip(sig2.inputs().iter()).enumerate() {
911                 let (x1, x2) = self.cmp(l, r);
912                 (values.0).0.extend(x1.0);
913                 (values.1).0.extend(x2.0);
914                 self.push_comma(&mut values.0, &mut values.1, len1, i);
915             }
916         } else {
917             for (i, l) in sig1.inputs().iter().enumerate() {
918                 values.0.push_highlighted(l.to_string());
919                 if i != len1 - 1 {
920                     values.0.push_highlighted(", ");
921                 }
922             }
923             for (i, r) in sig2.inputs().iter().enumerate() {
924                 values.1.push_highlighted(r.to_string());
925                 if i != len2 - 1 {
926                     values.1.push_highlighted(", ");
927                 }
928             }
929         }
930
931         if sig1.c_variadic {
932             if len1 > 0 {
933                 values.0.push_normal(", ");
934             }
935             values.0.push("...", !sig2.c_variadic);
936         }
937         if sig2.c_variadic {
938             if len2 > 0 {
939                 values.1.push_normal(", ");
940             }
941             values.1.push("...", !sig1.c_variadic);
942         }
943
944         // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
945         //                                   ^
946         values.0.push_normal(")");
947         values.1.push_normal(")");
948
949         // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
950         //                                     ^^^^^^^^
951         let output1 = sig1.output();
952         let output2 = sig2.output();
953         let (x1, x2) = self.cmp(output1, output2);
954         if !output1.is_unit() {
955             values.0.push_normal(" -> ");
956             (values.0).0.extend(x1.0);
957         }
958         if !output2.is_unit() {
959             values.1.push_normal(" -> ");
960             (values.1).0.extend(x2.0);
961         }
962         values
963     }
964
965     /// Compares two given types, eliding parts that are the same between them and highlighting
966     /// relevant differences, and return two representation of those types for highlighted printing.
967     fn cmp(&self, t1: Ty<'tcx>, t2: Ty<'tcx>) -> (DiagnosticStyledString, DiagnosticStyledString) {
968         debug!("cmp(t1={}, t1.kind={:?}, t2={}, t2.kind={:?})", t1, t1.kind, t2, t2.kind);
969
970         // helper functions
971         fn equals<'tcx>(a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
972             match (&a.kind, &b.kind) {
973                 (a, b) if *a == *b => true,
974                 (&ty::Int(_), &ty::Infer(ty::InferTy::IntVar(_)))
975                 | (
976                     &ty::Infer(ty::InferTy::IntVar(_)),
977                     &ty::Int(_) | &ty::Infer(ty::InferTy::IntVar(_)),
978                 )
979                 | (&ty::Float(_), &ty::Infer(ty::InferTy::FloatVar(_)))
980                 | (
981                     &ty::Infer(ty::InferTy::FloatVar(_)),
982                     &ty::Float(_) | &ty::Infer(ty::InferTy::FloatVar(_)),
983                 ) => true,
984                 _ => false,
985             }
986         }
987
988         fn push_ty_ref<'tcx>(
989             region: &ty::Region<'tcx>,
990             ty: Ty<'tcx>,
991             mutbl: hir::Mutability,
992             s: &mut DiagnosticStyledString,
993         ) {
994             let mut r = region.to_string();
995             if r == "'_" {
996                 r.clear();
997             } else {
998                 r.push(' ');
999             }
1000             s.push_highlighted(format!("&{}{}", r, mutbl.prefix_str()));
1001             s.push_normal(ty.to_string());
1002         }
1003
1004         // process starts here
1005         match (&t1.kind, &t2.kind) {
1006             (&ty::Adt(def1, sub1), &ty::Adt(def2, sub2)) => {
1007                 let sub_no_defaults_1 = self.strip_generic_default_params(def1.did, sub1);
1008                 let sub_no_defaults_2 = self.strip_generic_default_params(def2.did, sub2);
1009                 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
1010                 let path1 = self.tcx.def_path_str(def1.did);
1011                 let path2 = self.tcx.def_path_str(def2.did);
1012                 if def1.did == def2.did {
1013                     // Easy case. Replace same types with `_` to shorten the output and highlight
1014                     // the differing ones.
1015                     //     let x: Foo<Bar, Qux> = y::<Foo<Quz, Qux>>();
1016                     //     Foo<Bar, _>
1017                     //     Foo<Quz, _>
1018                     //         ---  ^ type argument elided
1019                     //         |
1020                     //         highlighted in output
1021                     values.0.push_normal(path1);
1022                     values.1.push_normal(path2);
1023
1024                     // Avoid printing out default generic parameters that are common to both
1025                     // types.
1026                     let len1 = sub_no_defaults_1.len();
1027                     let len2 = sub_no_defaults_2.len();
1028                     let common_len = cmp::min(len1, len2);
1029                     let remainder1: Vec<_> = sub1.types().skip(common_len).collect();
1030                     let remainder2: Vec<_> = sub2.types().skip(common_len).collect();
1031                     let common_default_params = remainder1
1032                         .iter()
1033                         .rev()
1034                         .zip(remainder2.iter().rev())
1035                         .filter(|(a, b)| a == b)
1036                         .count();
1037                     let len = sub1.len() - common_default_params;
1038                     let consts_offset = len - sub1.consts().count();
1039
1040                     // Only draw `<...>` if there're lifetime/type arguments.
1041                     if len > 0 {
1042                         values.0.push_normal("<");
1043                         values.1.push_normal("<");
1044                     }
1045
1046                     fn lifetime_display(lifetime: Region<'_>) -> String {
1047                         let s = lifetime.to_string();
1048                         if s.is_empty() { "'_".to_string() } else { s }
1049                     }
1050                     // At one point we'd like to elide all lifetimes here, they are irrelevant for
1051                     // all diagnostics that use this output
1052                     //
1053                     //     Foo<'x, '_, Bar>
1054                     //     Foo<'y, '_, Qux>
1055                     //         ^^  ^^  --- type arguments are not elided
1056                     //         |   |
1057                     //         |   elided as they were the same
1058                     //         not elided, they were different, but irrelevant
1059                     let lifetimes = sub1.regions().zip(sub2.regions());
1060                     for (i, lifetimes) in lifetimes.enumerate() {
1061                         let l1 = lifetime_display(lifetimes.0);
1062                         let l2 = lifetime_display(lifetimes.1);
1063                         if lifetimes.0 == lifetimes.1 {
1064                             values.0.push_normal("'_");
1065                             values.1.push_normal("'_");
1066                         } else {
1067                             values.0.push_highlighted(l1);
1068                             values.1.push_highlighted(l2);
1069                         }
1070                         self.push_comma(&mut values.0, &mut values.1, len, i);
1071                     }
1072
1073                     // We're comparing two types with the same path, so we compare the type
1074                     // arguments for both. If they are the same, do not highlight and elide from the
1075                     // output.
1076                     //     Foo<_, Bar>
1077                     //     Foo<_, Qux>
1078                     //         ^ elided type as this type argument was the same in both sides
1079                     let type_arguments = sub1.types().zip(sub2.types());
1080                     let regions_len = sub1.regions().count();
1081                     let num_display_types = consts_offset - regions_len;
1082                     for (i, (ta1, ta2)) in type_arguments.take(num_display_types).enumerate() {
1083                         let i = i + regions_len;
1084                         if ta1 == ta2 {
1085                             values.0.push_normal("_");
1086                             values.1.push_normal("_");
1087                         } else {
1088                             let (x1, x2) = self.cmp(ta1, ta2);
1089                             (values.0).0.extend(x1.0);
1090                             (values.1).0.extend(x2.0);
1091                         }
1092                         self.push_comma(&mut values.0, &mut values.1, len, i);
1093                     }
1094
1095                     // Do the same for const arguments, if they are equal, do not highlight and
1096                     // elide them from the output.
1097                     let const_arguments = sub1.consts().zip(sub2.consts());
1098                     for (i, (ca1, ca2)) in const_arguments.enumerate() {
1099                         let i = i + consts_offset;
1100                         if ca1 == ca2 {
1101                             values.0.push_normal("_");
1102                             values.1.push_normal("_");
1103                         } else {
1104                             values.0.push_highlighted(ca1.to_string());
1105                             values.1.push_highlighted(ca2.to_string());
1106                         }
1107                         self.push_comma(&mut values.0, &mut values.1, len, i);
1108                     }
1109
1110                     // Close the type argument bracket.
1111                     // Only draw `<...>` if there're lifetime/type arguments.
1112                     if len > 0 {
1113                         values.0.push_normal(">");
1114                         values.1.push_normal(">");
1115                     }
1116                     values
1117                 } else {
1118                     // Check for case:
1119                     //     let x: Foo<Bar<Qux> = foo::<Bar<Qux>>();
1120                     //     Foo<Bar<Qux>
1121                     //         ------- this type argument is exactly the same as the other type
1122                     //     Bar<Qux>
1123                     if self
1124                         .cmp_type_arg(
1125                             &mut values.0,
1126                             &mut values.1,
1127                             path1.clone(),
1128                             sub_no_defaults_1,
1129                             path2.clone(),
1130                             &t2,
1131                         )
1132                         .is_some()
1133                     {
1134                         return values;
1135                     }
1136                     // Check for case:
1137                     //     let x: Bar<Qux> = y:<Foo<Bar<Qux>>>();
1138                     //     Bar<Qux>
1139                     //     Foo<Bar<Qux>>
1140                     //         ------- this type argument is exactly the same as the other type
1141                     if self
1142                         .cmp_type_arg(
1143                             &mut values.1,
1144                             &mut values.0,
1145                             path2,
1146                             sub_no_defaults_2,
1147                             path1,
1148                             &t1,
1149                         )
1150                         .is_some()
1151                     {
1152                         return values;
1153                     }
1154
1155                     // We can't find anything in common, highlight relevant part of type path.
1156                     //     let x: foo::bar::Baz<Qux> = y:<foo::bar::Bar<Zar>>();
1157                     //     foo::bar::Baz<Qux>
1158                     //     foo::bar::Bar<Zar>
1159                     //               -------- this part of the path is different
1160
1161                     let t1_str = t1.to_string();
1162                     let t2_str = t2.to_string();
1163                     let min_len = t1_str.len().min(t2_str.len());
1164
1165                     const SEPARATOR: &str = "::";
1166                     let separator_len = SEPARATOR.len();
1167                     let split_idx: usize = t1_str
1168                         .split(SEPARATOR)
1169                         .zip(t2_str.split(SEPARATOR))
1170                         .take_while(|(mod1_str, mod2_str)| mod1_str == mod2_str)
1171                         .map(|(mod_str, _)| mod_str.len() + separator_len)
1172                         .sum();
1173
1174                     debug!(
1175                         "cmp: separator_len={}, split_idx={}, min_len={}",
1176                         separator_len, split_idx, min_len
1177                     );
1178
1179                     if split_idx >= min_len {
1180                         // paths are identical, highlight everything
1181                         (
1182                             DiagnosticStyledString::highlighted(t1_str),
1183                             DiagnosticStyledString::highlighted(t2_str),
1184                         )
1185                     } else {
1186                         let (common, uniq1) = t1_str.split_at(split_idx);
1187                         let (_, uniq2) = t2_str.split_at(split_idx);
1188                         debug!("cmp: common={}, uniq1={}, uniq2={}", common, uniq1, uniq2);
1189
1190                         values.0.push_normal(common);
1191                         values.0.push_highlighted(uniq1);
1192                         values.1.push_normal(common);
1193                         values.1.push_highlighted(uniq2);
1194
1195                         values
1196                     }
1197                 }
1198             }
1199
1200             // When finding T != &T, highlight only the borrow
1201             (&ty::Ref(r1, ref_ty1, mutbl1), _) if equals(&ref_ty1, &t2) => {
1202                 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
1203                 push_ty_ref(&r1, ref_ty1, mutbl1, &mut values.0);
1204                 values.1.push_normal(t2.to_string());
1205                 values
1206             }
1207             (_, &ty::Ref(r2, ref_ty2, mutbl2)) if equals(&t1, &ref_ty2) => {
1208                 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
1209                 values.0.push_normal(t1.to_string());
1210                 push_ty_ref(&r2, ref_ty2, mutbl2, &mut values.1);
1211                 values
1212             }
1213
1214             // When encountering &T != &mut T, highlight only the borrow
1215             (&ty::Ref(r1, ref_ty1, mutbl1), &ty::Ref(r2, ref_ty2, mutbl2))
1216                 if equals(&ref_ty1, &ref_ty2) =>
1217             {
1218                 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
1219                 push_ty_ref(&r1, ref_ty1, mutbl1, &mut values.0);
1220                 push_ty_ref(&r2, ref_ty2, mutbl2, &mut values.1);
1221                 values
1222             }
1223
1224             // When encountering tuples of the same size, highlight only the differing types
1225             (&ty::Tuple(substs1), &ty::Tuple(substs2)) if substs1.len() == substs2.len() => {
1226                 let mut values =
1227                     (DiagnosticStyledString::normal("("), DiagnosticStyledString::normal("("));
1228                 let len = substs1.len();
1229                 for (i, (left, right)) in substs1.types().zip(substs2.types()).enumerate() {
1230                     let (x1, x2) = self.cmp(left, right);
1231                     (values.0).0.extend(x1.0);
1232                     (values.1).0.extend(x2.0);
1233                     self.push_comma(&mut values.0, &mut values.1, len, i);
1234                 }
1235                 if len == 1 {
1236                     // Keep the output for single element tuples as `(ty,)`.
1237                     values.0.push_normal(",");
1238                     values.1.push_normal(",");
1239                 }
1240                 values.0.push_normal(")");
1241                 values.1.push_normal(")");
1242                 values
1243             }
1244
1245             (ty::FnDef(did1, substs1), ty::FnDef(did2, substs2)) => {
1246                 let sig1 = self.tcx.fn_sig(*did1).subst(self.tcx, substs1);
1247                 let sig2 = self.tcx.fn_sig(*did2).subst(self.tcx, substs2);
1248                 let mut values = self.cmp_fn_sig(&sig1, &sig2);
1249                 let path1 = format!(" {{{}}}", self.tcx.def_path_str_with_substs(*did1, substs1));
1250                 let path2 = format!(" {{{}}}", self.tcx.def_path_str_with_substs(*did2, substs2));
1251                 let same_path = path1 == path2;
1252                 values.0.push(path1, !same_path);
1253                 values.1.push(path2, !same_path);
1254                 values
1255             }
1256
1257             (ty::FnDef(did1, substs1), ty::FnPtr(sig2)) => {
1258                 let sig1 = self.tcx.fn_sig(*did1).subst(self.tcx, substs1);
1259                 let mut values = self.cmp_fn_sig(&sig1, sig2);
1260                 values.0.push_highlighted(format!(
1261                     " {{{}}}",
1262                     self.tcx.def_path_str_with_substs(*did1, substs1)
1263                 ));
1264                 values
1265             }
1266
1267             (ty::FnPtr(sig1), ty::FnDef(did2, substs2)) => {
1268                 let sig2 = self.tcx.fn_sig(*did2).subst(self.tcx, substs2);
1269                 let mut values = self.cmp_fn_sig(sig1, &sig2);
1270                 values.1.push_normal(format!(
1271                     " {{{}}}",
1272                     self.tcx.def_path_str_with_substs(*did2, substs2)
1273                 ));
1274                 values
1275             }
1276
1277             (ty::FnPtr(sig1), ty::FnPtr(sig2)) => self.cmp_fn_sig(sig1, sig2),
1278
1279             _ => {
1280                 if t1 == t2 {
1281                     // The two types are the same, elide and don't highlight.
1282                     (DiagnosticStyledString::normal("_"), DiagnosticStyledString::normal("_"))
1283                 } else {
1284                     // We couldn't find anything in common, highlight everything.
1285                     (
1286                         DiagnosticStyledString::highlighted(t1.to_string()),
1287                         DiagnosticStyledString::highlighted(t2.to_string()),
1288                     )
1289                 }
1290             }
1291         }
1292     }
1293
1294     pub fn note_type_err(
1295         &self,
1296         diag: &mut DiagnosticBuilder<'tcx>,
1297         cause: &ObligationCause<'tcx>,
1298         secondary_span: Option<(Span, String)>,
1299         mut values: Option<ValuePairs<'tcx>>,
1300         terr: &TypeError<'tcx>,
1301     ) {
1302         let span = cause.span(self.tcx);
1303         debug!("note_type_err cause={:?} values={:?}, terr={:?}", cause, values, terr);
1304
1305         // For some types of errors, expected-found does not make
1306         // sense, so just ignore the values we were given.
1307         if let TypeError::CyclicTy(_) = terr {
1308             values = None;
1309         }
1310         struct OpaqueTypesVisitor<'tcx> {
1311             types: FxHashMap<TyCategory, FxHashSet<Span>>,
1312             expected: FxHashMap<TyCategory, FxHashSet<Span>>,
1313             found: FxHashMap<TyCategory, FxHashSet<Span>>,
1314             ignore_span: Span,
1315             tcx: TyCtxt<'tcx>,
1316         }
1317
1318         impl<'tcx> OpaqueTypesVisitor<'tcx> {
1319             fn visit_expected_found(
1320                 tcx: TyCtxt<'tcx>,
1321                 expected: Ty<'tcx>,
1322                 found: Ty<'tcx>,
1323                 ignore_span: Span,
1324             ) -> Self {
1325                 let mut types_visitor = OpaqueTypesVisitor {
1326                     types: Default::default(),
1327                     expected: Default::default(),
1328                     found: Default::default(),
1329                     ignore_span,
1330                     tcx,
1331                 };
1332                 // The visitor puts all the relevant encountered types in `self.types`, but in
1333                 // here we want to visit two separate types with no relation to each other, so we
1334                 // move the results from `types` to `expected` or `found` as appropriate.
1335                 expected.visit_with(&mut types_visitor);
1336                 std::mem::swap(&mut types_visitor.expected, &mut types_visitor.types);
1337                 found.visit_with(&mut types_visitor);
1338                 std::mem::swap(&mut types_visitor.found, &mut types_visitor.types);
1339                 types_visitor
1340             }
1341
1342             fn report(&self, err: &mut DiagnosticBuilder<'_>) {
1343                 self.add_labels_for_types(err, "expected", &self.expected);
1344                 self.add_labels_for_types(err, "found", &self.found);
1345             }
1346
1347             fn add_labels_for_types(
1348                 &self,
1349                 err: &mut DiagnosticBuilder<'_>,
1350                 target: &str,
1351                 types: &FxHashMap<TyCategory, FxHashSet<Span>>,
1352             ) {
1353                 for (key, values) in types.iter() {
1354                     let count = values.len();
1355                     let kind = key.descr();
1356                     for sp in values {
1357                         err.span_label(
1358                             *sp,
1359                             format!(
1360                                 "{}{}{} {}{}",
1361                                 if sp.is_desugaring(DesugaringKind::Async) {
1362                                     "the `Output` of this `async fn`'s "
1363                                 } else if count == 1 {
1364                                     "the "
1365                                 } else {
1366                                     ""
1367                                 },
1368                                 if count > 1 { "one of the " } else { "" },
1369                                 target,
1370                                 kind,
1371                                 pluralize!(count),
1372                             ),
1373                         );
1374                     }
1375                 }
1376             }
1377         }
1378
1379         impl<'tcx> ty::fold::TypeVisitor<'tcx> for OpaqueTypesVisitor<'tcx> {
1380             fn visit_ty(&mut self, t: Ty<'tcx>) -> bool {
1381                 if let Some((kind, def_id)) = TyCategory::from_ty(t) {
1382                     let span = self.tcx.def_span(def_id);
1383                     // Avoid cluttering the output when the "found" and error span overlap:
1384                     //
1385                     // error[E0308]: mismatched types
1386                     //   --> $DIR/issue-20862.rs:2:5
1387                     //    |
1388                     // LL |     |y| x + y
1389                     //    |     ^^^^^^^^^
1390                     //    |     |
1391                     //    |     the found closure
1392                     //    |     expected `()`, found closure
1393                     //    |
1394                     //    = note: expected unit type `()`
1395                     //                 found closure `[closure@$DIR/issue-20862.rs:2:5: 2:14 x:_]`
1396                     if !self.ignore_span.overlaps(span) {
1397                         self.types.entry(kind).or_default().insert(span);
1398                     }
1399                 }
1400                 t.super_visit_with(self)
1401             }
1402         }
1403
1404         debug!("note_type_err(diag={:?})", diag);
1405         enum Mismatch<'a> {
1406             Variable(ty::error::ExpectedFound<Ty<'a>>),
1407             Fixed(&'static str),
1408         }
1409         let (expected_found, exp_found, is_simple_error) = match values {
1410             None => (None, Mismatch::Fixed("type"), false),
1411             Some(values) => {
1412                 let (is_simple_error, exp_found) = match values {
1413                     ValuePairs::Types(exp_found) => {
1414                         let is_simple_err =
1415                             exp_found.expected.is_simple_text() && exp_found.found.is_simple_text();
1416                         OpaqueTypesVisitor::visit_expected_found(
1417                             self.tcx,
1418                             exp_found.expected,
1419                             exp_found.found,
1420                             span,
1421                         )
1422                         .report(diag);
1423
1424                         (is_simple_err, Mismatch::Variable(exp_found))
1425                     }
1426                     ValuePairs::TraitRefs(_) => (false, Mismatch::Fixed("trait")),
1427                     _ => (false, Mismatch::Fixed("type")),
1428                 };
1429                 let vals = match self.values_str(&values) {
1430                     Some((expected, found)) => Some((expected, found)),
1431                     None => {
1432                         // Derived error. Cancel the emitter.
1433                         diag.cancel();
1434                         return;
1435                     }
1436                 };
1437                 (vals, exp_found, is_simple_error)
1438             }
1439         };
1440
1441         // Ignore msg for object safe coercion
1442         // since E0038 message will be printed
1443         match terr {
1444             TypeError::ObjectUnsafeCoercion(_) => {}
1445             _ => {
1446                 diag.span_label(span, terr.to_string());
1447                 if let Some((sp, msg)) = secondary_span {
1448                     diag.span_label(sp, msg);
1449                 }
1450             }
1451         };
1452         if let Some((expected, found)) = expected_found {
1453             let expected_label = match exp_found {
1454                 Mismatch::Variable(ef) => ef.expected.prefix_string(),
1455                 Mismatch::Fixed(s) => s.into(),
1456             };
1457             let found_label = match exp_found {
1458                 Mismatch::Variable(ef) => ef.found.prefix_string(),
1459                 Mismatch::Fixed(s) => s.into(),
1460             };
1461             let exp_found = match exp_found {
1462                 Mismatch::Variable(exp_found) => Some(exp_found),
1463                 Mismatch::Fixed(_) => None,
1464             };
1465             match (&terr, expected == found) {
1466                 (TypeError::Sorts(values), extra) => {
1467                     let sort_string = |ty: Ty<'tcx>| match (extra, &ty.kind) {
1468                         (true, ty::Opaque(def_id, _)) => format!(
1469                             " (opaque type at {})",
1470                             self.tcx
1471                                 .sess
1472                                 .source_map()
1473                                 .mk_substr_filename(self.tcx.def_span(*def_id)),
1474                         ),
1475                         (true, _) => format!(" ({})", ty.sort_string(self.tcx)),
1476                         (false, _) => "".to_string(),
1477                     };
1478                     if !(values.expected.is_simple_text() && values.found.is_simple_text())
1479                         || (exp_found.map_or(false, |ef| {
1480                             // This happens when the type error is a subset of the expectation,
1481                             // like when you have two references but one is `usize` and the other
1482                             // is `f32`. In those cases we still want to show the `note`. If the
1483                             // value from `ef` is `Infer(_)`, then we ignore it.
1484                             if !ef.expected.is_ty_infer() {
1485                                 ef.expected != values.expected
1486                             } else if !ef.found.is_ty_infer() {
1487                                 ef.found != values.found
1488                             } else {
1489                                 false
1490                             }
1491                         }))
1492                     {
1493                         diag.note_expected_found_extra(
1494                             &expected_label,
1495                             expected,
1496                             &found_label,
1497                             found,
1498                             &sort_string(values.expected),
1499                             &sort_string(values.found),
1500                         );
1501                     }
1502                 }
1503                 (TypeError::ObjectUnsafeCoercion(_), _) => {
1504                     diag.note_unsuccessfull_coercion(found, expected);
1505                 }
1506                 (_, _) => {
1507                     debug!(
1508                         "note_type_err: exp_found={:?}, expected={:?} found={:?}",
1509                         exp_found, expected, found
1510                     );
1511                     if !is_simple_error || terr.must_include_note() {
1512                         diag.note_expected_found(&expected_label, expected, &found_label, found);
1513                     }
1514                 }
1515             }
1516         }
1517         let exp_found = match exp_found {
1518             Mismatch::Variable(exp_found) => Some(exp_found),
1519             Mismatch::Fixed(_) => None,
1520         };
1521         if let Some(exp_found) = exp_found {
1522             self.suggest_as_ref_where_appropriate(span, &exp_found, diag);
1523         }
1524
1525         // In some (most?) cases cause.body_id points to actual body, but in some cases
1526         // it's a actual definition. According to the comments (e.g. in
1527         // librustc_typeck/check/compare_method.rs:compare_predicate_entailment) the latter
1528         // is relied upon by some other code. This might (or might not) need cleanup.
1529         let body_owner_def_id =
1530             self.tcx.hir().opt_local_def_id(cause.body_id).unwrap_or_else(|| {
1531                 self.tcx.hir().body_owner_def_id(hir::BodyId { hir_id: cause.body_id })
1532             });
1533         self.check_and_note_conflicting_crates(diag, terr);
1534         self.tcx.note_and_explain_type_err(diag, terr, cause, span, body_owner_def_id.to_def_id());
1535
1536         // It reads better to have the error origin as the final
1537         // thing.
1538         self.note_error_origin(diag, cause, exp_found);
1539     }
1540
1541     /// When encountering a case where `.as_ref()` on a `Result` or `Option` would be appropriate,
1542     /// suggests it.
1543     fn suggest_as_ref_where_appropriate(
1544         &self,
1545         span: Span,
1546         exp_found: &ty::error::ExpectedFound<Ty<'tcx>>,
1547         diag: &mut DiagnosticBuilder<'tcx>,
1548     ) {
1549         if let (ty::Adt(exp_def, exp_substs), ty::Ref(_, found_ty, _)) =
1550             (&exp_found.expected.kind, &exp_found.found.kind)
1551         {
1552             if let ty::Adt(found_def, found_substs) = found_ty.kind {
1553                 let path_str = format!("{:?}", exp_def);
1554                 if exp_def == &found_def {
1555                     let opt_msg = "you can convert from `&Option<T>` to `Option<&T>` using \
1556                                        `.as_ref()`";
1557                     let result_msg = "you can convert from `&Result<T, E>` to \
1558                                           `Result<&T, &E>` using `.as_ref()`";
1559                     let have_as_ref = &[
1560                         ("std::option::Option", opt_msg),
1561                         ("core::option::Option", opt_msg),
1562                         ("std::result::Result", result_msg),
1563                         ("core::result::Result", result_msg),
1564                     ];
1565                     if let Some(msg) = have_as_ref
1566                         .iter()
1567                         .find_map(|(path, msg)| (&path_str == path).then_some(msg))
1568                     {
1569                         let mut show_suggestion = true;
1570                         for (exp_ty, found_ty) in exp_substs.types().zip(found_substs.types()) {
1571                             match exp_ty.kind {
1572                                 ty::Ref(_, exp_ty, _) => {
1573                                     match (&exp_ty.kind, &found_ty.kind) {
1574                                         (_, ty::Param(_))
1575                                         | (_, ty::Infer(_))
1576                                         | (ty::Param(_), _)
1577                                         | (ty::Infer(_), _) => {}
1578                                         _ if ty::TyS::same_type(exp_ty, found_ty) => {}
1579                                         _ => show_suggestion = false,
1580                                     };
1581                                 }
1582                                 ty::Param(_) | ty::Infer(_) => {}
1583                                 _ => show_suggestion = false,
1584                             }
1585                         }
1586                         if let (Ok(snippet), true) =
1587                             (self.tcx.sess.source_map().span_to_snippet(span), show_suggestion)
1588                         {
1589                             diag.span_suggestion(
1590                                 span,
1591                                 msg,
1592                                 format!("{}.as_ref()", snippet),
1593                                 Applicability::MachineApplicable,
1594                             );
1595                         }
1596                     }
1597                 }
1598             }
1599         }
1600     }
1601
1602     pub fn report_and_explain_type_error(
1603         &self,
1604         trace: TypeTrace<'tcx>,
1605         terr: &TypeError<'tcx>,
1606     ) -> DiagnosticBuilder<'tcx> {
1607         debug!("report_and_explain_type_error(trace={:?}, terr={:?})", trace, terr);
1608
1609         let span = trace.cause.span(self.tcx);
1610         let failure_code = trace.cause.as_failure_code(terr);
1611         let mut diag = match failure_code {
1612             FailureCode::Error0038(did) => {
1613                 let violations = self.tcx.object_safety_violations(did);
1614                 report_object_safety_error(self.tcx, span, did, violations)
1615             }
1616             FailureCode::Error0317(failure_str) => {
1617                 struct_span_err!(self.tcx.sess, span, E0317, "{}", failure_str)
1618             }
1619             FailureCode::Error0580(failure_str) => {
1620                 struct_span_err!(self.tcx.sess, span, E0580, "{}", failure_str)
1621             }
1622             FailureCode::Error0308(failure_str) => {
1623                 struct_span_err!(self.tcx.sess, span, E0308, "{}", failure_str)
1624             }
1625             FailureCode::Error0644(failure_str) => {
1626                 struct_span_err!(self.tcx.sess, span, E0644, "{}", failure_str)
1627             }
1628         };
1629         self.note_type_err(&mut diag, &trace.cause, None, Some(trace.values), terr);
1630         diag
1631     }
1632
1633     fn values_str(
1634         &self,
1635         values: &ValuePairs<'tcx>,
1636     ) -> Option<(DiagnosticStyledString, DiagnosticStyledString)> {
1637         match *values {
1638             infer::Types(ref exp_found) => self.expected_found_str_ty(exp_found),
1639             infer::Regions(ref exp_found) => self.expected_found_str(exp_found),
1640             infer::Consts(ref exp_found) => self.expected_found_str(exp_found),
1641             infer::TraitRefs(ref exp_found) => {
1642                 let pretty_exp_found = ty::error::ExpectedFound {
1643                     expected: exp_found.expected.print_only_trait_path(),
1644                     found: exp_found.found.print_only_trait_path(),
1645                 };
1646                 self.expected_found_str(&pretty_exp_found)
1647             }
1648             infer::PolyTraitRefs(ref exp_found) => {
1649                 let pretty_exp_found = ty::error::ExpectedFound {
1650                     expected: exp_found.expected.print_only_trait_path(),
1651                     found: exp_found.found.print_only_trait_path(),
1652                 };
1653                 self.expected_found_str(&pretty_exp_found)
1654             }
1655         }
1656     }
1657
1658     fn expected_found_str_ty(
1659         &self,
1660         exp_found: &ty::error::ExpectedFound<Ty<'tcx>>,
1661     ) -> Option<(DiagnosticStyledString, DiagnosticStyledString)> {
1662         let exp_found = self.resolve_vars_if_possible(exp_found);
1663         if exp_found.references_error() {
1664             return None;
1665         }
1666
1667         Some(self.cmp(exp_found.expected, exp_found.found))
1668     }
1669
1670     /// Returns a string of the form "expected `{}`, found `{}`".
1671     fn expected_found_str<T: fmt::Display + TypeFoldable<'tcx>>(
1672         &self,
1673         exp_found: &ty::error::ExpectedFound<T>,
1674     ) -> Option<(DiagnosticStyledString, DiagnosticStyledString)> {
1675         let exp_found = self.resolve_vars_if_possible(exp_found);
1676         if exp_found.references_error() {
1677             return None;
1678         }
1679
1680         Some((
1681             DiagnosticStyledString::highlighted(exp_found.expected.to_string()),
1682             DiagnosticStyledString::highlighted(exp_found.found.to_string()),
1683         ))
1684     }
1685
1686     pub fn report_generic_bound_failure(
1687         &self,
1688         span: Span,
1689         origin: Option<SubregionOrigin<'tcx>>,
1690         bound_kind: GenericKind<'tcx>,
1691         sub: Region<'tcx>,
1692     ) {
1693         self.construct_generic_bound_failure(span, origin, bound_kind, sub).emit();
1694     }
1695
1696     pub fn construct_generic_bound_failure(
1697         &self,
1698         span: Span,
1699         origin: Option<SubregionOrigin<'tcx>>,
1700         bound_kind: GenericKind<'tcx>,
1701         sub: Region<'tcx>,
1702     ) -> DiagnosticBuilder<'a> {
1703         let hir = &self.tcx.hir();
1704         // Attempt to obtain the span of the parameter so we can
1705         // suggest adding an explicit lifetime bound to it.
1706         let generics = self
1707             .in_progress_typeck_results
1708             .map(|typeck_results| typeck_results.borrow().hir_owner)
1709             .map(|owner| {
1710                 let hir_id = hir.local_def_id_to_hir_id(owner);
1711                 let parent_id = hir.get_parent_item(hir_id);
1712                 (
1713                     // Parent item could be a `mod`, so we check the HIR before calling:
1714                     if let Some(Node::Item(Item {
1715                         kind: ItemKind::Trait(..) | ItemKind::Impl { .. },
1716                         ..
1717                     })) = hir.find(parent_id)
1718                     {
1719                         Some(self.tcx.generics_of(hir.local_def_id(parent_id).to_def_id()))
1720                     } else {
1721                         None
1722                     },
1723                     self.tcx.generics_of(owner.to_def_id()),
1724                 )
1725             });
1726         let type_param_span = match (generics, bound_kind) {
1727             (Some((_, ref generics)), GenericKind::Param(ref param)) => {
1728                 // Account for the case where `param` corresponds to `Self`,
1729                 // which doesn't have the expected type argument.
1730                 if !(generics.has_self && param.index == 0) {
1731                     let type_param = generics.type_param(param, self.tcx);
1732                     type_param.def_id.as_local().map(|def_id| {
1733                         // Get the `hir::Param` to verify whether it already has any bounds.
1734                         // We do this to avoid suggesting code that ends up as `T: 'a'b`,
1735                         // instead we suggest `T: 'a + 'b` in that case.
1736                         let id = hir.local_def_id_to_hir_id(def_id);
1737                         let mut has_bounds = false;
1738                         if let Node::GenericParam(param) = hir.get(id) {
1739                             has_bounds = !param.bounds.is_empty();
1740                         }
1741                         let sp = hir.span(id);
1742                         // `sp` only covers `T`, change it so that it covers
1743                         // `T:` when appropriate
1744                         let is_impl_trait = bound_kind.to_string().starts_with("impl ");
1745                         let sp = if has_bounds && !is_impl_trait {
1746                             sp.to(self
1747                                 .tcx
1748                                 .sess
1749                                 .source_map()
1750                                 .next_point(self.tcx.sess.source_map().next_point(sp)))
1751                         } else {
1752                             sp
1753                         };
1754                         (sp, has_bounds, is_impl_trait)
1755                     })
1756                 } else {
1757                     None
1758                 }
1759             }
1760             _ => None,
1761         };
1762         let new_lt = generics
1763             .as_ref()
1764             .and_then(|(parent_g, g)| {
1765                 let possible: Vec<_> = (b'a'..=b'z').map(|c| format!("'{}", c as char)).collect();
1766                 let mut lts_names = g
1767                     .params
1768                     .iter()
1769                     .filter(|p| matches!(p.kind, ty::GenericParamDefKind::Lifetime))
1770                     .map(|p| p.name.as_str())
1771                     .collect::<Vec<_>>();
1772                 if let Some(g) = parent_g {
1773                     lts_names.extend(
1774                         g.params
1775                             .iter()
1776                             .filter(|p| matches!(p.kind, ty::GenericParamDefKind::Lifetime))
1777                             .map(|p| p.name.as_str()),
1778                     );
1779                 }
1780                 let lts = lts_names.iter().map(|s| -> &str { &*s }).collect::<Vec<_>>();
1781                 possible.into_iter().find(|candidate| !lts.contains(&candidate.as_str()))
1782             })
1783             .unwrap_or("'lt".to_string());
1784         let add_lt_sugg = generics
1785             .as_ref()
1786             .and_then(|(_, g)| g.params.first())
1787             .and_then(|param| param.def_id.as_local())
1788             .map(|def_id| {
1789                 (
1790                     hir.span(hir.local_def_id_to_hir_id(def_id)).shrink_to_lo(),
1791                     format!("{}, ", new_lt),
1792                 )
1793             });
1794
1795         let labeled_user_string = match bound_kind {
1796             GenericKind::Param(ref p) => format!("the parameter type `{}`", p),
1797             GenericKind::Projection(ref p) => format!("the associated type `{}`", p),
1798         };
1799
1800         if let Some(SubregionOrigin::CompareImplMethodObligation {
1801             span,
1802             item_name,
1803             impl_item_def_id,
1804             trait_item_def_id,
1805         }) = origin
1806         {
1807             return self.report_extra_impl_obligation(
1808                 span,
1809                 item_name,
1810                 impl_item_def_id,
1811                 trait_item_def_id,
1812                 &format!("`{}: {}`", bound_kind, sub),
1813             );
1814         }
1815
1816         fn binding_suggestion<'tcx, S: fmt::Display>(
1817             err: &mut DiagnosticBuilder<'tcx>,
1818             type_param_span: Option<(Span, bool, bool)>,
1819             bound_kind: GenericKind<'tcx>,
1820             sub: S,
1821         ) {
1822             let msg = "consider adding an explicit lifetime bound";
1823             if let Some((sp, has_lifetimes, is_impl_trait)) = type_param_span {
1824                 let suggestion = if is_impl_trait {
1825                     format!("{} + {}", bound_kind, sub)
1826                 } else {
1827                     let tail = if has_lifetimes { " + " } else { "" };
1828                     format!("{}: {}{}", bound_kind, sub, tail)
1829                 };
1830                 err.span_suggestion(
1831                     sp,
1832                     &format!("{}...", msg),
1833                     suggestion,
1834                     Applicability::MaybeIncorrect, // Issue #41966
1835                 );
1836             } else {
1837                 let consider = format!(
1838                     "{} {}...",
1839                     msg,
1840                     if type_param_span.map(|(_, _, is_impl_trait)| is_impl_trait).unwrap_or(false) {
1841                         format!(" `{}` to `{}`", sub, bound_kind)
1842                     } else {
1843                         format!("`{}: {}`", bound_kind, sub)
1844                     },
1845                 );
1846                 err.help(&consider);
1847             }
1848         }
1849
1850         let new_binding_suggestion =
1851             |err: &mut DiagnosticBuilder<'tcx>,
1852              type_param_span: Option<(Span, bool, bool)>,
1853              bound_kind: GenericKind<'tcx>| {
1854                 let msg = "consider introducing an explicit lifetime bound";
1855                 if let Some((sp, has_lifetimes, is_impl_trait)) = type_param_span {
1856                     let suggestion = if is_impl_trait {
1857                         (sp.shrink_to_hi(), format!(" + {}", new_lt))
1858                     } else {
1859                         let tail = if has_lifetimes { " +" } else { "" };
1860                         (sp, format!("{}: {}{}", bound_kind, new_lt, tail))
1861                     };
1862                     let mut sugg =
1863                         vec![suggestion, (span.shrink_to_hi(), format!(" + {}", new_lt))];
1864                     if let Some(lt) = add_lt_sugg {
1865                         sugg.push(lt);
1866                         sugg.rotate_right(1);
1867                     }
1868                     // `MaybeIncorrect` due to issue #41966.
1869                     err.multipart_suggestion(msg, sugg, Applicability::MaybeIncorrect);
1870                 }
1871             };
1872
1873         let mut err = match *sub {
1874             ty::ReEarlyBound(ty::EarlyBoundRegion { name, .. })
1875             | ty::ReFree(ty::FreeRegion { bound_region: ty::BrNamed(_, name), .. }) => {
1876                 // Does the required lifetime have a nice name we can print?
1877                 let mut err = struct_span_err!(
1878                     self.tcx.sess,
1879                     span,
1880                     E0309,
1881                     "{} may not live long enough",
1882                     labeled_user_string
1883                 );
1884                 // Explicitly use the name instead of `sub`'s `Display` impl. The `Display` impl
1885                 // for the bound is not suitable for suggestions when `-Zverbose` is set because it
1886                 // uses `Debug` output, so we handle it specially here so that suggestions are
1887                 // always correct.
1888                 binding_suggestion(&mut err, type_param_span, bound_kind, name);
1889                 err
1890             }
1891
1892             ty::ReStatic => {
1893                 // Does the required lifetime have a nice name we can print?
1894                 let mut err = struct_span_err!(
1895                     self.tcx.sess,
1896                     span,
1897                     E0310,
1898                     "{} may not live long enough",
1899                     labeled_user_string
1900                 );
1901                 binding_suggestion(&mut err, type_param_span, bound_kind, "'static");
1902                 err
1903             }
1904
1905             _ => {
1906                 // If not, be less specific.
1907                 let mut err = struct_span_err!(
1908                     self.tcx.sess,
1909                     span,
1910                     E0311,
1911                     "{} may not live long enough",
1912                     labeled_user_string
1913                 );
1914                 note_and_explain_region(
1915                     self.tcx,
1916                     &mut err,
1917                     &format!("{} must be valid for ", labeled_user_string),
1918                     sub,
1919                     "...",
1920                 );
1921                 if let Some(infer::RelateParamBound(_, t)) = origin {
1922                     let t = self.resolve_vars_if_possible(&t);
1923                     match t.kind {
1924                         // We've got:
1925                         // fn get_later<G, T>(g: G, dest: &mut T) -> impl FnOnce() + '_
1926                         // suggest:
1927                         // fn get_later<'a, G: 'a, T>(g: G, dest: &mut T) -> impl FnOnce() + '_ + 'a
1928                         ty::Closure(_, _substs) | ty::Opaque(_, _substs) => {
1929                             new_binding_suggestion(&mut err, type_param_span, bound_kind);
1930                         }
1931                         _ => {
1932                             binding_suggestion(&mut err, type_param_span, bound_kind, new_lt);
1933                         }
1934                     }
1935                 }
1936                 err
1937             }
1938         };
1939
1940         if let Some(origin) = origin {
1941             self.note_region_origin(&mut err, &origin);
1942         }
1943         err
1944     }
1945
1946     fn report_sub_sup_conflict(
1947         &self,
1948         var_origin: RegionVariableOrigin,
1949         sub_origin: SubregionOrigin<'tcx>,
1950         sub_region: Region<'tcx>,
1951         sup_origin: SubregionOrigin<'tcx>,
1952         sup_region: Region<'tcx>,
1953     ) {
1954         let mut err = self.report_inference_failure(var_origin);
1955
1956         note_and_explain_region(
1957             self.tcx,
1958             &mut err,
1959             "first, the lifetime cannot outlive ",
1960             sup_region,
1961             "...",
1962         );
1963
1964         debug!("report_sub_sup_conflict: var_origin={:?}", var_origin);
1965         debug!("report_sub_sup_conflict: sub_region={:?}", sub_region);
1966         debug!("report_sub_sup_conflict: sub_origin={:?}", sub_origin);
1967         debug!("report_sub_sup_conflict: sup_region={:?}", sup_region);
1968         debug!("report_sub_sup_conflict: sup_origin={:?}", sup_origin);
1969
1970         if let (&infer::Subtype(ref sup_trace), &infer::Subtype(ref sub_trace)) =
1971             (&sup_origin, &sub_origin)
1972         {
1973             debug!("report_sub_sup_conflict: sup_trace={:?}", sup_trace);
1974             debug!("report_sub_sup_conflict: sub_trace={:?}", sub_trace);
1975             debug!("report_sub_sup_conflict: sup_trace.values={:?}", sup_trace.values);
1976             debug!("report_sub_sup_conflict: sub_trace.values={:?}", sub_trace.values);
1977
1978             if let (Some((sup_expected, sup_found)), Some((sub_expected, sub_found))) =
1979                 (self.values_str(&sup_trace.values), self.values_str(&sub_trace.values))
1980             {
1981                 if sub_expected == sup_expected && sub_found == sup_found {
1982                     note_and_explain_region(
1983                         self.tcx,
1984                         &mut err,
1985                         "...but the lifetime must also be valid for ",
1986                         sub_region,
1987                         "...",
1988                     );
1989                     err.span_note(
1990                         sup_trace.cause.span,
1991                         &format!("...so that the {}", sup_trace.cause.as_requirement_str()),
1992                     );
1993
1994                     err.note_expected_found(&"", sup_expected, &"", sup_found);
1995                     err.emit();
1996                     return;
1997                 }
1998             }
1999         }
2000
2001         self.note_region_origin(&mut err, &sup_origin);
2002
2003         note_and_explain_region(
2004             self.tcx,
2005             &mut err,
2006             "but, the lifetime must be valid for ",
2007             sub_region,
2008             "...",
2009         );
2010
2011         self.note_region_origin(&mut err, &sub_origin);
2012         err.emit();
2013     }
2014 }
2015
2016 impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
2017     fn report_inference_failure(
2018         &self,
2019         var_origin: RegionVariableOrigin,
2020     ) -> DiagnosticBuilder<'tcx> {
2021         let br_string = |br: ty::BoundRegion| {
2022             let mut s = match br {
2023                 ty::BrNamed(_, name) => name.to_string(),
2024                 _ => String::new(),
2025             };
2026             if !s.is_empty() {
2027                 s.push_str(" ");
2028             }
2029             s
2030         };
2031         let var_description = match var_origin {
2032             infer::MiscVariable(_) => String::new(),
2033             infer::PatternRegion(_) => " for pattern".to_string(),
2034             infer::AddrOfRegion(_) => " for borrow expression".to_string(),
2035             infer::Autoref(_, _) => " for autoref".to_string(),
2036             infer::Coercion(_) => " for automatic coercion".to_string(),
2037             infer::LateBoundRegion(_, br, infer::FnCall) => {
2038                 format!(" for lifetime parameter {}in function call", br_string(br))
2039             }
2040             infer::LateBoundRegion(_, br, infer::HigherRankedType) => {
2041                 format!(" for lifetime parameter {}in generic type", br_string(br))
2042             }
2043             infer::LateBoundRegion(_, br, infer::AssocTypeProjection(def_id)) => format!(
2044                 " for lifetime parameter {}in trait containing associated type `{}`",
2045                 br_string(br),
2046                 self.tcx.associated_item(def_id).ident
2047             ),
2048             infer::EarlyBoundRegion(_, name) => format!(" for lifetime parameter `{}`", name),
2049             infer::BoundRegionInCoherence(name) => {
2050                 format!(" for lifetime parameter `{}` in coherence check", name)
2051             }
2052             infer::UpvarRegion(ref upvar_id, _) => {
2053                 let var_name = self.tcx.hir().name(upvar_id.var_path.hir_id);
2054                 format!(" for capture of `{}` by closure", var_name)
2055             }
2056             infer::NLL(..) => bug!("NLL variable found in lexical phase"),
2057         };
2058
2059         struct_span_err!(
2060             self.tcx.sess,
2061             var_origin.span(),
2062             E0495,
2063             "cannot infer an appropriate lifetime{} due to conflicting requirements",
2064             var_description
2065         )
2066     }
2067 }
2068
2069 enum FailureCode {
2070     Error0038(DefId),
2071     Error0317(&'static str),
2072     Error0580(&'static str),
2073     Error0308(&'static str),
2074     Error0644(&'static str),
2075 }
2076
2077 trait ObligationCauseExt<'tcx> {
2078     fn as_failure_code(&self, terr: &TypeError<'tcx>) -> FailureCode;
2079     fn as_requirement_str(&self) -> &'static str;
2080 }
2081
2082 impl<'tcx> ObligationCauseExt<'tcx> for ObligationCause<'tcx> {
2083     fn as_failure_code(&self, terr: &TypeError<'tcx>) -> FailureCode {
2084         use self::FailureCode::*;
2085         use crate::traits::ObligationCauseCode::*;
2086         match self.code {
2087             CompareImplMethodObligation { .. } => Error0308("method not compatible with trait"),
2088             CompareImplTypeObligation { .. } => Error0308("type not compatible with trait"),
2089             MatchExpressionArm(box MatchExpressionArmCause { source, .. }) => {
2090                 Error0308(match source {
2091                     hir::MatchSource::IfLetDesugar { .. } => {
2092                         "`if let` arms have incompatible types"
2093                     }
2094                     hir::MatchSource::TryDesugar => {
2095                         "try expression alternatives have incompatible types"
2096                     }
2097                     _ => "`match` arms have incompatible types",
2098                 })
2099             }
2100             IfExpression { .. } => Error0308("`if` and `else` have incompatible types"),
2101             IfExpressionWithNoElse => Error0317("`if` may be missing an `else` clause"),
2102             MainFunctionType => Error0580("`main` function has wrong type"),
2103             StartFunctionType => Error0308("`#[start]` function has wrong type"),
2104             IntrinsicType => Error0308("intrinsic has wrong type"),
2105             MethodReceiver => Error0308("mismatched `self` parameter type"),
2106
2107             // In the case where we have no more specific thing to
2108             // say, also take a look at the error code, maybe we can
2109             // tailor to that.
2110             _ => match terr {
2111                 TypeError::CyclicTy(ty) if ty.is_closure() || ty.is_generator() => {
2112                     Error0644("closure/generator type that references itself")
2113                 }
2114                 TypeError::IntrinsicCast => {
2115                     Error0308("cannot coerce intrinsics to function pointers")
2116                 }
2117                 TypeError::ObjectUnsafeCoercion(did) => Error0038(*did),
2118                 _ => Error0308("mismatched types"),
2119             },
2120         }
2121     }
2122
2123     fn as_requirement_str(&self) -> &'static str {
2124         use crate::traits::ObligationCauseCode::*;
2125         match self.code {
2126             CompareImplMethodObligation { .. } => "method type is compatible with trait",
2127             CompareImplTypeObligation { .. } => "associated type is compatible with trait",
2128             ExprAssignable => "expression is assignable",
2129             MatchExpressionArm(box MatchExpressionArmCause { source, .. }) => match source {
2130                 hir::MatchSource::IfLetDesugar { .. } => "`if let` arms have compatible types",
2131                 _ => "`match` arms have compatible types",
2132             },
2133             IfExpression { .. } => "`if` and `else` have incompatible types",
2134             IfExpressionWithNoElse => "`if` missing an `else` returns `()`",
2135             MainFunctionType => "`main` function has the correct type",
2136             StartFunctionType => "`#[start]` function has the correct type",
2137             IntrinsicType => "intrinsic has the correct type",
2138             MethodReceiver => "method receiver has the correct type",
2139             _ => "types are compatible",
2140         }
2141     }
2142 }
2143
2144 /// This is a bare signal of what kind of type we're dealing with. `ty::TyKind` tracks
2145 /// extra information about each type, but we only care about the category.
2146 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
2147 pub enum TyCategory {
2148     Closure,
2149     Opaque,
2150     Generator,
2151     Foreign,
2152 }
2153
2154 impl TyCategory {
2155     fn descr(&self) -> &'static str {
2156         match self {
2157             Self::Closure => "closure",
2158             Self::Opaque => "opaque type",
2159             Self::Generator => "generator",
2160             Self::Foreign => "foreign type",
2161         }
2162     }
2163
2164     pub fn from_ty(ty: Ty<'_>) -> Option<(Self, DefId)> {
2165         match ty.kind {
2166             ty::Closure(def_id, _) => Some((Self::Closure, def_id)),
2167             ty::Opaque(def_id, _) => Some((Self::Opaque, def_id)),
2168             ty::Generator(def_id, ..) => Some((Self::Generator, def_id)),
2169             ty::Foreign(def_id) => Some((Self::Foreign, def_id)),
2170             _ => None,
2171         }
2172     }
2173 }