]> git.lizzy.rs Git - rust.git/blob - src/librustc/infer/error_reporting/mod.rs
Suggest removing `?` to resolve type errors.
[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, TypeFoldable};
60 use errors::{Applicability, DiagnosticBuilder, DiagnosticStyledString};
61 use std::{cmp, fmt};
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", 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_id::CrateNum;
448         use hir::map::DisambiguatedDefPathData;
449         use ty::print::Printer;
450         use ty::subst::Kind;
451
452         struct AbsolutePathPrinter<'a, 'gcx, 'tcx> {
453             tcx: TyCtxt<'a, 'gcx, 'tcx>,
454         }
455
456         struct NonTrivialPath;
457
458         impl<'gcx, 'tcx> Printer<'gcx, 'tcx> for AbsolutePathPrinter<'_, 'gcx, 'tcx> {
459             type Error = NonTrivialPath;
460
461             type Path = Vec<String>;
462             type Region = !;
463             type Type = !;
464             type DynExistential = !;
465
466             fn tcx<'a>(&'a self) -> TyCtxt<'a, 'gcx, 'tcx> {
467                 self.tcx
468             }
469
470             fn print_region(
471                 self,
472                 _region: ty::Region<'_>,
473             ) -> Result<Self::Region, Self::Error> {
474                 Err(NonTrivialPath)
475             }
476
477             fn print_type(
478                 self,
479                 _ty: Ty<'tcx>,
480             ) -> Result<Self::Type, Self::Error> {
481                 Err(NonTrivialPath)
482             }
483
484             fn print_dyn_existential(
485                 self,
486                 _predicates: &'tcx ty::List<ty::ExistentialPredicate<'tcx>>,
487             ) -> Result<Self::DynExistential, Self::Error> {
488                 Err(NonTrivialPath)
489             }
490
491             fn path_crate(
492                 self,
493                 cnum: CrateNum,
494             ) -> Result<Self::Path, Self::Error> {
495                 Ok(vec![self.tcx.original_crate_name(cnum).to_string()])
496             }
497             fn path_qualified(
498                 self,
499                 _self_ty: Ty<'tcx>,
500                 _trait_ref: Option<ty::TraitRef<'tcx>>,
501             ) -> Result<Self::Path, Self::Error> {
502                 Err(NonTrivialPath)
503             }
504
505             fn path_append_impl(
506                 self,
507                 _print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
508                 _disambiguated_data: &DisambiguatedDefPathData,
509                 _self_ty: Ty<'tcx>,
510                 _trait_ref: Option<ty::TraitRef<'tcx>>,
511             ) -> Result<Self::Path, Self::Error> {
512                 Err(NonTrivialPath)
513             }
514             fn path_append(
515                 self,
516                 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
517                 disambiguated_data: &DisambiguatedDefPathData,
518             ) -> Result<Self::Path, Self::Error> {
519                 let mut path = print_prefix(self)?;
520                 path.push(disambiguated_data.data.as_interned_str().to_string());
521                 Ok(path)
522             }
523             fn path_generic_args(
524                 self,
525                 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
526                 _args: &[Kind<'tcx>],
527             ) -> Result<Self::Path, Self::Error> {
528                 print_prefix(self)
529             }
530         }
531
532         let report_path_match = |err: &mut DiagnosticBuilder<'_>, did1: DefId, did2: DefId| {
533             // Only external crates, if either is from a local
534             // module we could have false positives
535             if !(did1.is_local() || did2.is_local()) && did1.krate != did2.krate {
536                 let abs_path = |def_id| {
537                     AbsolutePathPrinter { tcx: self.tcx }
538                         .print_def_path(def_id, &[])
539                 };
540
541                 // We compare strings because DefPath can be different
542                 // for imported and non-imported crates
543                 let same_path = || -> Result<_, NonTrivialPath> {
544                     Ok(
545                         self.tcx.def_path_str(did1) == self.tcx.def_path_str(did2) ||
546                         abs_path(did1)? == abs_path(did2)?
547                     )
548                 };
549                 if same_path().unwrap_or(false) {
550                     let crate_name = self.tcx.crate_name(did1.krate);
551                     err.span_note(
552                         sp,
553                         &format!(
554                             "Perhaps two different versions \
555                              of crate `{}` are being used?",
556                             crate_name
557                         ),
558                     );
559                 }
560             }
561         };
562         match *terr {
563             TypeError::Sorts(ref exp_found) => {
564                 // if they are both "path types", there's a chance of ambiguity
565                 // due to different versions of the same crate
566                 if let (&ty::Adt(exp_adt, _), &ty::Adt(found_adt, _))
567                      = (&exp_found.expected.sty, &exp_found.found.sty)
568                 {
569                     report_path_match(err, exp_adt.did, found_adt.did);
570                 }
571             }
572             TypeError::Traits(ref exp_found) => {
573                 report_path_match(err, exp_found.expected, exp_found.found);
574             }
575             _ => (), // FIXME(#22750) handle traits and stuff
576         }
577     }
578
579     fn note_error_origin(
580         &self,
581         err: &mut DiagnosticBuilder<'tcx>,
582         cause: &ObligationCause<'tcx>,
583         exp_found: Option<ty::error::ExpectedFound<Ty<'tcx>>>,
584     ) {
585         match cause.code {
586             ObligationCauseCode::MatchExpressionArmPattern { span, ty } => {
587                 if ty.is_suggestable() {  // don't show type `_`
588                     err.span_label(span, format!("this match expression has type `{}`", ty));
589                 }
590                 if let Some(ty::error::ExpectedFound { found, .. }) = exp_found {
591                     if ty.is_box() && ty.boxed_ty() == found {
592                         if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
593                             err.span_suggestion(
594                                 span,
595                                 "consider dereferencing the boxed value",
596                                 format!("*{}", snippet),
597                                 Applicability::MachineApplicable,
598                             );
599                         }
600                     }
601                 }
602             }
603             ObligationCauseCode::MatchExpressionArm {
604                 source,
605                 ref prior_arms,
606                 last_ty,
607                 discrim_hir_id,
608                 ..
609             } => match source {
610                 hir::MatchSource::IfLetDesugar { .. } => {
611                     let msg = "`if let` arms have incompatible types";
612                     err.span_label(cause.span, msg);
613                 }
614                 hir::MatchSource::TryDesugar => {
615                     if let Some(ty::error::ExpectedFound { expected, .. }) = exp_found {
616                         let discrim_expr = self.tcx.hir().expect_expr_by_hir_id(discrim_hir_id);
617                         let discrim_ty = if let hir::ExprKind::Call(_, args) = &discrim_expr.node {
618                             let arg_expr = args.first().expect("try desugaring call w/out arg");
619                             self.in_progress_tables.and_then(|tables| {
620                                 tables.borrow().expr_ty_opt(arg_expr)
621                             })
622                         } else {
623                             bug!("try desugaring w/out call expr as discriminant");
624                         };
625
626                         match discrim_ty {
627                             Some(ty) if expected == ty => {
628                                 let source_map = self.tcx.sess.source_map();
629                                 err.span_suggestion(
630                                     source_map.end_point(cause.span),
631                                     "try removing this `?`",
632                                     "".to_string(),
633                                     Applicability::MachineApplicable,
634                                 );
635                             },
636                             _ => {},
637                         }
638                     }
639                 }
640                 _ => {
641                     let msg = "`match` arms have incompatible types";
642                     err.span_label(cause.span, msg);
643                     if prior_arms.len() <= 4 {
644                         for sp in prior_arms {
645                             err.span_label(*sp, format!(
646                                 "this is found to be of type `{}`",
647                                 last_ty,
648                             ));
649                         }
650                     } else if let Some(sp) = prior_arms.last() {
651                         err.span_label(*sp, format!(
652                             "this and all prior arms are found to be of type `{}`", last_ty,
653                         ));
654                     }
655                 }
656             },
657             ObligationCauseCode::IfExpression { then, outer, semicolon } => {
658                 err.span_label(then, "expected because of this");
659                 outer.map(|sp| err.span_label(sp, "if and else have incompatible types"));
660                 if let Some(sp) = semicolon {
661                     err.span_suggestion_short(
662                         sp,
663                         "consider removing this semicolon",
664                         String::new(),
665                         Applicability::MachineApplicable,
666                     );
667                 }
668             }
669             _ => (),
670         }
671     }
672
673     /// Given that `other_ty` is the same as a type argument for `name` in `sub`, populate `value`
674     /// highlighting `name` and every type argument that isn't at `pos` (which is `other_ty`), and
675     /// populate `other_value` with `other_ty`.
676     ///
677     /// ```text
678     /// Foo<Bar<Qux>>
679     /// ^^^^--------^ this is highlighted
680     /// |   |
681     /// |   this type argument is exactly the same as the other type, not highlighted
682     /// this is highlighted
683     /// Bar<Qux>
684     /// -------- this type is the same as a type argument in the other type, not highlighted
685     /// ```
686     fn highlight_outer(
687         &self,
688         value: &mut DiagnosticStyledString,
689         other_value: &mut DiagnosticStyledString,
690         name: String,
691         sub: ty::subst::SubstsRef<'tcx>,
692         pos: usize,
693         other_ty: &Ty<'tcx>,
694     ) {
695         // `value` and `other_value` hold two incomplete type representation for display.
696         // `name` is the path of both types being compared. `sub`
697         value.push_highlighted(name);
698         let len = sub.len();
699         if len > 0 {
700             value.push_highlighted("<");
701         }
702
703         // Output the lifetimes for the first type
704         let lifetimes = sub.regions()
705             .map(|lifetime| {
706                 let s = lifetime.to_string();
707                 if s.is_empty() {
708                     "'_".to_string()
709                 } else {
710                     s
711                 }
712             })
713             .collect::<Vec<_>>()
714             .join(", ");
715         if !lifetimes.is_empty() {
716             if sub.regions().count() < len {
717                 value.push_normal(lifetimes + &", ");
718             } else {
719                 value.push_normal(lifetimes);
720             }
721         }
722
723         // Highlight all the type arguments that aren't at `pos` and compare the type argument at
724         // `pos` and `other_ty`.
725         for (i, type_arg) in sub.types().enumerate() {
726             if i == pos {
727                 let values = self.cmp(type_arg, other_ty);
728                 value.0.extend((values.0).0);
729                 other_value.0.extend((values.1).0);
730             } else {
731                 value.push_highlighted(type_arg.to_string());
732             }
733
734             if len > 0 && i != len - 1 {
735                 value.push_normal(", ");
736             }
737             //self.push_comma(&mut value, &mut other_value, len, i);
738         }
739         if len > 0 {
740             value.push_highlighted(">");
741         }
742     }
743
744     /// If `other_ty` is the same as a type argument present in `sub`, highlight `path` in `t1_out`,
745     /// as that is the difference to the other type.
746     ///
747     /// For the following code:
748     ///
749     /// ```norun
750     /// let x: Foo<Bar<Qux>> = foo::<Bar<Qux>>();
751     /// ```
752     ///
753     /// The type error output will behave in the following way:
754     ///
755     /// ```text
756     /// Foo<Bar<Qux>>
757     /// ^^^^--------^ this is highlighted
758     /// |   |
759     /// |   this type argument is exactly the same as the other type, not highlighted
760     /// this is highlighted
761     /// Bar<Qux>
762     /// -------- this type is the same as a type argument in the other type, not highlighted
763     /// ```
764     fn cmp_type_arg(
765         &self,
766         mut t1_out: &mut DiagnosticStyledString,
767         mut t2_out: &mut DiagnosticStyledString,
768         path: String,
769         sub: ty::subst::SubstsRef<'tcx>,
770         other_path: String,
771         other_ty: &Ty<'tcx>,
772     ) -> Option<()> {
773         for (i, ta) in sub.types().enumerate() {
774             if &ta == other_ty {
775                 self.highlight_outer(&mut t1_out, &mut t2_out, path, sub, i, &other_ty);
776                 return Some(());
777             }
778             if let &ty::Adt(def, _) = &ta.sty {
779                 let path_ = self.tcx.def_path_str(def.did.clone());
780                 if path_ == other_path {
781                     self.highlight_outer(&mut t1_out, &mut t2_out, path, sub, i, &other_ty);
782                     return Some(());
783                 }
784             }
785         }
786         None
787     }
788
789     /// Adds a `,` to the type representation only if it is appropriate.
790     fn push_comma(
791         &self,
792         value: &mut DiagnosticStyledString,
793         other_value: &mut DiagnosticStyledString,
794         len: usize,
795         pos: usize,
796     ) {
797         if len > 0 && pos != len - 1 {
798             value.push_normal(", ");
799             other_value.push_normal(", ");
800         }
801     }
802
803     /// For generic types with parameters with defaults, remove the parameters corresponding to
804     /// the defaults. This repeats a lot of the logic found in `ty::print::pretty`.
805     fn strip_generic_default_params(
806         &self,
807         def_id: DefId,
808         substs: ty::subst::SubstsRef<'tcx>,
809     ) -> SubstsRef<'tcx> {
810         let generics = self.tcx.generics_of(def_id);
811         let mut num_supplied_defaults = 0;
812         let mut type_params = generics.params.iter().rev().filter_map(|param| match param.kind {
813             ty::GenericParamDefKind::Lifetime => None,
814             ty::GenericParamDefKind::Type { has_default, .. } => Some((param.def_id, has_default)),
815             ty::GenericParamDefKind::Const => None, // FIXME(const_generics:defaults)
816         }).peekable();
817         let has_default = {
818             let has_default = type_params.peek().map(|(_, has_default)| has_default);
819             *has_default.unwrap_or(&false)
820         };
821         if has_default {
822             let types = substs.types().rev();
823             for ((def_id, has_default), actual) in type_params.zip(types) {
824                 if !has_default {
825                     break;
826                 }
827                 if self.tcx.type_of(def_id).subst(self.tcx, substs) != actual {
828                     break;
829                 }
830                 num_supplied_defaults += 1;
831             }
832         }
833         let len = generics.params.len();
834         let mut generics = generics.clone();
835         generics.params.truncate(len - num_supplied_defaults);
836         substs.truncate_to(self.tcx, &generics)
837     }
838
839     /// Compares two given types, eliding parts that are the same between them and highlighting
840     /// relevant differences, and return two representation of those types for highlighted printing.
841     fn cmp(&self, t1: Ty<'tcx>, t2: Ty<'tcx>) -> (DiagnosticStyledString, DiagnosticStyledString) {
842         fn equals<'tcx>(a: &Ty<'tcx>, b: &Ty<'tcx>) -> bool {
843             match (&a.sty, &b.sty) {
844                 (a, b) if *a == *b => true,
845                 (&ty::Int(_), &ty::Infer(ty::InferTy::IntVar(_)))
846                 | (&ty::Infer(ty::InferTy::IntVar(_)), &ty::Int(_))
847                 | (&ty::Infer(ty::InferTy::IntVar(_)), &ty::Infer(ty::InferTy::IntVar(_)))
848                 | (&ty::Float(_), &ty::Infer(ty::InferTy::FloatVar(_)))
849                 | (&ty::Infer(ty::InferTy::FloatVar(_)), &ty::Float(_))
850                 | (&ty::Infer(ty::InferTy::FloatVar(_)), &ty::Infer(ty::InferTy::FloatVar(_))) => {
851                     true
852                 }
853                 _ => false,
854             }
855         }
856
857         fn push_ty_ref<'tcx>(
858             r: &ty::Region<'tcx>,
859             ty: Ty<'tcx>,
860             mutbl: hir::Mutability,
861             s: &mut DiagnosticStyledString,
862         ) {
863             let mut r = r.to_string();
864             if r == "'_" {
865                 r.clear();
866             } else {
867                 r.push(' ');
868             }
869             s.push_highlighted(format!(
870                 "&{}{}",
871                 r,
872                 if mutbl == hir::MutMutable { "mut " } else { "" }
873             ));
874             s.push_normal(ty.to_string());
875         }
876
877         match (&t1.sty, &t2.sty) {
878             (&ty::Adt(def1, sub1), &ty::Adt(def2, sub2)) => {
879                 let sub_no_defaults_1 = self.strip_generic_default_params(def1.did, sub1);
880                 let sub_no_defaults_2 = self.strip_generic_default_params(def2.did, sub2);
881                 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
882                 let path1 = self.tcx.def_path_str(def1.did.clone());
883                 let path2 = self.tcx.def_path_str(def2.did.clone());
884                 if def1.did == def2.did {
885                     // Easy case. Replace same types with `_` to shorten the output and highlight
886                     // the differing ones.
887                     //     let x: Foo<Bar, Qux> = y::<Foo<Quz, Qux>>();
888                     //     Foo<Bar, _>
889                     //     Foo<Quz, _>
890                     //         ---  ^ type argument elided
891                     //         |
892                     //         highlighted in output
893                     values.0.push_normal(path1);
894                     values.1.push_normal(path2);
895
896                     // Avoid printing out default generic parameters that are common to both
897                     // types.
898                     let len1 = sub_no_defaults_1.len();
899                     let len2 = sub_no_defaults_2.len();
900                     let common_len = cmp::min(len1, len2);
901                     let remainder1: Vec<_> = sub1.types().skip(common_len).collect();
902                     let remainder2: Vec<_> = sub2.types().skip(common_len).collect();
903                     let common_default_params = remainder1
904                         .iter()
905                         .rev()
906                         .zip(remainder2.iter().rev())
907                         .filter(|(a, b)| a == b)
908                         .count();
909                     let len = sub1.len() - common_default_params;
910
911                     // Only draw `<...>` if there're lifetime/type arguments.
912                     if len > 0 {
913                         values.0.push_normal("<");
914                         values.1.push_normal("<");
915                     }
916
917                     fn lifetime_display(lifetime: Region<'_>) -> String {
918                         let s = lifetime.to_string();
919                         if s.is_empty() {
920                             "'_".to_string()
921                         } else {
922                             s
923                         }
924                     }
925                     // At one point we'd like to elide all lifetimes here, they are irrelevant for
926                     // all diagnostics that use this output
927                     //
928                     //     Foo<'x, '_, Bar>
929                     //     Foo<'y, '_, Qux>
930                     //         ^^  ^^  --- type arguments are not elided
931                     //         |   |
932                     //         |   elided as they were the same
933                     //         not elided, they were different, but irrelevant
934                     let lifetimes = sub1.regions().zip(sub2.regions());
935                     for (i, lifetimes) in lifetimes.enumerate() {
936                         let l1 = lifetime_display(lifetimes.0);
937                         let l2 = lifetime_display(lifetimes.1);
938                         if l1 == l2 {
939                             values.0.push_normal("'_");
940                             values.1.push_normal("'_");
941                         } else {
942                             values.0.push_highlighted(l1);
943                             values.1.push_highlighted(l2);
944                         }
945                         self.push_comma(&mut values.0, &mut values.1, len, i);
946                     }
947
948                     // We're comparing two types with the same path, so we compare the type
949                     // arguments for both. If they are the same, do not highlight and elide from the
950                     // output.
951                     //     Foo<_, Bar>
952                     //     Foo<_, Qux>
953                     //         ^ elided type as this type argument was the same in both sides
954                     let type_arguments = sub1.types().zip(sub2.types());
955                     let regions_len = sub1.regions().count();
956                     for (i, (ta1, ta2)) in type_arguments.take(len).enumerate() {
957                         let i = i + regions_len;
958                         if ta1 == ta2 {
959                             values.0.push_normal("_");
960                             values.1.push_normal("_");
961                         } else {
962                             let (x1, x2) = self.cmp(ta1, ta2);
963                             (values.0).0.extend(x1.0);
964                             (values.1).0.extend(x2.0);
965                         }
966                         self.push_comma(&mut values.0, &mut values.1, len, i);
967                     }
968
969                     // Close the type argument bracket.
970                     // Only draw `<...>` if there're lifetime/type arguments.
971                     if len > 0 {
972                         values.0.push_normal(">");
973                         values.1.push_normal(">");
974                     }
975                     values
976                 } else {
977                     // Check for case:
978                     //     let x: Foo<Bar<Qux> = foo::<Bar<Qux>>();
979                     //     Foo<Bar<Qux>
980                     //         ------- this type argument is exactly the same as the other type
981                     //     Bar<Qux>
982                     if self.cmp_type_arg(
983                         &mut values.0,
984                         &mut values.1,
985                         path1.clone(),
986                         sub_no_defaults_1,
987                         path2.clone(),
988                         &t2,
989                     ).is_some()
990                     {
991                         return values;
992                     }
993                     // Check for case:
994                     //     let x: Bar<Qux> = y:<Foo<Bar<Qux>>>();
995                     //     Bar<Qux>
996                     //     Foo<Bar<Qux>>
997                     //         ------- this type argument is exactly the same as the other type
998                     if self.cmp_type_arg(
999                         &mut values.1,
1000                         &mut values.0,
1001                         path2,
1002                         sub_no_defaults_2,
1003                         path1,
1004                         &t1,
1005                     ).is_some()
1006                     {
1007                         return values;
1008                     }
1009
1010                     // We couldn't find anything in common, highlight everything.
1011                     //     let x: Bar<Qux> = y::<Foo<Zar>>();
1012                     (
1013                         DiagnosticStyledString::highlighted(t1.to_string()),
1014                         DiagnosticStyledString::highlighted(t2.to_string()),
1015                     )
1016                 }
1017             }
1018
1019             // When finding T != &T, highlight only the borrow
1020             (&ty::Ref(r1, ref_ty1, mutbl1), _) if equals(&ref_ty1, &t2) => {
1021                 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
1022                 push_ty_ref(&r1, ref_ty1, mutbl1, &mut values.0);
1023                 values.1.push_normal(t2.to_string());
1024                 values
1025             }
1026             (_, &ty::Ref(r2, ref_ty2, mutbl2)) if equals(&t1, &ref_ty2) => {
1027                 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
1028                 values.0.push_normal(t1.to_string());
1029                 push_ty_ref(&r2, ref_ty2, mutbl2, &mut values.1);
1030                 values
1031             }
1032
1033             // When encountering &T != &mut T, highlight only the borrow
1034             (&ty::Ref(r1, ref_ty1, mutbl1), &ty::Ref(r2, ref_ty2, mutbl2))
1035                 if equals(&ref_ty1, &ref_ty2) =>
1036             {
1037                 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
1038                 push_ty_ref(&r1, ref_ty1, mutbl1, &mut values.0);
1039                 push_ty_ref(&r2, ref_ty2, mutbl2, &mut values.1);
1040                 values
1041             }
1042
1043             _ => {
1044                 if t1 == t2 {
1045                     // The two types are the same, elide and don't highlight.
1046                     (
1047                         DiagnosticStyledString::normal("_"),
1048                         DiagnosticStyledString::normal("_"),
1049                     )
1050                 } else {
1051                     // We couldn't find anything in common, highlight everything.
1052                     (
1053                         DiagnosticStyledString::highlighted(t1.to_string()),
1054                         DiagnosticStyledString::highlighted(t2.to_string()),
1055                     )
1056                 }
1057             }
1058         }
1059     }
1060
1061     pub fn note_type_err(
1062         &self,
1063         diag: &mut DiagnosticBuilder<'tcx>,
1064         cause: &ObligationCause<'tcx>,
1065         secondary_span: Option<(Span, String)>,
1066         mut values: Option<ValuePairs<'tcx>>,
1067         terr: &TypeError<'tcx>,
1068     ) {
1069         // For some types of errors, expected-found does not make
1070         // sense, so just ignore the values we were given.
1071         match terr {
1072             TypeError::CyclicTy(_) => {
1073                 values = None;
1074             }
1075             _ => {}
1076         }
1077
1078         let (expected_found, exp_found, is_simple_error) = match values {
1079             None => (None, None, false),
1080             Some(values) => {
1081                 let (is_simple_error, exp_found) = match values {
1082                     ValuePairs::Types(exp_found) => {
1083                         let is_simple_err =
1084                             exp_found.expected.is_primitive() && exp_found.found.is_primitive();
1085
1086                         (is_simple_err, Some(exp_found))
1087                     }
1088                     _ => (false, None),
1089                 };
1090                 let vals = match self.values_str(&values) {
1091                     Some((expected, found)) => Some((expected, found)),
1092                     None => {
1093                         // Derived error. Cancel the emitter.
1094                         self.tcx.sess.diagnostic().cancel(diag);
1095                         return;
1096                     }
1097                 };
1098                 (vals, exp_found, is_simple_error)
1099             }
1100         };
1101
1102         let span = cause.span(&self.tcx);
1103
1104         diag.span_label(span, terr.to_string());
1105         if let Some((sp, msg)) = secondary_span {
1106             diag.span_label(sp, msg);
1107         }
1108
1109         if let Some((expected, found)) = expected_found {
1110             match (terr, is_simple_error, expected == found) {
1111                 (&TypeError::Sorts(ref values), false, true) => {
1112                     diag.note_expected_found_extra(
1113                         &"type",
1114                         expected,
1115                         found,
1116                         &format!(" ({})", values.expected.sort_string(self.tcx)),
1117                         &format!(" ({})", values.found.sort_string(self.tcx)),
1118                     );
1119                 }
1120                 (_, false, _) => {
1121                     if let Some(exp_found) = exp_found {
1122                         let (def_id, ret_ty) = match exp_found.found.sty {
1123                             ty::FnDef(def, _) => {
1124                                 (Some(def), Some(self.tcx.fn_sig(def).output()))
1125                             }
1126                             _ => (None, None),
1127                         };
1128
1129                         let exp_is_struct = match exp_found.expected.sty {
1130                             ty::Adt(def, _) => def.is_struct(),
1131                             _ => false,
1132                         };
1133
1134                         if let (Some(def_id), Some(ret_ty)) = (def_id, ret_ty) {
1135                             if exp_is_struct && &exp_found.expected == ret_ty.skip_binder() {
1136                                 let message = format!(
1137                                     "did you mean `{}(/* fields */)`?",
1138                                     self.tcx.def_path_str(def_id)
1139                                 );
1140                                 diag.span_label(span, message);
1141                             }
1142                         }
1143                         self.suggest_as_ref_where_appropriate(span, &exp_found, diag);
1144                     }
1145
1146                     diag.note_expected_found(&"type", expected, found);
1147                 }
1148                 _ => (),
1149             }
1150         }
1151
1152         self.check_and_note_conflicting_crates(diag, terr, span);
1153         self.tcx.note_and_explain_type_err(diag, terr, span);
1154
1155         // It reads better to have the error origin as the final
1156         // thing.
1157         self.note_error_origin(diag, &cause, exp_found);
1158     }
1159
1160     /// When encountering a case where `.as_ref()` on a `Result` or `Option` would be appropriate,
1161     /// suggest it.
1162     fn suggest_as_ref_where_appropriate(
1163         &self,
1164         span: Span,
1165         exp_found: &ty::error::ExpectedFound<Ty<'tcx>>,
1166         diag: &mut DiagnosticBuilder<'tcx>,
1167     ) {
1168         match (&exp_found.expected.sty, &exp_found.found.sty) {
1169             (ty::Adt(exp_def, exp_substs), ty::Ref(_, found_ty, _)) => {
1170                 if let ty::Adt(found_def, found_substs) = found_ty.sty {
1171                     let path_str = format!("{:?}", exp_def);
1172                     if exp_def == &found_def {
1173                         let opt_msg = "you can convert from `&Option<T>` to `Option<&T>` using \
1174                                        `.as_ref()`";
1175                         let result_msg = "you can convert from `&Result<T, E>` to \
1176                                           `Result<&T, &E>` using `.as_ref()`";
1177                         let have_as_ref = &[
1178                             ("std::option::Option", opt_msg),
1179                             ("core::option::Option", opt_msg),
1180                             ("std::result::Result", result_msg),
1181                             ("core::result::Result", result_msg),
1182                         ];
1183                         if let Some(msg) = have_as_ref.iter()
1184                             .filter_map(|(path, msg)| if &path_str == path {
1185                                 Some(msg)
1186                             } else {
1187                                 None
1188                             }).next()
1189                         {
1190                             let mut show_suggestion = true;
1191                             for (exp_ty, found_ty) in exp_substs.types().zip(found_substs.types()) {
1192                                 match exp_ty.sty {
1193                                     ty::Ref(_, exp_ty, _) => {
1194                                         match (&exp_ty.sty, &found_ty.sty) {
1195                                             (_, ty::Param(_)) |
1196                                             (_, ty::Infer(_)) |
1197                                             (ty::Param(_), _) |
1198                                             (ty::Infer(_), _) => {}
1199                                             _ if ty::TyS::same_type(exp_ty, found_ty) => {}
1200                                             _ => show_suggestion = false,
1201                                         };
1202                                     }
1203                                     ty::Param(_) | ty::Infer(_) => {}
1204                                     _ => show_suggestion = false,
1205                                 }
1206                             }
1207                             if let (Ok(snippet), true) = (
1208                                 self.tcx.sess.source_map().span_to_snippet(span),
1209                                 show_suggestion,
1210                             ) {
1211                                 diag.span_suggestion(
1212                                     span,
1213                                     msg,
1214                                     format!("{}.as_ref()", snippet),
1215                                     Applicability::MachineApplicable,
1216                                 );
1217                             }
1218                         }
1219                     }
1220                 }
1221             }
1222             _ => {}
1223         }
1224     }
1225
1226     pub fn report_and_explain_type_error(
1227         &self,
1228         trace: TypeTrace<'tcx>,
1229         terr: &TypeError<'tcx>,
1230     ) -> DiagnosticBuilder<'tcx> {
1231         debug!(
1232             "report_and_explain_type_error(trace={:?}, terr={:?})",
1233             trace, terr
1234         );
1235
1236         let span = trace.cause.span(&self.tcx);
1237         let failure_code = trace.cause.as_failure_code(terr);
1238         let mut diag = match failure_code {
1239             FailureCode::Error0317(failure_str) => {
1240                 struct_span_err!(self.tcx.sess, span, E0317, "{}", failure_str)
1241             }
1242             FailureCode::Error0580(failure_str) => {
1243                 struct_span_err!(self.tcx.sess, span, E0580, "{}", failure_str)
1244             }
1245             FailureCode::Error0308(failure_str) => {
1246                 struct_span_err!(self.tcx.sess, span, E0308, "{}", failure_str)
1247             }
1248             FailureCode::Error0644(failure_str) => {
1249                 struct_span_err!(self.tcx.sess, span, E0644, "{}", failure_str)
1250             }
1251         };
1252         self.note_type_err(&mut diag, &trace.cause, None, Some(trace.values), terr);
1253         diag
1254     }
1255
1256     fn values_str(
1257         &self,
1258         values: &ValuePairs<'tcx>,
1259     ) -> Option<(DiagnosticStyledString, DiagnosticStyledString)> {
1260         match *values {
1261             infer::Types(ref exp_found) => self.expected_found_str_ty(exp_found),
1262             infer::Regions(ref exp_found) => self.expected_found_str(exp_found),
1263             infer::TraitRefs(ref exp_found) => self.expected_found_str(exp_found),
1264             infer::PolyTraitRefs(ref exp_found) => self.expected_found_str(exp_found),
1265         }
1266     }
1267
1268     fn expected_found_str_ty(
1269         &self,
1270         exp_found: &ty::error::ExpectedFound<Ty<'tcx>>,
1271     ) -> Option<(DiagnosticStyledString, DiagnosticStyledString)> {
1272         let exp_found = self.resolve_type_vars_if_possible(exp_found);
1273         if exp_found.references_error() {
1274             return None;
1275         }
1276
1277         Some(self.cmp(exp_found.expected, exp_found.found))
1278     }
1279
1280     /// Returns a string of the form "expected `{}`, found `{}`".
1281     fn expected_found_str<T: fmt::Display + TypeFoldable<'tcx>>(
1282         &self,
1283         exp_found: &ty::error::ExpectedFound<T>,
1284     ) -> Option<(DiagnosticStyledString, DiagnosticStyledString)> {
1285         let exp_found = self.resolve_type_vars_if_possible(exp_found);
1286         if exp_found.references_error() {
1287             return None;
1288         }
1289
1290         Some((
1291             DiagnosticStyledString::highlighted(exp_found.expected.to_string()),
1292             DiagnosticStyledString::highlighted(exp_found.found.to_string()),
1293         ))
1294     }
1295
1296     pub fn report_generic_bound_failure(
1297         &self,
1298         region_scope_tree: &region::ScopeTree,
1299         span: Span,
1300         origin: Option<SubregionOrigin<'tcx>>,
1301         bound_kind: GenericKind<'tcx>,
1302         sub: Region<'tcx>,
1303     ) {
1304         self.construct_generic_bound_failure(region_scope_tree, span, origin, bound_kind, sub)
1305             .emit()
1306     }
1307
1308     pub fn construct_generic_bound_failure(
1309         &self,
1310         region_scope_tree: &region::ScopeTree,
1311         span: Span,
1312         origin: Option<SubregionOrigin<'tcx>>,
1313         bound_kind: GenericKind<'tcx>,
1314         sub: Region<'tcx>,
1315     ) -> DiagnosticBuilder<'a> {
1316         // Attempt to obtain the span of the parameter so we can
1317         // suggest adding an explicit lifetime bound to it.
1318         let type_param_span = match (self.in_progress_tables, bound_kind) {
1319             (Some(ref table), GenericKind::Param(ref param)) => {
1320                 let table = table.borrow();
1321                 table.local_id_root.and_then(|did| {
1322                     let generics = self.tcx.generics_of(did);
1323                     // Account for the case where `did` corresponds to `Self`, which doesn't have
1324                     // the expected type argument.
1325                     if !param.is_self() {
1326                         let type_param = generics.type_param(param, self.tcx);
1327                         let hir = &self.tcx.hir();
1328                         hir.as_local_node_id(type_param.def_id).map(|id| {
1329                             // Get the `hir::Param` to verify whether it already has any bounds.
1330                             // We do this to avoid suggesting code that ends up as `T: 'a'b`,
1331                             // instead we suggest `T: 'a + 'b` in that case.
1332                             let mut has_bounds = false;
1333                             if let Node::GenericParam(ref param) = hir.get(id) {
1334                                 has_bounds = !param.bounds.is_empty();
1335                             }
1336                             let sp = hir.span(id);
1337                             // `sp` only covers `T`, change it so that it covers
1338                             // `T:` when appropriate
1339                             let is_impl_trait = bound_kind.to_string().starts_with("impl ");
1340                             let sp = if has_bounds && !is_impl_trait {
1341                                 sp.to(self.tcx
1342                                     .sess
1343                                     .source_map()
1344                                     .next_point(self.tcx.sess.source_map().next_point(sp)))
1345                             } else {
1346                                 sp
1347                             };
1348                             (sp, has_bounds, is_impl_trait)
1349                         })
1350                     } else {
1351                         None
1352                     }
1353                 })
1354             }
1355             _ => None,
1356         };
1357
1358         let labeled_user_string = match bound_kind {
1359             GenericKind::Param(ref p) => format!("the parameter type `{}`", p),
1360             GenericKind::Projection(ref p) => format!("the associated type `{}`", p),
1361         };
1362
1363         if let Some(SubregionOrigin::CompareImplMethodObligation {
1364             span,
1365             item_name,
1366             impl_item_def_id,
1367             trait_item_def_id,
1368         }) = origin
1369         {
1370             return self.report_extra_impl_obligation(
1371                 span,
1372                 item_name,
1373                 impl_item_def_id,
1374                 trait_item_def_id,
1375                 &format!("`{}: {}`", bound_kind, sub),
1376             );
1377         }
1378
1379         fn binding_suggestion<'tcx, S: fmt::Display>(
1380             err: &mut DiagnosticBuilder<'tcx>,
1381             type_param_span: Option<(Span, bool, bool)>,
1382             bound_kind: GenericKind<'tcx>,
1383             sub: S,
1384         ) {
1385             let consider = format!(
1386                 "consider adding an explicit lifetime bound {}",
1387                 if type_param_span.map(|(_, _, is_impl_trait)| is_impl_trait).unwrap_or(false) {
1388                     format!(" `{}` to `{}`...", sub, bound_kind)
1389                 } else {
1390                     format!("`{}: {}`...", bound_kind, sub)
1391                 },
1392             );
1393             if let Some((sp, has_lifetimes, is_impl_trait)) = type_param_span {
1394                 let suggestion = if is_impl_trait {
1395                     format!("{} + {}", bound_kind, sub)
1396                 } else {
1397                     let tail = if has_lifetimes { " + " } else { "" };
1398                     format!("{}: {}{}", bound_kind, sub, tail)
1399                 };
1400                 err.span_suggestion_short(
1401                     sp,
1402                     &consider,
1403                     suggestion,
1404                     Applicability::MaybeIncorrect, // Issue #41966
1405                 );
1406             } else {
1407                 err.help(&consider);
1408             }
1409         }
1410
1411         let mut err = match *sub {
1412             ty::ReEarlyBound(_)
1413             | ty::ReFree(ty::FreeRegion {
1414                 bound_region: ty::BrNamed(..),
1415                 ..
1416             }) => {
1417                 // Does the required lifetime have a nice name we can print?
1418                 let mut err = struct_span_err!(
1419                     self.tcx.sess,
1420                     span,
1421                     E0309,
1422                     "{} may not live long enough",
1423                     labeled_user_string
1424                 );
1425                 binding_suggestion(&mut err, type_param_span, bound_kind, sub);
1426                 err
1427             }
1428
1429             ty::ReStatic => {
1430                 // Does the required lifetime have a nice name we can print?
1431                 let mut err = struct_span_err!(
1432                     self.tcx.sess,
1433                     span,
1434                     E0310,
1435                     "{} may not live long enough",
1436                     labeled_user_string
1437                 );
1438                 binding_suggestion(&mut err, type_param_span, bound_kind, "'static");
1439                 err
1440             }
1441
1442             _ => {
1443                 // If not, be less specific.
1444                 let mut err = struct_span_err!(
1445                     self.tcx.sess,
1446                     span,
1447                     E0311,
1448                     "{} may not live long enough",
1449                     labeled_user_string
1450                 );
1451                 err.help(&format!(
1452                     "consider adding an explicit lifetime bound for `{}`",
1453                     bound_kind
1454                 ));
1455                 self.tcx.note_and_explain_region(
1456                     region_scope_tree,
1457                     &mut err,
1458                     &format!("{} must be valid for ", labeled_user_string),
1459                     sub,
1460                     "...",
1461                 );
1462                 err
1463             }
1464         };
1465
1466         if let Some(origin) = origin {
1467             self.note_region_origin(&mut err, &origin);
1468         }
1469         err
1470     }
1471
1472     fn report_sub_sup_conflict(
1473         &self,
1474         region_scope_tree: &region::ScopeTree,
1475         var_origin: RegionVariableOrigin,
1476         sub_origin: SubregionOrigin<'tcx>,
1477         sub_region: Region<'tcx>,
1478         sup_origin: SubregionOrigin<'tcx>,
1479         sup_region: Region<'tcx>,
1480     ) {
1481         let mut err = self.report_inference_failure(var_origin);
1482
1483         self.tcx.note_and_explain_region(
1484             region_scope_tree,
1485             &mut err,
1486             "first, the lifetime cannot outlive ",
1487             sup_region,
1488             "...",
1489         );
1490
1491         match (&sup_origin, &sub_origin) {
1492             (&infer::Subtype(ref sup_trace), &infer::Subtype(ref sub_trace)) => {
1493                 debug!("report_sub_sup_conflict: var_origin={:?}", var_origin);
1494                 debug!("report_sub_sup_conflict: sub_region={:?}", sub_region);
1495                 debug!("report_sub_sup_conflict: sub_origin={:?}", sub_origin);
1496                 debug!("report_sub_sup_conflict: sup_region={:?}", sup_region);
1497                 debug!("report_sub_sup_conflict: sup_origin={:?}", sup_origin);
1498                 debug!("report_sub_sup_conflict: sup_trace={:?}", sup_trace);
1499                 debug!("report_sub_sup_conflict: sub_trace={:?}", sub_trace);
1500                 debug!("report_sub_sup_conflict: sup_trace.values={:?}", sup_trace.values);
1501                 debug!("report_sub_sup_conflict: sub_trace.values={:?}", sub_trace.values);
1502
1503                 if let (Some((sup_expected, sup_found)), Some((sub_expected, sub_found))) = (
1504                     self.values_str(&sup_trace.values),
1505                     self.values_str(&sub_trace.values),
1506                 ) {
1507                     if sub_expected == sup_expected && sub_found == sup_found {
1508                         self.tcx.note_and_explain_region(
1509                             region_scope_tree,
1510                             &mut err,
1511                             "...but the lifetime must also be valid for ",
1512                             sub_region,
1513                             "...",
1514                         );
1515                         err.note(&format!(
1516                             "...so that the {}:\nexpected {}\n   found {}",
1517                             sup_trace.cause.as_requirement_str(),
1518                             sup_expected.content(),
1519                             sup_found.content()
1520                         ));
1521                         err.emit();
1522                         return;
1523                     }
1524                 }
1525             }
1526             _ => {}
1527         }
1528
1529         self.note_region_origin(&mut err, &sup_origin);
1530
1531         self.tcx.note_and_explain_region(
1532             region_scope_tree,
1533             &mut err,
1534             "but, the lifetime must be valid for ",
1535             sub_region,
1536             "...",
1537         );
1538
1539         self.note_region_origin(&mut err, &sub_origin);
1540         err.emit();
1541     }
1542 }
1543
1544 impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
1545     fn report_inference_failure(
1546         &self,
1547         var_origin: RegionVariableOrigin,
1548     ) -> DiagnosticBuilder<'tcx> {
1549         let br_string = |br: ty::BoundRegion| {
1550             let mut s = match br {
1551                 ty::BrNamed(_, name) => name.to_string(),
1552                 _ => String::new(),
1553             };
1554             if !s.is_empty() {
1555                 s.push_str(" ");
1556             }
1557             s
1558         };
1559         let var_description = match var_origin {
1560             infer::MiscVariable(_) => String::new(),
1561             infer::PatternRegion(_) => " for pattern".to_string(),
1562             infer::AddrOfRegion(_) => " for borrow expression".to_string(),
1563             infer::Autoref(_) => " for autoref".to_string(),
1564             infer::Coercion(_) => " for automatic coercion".to_string(),
1565             infer::LateBoundRegion(_, br, infer::FnCall) => {
1566                 format!(" for lifetime parameter {}in function call", br_string(br))
1567             }
1568             infer::LateBoundRegion(_, br, infer::HigherRankedType) => {
1569                 format!(" for lifetime parameter {}in generic type", br_string(br))
1570             }
1571             infer::LateBoundRegion(_, br, infer::AssocTypeProjection(def_id)) => format!(
1572                 " for lifetime parameter {}in trait containing associated type `{}`",
1573                 br_string(br),
1574                 self.tcx.associated_item(def_id).ident
1575             ),
1576             infer::EarlyBoundRegion(_, name) => format!(" for lifetime parameter `{}`", name),
1577             infer::BoundRegionInCoherence(name) => {
1578                 format!(" for lifetime parameter `{}` in coherence check", name)
1579             }
1580             infer::UpvarRegion(ref upvar_id, _) => {
1581                 let var_name = self.tcx.hir().name_by_hir_id(upvar_id.var_path.hir_id);
1582                 format!(" for capture of `{}` by closure", var_name)
1583             }
1584             infer::NLL(..) => bug!("NLL variable found in lexical phase"),
1585         };
1586
1587         struct_span_err!(
1588             self.tcx.sess,
1589             var_origin.span(),
1590             E0495,
1591             "cannot infer an appropriate lifetime{} \
1592              due to conflicting requirements",
1593             var_description
1594         )
1595     }
1596 }
1597
1598 enum FailureCode {
1599     Error0317(&'static str),
1600     Error0580(&'static str),
1601     Error0308(&'static str),
1602     Error0644(&'static str),
1603 }
1604
1605 impl<'tcx> ObligationCause<'tcx> {
1606     fn as_failure_code(&self, terr: &TypeError<'tcx>) -> FailureCode {
1607         use self::FailureCode::*;
1608         use crate::traits::ObligationCauseCode::*;
1609         match self.code {
1610             CompareImplMethodObligation { .. } => Error0308("method not compatible with trait"),
1611             MatchExpressionArm { source, .. } => Error0308(match source {
1612                 hir::MatchSource::IfLetDesugar { .. } => "`if let` arms have incompatible types",
1613                 hir::MatchSource::TryDesugar => {
1614                     "try expression alternatives have incompatible types"
1615                 }
1616                 _ => "match arms have incompatible types",
1617             }),
1618             IfExpression { .. } => Error0308("if and else have incompatible types"),
1619             IfExpressionWithNoElse => Error0317("if may be missing an else clause"),
1620             MainFunctionType => Error0580("main function has wrong type"),
1621             StartFunctionType => Error0308("start function has wrong type"),
1622             IntrinsicType => Error0308("intrinsic has wrong type"),
1623             MethodReceiver => Error0308("mismatched method receiver"),
1624
1625             // In the case where we have no more specific thing to
1626             // say, also take a look at the error code, maybe we can
1627             // tailor to that.
1628             _ => match terr {
1629                 TypeError::CyclicTy(ty) if ty.is_closure() || ty.is_generator() => {
1630                     Error0644("closure/generator type that references itself")
1631                 }
1632                 _ => Error0308("mismatched types"),
1633             },
1634         }
1635     }
1636
1637     fn as_requirement_str(&self) -> &'static str {
1638         use crate::traits::ObligationCauseCode::*;
1639         match self.code {
1640             CompareImplMethodObligation { .. } => "method type is compatible with trait",
1641             ExprAssignable => "expression is assignable",
1642             MatchExpressionArm { source, .. } => match source {
1643                 hir::MatchSource::IfLetDesugar { .. } => "`if let` arms have compatible types",
1644                 _ => "match arms have compatible types",
1645             },
1646             IfExpression { .. } => "if and else have compatible types",
1647             IfExpressionWithNoElse => "if missing an else returns ()",
1648             MainFunctionType => "`main` function has the correct type",
1649             StartFunctionType => "`start` function has the correct type",
1650             IntrinsicType => "intrinsic has the correct type",
1651             MethodReceiver => "method receiver has the correct type",
1652             _ => "types are compatible",
1653         }
1654     }
1655 }