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