]> git.lizzy.rs Git - rust.git/blob - src/librustc/infer/error_reporting/mod.rs
rustc: rename PrintContext to PrintCx.
[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 use crate::infer::{self, SuppressRegionErrors};
52
53 use crate::hir;
54 use crate::hir::def_id::DefId;
55 use crate::hir::Node;
56 use crate::middle::region;
57 use crate::traits::{ObligationCause, ObligationCauseCode};
58 use crate::ty::error::TypeError;
59 use crate::ty::{self, subst::{Subst, SubstsRef}, Region, Ty, TyCtxt, TyKind, TypeFoldable};
60 use errors::{Applicability, DiagnosticBuilder, DiagnosticStyledString};
61 use std::{cmp, fmt};
62 use syntax_pos::{Pos, Span};
63
64 mod note;
65
66 mod need_type_info;
67
68 pub mod nice_region_error;
69
70 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
71     pub fn note_and_explain_region(
72         self,
73         region_scope_tree: &region::ScopeTree,
74         err: &mut DiagnosticBuilder<'_>,
75         prefix: &str,
76         region: ty::Region<'tcx>,
77         suffix: &str,
78     ) {
79         let (description, span) = match *region {
80             ty::ReScope(scope) => {
81                 let new_string;
82                 let unknown_scope = || {
83                     format!(
84                         "{}unknown scope: {:?}{}.  Please report a bug.",
85                         prefix, scope, suffix
86                     )
87                 };
88                 let span = scope.span(self, region_scope_tree);
89                 let tag = match self.hir().find(scope.node_id(self, region_scope_tree)) {
90                     Some(Node::Block(_)) => "block",
91                     Some(Node::Expr(expr)) => match expr.node {
92                         hir::ExprKind::Call(..) => "call",
93                         hir::ExprKind::MethodCall(..) => "method call",
94                         hir::ExprKind::Match(.., hir::MatchSource::IfLetDesugar { .. }) => "if let",
95                         hir::ExprKind::Match(.., hir::MatchSource::WhileLetDesugar) => "while let",
96                         hir::ExprKind::Match(.., hir::MatchSource::ForLoopDesugar) => "for",
97                         hir::ExprKind::Match(..) => "match",
98                         _ => "expression",
99                     },
100                     Some(Node::Stmt(_)) => "statement",
101                     Some(Node::Item(it)) => Self::item_scope_tag(&it),
102                     Some(Node::TraitItem(it)) => Self::trait_item_scope_tag(&it),
103                     Some(Node::ImplItem(it)) => Self::impl_item_scope_tag(&it),
104                     Some(_) | None => {
105                         err.span_note(span, &unknown_scope());
106                         return;
107                     }
108                 };
109                 let scope_decorated_tag = match scope.data {
110                     region::ScopeData::Node => tag,
111                     region::ScopeData::CallSite => "scope of call-site for function",
112                     region::ScopeData::Arguments => "scope of function body",
113                     region::ScopeData::Destruction => {
114                         new_string = format!("destruction scope surrounding {}", tag);
115                         &new_string[..]
116                     }
117                     region::ScopeData::Remainder(first_statement_index) => {
118                         new_string = format!(
119                             "block suffix following statement {}",
120                             first_statement_index.index()
121                         );
122                         &new_string[..]
123                     }
124                 };
125                 self.explain_span(scope_decorated_tag, span)
126             }
127
128             ty::ReEarlyBound(_) | ty::ReFree(_) | ty::ReStatic => {
129                 self.msg_span_from_free_region(region)
130             }
131
132             ty::ReEmpty => ("the empty lifetime".to_owned(), None),
133
134             ty::RePlaceholder(_) => (format!("any other region"), None),
135
136             // FIXME(#13998) RePlaceholder should probably print like
137             // ReFree rather than dumping Debug output on the user.
138             //
139             // We shouldn't really be having unification failures with ReVar
140             // and ReLateBound though.
141             ty::ReVar(_) | ty::ReLateBound(..) | ty::ReErased => {
142                 (format!("lifetime {:?}", region), None)
143             }
144
145             // We shouldn't encounter an error message with ReClosureBound.
146             ty::ReClosureBound(..) => {
147                 bug!("encountered unexpected ReClosureBound: {:?}", region,);
148             }
149         };
150
151         TyCtxt::emit_msg_span(err, prefix, description, span, suffix);
152     }
153
154     pub fn note_and_explain_free_region(
155         self,
156         err: &mut DiagnosticBuilder<'_>,
157         prefix: &str,
158         region: ty::Region<'tcx>,
159         suffix: &str,
160     ) {
161         let (description, span) = self.msg_span_from_free_region(region);
162
163         TyCtxt::emit_msg_span(err, prefix, description, span, suffix);
164     }
165
166     fn msg_span_from_free_region(self, region: ty::Region<'tcx>) -> (String, Option<Span>) {
167         match *region {
168             ty::ReEarlyBound(_) | ty::ReFree(_) => {
169                 self.msg_span_from_early_bound_and_free_regions(region)
170             }
171             ty::ReStatic => ("the static lifetime".to_owned(), None),
172             ty::ReEmpty => ("an empty lifetime".to_owned(), None),
173             _ => bug!("{:?}", region),
174         }
175     }
176
177     fn msg_span_from_early_bound_and_free_regions(
178         self,
179         region: ty::Region<'tcx>,
180     ) -> (String, Option<Span>) {
181         let cm = self.sess.source_map();
182
183         let scope = region.free_region_binding_scope(self);
184         let node = self.hir().as_local_hir_id(scope).unwrap_or(hir::DUMMY_HIR_ID);
185         let tag = match self.hir().find_by_hir_id(node) {
186             Some(Node::Block(_)) | Some(Node::Expr(_)) => "body",
187             Some(Node::Item(it)) => Self::item_scope_tag(&it),
188             Some(Node::TraitItem(it)) => Self::trait_item_scope_tag(&it),
189             Some(Node::ImplItem(it)) => Self::impl_item_scope_tag(&it),
190             _ => unreachable!(),
191         };
192         let (prefix, span) = match *region {
193             ty::ReEarlyBound(ref br) => {
194                 let mut sp = cm.def_span(self.hir().span_by_hir_id(node));
195                 if let Some(param) = self.hir()
196                     .get_generics(scope)
197                     .and_then(|generics| generics.get_named(&br.name))
198                 {
199                     sp = param.span;
200                 }
201                 (format!("the lifetime {} as defined on", br.name), sp)
202             }
203             ty::ReFree(ty::FreeRegion {
204                 bound_region: ty::BoundRegion::BrNamed(_, ref name),
205                 ..
206             }) => {
207                 let mut sp = cm.def_span(self.hir().span_by_hir_id(node));
208                 if let Some(param) = self.hir()
209                     .get_generics(scope)
210                     .and_then(|generics| generics.get_named(&name))
211                 {
212                     sp = param.span;
213                 }
214                 (format!("the lifetime {} as defined on", name), sp)
215             }
216             ty::ReFree(ref fr) => match fr.bound_region {
217                 ty::BrAnon(idx) => (
218                     format!("the anonymous lifetime #{} defined on", idx + 1),
219                     self.hir().span_by_hir_id(node),
220                 ),
221                 ty::BrFresh(_) => (
222                     "an anonymous lifetime defined on".to_owned(),
223                     self.hir().span_by_hir_id(node),
224                 ),
225                 _ => (
226                     format!("the lifetime {} as defined on", fr.bound_region),
227                     cm.def_span(self.hir().span_by_hir_id(node)),
228                 ),
229             },
230             _ => bug!(),
231         };
232         let (msg, opt_span) = self.explain_span(tag, span);
233         (format!("{} {}", prefix, msg), opt_span)
234     }
235
236     fn emit_msg_span(
237         err: &mut DiagnosticBuilder<'_>,
238         prefix: &str,
239         description: String,
240         span: Option<Span>,
241         suffix: &str,
242     ) {
243         let message = format!("{}{}{}", prefix, description, suffix);
244
245         if let Some(span) = span {
246             err.span_note(span, &message);
247         } else {
248             err.note(&message);
249         }
250     }
251
252     fn item_scope_tag(item: &hir::Item) -> &'static str {
253         match item.node {
254             hir::ItemKind::Impl(..) => "impl",
255             hir::ItemKind::Struct(..) => "struct",
256             hir::ItemKind::Union(..) => "union",
257             hir::ItemKind::Enum(..) => "enum",
258             hir::ItemKind::Trait(..) => "trait",
259             hir::ItemKind::Fn(..) => "function body",
260             _ => "item",
261         }
262     }
263
264     fn trait_item_scope_tag(item: &hir::TraitItem) -> &'static str {
265         match item.node {
266             hir::TraitItemKind::Method(..) => "method body",
267             hir::TraitItemKind::Const(..) | hir::TraitItemKind::Type(..) => "associated item",
268         }
269     }
270
271     fn impl_item_scope_tag(item: &hir::ImplItem) -> &'static str {
272         match item.node {
273             hir::ImplItemKind::Method(..) => "method body",
274             hir::ImplItemKind::Const(..)
275             | hir::ImplItemKind::Existential(..)
276             | hir::ImplItemKind::Type(..) => "associated item",
277         }
278     }
279
280     fn explain_span(self, heading: &str, span: Span) -> (String, Option<Span>) {
281         let lo = self.sess.source_map().lookup_char_pos_adj(span.lo());
282         (
283             format!("the {} at {}:{}", heading, lo.line, lo.col.to_usize() + 1),
284             Some(span),
285         )
286     }
287 }
288
289 impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
290     pub fn report_region_errors(
291         &self,
292         region_scope_tree: &region::ScopeTree,
293         errors: &Vec<RegionResolutionError<'tcx>>,
294         suppress: SuppressRegionErrors,
295     ) {
296         debug!(
297             "report_region_errors(): {} errors to start, suppress = {:?}",
298             errors.len(),
299             suppress
300         );
301
302         if suppress.suppressed() {
303             return;
304         }
305
306         // try to pre-process the errors, which will group some of them
307         // together into a `ProcessedErrors` group:
308         let errors = self.process_errors(errors);
309
310         debug!(
311             "report_region_errors: {} errors after preprocessing",
312             errors.len()
313         );
314
315         for error in errors {
316             debug!("report_region_errors: error = {:?}", error);
317
318             if !self.try_report_nice_region_error(&error) {
319                 match error.clone() {
320                     // These errors could indicate all manner of different
321                     // problems with many different solutions. Rather
322                     // than generate a "one size fits all" error, what we
323                     // attempt to do is go through a number of specific
324                     // scenarios and try to find the best way to present
325                     // the error. If all of these fails, we fall back to a rather
326                     // general bit of code that displays the error information
327                     RegionResolutionError::ConcreteFailure(origin, sub, sup) => {
328                         if sub.is_placeholder() || sup.is_placeholder() {
329                             self.report_placeholder_failure(region_scope_tree, origin, sub, sup)
330                                 .emit();
331                         } else {
332                             self.report_concrete_failure(region_scope_tree, origin, sub, sup)
333                                 .emit();
334                         }
335                     }
336
337                     RegionResolutionError::GenericBoundFailure(origin, param_ty, sub) => {
338                         self.report_generic_bound_failure(
339                             region_scope_tree,
340                             origin.span(),
341                             Some(origin),
342                             param_ty,
343                             sub,
344                         );
345                     }
346
347                     RegionResolutionError::SubSupConflict(
348                         _,
349                         var_origin,
350                         sub_origin,
351                         sub_r,
352                         sup_origin,
353                         sup_r,
354                     ) => {
355                         if sub_r.is_placeholder() {
356                             self.report_placeholder_failure(
357                                 region_scope_tree,
358                                 sub_origin,
359                                 sub_r,
360                                 sup_r,
361                             )
362                                 .emit();
363                         } else if sup_r.is_placeholder() {
364                             self.report_placeholder_failure(
365                                 region_scope_tree,
366                                 sup_origin,
367                                 sub_r,
368                                 sup_r,
369                             )
370                                 .emit();
371                         } else {
372                             self.report_sub_sup_conflict(
373                                 region_scope_tree,
374                                 var_origin,
375                                 sub_origin,
376                                 sub_r,
377                                 sup_origin,
378                                 sup_r,
379                             );
380                         }
381                     }
382                 }
383             }
384         }
385     }
386
387     // This method goes through all the errors and try to group certain types
388     // of error together, for the purpose of suggesting explicit lifetime
389     // parameters to the user. This is done so that we can have a more
390     // complete view of what lifetimes should be the same.
391     // If the return value is an empty vector, it means that processing
392     // failed (so the return value of this method should not be used).
393     //
394     // The method also attempts to weed out messages that seem like
395     // duplicates that will be unhelpful to the end-user. But
396     // obviously it never weeds out ALL errors.
397     fn process_errors(
398         &self,
399         errors: &Vec<RegionResolutionError<'tcx>>,
400     ) -> Vec<RegionResolutionError<'tcx>> {
401         debug!("process_errors()");
402
403         // We want to avoid reporting generic-bound failures if we can
404         // avoid it: these have a very high rate of being unhelpful in
405         // practice. This is because they are basically secondary
406         // checks that test the state of the region graph after the
407         // rest of inference is done, and the other kinds of errors
408         // indicate that the region constraint graph is internally
409         // inconsistent, so these test results are likely to be
410         // meaningless.
411         //
412         // Therefore, we filter them out of the list unless they are
413         // the only thing in the list.
414
415         let is_bound_failure = |e: &RegionResolutionError<'tcx>| match *e {
416             RegionResolutionError::GenericBoundFailure(..) => true,
417             RegionResolutionError::ConcreteFailure(..)
418             | RegionResolutionError::SubSupConflict(..) => false,
419         };
420
421         let mut errors = if errors.iter().all(|e| is_bound_failure(e)) {
422             errors.clone()
423         } else {
424             errors
425             .iter()
426             .filter(|&e| !is_bound_failure(e))
427             .cloned()
428             .collect()
429         };
430
431         // sort the errors by span, for better error message stability.
432         errors.sort_by_key(|u| match *u {
433             RegionResolutionError::ConcreteFailure(ref sro, _, _) => sro.span(),
434             RegionResolutionError::GenericBoundFailure(ref sro, _, _) => sro.span(),
435             RegionResolutionError::SubSupConflict(_, ref rvo, _, _, _, _) => rvo.span(),
436         });
437         errors
438     }
439
440     /// Adds a note if the types come from similarly named crates
441     fn check_and_note_conflicting_crates(
442         &self,
443         err: &mut DiagnosticBuilder<'_>,
444         terr: &TypeError<'tcx>,
445         sp: Span,
446     ) {
447         let report_path_match = |err: &mut DiagnosticBuilder<'_>, did1: DefId, did2: DefId| {
448             // Only external crates, if either is from a local
449             // module we could have false positives
450             if !(did1.is_local() || did2.is_local()) && did1.krate != did2.krate {
451                 let exp_path = self.tcx.item_path_str(did1);
452                 let found_path = self.tcx.item_path_str(did2);
453                 let exp_abs_path = self.tcx.absolute_item_path_str(did1);
454                 let found_abs_path = self.tcx.absolute_item_path_str(did2);
455                 // We compare strings because DefPath can be different
456                 // for imported and non-imported crates
457                 if exp_path == found_path || exp_abs_path == found_abs_path {
458                     let crate_name = self.tcx.crate_name(did1.krate);
459                     err.span_note(
460                         sp,
461                         &format!(
462                             "Perhaps two different versions \
463                              of crate `{}` are being used?",
464                             crate_name
465                         ),
466                     );
467                 }
468             }
469         };
470         match *terr {
471             TypeError::Sorts(ref exp_found) => {
472                 // if they are both "path types", there's a chance of ambiguity
473                 // due to different versions of the same crate
474                 if let (&ty::Adt(exp_adt, _), &ty::Adt(found_adt, _))
475                      = (&exp_found.expected.sty, &exp_found.found.sty)
476                 {
477                     report_path_match(err, exp_adt.did, found_adt.did);
478                 }
479             }
480             TypeError::Traits(ref exp_found) => {
481                 report_path_match(err, exp_found.expected, exp_found.found);
482             }
483             _ => (), // FIXME(#22750) handle traits and stuff
484         }
485     }
486
487     fn note_error_origin(
488         &self,
489         err: &mut DiagnosticBuilder<'tcx>,
490         cause: &ObligationCause<'tcx>,
491         exp_found: Option<ty::error::ExpectedFound<Ty<'tcx>>>,
492     ) {
493         match cause.code {
494             ObligationCauseCode::MatchExpressionArmPattern { span, ty } => {
495                 if ty.is_suggestable() {  // don't show type `_`
496                     err.span_label(span, format!("this match expression has type `{}`", ty));
497                 }
498                 if let Some(ty::error::ExpectedFound { found, .. }) = exp_found {
499                     if ty.is_box() && ty.boxed_ty() == found {
500                         if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
501                             err.span_suggestion(
502                                 span,
503                                 "consider dereferencing the boxed value",
504                                 format!("*{}", snippet),
505                                 Applicability::MachineApplicable,
506                             );
507                         }
508                     }
509                 }
510             }
511             ObligationCauseCode::MatchExpressionArm {
512                 source,
513                 ref prior_arms,
514                 last_ty,
515                 ..
516             } => match source {
517                 hir::MatchSource::IfLetDesugar { .. } => {
518                     let msg = "`if let` arms have incompatible types";
519                     err.span_label(cause.span, msg);
520                 }
521                 hir::MatchSource::TryDesugar => {}
522                 _ => {
523                     let msg = "`match` arms have incompatible types";
524                     err.span_label(cause.span, msg);
525                     if prior_arms.len() <= 4 {
526                         for sp in prior_arms {
527                             err.span_label(*sp, format!(
528                                 "this is found to be of type `{}`",
529                                 last_ty,
530                             ));
531                         }
532                     } else if let Some(sp) = prior_arms.last() {
533                         err.span_label(*sp, format!(
534                             "this and all prior arms are found to be of type `{}`", last_ty,
535                         ));
536                     }
537                 }
538             },
539             ObligationCauseCode::IfExpression { then, outer, semicolon } => {
540                 err.span_label(then, "expected because of this");
541                 outer.map(|sp| err.span_label(sp, "if and else have incompatible types"));
542                 if let Some(sp) = semicolon {
543                     err.span_suggestion_short(
544                         sp,
545                         "consider removing this semicolon",
546                         String::new(),
547                         Applicability::MachineApplicable,
548                     );
549                 }
550             }
551             _ => (),
552         }
553     }
554
555     /// Given that `other_ty` is the same as a type argument for `name` in `sub`, populate `value`
556     /// highlighting `name` and every type argument that isn't at `pos` (which is `other_ty`), and
557     /// populate `other_value` with `other_ty`.
558     ///
559     /// ```text
560     /// Foo<Bar<Qux>>
561     /// ^^^^--------^ this is highlighted
562     /// |   |
563     /// |   this type argument is exactly the same as the other type, not highlighted
564     /// this is highlighted
565     /// Bar<Qux>
566     /// -------- this type is the same as a type argument in the other type, not highlighted
567     /// ```
568     fn highlight_outer(
569         &self,
570         value: &mut DiagnosticStyledString,
571         other_value: &mut DiagnosticStyledString,
572         name: String,
573         sub: ty::subst::SubstsRef<'tcx>,
574         pos: usize,
575         other_ty: &Ty<'tcx>,
576     ) {
577         // `value` and `other_value` hold two incomplete type representation for display.
578         // `name` is the path of both types being compared. `sub`
579         value.push_highlighted(name);
580         let len = sub.len();
581         if len > 0 {
582             value.push_highlighted("<");
583         }
584
585         // Output the lifetimes for the first type
586         let lifetimes = sub.regions()
587             .map(|lifetime| {
588                 let s = lifetime.to_string();
589                 if s.is_empty() {
590                     "'_".to_string()
591                 } else {
592                     s
593                 }
594             })
595             .collect::<Vec<_>>()
596             .join(", ");
597         if !lifetimes.is_empty() {
598             if sub.regions().count() < len {
599                 value.push_normal(lifetimes + &", ");
600             } else {
601                 value.push_normal(lifetimes);
602             }
603         }
604
605         // Highlight all the type arguments that aren't at `pos` and compare the type argument at
606         // `pos` and `other_ty`.
607         for (i, type_arg) in sub.types().enumerate() {
608             if i == pos {
609                 let values = self.cmp(type_arg, other_ty);
610                 value.0.extend((values.0).0);
611                 other_value.0.extend((values.1).0);
612             } else {
613                 value.push_highlighted(type_arg.to_string());
614             }
615
616             if len > 0 && i != len - 1 {
617                 value.push_normal(", ");
618             }
619             //self.push_comma(&mut value, &mut other_value, len, i);
620         }
621         if len > 0 {
622             value.push_highlighted(">");
623         }
624     }
625
626     /// If `other_ty` is the same as a type argument present in `sub`, highlight `path` in `t1_out`,
627     /// as that is the difference to the other type.
628     ///
629     /// For the following code:
630     ///
631     /// ```norun
632     /// let x: Foo<Bar<Qux>> = foo::<Bar<Qux>>();
633     /// ```
634     ///
635     /// The type error output will behave in the following way:
636     ///
637     /// ```text
638     /// Foo<Bar<Qux>>
639     /// ^^^^--------^ this is highlighted
640     /// |   |
641     /// |   this type argument is exactly the same as the other type, not highlighted
642     /// this is highlighted
643     /// Bar<Qux>
644     /// -------- this type is the same as a type argument in the other type, not highlighted
645     /// ```
646     fn cmp_type_arg(
647         &self,
648         mut t1_out: &mut DiagnosticStyledString,
649         mut t2_out: &mut DiagnosticStyledString,
650         path: String,
651         sub: ty::subst::SubstsRef<'tcx>,
652         other_path: String,
653         other_ty: &Ty<'tcx>,
654     ) -> Option<()> {
655         for (i, ta) in sub.types().enumerate() {
656             if &ta == other_ty {
657                 self.highlight_outer(&mut t1_out, &mut t2_out, path, sub, i, &other_ty);
658                 return Some(());
659             }
660             if let &ty::Adt(def, _) = &ta.sty {
661                 let path_ = self.tcx.item_path_str(def.did.clone());
662                 if path_ == other_path {
663                     self.highlight_outer(&mut t1_out, &mut t2_out, path, sub, i, &other_ty);
664                     return Some(());
665                 }
666             }
667         }
668         None
669     }
670
671     /// Adds a `,` to the type representation only if it is appropriate.
672     fn push_comma(
673         &self,
674         value: &mut DiagnosticStyledString,
675         other_value: &mut DiagnosticStyledString,
676         len: usize,
677         pos: usize,
678     ) {
679         if len > 0 && pos != len - 1 {
680             value.push_normal(", ");
681             other_value.push_normal(", ");
682         }
683     }
684
685     /// For generic types with parameters with defaults, remove the parameters corresponding to
686     /// the defaults. This repeats a lot of the logic found in `PrintCx::parameterized`.
687     fn strip_generic_default_params(
688         &self,
689         def_id: DefId,
690         substs: ty::subst::SubstsRef<'tcx>,
691     ) -> SubstsRef<'tcx> {
692         let generics = self.tcx.generics_of(def_id);
693         let mut num_supplied_defaults = 0;
694         let mut type_params = generics.params.iter().rev().filter_map(|param| match param.kind {
695             ty::GenericParamDefKind::Lifetime => None,
696             ty::GenericParamDefKind::Type { has_default, .. } => Some((param.def_id, has_default)),
697             ty::GenericParamDefKind::Const => None, // FIXME(const_generics:defaults)
698         }).peekable();
699         let has_default = {
700             let has_default = type_params.peek().map(|(_, has_default)| has_default);
701             *has_default.unwrap_or(&false)
702         };
703         if has_default {
704             let types = substs.types().rev();
705             for ((def_id, has_default), actual) in type_params.zip(types) {
706                 if !has_default {
707                     break;
708                 }
709                 if self.tcx.type_of(def_id).subst(self.tcx, substs) != actual {
710                     break;
711                 }
712                 num_supplied_defaults += 1;
713             }
714         }
715         let len = generics.params.len();
716         let mut generics = generics.clone();
717         generics.params.truncate(len - num_supplied_defaults);
718         substs.truncate_to(self.tcx, &generics)
719     }
720
721     /// Compares two given types, eliding parts that are the same between them and highlighting
722     /// relevant differences, and return two representation of those types for highlighted printing.
723     fn cmp(&self, t1: Ty<'tcx>, t2: Ty<'tcx>) -> (DiagnosticStyledString, DiagnosticStyledString) {
724         fn equals<'tcx>(a: &Ty<'tcx>, b: &Ty<'tcx>) -> bool {
725             match (&a.sty, &b.sty) {
726                 (a, b) if *a == *b => true,
727                 (&ty::Int(_), &ty::Infer(ty::InferTy::IntVar(_)))
728                 | (&ty::Infer(ty::InferTy::IntVar(_)), &ty::Int(_))
729                 | (&ty::Infer(ty::InferTy::IntVar(_)), &ty::Infer(ty::InferTy::IntVar(_)))
730                 | (&ty::Float(_), &ty::Infer(ty::InferTy::FloatVar(_)))
731                 | (&ty::Infer(ty::InferTy::FloatVar(_)), &ty::Float(_))
732                 | (&ty::Infer(ty::InferTy::FloatVar(_)), &ty::Infer(ty::InferTy::FloatVar(_))) => {
733                     true
734                 }
735                 _ => false,
736             }
737         }
738
739         fn push_ty_ref<'tcx>(
740             r: &ty::Region<'tcx>,
741             ty: Ty<'tcx>,
742             mutbl: hir::Mutability,
743             s: &mut DiagnosticStyledString,
744         ) {
745             let r = &r.to_string();
746             s.push_highlighted(format!(
747                 "&{}{}{}",
748                 r,
749                 if r == "" { "" } else { " " },
750                 if mutbl == hir::MutMutable { "mut " } else { "" }
751             ));
752             s.push_normal(ty.to_string());
753         }
754
755         match (&t1.sty, &t2.sty) {
756             (&ty::Adt(def1, sub1), &ty::Adt(def2, sub2)) => {
757                 let sub_no_defaults_1 = self.strip_generic_default_params(def1.did, sub1);
758                 let sub_no_defaults_2 = self.strip_generic_default_params(def2.did, sub2);
759                 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
760                 let path1 = self.tcx.item_path_str(def1.did.clone());
761                 let path2 = self.tcx.item_path_str(def2.did.clone());
762                 if def1.did == def2.did {
763                     // Easy case. Replace same types with `_` to shorten the output and highlight
764                     // the differing ones.
765                     //     let x: Foo<Bar, Qux> = y::<Foo<Quz, Qux>>();
766                     //     Foo<Bar, _>
767                     //     Foo<Quz, _>
768                     //         ---  ^ type argument elided
769                     //         |
770                     //         highlighted in output
771                     values.0.push_normal(path1);
772                     values.1.push_normal(path2);
773
774                     // Avoid printing out default generic parameters that are common to both
775                     // types.
776                     let len1 = sub_no_defaults_1.len();
777                     let len2 = sub_no_defaults_2.len();
778                     let common_len = cmp::min(len1, len2);
779                     let remainder1: Vec<_> = sub1.types().skip(common_len).collect();
780                     let remainder2: Vec<_> = sub2.types().skip(common_len).collect();
781                     let common_default_params = remainder1
782                         .iter()
783                         .rev()
784                         .zip(remainder2.iter().rev())
785                         .filter(|(a, b)| a == b)
786                         .count();
787                     let len = sub1.len() - common_default_params;
788
789                     // Only draw `<...>` if there're lifetime/type arguments.
790                     if len > 0 {
791                         values.0.push_normal("<");
792                         values.1.push_normal("<");
793                     }
794
795                     fn lifetime_display(lifetime: Region<'_>) -> String {
796                         let s = lifetime.to_string();
797                         if s.is_empty() {
798                             "'_".to_string()
799                         } else {
800                             s
801                         }
802                     }
803                     // At one point we'd like to elide all lifetimes here, they are irrelevant for
804                     // all diagnostics that use this output
805                     //
806                     //     Foo<'x, '_, Bar>
807                     //     Foo<'y, '_, Qux>
808                     //         ^^  ^^  --- type arguments are not elided
809                     //         |   |
810                     //         |   elided as they were the same
811                     //         not elided, they were different, but irrelevant
812                     let lifetimes = sub1.regions().zip(sub2.regions());
813                     for (i, lifetimes) in lifetimes.enumerate() {
814                         let l1 = lifetime_display(lifetimes.0);
815                         let l2 = lifetime_display(lifetimes.1);
816                         if l1 == l2 {
817                             values.0.push_normal("'_");
818                             values.1.push_normal("'_");
819                         } else {
820                             values.0.push_highlighted(l1);
821                             values.1.push_highlighted(l2);
822                         }
823                         self.push_comma(&mut values.0, &mut values.1, len, i);
824                     }
825
826                     // We're comparing two types with the same path, so we compare the type
827                     // arguments for both. If they are the same, do not highlight and elide from the
828                     // output.
829                     //     Foo<_, Bar>
830                     //     Foo<_, Qux>
831                     //         ^ elided type as this type argument was the same in both sides
832                     let type_arguments = sub1.types().zip(sub2.types());
833                     let regions_len = sub1.regions().count();
834                     for (i, (ta1, ta2)) in type_arguments.take(len).enumerate() {
835                         let i = i + regions_len;
836                         if ta1 == ta2 {
837                             values.0.push_normal("_");
838                             values.1.push_normal("_");
839                         } else {
840                             let (x1, x2) = self.cmp(ta1, ta2);
841                             (values.0).0.extend(x1.0);
842                             (values.1).0.extend(x2.0);
843                         }
844                         self.push_comma(&mut values.0, &mut values.1, len, i);
845                     }
846
847                     // Close the type argument bracket.
848                     // Only draw `<...>` if there're lifetime/type arguments.
849                     if len > 0 {
850                         values.0.push_normal(">");
851                         values.1.push_normal(">");
852                     }
853                     values
854                 } else {
855                     // Check for case:
856                     //     let x: Foo<Bar<Qux> = foo::<Bar<Qux>>();
857                     //     Foo<Bar<Qux>
858                     //         ------- this type argument is exactly the same as the other type
859                     //     Bar<Qux>
860                     if self.cmp_type_arg(
861                         &mut values.0,
862                         &mut values.1,
863                         path1.clone(),
864                         sub_no_defaults_1,
865                         path2.clone(),
866                         &t2,
867                     ).is_some()
868                     {
869                         return values;
870                     }
871                     // Check for case:
872                     //     let x: Bar<Qux> = y:<Foo<Bar<Qux>>>();
873                     //     Bar<Qux>
874                     //     Foo<Bar<Qux>>
875                     //         ------- this type argument is exactly the same as the other type
876                     if self.cmp_type_arg(
877                         &mut values.1,
878                         &mut values.0,
879                         path2,
880                         sub_no_defaults_2,
881                         path1,
882                         &t1,
883                     ).is_some()
884                     {
885                         return values;
886                     }
887
888                     // We couldn't find anything in common, highlight everything.
889                     //     let x: Bar<Qux> = y::<Foo<Zar>>();
890                     (
891                         DiagnosticStyledString::highlighted(t1.to_string()),
892                         DiagnosticStyledString::highlighted(t2.to_string()),
893                     )
894                 }
895             }
896
897             // When finding T != &T, highlight only the borrow
898             (&ty::Ref(r1, ref_ty1, mutbl1), _) if equals(&ref_ty1, &t2) => {
899                 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
900                 push_ty_ref(&r1, ref_ty1, mutbl1, &mut values.0);
901                 values.1.push_normal(t2.to_string());
902                 values
903             }
904             (_, &ty::Ref(r2, ref_ty2, mutbl2)) if equals(&t1, &ref_ty2) => {
905                 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
906                 values.0.push_normal(t1.to_string());
907                 push_ty_ref(&r2, ref_ty2, mutbl2, &mut values.1);
908                 values
909             }
910
911             // When encountering &T != &mut T, highlight only the borrow
912             (&ty::Ref(r1, ref_ty1, mutbl1), &ty::Ref(r2, ref_ty2, mutbl2))
913                 if equals(&ref_ty1, &ref_ty2) =>
914             {
915                 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
916                 push_ty_ref(&r1, ref_ty1, mutbl1, &mut values.0);
917                 push_ty_ref(&r2, ref_ty2, mutbl2, &mut values.1);
918                 values
919             }
920
921             _ => {
922                 if t1 == t2 {
923                     // The two types are the same, elide and don't highlight.
924                     (
925                         DiagnosticStyledString::normal("_"),
926                         DiagnosticStyledString::normal("_"),
927                     )
928                 } else {
929                     // We couldn't find anything in common, highlight everything.
930                     (
931                         DiagnosticStyledString::highlighted(t1.to_string()),
932                         DiagnosticStyledString::highlighted(t2.to_string()),
933                     )
934                 }
935             }
936         }
937     }
938
939     pub fn note_type_err(
940         &self,
941         diag: &mut DiagnosticBuilder<'tcx>,
942         cause: &ObligationCause<'tcx>,
943         secondary_span: Option<(Span, String)>,
944         mut values: Option<ValuePairs<'tcx>>,
945         terr: &TypeError<'tcx>,
946     ) {
947         // For some types of errors, expected-found does not make
948         // sense, so just ignore the values we were given.
949         match terr {
950             TypeError::CyclicTy(_) => {
951                 values = None;
952             }
953             _ => {}
954         }
955
956         let (expected_found, exp_found, is_simple_error) = match values {
957             None => (None, None, false),
958             Some(values) => {
959                 let (is_simple_error, exp_found) = match values {
960                     ValuePairs::Types(exp_found) => {
961                         let is_simple_err =
962                             exp_found.expected.is_primitive() && exp_found.found.is_primitive();
963
964                         (is_simple_err, Some(exp_found))
965                     }
966                     _ => (false, None),
967                 };
968                 let vals = match self.values_str(&values) {
969                     Some((expected, found)) => Some((expected, found)),
970                     None => {
971                         // Derived error. Cancel the emitter.
972                         self.tcx.sess.diagnostic().cancel(diag);
973                         return;
974                     }
975                 };
976                 (vals, exp_found, is_simple_error)
977             }
978         };
979
980         let span = cause.span(&self.tcx);
981
982         diag.span_label(span, terr.to_string());
983         if let Some((sp, msg)) = secondary_span {
984             diag.span_label(sp, msg);
985         }
986
987         if let Some((expected, found)) = expected_found {
988             match (terr, is_simple_error, expected == found) {
989                 (&TypeError::Sorts(ref values), false, true) => {
990                     diag.note_expected_found_extra(
991                         &"type",
992                         expected,
993                         found,
994                         &format!(" ({})", values.expected.sort_string(self.tcx)),
995                         &format!(" ({})", values.found.sort_string(self.tcx)),
996                     );
997                 }
998                 (_, false, _) => {
999                     if let Some(exp_found) = exp_found {
1000                         let (def_id, ret_ty) = match exp_found.found.sty {
1001                             TyKind::FnDef(def, _) => {
1002                                 (Some(def), Some(self.tcx.fn_sig(def).output()))
1003                             }
1004                             _ => (None, None),
1005                         };
1006
1007                         let exp_is_struct = match exp_found.expected.sty {
1008                             TyKind::Adt(def, _) => def.is_struct(),
1009                             _ => false,
1010                         };
1011
1012                         if let (Some(def_id), Some(ret_ty)) = (def_id, ret_ty) {
1013                             if exp_is_struct && &exp_found.expected == ret_ty.skip_binder() {
1014                                 let message = format!(
1015                                     "did you mean `{}(/* fields */)`?",
1016                                     self.tcx.item_path_str(def_id)
1017                                 );
1018                                 diag.span_label(span, message);
1019                             }
1020                         }
1021                         self.suggest_as_ref_where_appropriate(span, &exp_found, diag);
1022                     }
1023
1024                     diag.note_expected_found(&"type", expected, found);
1025                 }
1026                 _ => (),
1027             }
1028         }
1029
1030         self.check_and_note_conflicting_crates(diag, terr, span);
1031         self.tcx.note_and_explain_type_err(diag, terr, span);
1032
1033         // It reads better to have the error origin as the final
1034         // thing.
1035         self.note_error_origin(diag, &cause, exp_found);
1036     }
1037
1038     /// When encountering a case where `.as_ref()` on a `Result` or `Option` would be appropriate,
1039     /// suggest it.
1040     fn suggest_as_ref_where_appropriate(
1041         &self,
1042         span: Span,
1043         exp_found: &ty::error::ExpectedFound<Ty<'tcx>>,
1044         diag: &mut DiagnosticBuilder<'tcx>,
1045     ) {
1046         match (&exp_found.expected.sty, &exp_found.found.sty) {
1047             (TyKind::Adt(exp_def, exp_substs), TyKind::Ref(_, found_ty, _)) => {
1048                 if let TyKind::Adt(found_def, found_substs) = found_ty.sty {
1049                     let path_str = format!("{:?}", exp_def);
1050                     if exp_def == &found_def {
1051                         let opt_msg = "you can convert from `&Option<T>` to `Option<&T>` using \
1052                                        `.as_ref()`";
1053                         let result_msg = "you can convert from `&Result<T, E>` to \
1054                                           `Result<&T, &E>` using `.as_ref()`";
1055                         let have_as_ref = &[
1056                             ("std::option::Option", opt_msg),
1057                             ("core::option::Option", opt_msg),
1058                             ("std::result::Result", result_msg),
1059                             ("core::result::Result", result_msg),
1060                         ];
1061                         if let Some(msg) = have_as_ref.iter()
1062                             .filter_map(|(path, msg)| if &path_str == path {
1063                                 Some(msg)
1064                             } else {
1065                                 None
1066                             }).next()
1067                         {
1068                             let mut show_suggestion = true;
1069                             for (exp_ty, found_ty) in exp_substs.types().zip(found_substs.types()) {
1070                                 match exp_ty.sty {
1071                                     TyKind::Ref(_, exp_ty, _) => {
1072                                         match (&exp_ty.sty, &found_ty.sty) {
1073                                             (_, TyKind::Param(_)) |
1074                                             (_, TyKind::Infer(_)) |
1075                                             (TyKind::Param(_), _) |
1076                                             (TyKind::Infer(_), _) => {}
1077                                             _ if ty::TyS::same_type(exp_ty, found_ty) => {}
1078                                             _ => show_suggestion = false,
1079                                         };
1080                                     }
1081                                     TyKind::Param(_) | TyKind::Infer(_) => {}
1082                                     _ => show_suggestion = false,
1083                                 }
1084                             }
1085                             if let (Ok(snippet), true) = (
1086                                 self.tcx.sess.source_map().span_to_snippet(span),
1087                                 show_suggestion,
1088                             ) {
1089                                 diag.span_suggestion(
1090                                     span,
1091                                     msg,
1092                                     format!("{}.as_ref()", snippet),
1093                                     Applicability::MachineApplicable,
1094                                 );
1095                             }
1096                         }
1097                     }
1098                 }
1099             }
1100             _ => {}
1101         }
1102     }
1103
1104     pub fn report_and_explain_type_error(
1105         &self,
1106         trace: TypeTrace<'tcx>,
1107         terr: &TypeError<'tcx>,
1108     ) -> DiagnosticBuilder<'tcx> {
1109         debug!(
1110             "report_and_explain_type_error(trace={:?}, terr={:?})",
1111             trace, terr
1112         );
1113
1114         let span = trace.cause.span(&self.tcx);
1115         let failure_code = trace.cause.as_failure_code(terr);
1116         let mut diag = match failure_code {
1117             FailureCode::Error0317(failure_str) => {
1118                 struct_span_err!(self.tcx.sess, span, E0317, "{}", failure_str)
1119             }
1120             FailureCode::Error0580(failure_str) => {
1121                 struct_span_err!(self.tcx.sess, span, E0580, "{}", failure_str)
1122             }
1123             FailureCode::Error0308(failure_str) => {
1124                 struct_span_err!(self.tcx.sess, span, E0308, "{}", failure_str)
1125             }
1126             FailureCode::Error0644(failure_str) => {
1127                 struct_span_err!(self.tcx.sess, span, E0644, "{}", failure_str)
1128             }
1129         };
1130         self.note_type_err(&mut diag, &trace.cause, None, Some(trace.values), terr);
1131         diag
1132     }
1133
1134     fn values_str(
1135         &self,
1136         values: &ValuePairs<'tcx>,
1137     ) -> Option<(DiagnosticStyledString, DiagnosticStyledString)> {
1138         match *values {
1139             infer::Types(ref exp_found) => self.expected_found_str_ty(exp_found),
1140             infer::Regions(ref exp_found) => self.expected_found_str(exp_found),
1141             infer::TraitRefs(ref exp_found) => self.expected_found_str(exp_found),
1142             infer::PolyTraitRefs(ref exp_found) => self.expected_found_str(exp_found),
1143         }
1144     }
1145
1146     fn expected_found_str_ty(
1147         &self,
1148         exp_found: &ty::error::ExpectedFound<Ty<'tcx>>,
1149     ) -> Option<(DiagnosticStyledString, DiagnosticStyledString)> {
1150         let exp_found = self.resolve_type_vars_if_possible(exp_found);
1151         if exp_found.references_error() {
1152             return None;
1153         }
1154
1155         Some(self.cmp(exp_found.expected, exp_found.found))
1156     }
1157
1158     /// Returns a string of the form "expected `{}`, found `{}`".
1159     fn expected_found_str<T: fmt::Display + TypeFoldable<'tcx>>(
1160         &self,
1161         exp_found: &ty::error::ExpectedFound<T>,
1162     ) -> Option<(DiagnosticStyledString, DiagnosticStyledString)> {
1163         let exp_found = self.resolve_type_vars_if_possible(exp_found);
1164         if exp_found.references_error() {
1165             return None;
1166         }
1167
1168         Some((
1169             DiagnosticStyledString::highlighted(exp_found.expected.to_string()),
1170             DiagnosticStyledString::highlighted(exp_found.found.to_string()),
1171         ))
1172     }
1173
1174     pub fn report_generic_bound_failure(
1175         &self,
1176         region_scope_tree: &region::ScopeTree,
1177         span: Span,
1178         origin: Option<SubregionOrigin<'tcx>>,
1179         bound_kind: GenericKind<'tcx>,
1180         sub: Region<'tcx>,
1181     ) {
1182         self.construct_generic_bound_failure(region_scope_tree, span, origin, bound_kind, sub)
1183             .emit()
1184     }
1185
1186     pub fn construct_generic_bound_failure(
1187         &self,
1188         region_scope_tree: &region::ScopeTree,
1189         span: Span,
1190         origin: Option<SubregionOrigin<'tcx>>,
1191         bound_kind: GenericKind<'tcx>,
1192         sub: Region<'tcx>,
1193     ) -> DiagnosticBuilder<'a> {
1194         // Attempt to obtain the span of the parameter so we can
1195         // suggest adding an explicit lifetime bound to it.
1196         let type_param_span = match (self.in_progress_tables, bound_kind) {
1197             (Some(ref table), GenericKind::Param(ref param)) => {
1198                 let table = table.borrow();
1199                 table.local_id_root.and_then(|did| {
1200                     let generics = self.tcx.generics_of(did);
1201                     // Account for the case where `did` corresponds to `Self`, which doesn't have
1202                     // the expected type argument.
1203                     if !param.is_self() {
1204                         let type_param = generics.type_param(param, self.tcx);
1205                         let hir = &self.tcx.hir();
1206                         hir.as_local_node_id(type_param.def_id).map(|id| {
1207                             // Get the `hir::Param` to verify whether it already has any bounds.
1208                             // We do this to avoid suggesting code that ends up as `T: 'a'b`,
1209                             // instead we suggest `T: 'a + 'b` in that case.
1210                             let mut has_bounds = false;
1211                             if let Node::GenericParam(ref param) = hir.get(id) {
1212                                 has_bounds = !param.bounds.is_empty();
1213                             }
1214                             let sp = hir.span(id);
1215                             // `sp` only covers `T`, change it so that it covers
1216                             // `T:` when appropriate
1217                             let is_impl_trait = bound_kind.to_string().starts_with("impl ");
1218                             let sp = if has_bounds && !is_impl_trait {
1219                                 sp.to(self.tcx
1220                                     .sess
1221                                     .source_map()
1222                                     .next_point(self.tcx.sess.source_map().next_point(sp)))
1223                             } else {
1224                                 sp
1225                             };
1226                             (sp, has_bounds, is_impl_trait)
1227                         })
1228                     } else {
1229                         None
1230                     }
1231                 })
1232             }
1233             _ => None,
1234         };
1235
1236         let labeled_user_string = match bound_kind {
1237             GenericKind::Param(ref p) => format!("the parameter type `{}`", p),
1238             GenericKind::Projection(ref p) => format!("the associated type `{}`", p),
1239         };
1240
1241         if let Some(SubregionOrigin::CompareImplMethodObligation {
1242             span,
1243             item_name,
1244             impl_item_def_id,
1245             trait_item_def_id,
1246         }) = origin
1247         {
1248             return self.report_extra_impl_obligation(
1249                 span,
1250                 item_name,
1251                 impl_item_def_id,
1252                 trait_item_def_id,
1253                 &format!("`{}: {}`", bound_kind, sub),
1254             );
1255         }
1256
1257         fn binding_suggestion<'tcx, S: fmt::Display>(
1258             err: &mut DiagnosticBuilder<'tcx>,
1259             type_param_span: Option<(Span, bool, bool)>,
1260             bound_kind: GenericKind<'tcx>,
1261             sub: S,
1262         ) {
1263             let consider = format!(
1264                 "consider adding an explicit lifetime bound {}",
1265                 if type_param_span.map(|(_, _, is_impl_trait)| is_impl_trait).unwrap_or(false) {
1266                     format!(" `{}` to `{}`...", sub, bound_kind)
1267                 } else {
1268                     format!("`{}: {}`...", bound_kind, sub)
1269                 },
1270             );
1271             if let Some((sp, has_lifetimes, is_impl_trait)) = type_param_span {
1272                 let suggestion = if is_impl_trait {
1273                     format!("{} + {}", bound_kind, sub)
1274                 } else {
1275                     let tail = if has_lifetimes { " + " } else { "" };
1276                     format!("{}: {}{}", bound_kind, sub, tail)
1277                 };
1278                 err.span_suggestion_short(
1279                     sp,
1280                     &consider,
1281                     suggestion,
1282                     Applicability::MaybeIncorrect, // Issue #41966
1283                 );
1284             } else {
1285                 err.help(&consider);
1286             }
1287         }
1288
1289         let mut err = match *sub {
1290             ty::ReEarlyBound(_)
1291             | ty::ReFree(ty::FreeRegion {
1292                 bound_region: ty::BrNamed(..),
1293                 ..
1294             }) => {
1295                 // Does the required lifetime have a nice name we can print?
1296                 let mut err = struct_span_err!(
1297                     self.tcx.sess,
1298                     span,
1299                     E0309,
1300                     "{} may not live long enough",
1301                     labeled_user_string
1302                 );
1303                 binding_suggestion(&mut err, type_param_span, bound_kind, sub);
1304                 err
1305             }
1306
1307             ty::ReStatic => {
1308                 // Does the required lifetime have a nice name we can print?
1309                 let mut err = struct_span_err!(
1310                     self.tcx.sess,
1311                     span,
1312                     E0310,
1313                     "{} may not live long enough",
1314                     labeled_user_string
1315                 );
1316                 binding_suggestion(&mut err, type_param_span, bound_kind, "'static");
1317                 err
1318             }
1319
1320             _ => {
1321                 // If not, be less specific.
1322                 let mut err = struct_span_err!(
1323                     self.tcx.sess,
1324                     span,
1325                     E0311,
1326                     "{} may not live long enough",
1327                     labeled_user_string
1328                 );
1329                 err.help(&format!(
1330                     "consider adding an explicit lifetime bound for `{}`",
1331                     bound_kind
1332                 ));
1333                 self.tcx.note_and_explain_region(
1334                     region_scope_tree,
1335                     &mut err,
1336                     &format!("{} must be valid for ", labeled_user_string),
1337                     sub,
1338                     "...",
1339                 );
1340                 err
1341             }
1342         };
1343
1344         if let Some(origin) = origin {
1345             self.note_region_origin(&mut err, &origin);
1346         }
1347         err
1348     }
1349
1350     fn report_sub_sup_conflict(
1351         &self,
1352         region_scope_tree: &region::ScopeTree,
1353         var_origin: RegionVariableOrigin,
1354         sub_origin: SubregionOrigin<'tcx>,
1355         sub_region: Region<'tcx>,
1356         sup_origin: SubregionOrigin<'tcx>,
1357         sup_region: Region<'tcx>,
1358     ) {
1359         let mut err = self.report_inference_failure(var_origin);
1360
1361         self.tcx.note_and_explain_region(
1362             region_scope_tree,
1363             &mut err,
1364             "first, the lifetime cannot outlive ",
1365             sup_region,
1366             "...",
1367         );
1368
1369         match (&sup_origin, &sub_origin) {
1370             (&infer::Subtype(ref sup_trace), &infer::Subtype(ref sub_trace)) => {
1371                 debug!("report_sub_sup_conflict: var_origin={:?}", var_origin);
1372                 debug!("report_sub_sup_conflict: sub_region={:?}", sub_region);
1373                 debug!("report_sub_sup_conflict: sub_origin={:?}", sub_origin);
1374                 debug!("report_sub_sup_conflict: sup_region={:?}", sup_region);
1375                 debug!("report_sub_sup_conflict: sup_origin={:?}", sup_origin);
1376                 debug!("report_sub_sup_conflict: sup_trace={:?}", sup_trace);
1377                 debug!("report_sub_sup_conflict: sub_trace={:?}", sub_trace);
1378                 debug!("report_sub_sup_conflict: sup_trace.values={:?}", sup_trace.values);
1379                 debug!("report_sub_sup_conflict: sub_trace.values={:?}", sub_trace.values);
1380
1381                 if let (Some((sup_expected, sup_found)), Some((sub_expected, sub_found))) = (
1382                     self.values_str(&sup_trace.values),
1383                     self.values_str(&sub_trace.values),
1384                 ) {
1385                     if sub_expected == sup_expected && sub_found == sup_found {
1386                         self.tcx.note_and_explain_region(
1387                             region_scope_tree,
1388                             &mut err,
1389                             "...but the lifetime must also be valid for ",
1390                             sub_region,
1391                             "...",
1392                         );
1393                         err.note(&format!(
1394                             "...so that the {}:\nexpected {}\n   found {}",
1395                             sup_trace.cause.as_requirement_str(),
1396                             sup_expected.content(),
1397                             sup_found.content()
1398                         ));
1399                         err.emit();
1400                         return;
1401                     }
1402                 }
1403             }
1404             _ => {}
1405         }
1406
1407         self.note_region_origin(&mut err, &sup_origin);
1408
1409         self.tcx.note_and_explain_region(
1410             region_scope_tree,
1411             &mut err,
1412             "but, the lifetime must be valid for ",
1413             sub_region,
1414             "...",
1415         );
1416
1417         self.note_region_origin(&mut err, &sub_origin);
1418         err.emit();
1419     }
1420 }
1421
1422 impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
1423     fn report_inference_failure(
1424         &self,
1425         var_origin: RegionVariableOrigin,
1426     ) -> DiagnosticBuilder<'tcx> {
1427         let br_string = |br: ty::BoundRegion| {
1428             let mut s = br.to_string();
1429             if !s.is_empty() {
1430                 s.push_str(" ");
1431             }
1432             s
1433         };
1434         let var_description = match var_origin {
1435             infer::MiscVariable(_) => String::new(),
1436             infer::PatternRegion(_) => " for pattern".to_string(),
1437             infer::AddrOfRegion(_) => " for borrow expression".to_string(),
1438             infer::Autoref(_) => " for autoref".to_string(),
1439             infer::Coercion(_) => " for automatic coercion".to_string(),
1440             infer::LateBoundRegion(_, br, infer::FnCall) => {
1441                 format!(" for lifetime parameter {}in function call", br_string(br))
1442             }
1443             infer::LateBoundRegion(_, br, infer::HigherRankedType) => {
1444                 format!(" for lifetime parameter {}in generic type", br_string(br))
1445             }
1446             infer::LateBoundRegion(_, br, infer::AssocTypeProjection(def_id)) => format!(
1447                 " for lifetime parameter {}in trait containing associated type `{}`",
1448                 br_string(br),
1449                 self.tcx.associated_item(def_id).ident
1450             ),
1451             infer::EarlyBoundRegion(_, name) => format!(" for lifetime parameter `{}`", name),
1452             infer::BoundRegionInCoherence(name) => {
1453                 format!(" for lifetime parameter `{}` in coherence check", name)
1454             }
1455             infer::UpvarRegion(ref upvar_id, _) => {
1456                 let var_name = self.tcx.hir().name_by_hir_id(upvar_id.var_path.hir_id);
1457                 format!(" for capture of `{}` by closure", var_name)
1458             }
1459             infer::NLL(..) => bug!("NLL variable found in lexical phase"),
1460         };
1461
1462         struct_span_err!(
1463             self.tcx.sess,
1464             var_origin.span(),
1465             E0495,
1466             "cannot infer an appropriate lifetime{} \
1467              due to conflicting requirements",
1468             var_description
1469         )
1470     }
1471 }
1472
1473 enum FailureCode {
1474     Error0317(&'static str),
1475     Error0580(&'static str),
1476     Error0308(&'static str),
1477     Error0644(&'static str),
1478 }
1479
1480 impl<'tcx> ObligationCause<'tcx> {
1481     fn as_failure_code(&self, terr: &TypeError<'tcx>) -> FailureCode {
1482         use self::FailureCode::*;
1483         use crate::traits::ObligationCauseCode::*;
1484         match self.code {
1485             CompareImplMethodObligation { .. } => Error0308("method not compatible with trait"),
1486             MatchExpressionArm { source, .. } => Error0308(match source {
1487                 hir::MatchSource::IfLetDesugar { .. } => "`if let` arms have incompatible types",
1488                 hir::MatchSource::TryDesugar => {
1489                     "try expression alternatives have incompatible types"
1490                 }
1491                 _ => "match arms have incompatible types",
1492             }),
1493             IfExpression { .. } => Error0308("if and else have incompatible types"),
1494             IfExpressionWithNoElse => Error0317("if may be missing an else clause"),
1495             MainFunctionType => Error0580("main function has wrong type"),
1496             StartFunctionType => Error0308("start function has wrong type"),
1497             IntrinsicType => Error0308("intrinsic has wrong type"),
1498             MethodReceiver => Error0308("mismatched method receiver"),
1499
1500             // In the case where we have no more specific thing to
1501             // say, also take a look at the error code, maybe we can
1502             // tailor to that.
1503             _ => match terr {
1504                 TypeError::CyclicTy(ty) if ty.is_closure() || ty.is_generator() => {
1505                     Error0644("closure/generator type that references itself")
1506                 }
1507                 _ => Error0308("mismatched types"),
1508             },
1509         }
1510     }
1511
1512     fn as_requirement_str(&self) -> &'static str {
1513         use crate::traits::ObligationCauseCode::*;
1514         match self.code {
1515             CompareImplMethodObligation { .. } => "method type is compatible with trait",
1516             ExprAssignable => "expression is assignable",
1517             MatchExpressionArm { source, .. } => match source {
1518                 hir::MatchSource::IfLetDesugar { .. } => "`if let` arms have compatible types",
1519                 _ => "match arms have compatible types",
1520             },
1521             IfExpression { .. } => "if and else have compatible types",
1522             IfExpressionWithNoElse => "if missing an else returns ()",
1523             MainFunctionType => "`main` function has the correct type",
1524             StartFunctionType => "`start` function has the correct type",
1525             IntrinsicType => "intrinsic has the correct type",
1526             MethodReceiver => "method receiver has the correct type",
1527             _ => "types are compatible",
1528         }
1529     }
1530 }