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