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