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