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