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