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