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