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