]> git.lizzy.rs Git - rust.git/blob - src/librustc/infer/error_reporting/mod.rs
cccdcc68a579328b0528c7a5b150ac7b69b75db2
[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 = exp_found.expected.is_simple_text()
1167                             && exp_found.found.is_simple_text();
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, expected == found) {
1205                 (TypeError::Sorts(values), 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                     if !(values.expected.is_simple_text() && values.found.is_simple_text()) || (
1216                         exp_found.map_or(false, |ef| {
1217                             // This happens when the type error is a subset of the expectation,
1218                             // like when you have two references but one is `usize` and the other
1219                             // is `f32`. In those cases we still want to show the `note`. If the
1220                             // value from `ef` is `Infer(_)`, then we ignore it.
1221                             if !ef.expected.is_ty_infer() {
1222                                 ef.expected != values.expected
1223                             } else if !ef.found.is_ty_infer() {
1224                                 ef.found != values.found
1225                             } else {
1226                                 false
1227                             }
1228                         })
1229                     ) {
1230                         diag.note_expected_found_extra(
1231                             &expected_label,
1232                             expected,
1233                             &found_label,
1234                             found,
1235                             &sort_string(values.expected),
1236                             &sort_string(values.found),
1237                         );
1238                     }
1239                 }
1240                 (TypeError::ObjectUnsafeCoercion(_), _) => {
1241                     diag.note_unsuccessfull_coercion(found, expected);
1242                 }
1243                 (_, _) => {
1244                     debug!(
1245                         "note_type_err: exp_found={:?}, expected={:?} found={:?}",
1246                         exp_found, expected, found
1247                     );
1248                     if !is_simple_error || terr.must_include_note() {
1249                         diag.note_expected_found(&expected_label, expected, &found_label, found);
1250                     }
1251                 }
1252             }
1253         }
1254         if let Some(exp_found) = exp_found {
1255             self.suggest_as_ref_where_appropriate(span, &exp_found, diag);
1256         }
1257
1258         // In some (most?) cases cause.body_id points to actual body, but in some cases
1259         // it's a actual definition. According to the comments (e.g. in
1260         // librustc_typeck/check/compare_method.rs:compare_predicate_entailment) the latter
1261         // is relied upon by some other code. This might (or might not) need cleanup.
1262         let body_owner_def_id = self.tcx.hir().opt_local_def_id(cause.body_id)
1263             .unwrap_or_else(|| {
1264                 self.tcx.hir().body_owner_def_id(hir::BodyId { hir_id: cause.body_id })
1265             });
1266         self.check_and_note_conflicting_crates(diag, terr, span);
1267         self.tcx.note_and_explain_type_err(diag, terr, span, body_owner_def_id);
1268
1269         // It reads better to have the error origin as the final
1270         // thing.
1271         self.note_error_origin(diag, &cause, exp_found);
1272     }
1273
1274     /// When encountering a case where `.as_ref()` on a `Result` or `Option` would be appropriate,
1275     /// suggest it.
1276     fn suggest_as_ref_where_appropriate(
1277         &self,
1278         span: Span,
1279         exp_found: &ty::error::ExpectedFound<Ty<'tcx>>,
1280         diag: &mut DiagnosticBuilder<'tcx>,
1281     ) {
1282         match (&exp_found.expected.kind, &exp_found.found.kind) {
1283             (ty::Adt(exp_def, exp_substs), ty::Ref(_, found_ty, _)) => {
1284                 if let ty::Adt(found_def, found_substs) = found_ty.kind {
1285                     let path_str = format!("{:?}", exp_def);
1286                     if exp_def == &found_def {
1287                         let opt_msg = "you can convert from `&Option<T>` to `Option<&T>` using \
1288                                        `.as_ref()`";
1289                         let result_msg = "you can convert from `&Result<T, E>` to \
1290                                           `Result<&T, &E>` using `.as_ref()`";
1291                         let have_as_ref = &[
1292                             ("std::option::Option", opt_msg),
1293                             ("core::option::Option", opt_msg),
1294                             ("std::result::Result", result_msg),
1295                             ("core::result::Result", result_msg),
1296                         ];
1297                         if let Some(msg) = have_as_ref.iter()
1298                             .filter_map(|(path, msg)| if &path_str == path {
1299                                 Some(msg)
1300                             } else {
1301                                 None
1302                             }).next()
1303                         {
1304                             let mut show_suggestion = true;
1305                             for (exp_ty, found_ty) in exp_substs.types().zip(found_substs.types()) {
1306                                 match exp_ty.kind {
1307                                     ty::Ref(_, exp_ty, _) => {
1308                                         match (&exp_ty.kind, &found_ty.kind) {
1309                                             (_, ty::Param(_)) |
1310                                             (_, ty::Infer(_)) |
1311                                             (ty::Param(_), _) |
1312                                             (ty::Infer(_), _) => {}
1313                                             _ if ty::TyS::same_type(exp_ty, found_ty) => {}
1314                                             _ => show_suggestion = false,
1315                                         };
1316                                     }
1317                                     ty::Param(_) | ty::Infer(_) => {}
1318                                     _ => show_suggestion = false,
1319                                 }
1320                             }
1321                             if let (Ok(snippet), true) = (
1322                                 self.tcx.sess.source_map().span_to_snippet(span),
1323                                 show_suggestion,
1324                             ) {
1325                                 diag.span_suggestion(
1326                                     span,
1327                                     msg,
1328                                     format!("{}.as_ref()", snippet),
1329                                     Applicability::MachineApplicable,
1330                                 );
1331                             }
1332                         }
1333                     }
1334                 }
1335             }
1336             _ => {}
1337         }
1338     }
1339
1340     pub fn report_and_explain_type_error(
1341         &self,
1342         trace: TypeTrace<'tcx>,
1343         terr: &TypeError<'tcx>,
1344     ) -> DiagnosticBuilder<'tcx> {
1345         debug!(
1346             "report_and_explain_type_error(trace={:?}, terr={:?})",
1347             trace, terr
1348         );
1349
1350         let span = trace.cause.span(self.tcx);
1351         let failure_code = trace.cause.as_failure_code(terr);
1352         let mut diag = match failure_code {
1353             FailureCode::Error0038(did) => {
1354                 let violations = self.tcx.object_safety_violations(did);
1355                 self.tcx.report_object_safety_error(span, did, violations)
1356             }
1357             FailureCode::Error0317(failure_str) => {
1358                 struct_span_err!(self.tcx.sess, span, E0317, "{}", failure_str)
1359             }
1360             FailureCode::Error0580(failure_str) => {
1361                 struct_span_err!(self.tcx.sess, span, E0580, "{}", failure_str)
1362             }
1363             FailureCode::Error0308(failure_str) => {
1364                 struct_span_err!(self.tcx.sess, span, E0308, "{}", failure_str)
1365             }
1366             FailureCode::Error0644(failure_str) => {
1367                 struct_span_err!(self.tcx.sess, span, E0644, "{}", failure_str)
1368             }
1369         };
1370         self.note_type_err(&mut diag, &trace.cause, None, Some(trace.values), terr);
1371         diag
1372     }
1373
1374     fn values_str(
1375         &self,
1376         values: &ValuePairs<'tcx>,
1377     ) -> Option<(DiagnosticStyledString, DiagnosticStyledString)> {
1378         match *values {
1379             infer::Types(ref exp_found) => self.expected_found_str_ty(exp_found),
1380             infer::Regions(ref exp_found) => self.expected_found_str(exp_found),
1381             infer::Consts(ref exp_found) => self.expected_found_str(exp_found),
1382             infer::TraitRefs(ref exp_found) => self.expected_found_str(exp_found),
1383             infer::PolyTraitRefs(ref exp_found) => self.expected_found_str(exp_found),
1384         }
1385     }
1386
1387     fn expected_found_str_ty(
1388         &self,
1389         exp_found: &ty::error::ExpectedFound<Ty<'tcx>>,
1390     ) -> Option<(DiagnosticStyledString, DiagnosticStyledString)> {
1391         let exp_found = self.resolve_vars_if_possible(exp_found);
1392         if exp_found.references_error() {
1393             return None;
1394         }
1395
1396         Some(self.cmp(exp_found.expected, exp_found.found))
1397     }
1398
1399     /// Returns a string of the form "expected `{}`, found `{}`".
1400     fn expected_found_str<T: fmt::Display + TypeFoldable<'tcx>>(
1401         &self,
1402         exp_found: &ty::error::ExpectedFound<T>,
1403     ) -> Option<(DiagnosticStyledString, DiagnosticStyledString)> {
1404         let exp_found = self.resolve_vars_if_possible(exp_found);
1405         if exp_found.references_error() {
1406             return None;
1407         }
1408
1409         Some((
1410             DiagnosticStyledString::highlighted(exp_found.expected.to_string()),
1411             DiagnosticStyledString::highlighted(exp_found.found.to_string()),
1412         ))
1413     }
1414
1415     pub fn report_generic_bound_failure(
1416         &self,
1417         region_scope_tree: &region::ScopeTree,
1418         span: Span,
1419         origin: Option<SubregionOrigin<'tcx>>,
1420         bound_kind: GenericKind<'tcx>,
1421         sub: Region<'tcx>,
1422     ) {
1423         self.construct_generic_bound_failure(region_scope_tree, span, origin, bound_kind, sub)
1424             .emit()
1425     }
1426
1427     pub fn construct_generic_bound_failure(
1428         &self,
1429         region_scope_tree: &region::ScopeTree,
1430         span: Span,
1431         origin: Option<SubregionOrigin<'tcx>>,
1432         bound_kind: GenericKind<'tcx>,
1433         sub: Region<'tcx>,
1434     ) -> DiagnosticBuilder<'a> {
1435         // Attempt to obtain the span of the parameter so we can
1436         // suggest adding an explicit lifetime bound to it.
1437         let type_param_span = match (self.in_progress_tables, bound_kind) {
1438             (Some(ref table), GenericKind::Param(ref param)) => {
1439                 let table = table.borrow();
1440                 table.local_id_root.and_then(|did| {
1441                     let generics = self.tcx.generics_of(did);
1442                     // Account for the case where `did` corresponds to `Self`, which doesn't have
1443                     // the expected type argument.
1444                     if !(generics.has_self && param.index == 0) {
1445                         let type_param = generics.type_param(param, self.tcx);
1446                         let hir = &self.tcx.hir();
1447                         hir.as_local_hir_id(type_param.def_id).map(|id| {
1448                             // Get the `hir::Param` to verify whether it already has any bounds.
1449                             // We do this to avoid suggesting code that ends up as `T: 'a'b`,
1450                             // instead we suggest `T: 'a + 'b` in that case.
1451                             let mut has_bounds = false;
1452                             if let Node::GenericParam(param) = hir.get(id) {
1453                                 has_bounds = !param.bounds.is_empty();
1454                             }
1455                             let sp = hir.span(id);
1456                             // `sp` only covers `T`, change it so that it covers
1457                             // `T:` when appropriate
1458                             let is_impl_trait = bound_kind.to_string().starts_with("impl ");
1459                             let sp = if has_bounds && !is_impl_trait {
1460                                 sp.to(self.tcx
1461                                     .sess
1462                                     .source_map()
1463                                     .next_point(self.tcx.sess.source_map().next_point(sp)))
1464                             } else {
1465                                 sp
1466                             };
1467                             (sp, has_bounds, is_impl_trait)
1468                         })
1469                     } else {
1470                         None
1471                     }
1472                 })
1473             }
1474             _ => None,
1475         };
1476
1477         let labeled_user_string = match bound_kind {
1478             GenericKind::Param(ref p) => format!("the parameter type `{}`", p),
1479             GenericKind::Projection(ref p) => format!("the associated type `{}`", p),
1480         };
1481
1482         if let Some(SubregionOrigin::CompareImplMethodObligation {
1483             span,
1484             item_name,
1485             impl_item_def_id,
1486             trait_item_def_id,
1487         }) = origin
1488         {
1489             return self.report_extra_impl_obligation(
1490                 span,
1491                 item_name,
1492                 impl_item_def_id,
1493                 trait_item_def_id,
1494                 &format!("`{}: {}`", bound_kind, sub),
1495             );
1496         }
1497
1498         fn binding_suggestion<'tcx, S: fmt::Display>(
1499             err: &mut DiagnosticBuilder<'tcx>,
1500             type_param_span: Option<(Span, bool, bool)>,
1501             bound_kind: GenericKind<'tcx>,
1502             sub: S,
1503         ) {
1504             let consider = format!(
1505                 "consider adding an explicit lifetime bound {}",
1506                 if type_param_span.map(|(_, _, is_impl_trait)| is_impl_trait).unwrap_or(false) {
1507                     format!(" `{}` to `{}`...", sub, bound_kind)
1508                 } else {
1509                     format!("`{}: {}`...", bound_kind, sub)
1510                 },
1511             );
1512             if let Some((sp, has_lifetimes, is_impl_trait)) = type_param_span {
1513                 let suggestion = if is_impl_trait {
1514                     format!("{} + {}", bound_kind, sub)
1515                 } else {
1516                     let tail = if has_lifetimes { " + " } else { "" };
1517                     format!("{}: {}{}", bound_kind, sub, tail)
1518                 };
1519                 err.span_suggestion_short(
1520                     sp,
1521                     &consider,
1522                     suggestion,
1523                     Applicability::MaybeIncorrect, // Issue #41966
1524                 );
1525             } else {
1526                 err.help(&consider);
1527             }
1528         }
1529
1530         let mut err = match *sub {
1531             ty::ReEarlyBound(_)
1532             | ty::ReFree(ty::FreeRegion {
1533                 bound_region: ty::BrNamed(..),
1534                 ..
1535             }) => {
1536                 // Does the required lifetime have a nice name we can print?
1537                 let mut err = struct_span_err!(
1538                     self.tcx.sess,
1539                     span,
1540                     E0309,
1541                     "{} may not live long enough",
1542                     labeled_user_string
1543                 );
1544                 binding_suggestion(&mut err, type_param_span, bound_kind, sub);
1545                 err
1546             }
1547
1548             ty::ReStatic => {
1549                 // Does the required lifetime have a nice name we can print?
1550                 let mut err = struct_span_err!(
1551                     self.tcx.sess,
1552                     span,
1553                     E0310,
1554                     "{} may not live long enough",
1555                     labeled_user_string
1556                 );
1557                 binding_suggestion(&mut err, type_param_span, bound_kind, "'static");
1558                 err
1559             }
1560
1561             _ => {
1562                 // If not, be less specific.
1563                 let mut err = struct_span_err!(
1564                     self.tcx.sess,
1565                     span,
1566                     E0311,
1567                     "{} may not live long enough",
1568                     labeled_user_string
1569                 );
1570                 err.help(&format!(
1571                     "consider adding an explicit lifetime bound for `{}`",
1572                     bound_kind
1573                 ));
1574                 self.tcx.note_and_explain_region(
1575                     region_scope_tree,
1576                     &mut err,
1577                     &format!("{} must be valid for ", labeled_user_string),
1578                     sub,
1579                     "...",
1580                 );
1581                 err
1582             }
1583         };
1584
1585         if let Some(origin) = origin {
1586             self.note_region_origin(&mut err, &origin);
1587         }
1588         err
1589     }
1590
1591     fn report_sub_sup_conflict(
1592         &self,
1593         region_scope_tree: &region::ScopeTree,
1594         var_origin: RegionVariableOrigin,
1595         sub_origin: SubregionOrigin<'tcx>,
1596         sub_region: Region<'tcx>,
1597         sup_origin: SubregionOrigin<'tcx>,
1598         sup_region: Region<'tcx>,
1599     ) {
1600         let mut err = self.report_inference_failure(var_origin);
1601
1602         self.tcx.note_and_explain_region(
1603             region_scope_tree,
1604             &mut err,
1605             "first, the lifetime cannot outlive ",
1606             sup_region,
1607             "...",
1608         );
1609
1610         match (&sup_origin, &sub_origin) {
1611             (&infer::Subtype(ref sup_trace), &infer::Subtype(ref sub_trace)) => {
1612                 debug!("report_sub_sup_conflict: var_origin={:?}", var_origin);
1613                 debug!("report_sub_sup_conflict: sub_region={:?}", sub_region);
1614                 debug!("report_sub_sup_conflict: sub_origin={:?}", sub_origin);
1615                 debug!("report_sub_sup_conflict: sup_region={:?}", sup_region);
1616                 debug!("report_sub_sup_conflict: sup_origin={:?}", sup_origin);
1617                 debug!("report_sub_sup_conflict: sup_trace={:?}", sup_trace);
1618                 debug!("report_sub_sup_conflict: sub_trace={:?}", sub_trace);
1619                 debug!("report_sub_sup_conflict: sup_trace.values={:?}", sup_trace.values);
1620                 debug!("report_sub_sup_conflict: sub_trace.values={:?}", sub_trace.values);
1621
1622                 if let (Some((sup_expected, sup_found)), Some((sub_expected, sub_found))) = (
1623                     self.values_str(&sup_trace.values),
1624                     self.values_str(&sub_trace.values),
1625                 ) {
1626                     if sub_expected == sup_expected && sub_found == sup_found {
1627                         self.tcx.note_and_explain_region(
1628                             region_scope_tree,
1629                             &mut err,
1630                             "...but the lifetime must also be valid for ",
1631                             sub_region,
1632                             "...",
1633                         );
1634                         err.note(&format!(
1635                             "...so that the {}:\nexpected {}\n   found {}",
1636                             sup_trace.cause.as_requirement_str(),
1637                             sup_expected.content(),
1638                             sup_found.content()
1639                         ));
1640                         err.emit();
1641                         return;
1642                     }
1643                 }
1644             }
1645             _ => {}
1646         }
1647
1648         self.note_region_origin(&mut err, &sup_origin);
1649
1650         self.tcx.note_and_explain_region(
1651             region_scope_tree,
1652             &mut err,
1653             "but, the lifetime must be valid for ",
1654             sub_region,
1655             "...",
1656         );
1657
1658         self.note_region_origin(&mut err, &sub_origin);
1659         err.emit();
1660     }
1661 }
1662
1663 impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
1664     fn report_inference_failure(
1665         &self,
1666         var_origin: RegionVariableOrigin,
1667     ) -> DiagnosticBuilder<'tcx> {
1668         let br_string = |br: ty::BoundRegion| {
1669             let mut s = match br {
1670                 ty::BrNamed(_, name) => name.to_string(),
1671                 _ => String::new(),
1672             };
1673             if !s.is_empty() {
1674                 s.push_str(" ");
1675             }
1676             s
1677         };
1678         let var_description = match var_origin {
1679             infer::MiscVariable(_) => String::new(),
1680             infer::PatternRegion(_) => " for pattern".to_string(),
1681             infer::AddrOfRegion(_) => " for borrow expression".to_string(),
1682             infer::Autoref(_) => " for autoref".to_string(),
1683             infer::Coercion(_) => " for automatic coercion".to_string(),
1684             infer::LateBoundRegion(_, br, infer::FnCall) => {
1685                 format!(" for lifetime parameter {}in function call", br_string(br))
1686             }
1687             infer::LateBoundRegion(_, br, infer::HigherRankedType) => {
1688                 format!(" for lifetime parameter {}in generic type", br_string(br))
1689             }
1690             infer::LateBoundRegion(_, br, infer::AssocTypeProjection(def_id)) => format!(
1691                 " for lifetime parameter {}in trait containing associated type `{}`",
1692                 br_string(br),
1693                 self.tcx.associated_item(def_id).ident
1694             ),
1695             infer::EarlyBoundRegion(_, name) => format!(" for lifetime parameter `{}`", name),
1696             infer::BoundRegionInCoherence(name) => {
1697                 format!(" for lifetime parameter `{}` in coherence check", name)
1698             }
1699             infer::UpvarRegion(ref upvar_id, _) => {
1700                 let var_name = self.tcx.hir().name(upvar_id.var_path.hir_id);
1701                 format!(" for capture of `{}` by closure", var_name)
1702             }
1703             infer::NLL(..) => bug!("NLL variable found in lexical phase"),
1704         };
1705
1706         struct_span_err!(
1707             self.tcx.sess,
1708             var_origin.span(),
1709             E0495,
1710             "cannot infer an appropriate lifetime{} \
1711              due to conflicting requirements",
1712             var_description
1713         )
1714     }
1715 }
1716
1717 enum FailureCode {
1718     Error0038(DefId),
1719     Error0317(&'static str),
1720     Error0580(&'static str),
1721     Error0308(&'static str),
1722     Error0644(&'static str),
1723 }
1724
1725 impl<'tcx> ObligationCause<'tcx> {
1726     fn as_failure_code(&self, terr: &TypeError<'tcx>) -> FailureCode {
1727         use self::FailureCode::*;
1728         use crate::traits::ObligationCauseCode::*;
1729         match self.code {
1730             CompareImplMethodObligation { .. } => Error0308("method not compatible with trait"),
1731             MatchExpressionArm(box MatchExpressionArmCause { source, .. }) =>
1732                 Error0308(match source {
1733                     hir::MatchSource::IfLetDesugar { .. } =>
1734                         "`if let` arms have incompatible types",
1735                     hir::MatchSource::TryDesugar => {
1736                         "try expression alternatives have incompatible types"
1737                     }
1738                     _ => "match arms have incompatible types",
1739                 }),
1740             IfExpression { .. } => Error0308("if and else have incompatible types"),
1741             IfExpressionWithNoElse => Error0317("if may be missing an else clause"),
1742             MainFunctionType => Error0580("main function has wrong type"),
1743             StartFunctionType => Error0308("start function has wrong type"),
1744             IntrinsicType => Error0308("intrinsic has wrong type"),
1745             MethodReceiver => Error0308("mismatched `self` parameter type"),
1746
1747             // In the case where we have no more specific thing to
1748             // say, also take a look at the error code, maybe we can
1749             // tailor to that.
1750             _ => match terr {
1751                 TypeError::CyclicTy(ty) if ty.is_closure() || ty.is_generator() => {
1752                     Error0644("closure/generator type that references itself")
1753                 }
1754                 TypeError::IntrinsicCast => {
1755                     Error0308("cannot coerce intrinsics to function pointers")
1756                 }
1757                 TypeError::ObjectUnsafeCoercion(did) => Error0038(did.clone()),
1758                 _ => Error0308("mismatched types"),
1759             },
1760         }
1761     }
1762
1763     fn as_requirement_str(&self) -> &'static str {
1764         use crate::traits::ObligationCauseCode::*;
1765         match self.code {
1766             CompareImplMethodObligation { .. } => "method type is compatible with trait",
1767             ExprAssignable => "expression is assignable",
1768             MatchExpressionArm(box MatchExpressionArmCause { source, .. }) => match source {
1769                 hir::MatchSource::IfLetDesugar { .. } => "`if let` arms have compatible types",
1770                 _ => "match arms have compatible types",
1771             },
1772             IfExpression { .. } => "if and else have incompatible types",
1773             IfExpressionWithNoElse => "if missing an else returns ()",
1774             MainFunctionType => "`main` function has the correct type",
1775             StartFunctionType => "`start` function has the correct type",
1776             IntrinsicType => "intrinsic has the correct type",
1777             MethodReceiver => "method receiver has the correct type",
1778             _ => "types are compatible",
1779         }
1780     }
1781 }