]> git.lizzy.rs Git - rust.git/blob - src/librustc/infer/error_reporting/mod.rs
8e8576b83e4ed4d238638768cbe61d012d928b0b
[rust.git] / src / librustc / infer / error_reporting / mod.rs
1 // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! Error Reporting Code for the inference engine
12 //!
13 //! Because of the way inference, and in particular region inference,
14 //! works, it often happens that errors are not detected until far after
15 //! the relevant line of code has been type-checked. Therefore, there is
16 //! an elaborate system to track why a particular constraint in the
17 //! inference graph arose so that we can explain to the user what gave
18 //! rise to a particular error.
19 //!
20 //! The basis of the system are the "origin" types. An "origin" is the
21 //! reason that a constraint or inference variable arose. There are
22 //! different "origin" enums for different kinds of constraints/variables
23 //! (e.g., `TypeOrigin`, `RegionVariableOrigin`). An origin always has
24 //! a span, but also more information so that we can generate a meaningful
25 //! error message.
26 //!
27 //! Having a catalogue of all the different reasons an error can arise is
28 //! also useful for other reasons, like cross-referencing FAQs etc, though
29 //! we are not really taking advantage of this yet.
30 //!
31 //! # Region Inference
32 //!
33 //! Region inference is particularly tricky because it always succeeds "in
34 //! the moment" and simply registers a constraint. Then, at the end, we
35 //! can compute the full graph and report errors, so we need to be able to
36 //! store and later report what gave rise to the conflicting constraints.
37 //!
38 //! # Subtype Trace
39 //!
40 //! Determining whether `T1 <: T2` often involves a number of subtypes and
41 //! subconstraints along the way. A "TypeTrace" is an extended version
42 //! of an origin that traces the types and other values that were being
43 //! compared. It is not necessarily comprehensive (in fact, at the time of
44 //! this writing it only tracks the root values being compared) but I'd
45 //! like to extend it to include significant "waypoints". For example, if
46 //! you are comparing `(T1, T2) <: (T3, T4)`, and the problem is that `T2
47 //! <: T4` fails, I'd like the trace to include enough information to say
48 //! "in the 2nd element of the tuple". Similarly, failures when comparing
49 //! arguments or return types in fn types should be able to cite the
50 //! specific position, etc.
51 //!
52 //! # Reality vs plan
53 //!
54 //! Of course, there is still a LOT of code in typeck that has yet to be
55 //! ported to this system, and which relies on string concatenation at the
56 //! time of error detection.
57
58 use infer;
59 use super::{InferCtxt, TypeTrace, SubregionOrigin, RegionVariableOrigin, ValuePairs};
60 use super::region_inference::{RegionResolutionError, ConcreteFailure, SubSupConflict,
61                               GenericBoundFailure, GenericKind};
62
63 use std::fmt;
64 use hir;
65 use hir::map as hir_map;
66 use hir::def_id::DefId;
67 use middle::region;
68 use traits::{ObligationCause, ObligationCauseCode};
69 use ty::{self, Region, TyCtxt, TypeFoldable};
70 use ty::error::TypeError;
71 use syntax::ast::DUMMY_NODE_ID;
72 use syntax_pos::{Pos, Span};
73 use errors::{DiagnosticBuilder, DiagnosticStyledString};
74
75 mod note;
76
77 mod need_type_info;
78 mod util;
79 mod named_anon_conflict;
80 mod anon_anon_conflict;
81
82 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
83     pub fn note_and_explain_region(self,
84                                    err: &mut DiagnosticBuilder,
85                                    prefix: &str,
86                                    region: ty::Region<'tcx>,
87                                    suffix: &str) {
88         fn item_scope_tag(item: &hir::Item) -> &'static str {
89             match item.node {
90                 hir::ItemImpl(..) => "impl",
91                 hir::ItemStruct(..) => "struct",
92                 hir::ItemUnion(..) => "union",
93                 hir::ItemEnum(..) => "enum",
94                 hir::ItemTrait(..) => "trait",
95                 hir::ItemFn(..) => "function body",
96                 _ => "item"
97             }
98         }
99
100         fn trait_item_scope_tag(item: &hir::TraitItem) -> &'static str {
101             match item.node {
102                 hir::TraitItemKind::Method(..) => "method body",
103                 hir::TraitItemKind::Const(..) |
104                 hir::TraitItemKind::Type(..) => "associated item"
105             }
106         }
107
108         fn impl_item_scope_tag(item: &hir::ImplItem) -> &'static str {
109             match item.node {
110                 hir::ImplItemKind::Method(..) => "method body",
111                 hir::ImplItemKind::Const(..) |
112                 hir::ImplItemKind::Type(_) => "associated item"
113             }
114         }
115
116         fn explain_span<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>,
117                                         heading: &str, span: Span)
118                                         -> (String, Option<Span>) {
119             let lo = tcx.sess.codemap().lookup_char_pos_adj(span.lo);
120             (format!("the {} at {}:{}", heading, lo.line, lo.col.to_usize() + 1),
121              Some(span))
122         }
123
124         let (description, span) = match *region {
125             ty::ReScope(scope) => {
126                 let new_string;
127                 let unknown_scope = || {
128                     format!("{}unknown scope: {:?}{}.  Please report a bug.",
129                             prefix, scope, suffix)
130                 };
131                 let span = match scope.span(&self.hir) {
132                     Some(s) => s,
133                     None => {
134                         err.note(&unknown_scope());
135                         return;
136                     }
137                 };
138                 let tag = match self.hir.find(scope.node_id()) {
139                     Some(hir_map::NodeBlock(_)) => "block",
140                     Some(hir_map::NodeExpr(expr)) => match expr.node {
141                         hir::ExprCall(..) => "call",
142                         hir::ExprMethodCall(..) => "method call",
143                         hir::ExprMatch(.., hir::MatchSource::IfLetDesugar { .. }) => "if let",
144                         hir::ExprMatch(.., hir::MatchSource::WhileLetDesugar) =>  "while let",
145                         hir::ExprMatch(.., hir::MatchSource::ForLoopDesugar) =>  "for",
146                         hir::ExprMatch(..) => "match",
147                         _ => "expression",
148                     },
149                     Some(hir_map::NodeStmt(_)) => "statement",
150                     Some(hir_map::NodeItem(it)) => item_scope_tag(&it),
151                     Some(hir_map::NodeTraitItem(it)) => trait_item_scope_tag(&it),
152                     Some(hir_map::NodeImplItem(it)) => impl_item_scope_tag(&it),
153                     Some(_) | None => {
154                         err.span_note(span, &unknown_scope());
155                         return;
156                     }
157                 };
158                 let scope_decorated_tag = match scope {
159                     region::CodeExtent::Misc(_) => tag,
160                     region::CodeExtent::CallSiteScope(_) => {
161                         "scope of call-site for function"
162                     }
163                     region::CodeExtent::ParameterScope(_) => {
164                         "scope of function body"
165                     }
166                     region::CodeExtent::DestructionScope(_) => {
167                         new_string = format!("destruction scope surrounding {}", tag);
168                         &new_string[..]
169                     }
170                     region::CodeExtent::Remainder(r) => {
171                         new_string = format!("block suffix following statement {}",
172                                              r.first_statement_index);
173                         &new_string[..]
174                     }
175                 };
176                 explain_span(self, scope_decorated_tag, span)
177             }
178
179             ty::ReEarlyBound(_) |
180             ty::ReFree(_) => {
181                 let scope = match *region {
182                     ty::ReEarlyBound(ref br) => {
183                         self.parent_def_id(br.def_id).unwrap()
184                     }
185                     ty::ReFree(ref fr) => fr.scope,
186                     _ => bug!()
187                 };
188                 let prefix = match *region {
189                     ty::ReEarlyBound(ref br) => {
190                         format!("the lifetime {} as defined on", br.name)
191                     }
192                     ty::ReFree(ref fr) => {
193                         match fr.bound_region {
194                             ty::BrAnon(idx) => {
195                                 format!("the anonymous lifetime #{} defined on", idx + 1)
196                             }
197                             ty::BrFresh(_) => "an anonymous lifetime defined on".to_owned(),
198                             _ => {
199                                 format!("the lifetime {} as defined on",
200                                         fr.bound_region)
201                             }
202                         }
203                     }
204                     _ => bug!()
205                 };
206
207                 let node = self.hir.as_local_node_id(scope)
208                                    .unwrap_or(DUMMY_NODE_ID);
209                 let unknown;
210                 let tag = match self.hir.find(node) {
211                     Some(hir_map::NodeBlock(_)) |
212                     Some(hir_map::NodeExpr(_)) => "body",
213                     Some(hir_map::NodeItem(it)) => item_scope_tag(&it),
214                     Some(hir_map::NodeTraitItem(it)) => trait_item_scope_tag(&it),
215                     Some(hir_map::NodeImplItem(it)) => impl_item_scope_tag(&it),
216
217                     // this really should not happen, but it does:
218                     // FIXME(#27942)
219                     Some(_) => {
220                         unknown = format!("unexpected node ({}) for scope {:?}.  \
221                                            Please report a bug.",
222                                           self.hir.node_to_string(node), scope);
223                         &unknown
224                     }
225                     None => {
226                         unknown = format!("unknown node for scope {:?}.  \
227                                            Please report a bug.", scope);
228                         &unknown
229                     }
230                 };
231                 let (msg, opt_span) = explain_span(self, tag, self.hir.span(node));
232                 (format!("{} {}", prefix, msg), opt_span)
233             }
234
235             ty::ReStatic => ("the static lifetime".to_owned(), None),
236
237             ty::ReEmpty => ("the empty lifetime".to_owned(), None),
238
239             // FIXME(#13998) ReSkolemized should probably print like
240             // ReFree rather than dumping Debug output on the user.
241             //
242             // We shouldn't really be having unification failures with ReVar
243             // and ReLateBound though.
244             ty::ReSkolemized(..) |
245             ty::ReVar(_) |
246             ty::ReLateBound(..) |
247             ty::ReErased => {
248                 (format!("lifetime {:?}", region), None)
249             }
250         };
251         let message = format!("{}{}{}", prefix, description, suffix);
252         if let Some(span) = span {
253             err.span_note(span, &message);
254         } else {
255             err.note(&message);
256         }
257     }
258 }
259
260 impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
261
262     pub fn report_region_errors(&self, errors: &Vec<RegionResolutionError<'tcx>>) {
263         debug!("report_region_errors(): {} errors to start", errors.len());
264
265         // try to pre-process the errors, which will group some of them
266         // together into a `ProcessedErrors` group:
267         let errors = self.process_errors(errors);
268
269         debug!("report_region_errors: {} errors after preprocessing", errors.len());
270
271         for error in errors {
272             debug!("report_region_errors: error = {:?}", error);
273
274             if !self.try_report_named_anon_conflict(&error) &&
275                !self.try_report_anon_anon_conflict(&error) {
276
277                match error.clone() {
278                   // These errors could indicate all manner of different
279                   // problems with many different solutions. Rather
280                   // than generate a "one size fits all" error, what we
281                   // attempt to do is go through a number of specific
282                   // scenarios and try to find the best way to present
283                   // the error. If all of these fails, we fall back to a rather
284                   // general bit of code that displays the error information
285                   ConcreteFailure(origin, sub, sup) => {
286
287                       self.report_concrete_failure(origin, sub, sup).emit();
288                   }
289
290                   GenericBoundFailure(kind, param_ty, sub) => {
291                       self.report_generic_bound_failure(kind, param_ty, sub);
292                   }
293
294                   SubSupConflict(var_origin, sub_origin, sub_r, sup_origin, sup_r) => {
295                         self.report_sub_sup_conflict(var_origin,
296                                                      sub_origin,
297                                                      sub_r,
298                                                      sup_origin,
299                                                      sup_r);
300                   }
301                }
302             }
303         }
304     }
305
306     // This method goes through all the errors and try to group certain types
307     // of error together, for the purpose of suggesting explicit lifetime
308     // parameters to the user. This is done so that we can have a more
309     // complete view of what lifetimes should be the same.
310     // If the return value is an empty vector, it means that processing
311     // failed (so the return value of this method should not be used).
312     //
313     // The method also attempts to weed out messages that seem like
314     // duplicates that will be unhelpful to the end-user. But
315     // obviously it never weeds out ALL errors.
316     fn process_errors(&self, errors: &Vec<RegionResolutionError<'tcx>>)
317                       -> Vec<RegionResolutionError<'tcx>> {
318         debug!("process_errors()");
319
320         // We want to avoid reporting generic-bound failures if we can
321         // avoid it: these have a very high rate of being unhelpful in
322         // practice. This is because they are basically secondary
323         // checks that test the state of the region graph after the
324         // rest of inference is done, and the other kinds of errors
325         // indicate that the region constraint graph is internally
326         // inconsistent, so these test results are likely to be
327         // meaningless.
328         //
329         // Therefore, we filter them out of the list unless they are
330         // the only thing in the list.
331
332         let is_bound_failure = |e: &RegionResolutionError<'tcx>| match *e {
333             ConcreteFailure(..) => false,
334             SubSupConflict(..) => false,
335             GenericBoundFailure(..) => true,
336         };
337
338         if errors.iter().all(|e| is_bound_failure(e)) {
339             errors.clone()
340         } else {
341             errors.iter().filter(|&e| !is_bound_failure(e)).cloned().collect()
342         }
343     }
344
345     /// Adds a note if the types come from similarly named crates
346     fn check_and_note_conflicting_crates(&self,
347                                          err: &mut DiagnosticBuilder,
348                                          terr: &TypeError<'tcx>,
349                                          sp: Span) {
350         let report_path_match = |err: &mut DiagnosticBuilder, did1: DefId, did2: DefId| {
351             // Only external crates, if either is from a local
352             // module we could have false positives
353             if !(did1.is_local() || did2.is_local()) && did1.krate != did2.krate {
354                 let exp_path = self.tcx.item_path_str(did1);
355                 let found_path = self.tcx.item_path_str(did2);
356                 let exp_abs_path = self.tcx.absolute_item_path_str(did1);
357                 let found_abs_path = self.tcx.absolute_item_path_str(did2);
358                 // We compare strings because DefPath can be different
359                 // for imported and non-imported crates
360                 if exp_path == found_path
361                 || exp_abs_path == found_abs_path {
362                     let crate_name = self.tcx.sess.cstore.crate_name(did1.krate);
363                     err.span_note(sp, &format!("Perhaps two different versions \
364                                                 of crate `{}` are being used?",
365                                                crate_name));
366                 }
367             }
368         };
369         match *terr {
370             TypeError::Sorts(ref exp_found) => {
371                 // if they are both "path types", there's a chance of ambiguity
372                 // due to different versions of the same crate
373                 match (&exp_found.expected.sty, &exp_found.found.sty) {
374                     (&ty::TyAdt(exp_adt, _), &ty::TyAdt(found_adt, _)) => {
375                         report_path_match(err, exp_adt.did, found_adt.did);
376                     },
377                     _ => ()
378                 }
379             },
380             TypeError::Traits(ref exp_found) => {
381                 report_path_match(err, exp_found.expected, exp_found.found);
382             },
383             _ => () // FIXME(#22750) handle traits and stuff
384         }
385     }
386
387     fn note_error_origin(&self,
388                          err: &mut DiagnosticBuilder<'tcx>,
389                          cause: &ObligationCause<'tcx>)
390     {
391         match cause.code {
392             ObligationCauseCode::MatchExpressionArm { arm_span, source } => match source {
393                 hir::MatchSource::IfLetDesugar {..} => {
394                     err.span_note(arm_span, "`if let` arm with an incompatible type");
395                 }
396                 _ => {
397                     err.span_note(arm_span, "match arm with an incompatible type");
398                 }
399             },
400             _ => ()
401         }
402     }
403
404     /// Given that `other_ty` is the same as a type argument for `name` in `sub`, populate `value`
405     /// highlighting `name` and every type argument that isn't at `pos` (which is `other_ty`), and
406     /// populate `other_value` with `other_ty`.
407     ///
408     /// ```text
409     /// Foo<Bar<Qux>>
410     /// ^^^^--------^ this is highlighted
411     /// |   |
412     /// |   this type argument is exactly the same as the other type, not highlighted
413     /// this is highlighted
414     /// Bar<Qux>
415     /// -------- this type is the same as a type argument in the other type, not highlighted
416     /// ```
417     fn highlight_outer(&self,
418                        mut value: &mut DiagnosticStyledString,
419                        mut other_value: &mut DiagnosticStyledString,
420                        name: String,
421                        sub: &ty::subst::Substs<'tcx>,
422                        pos: usize,
423                        other_ty: &ty::Ty<'tcx>) {
424         // `value` and `other_value` hold two incomplete type representation for display.
425         // `name` is the path of both types being compared. `sub`
426         value.push_highlighted(name);
427         let len = sub.len();
428         if len > 0 {
429             value.push_highlighted("<");
430         }
431
432         // Output the lifetimes fot the first type
433         let lifetimes = sub.regions().map(|lifetime| {
434             let s = format!("{}", lifetime);
435             if s.is_empty() {
436                 "'_".to_string()
437             } else {
438                 s
439             }
440         }).collect::<Vec<_>>().join(", ");
441         if !lifetimes.is_empty() {
442             if sub.regions().count() < len {
443                 value.push_normal(lifetimes + &", ");
444             } else {
445                 value.push_normal(lifetimes);
446             }
447         }
448
449         // Highlight all the type arguments that aren't at `pos` and compare the type argument at
450         // `pos` and `other_ty`.
451         for (i, type_arg) in sub.types().enumerate() {
452             if i == pos {
453                 let values = self.cmp(type_arg, other_ty);
454                 value.0.extend((values.0).0);
455                 other_value.0.extend((values.1).0);
456             } else {
457                 value.push_highlighted(format!("{}", type_arg));
458             }
459
460             if len > 0 && i != len - 1 {
461                 value.push_normal(", ");
462             }
463             //self.push_comma(&mut value, &mut other_value, len, i);
464         }
465         if len > 0 {
466             value.push_highlighted(">");
467         }
468     }
469
470     /// If `other_ty` is the same as a type argument present in `sub`, highlight `path` in `t1_out`,
471     /// as that is the difference to the other type.
472     ///
473     /// For the following code:
474     ///
475     /// ```norun
476     /// let x: Foo<Bar<Qux>> = foo::<Bar<Qux>>();
477     /// ```
478     ///
479     /// The type error output will behave in the following way:
480     ///
481     /// ```text
482     /// Foo<Bar<Qux>>
483     /// ^^^^--------^ this is highlighted
484     /// |   |
485     /// |   this type argument is exactly the same as the other type, not highlighted
486     /// this is highlighted
487     /// Bar<Qux>
488     /// -------- this type is the same as a type argument in the other type, not highlighted
489     /// ```
490     fn cmp_type_arg(&self,
491                     mut t1_out: &mut DiagnosticStyledString,
492                     mut t2_out: &mut DiagnosticStyledString,
493                     path: String,
494                     sub: &ty::subst::Substs<'tcx>,
495                     other_path: String,
496                     other_ty: &ty::Ty<'tcx>) -> Option<()> {
497         for (i, ta) in sub.types().enumerate() {
498             if &ta == other_ty {
499                 self.highlight_outer(&mut t1_out, &mut t2_out, path, sub, i, &other_ty);
500                 return Some(());
501             }
502             if let &ty::TyAdt(def, _) = &ta.sty {
503                 let path_ = self.tcx.item_path_str(def.did.clone());
504                 if path_ == other_path {
505                     self.highlight_outer(&mut t1_out, &mut t2_out, path, sub, i, &other_ty);
506                     return Some(());
507                 }
508             }
509         }
510         None
511     }
512
513     /// Add a `,` to the type representation only if it is appropriate.
514     fn push_comma(&self,
515                   value: &mut DiagnosticStyledString,
516                   other_value: &mut DiagnosticStyledString,
517                   len: usize,
518                   pos: usize) {
519         if len > 0 && pos != len - 1 {
520             value.push_normal(", ");
521             other_value.push_normal(", ");
522         }
523     }
524
525     /// Compare two given types, eliding parts that are the same between them and highlighting
526     /// relevant differences, and return two representation of those types for highlighted printing.
527     fn cmp(&self, t1: ty::Ty<'tcx>, t2: ty::Ty<'tcx>)
528         -> (DiagnosticStyledString, DiagnosticStyledString)
529     {
530         match (&t1.sty, &t2.sty) {
531             (&ty::TyAdt(def1, sub1), &ty::TyAdt(def2, sub2)) => {
532                 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
533                 let path1 = self.tcx.item_path_str(def1.did.clone());
534                 let path2 = self.tcx.item_path_str(def2.did.clone());
535                 if def1.did == def2.did {
536                     // Easy case. Replace same types with `_` to shorten the output and highlight
537                     // the differing ones.
538                     //     let x: Foo<Bar, Qux> = y::<Foo<Quz, Qux>>();
539                     //     Foo<Bar, _>
540                     //     Foo<Quz, _>
541                     //         ---  ^ type argument elided
542                     //         |
543                     //         highlighted in output
544                     values.0.push_normal(path1);
545                     values.1.push_normal(path2);
546
547                     // Only draw `<...>` if there're lifetime/type arguments.
548                     let len = sub1.len();
549                     if len > 0 {
550                         values.0.push_normal("<");
551                         values.1.push_normal("<");
552                     }
553
554                     fn lifetime_display(lifetime: Region) -> String {
555                         let s = format!("{}", lifetime);
556                         if s.is_empty() {
557                             "'_".to_string()
558                         } else {
559                             s
560                         }
561                     }
562                     // At one point we'd like to elide all lifetimes here, they are irrelevant for
563                     // all diagnostics that use this output
564                     //
565                     //     Foo<'x, '_, Bar>
566                     //     Foo<'y, '_, Qux>
567                     //         ^^  ^^  --- type arguments are not elided
568                     //         |   |
569                     //         |   elided as they were the same
570                     //         not elided, they were different, but irrelevant
571                     let lifetimes = sub1.regions().zip(sub2.regions());
572                     for (i, lifetimes) in lifetimes.enumerate() {
573                         let l1 = lifetime_display(lifetimes.0);
574                         let l2 = lifetime_display(lifetimes.1);
575                         if l1 == l2 {
576                             values.0.push_normal("'_");
577                             values.1.push_normal("'_");
578                         } else {
579                             values.0.push_highlighted(l1);
580                             values.1.push_highlighted(l2);
581                         }
582                         self.push_comma(&mut values.0, &mut values.1, len, i);
583                     }
584
585                     // We're comparing two types with the same path, so we compare the type
586                     // arguments for both. If they are the same, do not highlight and elide from the
587                     // output.
588                     //     Foo<_, Bar>
589                     //     Foo<_, Qux>
590                     //         ^ elided type as this type argument was the same in both sides
591                     let type_arguments = sub1.types().zip(sub2.types());
592                     let regions_len = sub1.regions().collect::<Vec<_>>().len();
593                     for (i, (ta1, ta2)) in type_arguments.enumerate() {
594                         let i = i + regions_len;
595                         if ta1 == ta2 {
596                             values.0.push_normal("_");
597                             values.1.push_normal("_");
598                         } else {
599                             let (x1, x2) = self.cmp(ta1, ta2);
600                             (values.0).0.extend(x1.0);
601                             (values.1).0.extend(x2.0);
602                         }
603                         self.push_comma(&mut values.0, &mut values.1, len, i);
604                     }
605
606                     // Close the type argument bracket.
607                     // Only draw `<...>` if there're lifetime/type arguments.
608                     if len > 0 {
609                         values.0.push_normal(">");
610                         values.1.push_normal(">");
611                     }
612                     values
613                 } else {
614                     // Check for case:
615                     //     let x: Foo<Bar<Qux> = foo::<Bar<Qux>>();
616                     //     Foo<Bar<Qux>
617                     //         ------- this type argument is exactly the same as the other type
618                     //     Bar<Qux>
619                     if self.cmp_type_arg(&mut values.0,
620                                          &mut values.1,
621                                          path1.clone(),
622                                          sub1,
623                                          path2.clone(),
624                                          &t2).is_some() {
625                         return values;
626                     }
627                     // Check for case:
628                     //     let x: Bar<Qux> = y:<Foo<Bar<Qux>>>();
629                     //     Bar<Qux>
630                     //     Foo<Bar<Qux>>
631                     //         ------- this type argument is exactly the same as the other type
632                     if self.cmp_type_arg(&mut values.1,
633                                          &mut values.0,
634                                          path2,
635                                          sub2,
636                                          path1,
637                                          &t1).is_some() {
638                         return values;
639                     }
640
641                     // We couldn't find anything in common, highlight everything.
642                     //     let x: Bar<Qux> = y::<Foo<Zar>>();
643                     (DiagnosticStyledString::highlighted(format!("{}", t1)),
644                      DiagnosticStyledString::highlighted(format!("{}", t2)))
645                 }
646             }
647             _ => {
648                 if t1 == t2 {
649                     // The two types are the same, elide and don't highlight.
650                     (DiagnosticStyledString::normal("_"), DiagnosticStyledString::normal("_"))
651                 } else {
652                     // We couldn't find anything in common, highlight everything.
653                     (DiagnosticStyledString::highlighted(format!("{}", t1)),
654                      DiagnosticStyledString::highlighted(format!("{}", t2)))
655                 }
656             }
657         }
658     }
659
660     pub fn note_type_err(&self,
661                          diag: &mut DiagnosticBuilder<'tcx>,
662                          cause: &ObligationCause<'tcx>,
663                          secondary_span: Option<(Span, String)>,
664                          values: Option<ValuePairs<'tcx>>,
665                          terr: &TypeError<'tcx>)
666     {
667         let (expected_found, is_simple_error) = match values {
668             None => (None, false),
669             Some(values) => {
670                 let is_simple_error = match values {
671                     ValuePairs::Types(exp_found) => {
672                         exp_found.expected.is_primitive() && exp_found.found.is_primitive()
673                     }
674                     _ => false,
675                 };
676                 let vals = match self.values_str(&values) {
677                     Some((expected, found)) => Some((expected, found)),
678                     None => {
679                         // Derived error. Cancel the emitter.
680                         self.tcx.sess.diagnostic().cancel(diag);
681                         return
682                     }
683                 };
684                 (vals, is_simple_error)
685             }
686         };
687
688         let span = cause.span;
689
690         if let Some((expected, found)) = expected_found {
691             match (terr, is_simple_error, expected == found) {
692                 (&TypeError::Sorts(ref values), false, true) => {
693                     diag.note_expected_found_extra(
694                         &"type", expected, found,
695                         &format!(" ({})", values.expected.sort_string(self.tcx)),
696                         &format!(" ({})", values.found.sort_string(self.tcx)));
697                 }
698                 (_, false,  _) => {
699                     diag.note_expected_found(&"type", expected, found);
700                 }
701                 _ => (),
702             }
703         }
704
705         diag.span_label(span, terr.to_string());
706         if let Some((sp, msg)) = secondary_span {
707             diag.span_label(sp, msg);
708         }
709
710         self.note_error_origin(diag, &cause);
711         self.check_and_note_conflicting_crates(diag, terr, span);
712         self.tcx.note_and_explain_type_err(diag, terr, span);
713     }
714
715     pub fn report_and_explain_type_error(&self,
716                                          trace: TypeTrace<'tcx>,
717                                          terr: &TypeError<'tcx>)
718                                          -> DiagnosticBuilder<'tcx>
719     {
720         let span = trace.cause.span;
721         let failure_str = trace.cause.as_failure_str();
722         let mut diag = match trace.cause.code {
723             ObligationCauseCode::IfExpressionWithNoElse => {
724                 struct_span_err!(self.tcx.sess, span, E0317, "{}", failure_str)
725             }
726             ObligationCauseCode::MainFunctionType => {
727                 struct_span_err!(self.tcx.sess, span, E0580, "{}", failure_str)
728             }
729             _ => {
730                 struct_span_err!(self.tcx.sess, span, E0308, "{}", failure_str)
731             }
732         };
733         self.note_type_err(&mut diag, &trace.cause, None, Some(trace.values), terr);
734         diag
735     }
736
737     fn values_str(&self, values: &ValuePairs<'tcx>)
738         -> Option<(DiagnosticStyledString, DiagnosticStyledString)>
739     {
740         match *values {
741             infer::Types(ref exp_found) => self.expected_found_str_ty(exp_found),
742             infer::TraitRefs(ref exp_found) => self.expected_found_str(exp_found),
743             infer::PolyTraitRefs(ref exp_found) => self.expected_found_str(exp_found),
744         }
745     }
746
747     fn expected_found_str_ty(&self,
748                              exp_found: &ty::error::ExpectedFound<ty::Ty<'tcx>>)
749                              -> Option<(DiagnosticStyledString, DiagnosticStyledString)> {
750         let exp_found = self.resolve_type_vars_if_possible(exp_found);
751         if exp_found.references_error() {
752             return None;
753         }
754
755         Some(self.cmp(exp_found.expected, exp_found.found))
756     }
757
758     /// Returns a string of the form "expected `{}`, found `{}`".
759     fn expected_found_str<T: fmt::Display + TypeFoldable<'tcx>>(
760         &self,
761         exp_found: &ty::error::ExpectedFound<T>)
762         -> Option<(DiagnosticStyledString, DiagnosticStyledString)>
763     {
764         let exp_found = self.resolve_type_vars_if_possible(exp_found);
765         if exp_found.references_error() {
766             return None;
767         }
768
769         Some((DiagnosticStyledString::highlighted(format!("{}", exp_found.expected)),
770               DiagnosticStyledString::highlighted(format!("{}", exp_found.found))))
771     }
772
773     fn report_generic_bound_failure(&self,
774                                     origin: SubregionOrigin<'tcx>,
775                                     bound_kind: GenericKind<'tcx>,
776                                     sub: Region<'tcx>)
777     {
778         // FIXME: it would be better to report the first error message
779         // with the span of the parameter itself, rather than the span
780         // where the error was detected. But that span is not readily
781         // accessible.
782
783         let labeled_user_string = match bound_kind {
784             GenericKind::Param(ref p) =>
785                 format!("the parameter type `{}`", p),
786             GenericKind::Projection(ref p) =>
787                 format!("the associated type `{}`", p),
788         };
789
790         if let SubregionOrigin::CompareImplMethodObligation {
791             span, item_name, impl_item_def_id, trait_item_def_id, lint_id
792         } = origin {
793             self.report_extra_impl_obligation(span,
794                                               item_name,
795                                               impl_item_def_id,
796                                               trait_item_def_id,
797                                               &format!("`{}: {}`", bound_kind, sub),
798                                               lint_id)
799                 .emit();
800             return;
801         }
802
803         let mut err = match *sub {
804             ty::ReEarlyBound(_) |
805             ty::ReFree(ty::FreeRegion {bound_region: ty::BrNamed(..), ..}) => {
806                 // Does the required lifetime have a nice name we can print?
807                 let mut err = struct_span_err!(self.tcx.sess,
808                                                origin.span(),
809                                                E0309,
810                                                "{} may not live long enough",
811                                                labeled_user_string);
812                 err.help(&format!("consider adding an explicit lifetime bound `{}: {}`...",
813                          bound_kind,
814                          sub));
815                 err
816             }
817
818             ty::ReStatic => {
819                 // Does the required lifetime have a nice name we can print?
820                 let mut err = struct_span_err!(self.tcx.sess,
821                                                origin.span(),
822                                                E0310,
823                                                "{} may not live long enough",
824                                                labeled_user_string);
825                 err.help(&format!("consider adding an explicit lifetime \
826                                    bound `{}: 'static`...",
827                                   bound_kind));
828                 err
829             }
830
831             _ => {
832                 // If not, be less specific.
833                 let mut err = struct_span_err!(self.tcx.sess,
834                                                origin.span(),
835                                                E0311,
836                                                "{} may not live long enough",
837                                                labeled_user_string);
838                 err.help(&format!("consider adding an explicit lifetime bound for `{}`",
839                                   bound_kind));
840                 self.tcx.note_and_explain_region(
841                     &mut err,
842                     &format!("{} must be valid for ", labeled_user_string),
843                     sub,
844                     "...");
845                 err
846             }
847         };
848
849         self.note_region_origin(&mut err, &origin);
850         err.emit();
851     }
852
853     fn report_sub_sup_conflict(&self,
854                                var_origin: RegionVariableOrigin,
855                                sub_origin: SubregionOrigin<'tcx>,
856                                sub_region: Region<'tcx>,
857                                sup_origin: SubregionOrigin<'tcx>,
858                                sup_region: Region<'tcx>) {
859         let mut err = self.report_inference_failure(var_origin);
860
861         self.tcx.note_and_explain_region(&mut err,
862             "first, the lifetime cannot outlive ",
863             sup_region,
864             "...");
865
866         self.note_region_origin(&mut err, &sup_origin);
867
868         self.tcx.note_and_explain_region(&mut err,
869             "but, the lifetime must be valid for ",
870             sub_region,
871             "...");
872
873         self.note_region_origin(&mut err, &sub_origin);
874         err.emit();
875     }
876 }
877
878 impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
879     fn report_inference_failure(&self,
880                                 var_origin: RegionVariableOrigin)
881                                 -> DiagnosticBuilder<'tcx> {
882         let br_string = |br: ty::BoundRegion| {
883             let mut s = br.to_string();
884             if !s.is_empty() {
885                 s.push_str(" ");
886             }
887             s
888         };
889         let var_description = match var_origin {
890             infer::MiscVariable(_) => "".to_string(),
891             infer::PatternRegion(_) => " for pattern".to_string(),
892             infer::AddrOfRegion(_) => " for borrow expression".to_string(),
893             infer::Autoref(_) => " for autoref".to_string(),
894             infer::Coercion(_) => " for automatic coercion".to_string(),
895             infer::LateBoundRegion(_, br, infer::FnCall) => {
896                 format!(" for lifetime parameter {}in function call",
897                         br_string(br))
898             }
899             infer::LateBoundRegion(_, br, infer::HigherRankedType) => {
900                 format!(" for lifetime parameter {}in generic type", br_string(br))
901             }
902             infer::LateBoundRegion(_, br, infer::AssocTypeProjection(type_name)) => {
903                 format!(" for lifetime parameter {}in trait containing associated type `{}`",
904                         br_string(br), type_name)
905             }
906             infer::EarlyBoundRegion(_, name) => {
907                 format!(" for lifetime parameter `{}`",
908                         name)
909             }
910             infer::BoundRegionInCoherence(name) => {
911                 format!(" for lifetime parameter `{}` in coherence check",
912                         name)
913             }
914             infer::UpvarRegion(ref upvar_id, _) => {
915                 format!(" for capture of `{}` by closure",
916                         self.tcx.local_var_name_str(upvar_id.var_id).to_string())
917             }
918         };
919
920         struct_span_err!(self.tcx.sess, var_origin.span(), E0495,
921                   "cannot infer an appropriate lifetime{} \
922                    due to conflicting requirements",
923                   var_description)
924     }
925 }
926
927 impl<'tcx> ObligationCause<'tcx> {
928     fn as_failure_str(&self) -> &'static str {
929         use traits::ObligationCauseCode::*;
930         match self.code {
931             CompareImplMethodObligation { .. } => "method not compatible with trait",
932             MatchExpressionArm { source, .. } => match source {
933                 hir::MatchSource::IfLetDesugar{..} => "`if let` arms have incompatible types",
934                 _ => "match arms have incompatible types",
935             },
936             IfExpression => "if and else have incompatible types",
937             IfExpressionWithNoElse => "if may be missing an else clause",
938             EquatePredicate => "equality predicate not satisfied",
939             MainFunctionType => "main function has wrong type",
940             StartFunctionType => "start function has wrong type",
941             IntrinsicType => "intrinsic has wrong type",
942             MethodReceiver => "mismatched method receiver",
943             _ => "mismatched types",
944         }
945     }
946
947     fn as_requirement_str(&self) -> &'static str {
948         use traits::ObligationCauseCode::*;
949         match self.code {
950             CompareImplMethodObligation { .. } => "method type is compatible with trait",
951             ExprAssignable => "expression is assignable",
952             MatchExpressionArm { source, .. } => match source {
953                 hir::MatchSource::IfLetDesugar{..} => "`if let` arms have compatible types",
954                 _ => "match arms have compatible types",
955             },
956             IfExpression => "if and else have compatible types",
957             IfExpressionWithNoElse => "if missing an else returns ()",
958             EquatePredicate => "equality where clause is satisfied",
959             MainFunctionType => "`main` function has the correct type",
960             StartFunctionType => "`start` function has the correct type",
961             IntrinsicType => "intrinsic has the correct type",
962             MethodReceiver => "method receiver has the correct type",
963             _ => "types are compatible",
964         }
965     }
966 }