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