]> git.lizzy.rs Git - rust.git/blob - src/librustc/infer/error_reporting.rs
Unignore u128 test for stage 0,1
[rust.git] / src / librustc / infer / error_reporting.rs
1 // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! Error Reporting Code for the inference engine
12 //!
13 //! Because of the way inference, and in particular region inference,
14 //! works, it often happens that errors are not detected until far after
15 //! the relevant line of code has been type-checked. Therefore, there is
16 //! an elaborate system to track why a particular constraint in the
17 //! inference graph arose so that we can explain to the user what gave
18 //! rise to a particular error.
19 //!
20 //! The basis of the system are the "origin" types. An "origin" is the
21 //! reason that a constraint or inference variable arose. There are
22 //! different "origin" enums for different kinds of constraints/variables
23 //! (e.g., `TypeOrigin`, `RegionVariableOrigin`). An origin always has
24 //! a span, but also more information so that we can generate a meaningful
25 //! error message.
26 //!
27 //! Having a catalogue of all the different reasons an error can arise is
28 //! also useful for other reasons, like cross-referencing FAQs etc, though
29 //! we are not really taking advantage of this yet.
30 //!
31 //! # Region Inference
32 //!
33 //! Region inference is particularly tricky because it always succeeds "in
34 //! the moment" and simply registers a constraint. Then, at the end, we
35 //! can compute the full graph and report errors, so we need to be able to
36 //! store and later report what gave rise to the conflicting constraints.
37 //!
38 //! # Subtype Trace
39 //!
40 //! Determining whether `T1 <: T2` often involves a number of subtypes and
41 //! subconstraints along the way. A "TypeTrace" is an extended version
42 //! of an origin that traces the types and other values that were being
43 //! compared. It is not necessarily comprehensive (in fact, at the time of
44 //! this writing it only tracks the root values being compared) but I'd
45 //! like to extend it to include significant "waypoints". For example, if
46 //! you are comparing `(T1, T2) <: (T3, T4)`, and the problem is that `T2
47 //! <: T4` fails, I'd like the trace to include enough information to say
48 //! "in the 2nd element of the tuple". Similarly, failures when comparing
49 //! arguments or return types in fn types should be able to cite the
50 //! specific position, etc.
51 //!
52 //! # Reality vs plan
53 //!
54 //! Of course, there is still a LOT of code in typeck that has yet to be
55 //! ported to this system, and which relies on string concatenation at the
56 //! time of error detection.
57
58 use super::InferCtxt;
59 use super::TypeTrace;
60 use super::SubregionOrigin;
61 use super::RegionVariableOrigin;
62 use super::ValuePairs;
63 use super::region_inference::RegionResolutionError;
64 use super::region_inference::ConcreteFailure;
65 use super::region_inference::SubSupConflict;
66 use super::region_inference::GenericBoundFailure;
67 use super::region_inference::GenericKind;
68 use super::region_inference::ProcessedErrors;
69 use super::region_inference::ProcessedErrorOrigin;
70 use super::region_inference::SameRegions;
71
72 use hir::map as hir_map;
73 use hir;
74
75 use lint;
76 use hir::def_id::DefId;
77 use infer;
78 use middle::region;
79 use traits::{ObligationCause, ObligationCauseCode};
80 use ty::{self, TyCtxt, TypeFoldable};
81 use ty::{Region, ReFree};
82 use ty::error::TypeError;
83
84 use std::fmt;
85 use syntax::ast;
86 use syntax_pos::{Pos, Span};
87 use errors::DiagnosticBuilder;
88
89 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
90     pub fn note_and_explain_region(self,
91                                    err: &mut DiagnosticBuilder,
92                                    prefix: &str,
93                                    region: &'tcx ty::Region,
94                                    suffix: &str) {
95         fn item_scope_tag(item: &hir::Item) -> &'static str {
96             match item.node {
97                 hir::ItemImpl(..) => "impl",
98                 hir::ItemStruct(..) => "struct",
99                 hir::ItemUnion(..) => "union",
100                 hir::ItemEnum(..) => "enum",
101                 hir::ItemTrait(..) => "trait",
102                 hir::ItemFn(..) => "function body",
103                 _ => "item"
104             }
105         }
106
107         fn trait_item_scope_tag(item: &hir::TraitItem) -> &'static str {
108             match item.node {
109                 hir::TraitItemKind::Method(..) => "method body",
110                 hir::TraitItemKind::Const(..) |
111                 hir::TraitItemKind::Type(..) => "associated item"
112             }
113         }
114
115         fn impl_item_scope_tag(item: &hir::ImplItem) -> &'static str {
116             match item.node {
117                 hir::ImplItemKind::Method(..) => "method body",
118                 hir::ImplItemKind::Const(..) |
119                 hir::ImplItemKind::Type(_) => "associated item"
120             }
121         }
122
123         fn explain_span<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>,
124                                         heading: &str, span: Span)
125                                         -> (String, Option<Span>) {
126             let lo = tcx.sess.codemap().lookup_char_pos_adj(span.lo);
127             (format!("the {} at {}:{}", heading, lo.line, lo.col.to_usize()),
128              Some(span))
129         }
130
131         let (description, span) = match *region {
132             ty::ReScope(scope) => {
133                 let new_string;
134                 let unknown_scope = || {
135                     format!("{}unknown scope: {:?}{}.  Please report a bug.",
136                             prefix, scope, suffix)
137                 };
138                 let span = match scope.span(&self.region_maps, &self.hir) {
139                     Some(s) => s,
140                     None => {
141                         err.note(&unknown_scope());
142                         return;
143                     }
144                 };
145                 let tag = match self.hir.find(scope.node_id(&self.region_maps)) {
146                     Some(hir_map::NodeBlock(_)) => "block",
147                     Some(hir_map::NodeExpr(expr)) => match expr.node {
148                         hir::ExprCall(..) => "call",
149                         hir::ExprMethodCall(..) => "method call",
150                         hir::ExprMatch(.., hir::MatchSource::IfLetDesugar { .. }) => "if let",
151                         hir::ExprMatch(.., hir::MatchSource::WhileLetDesugar) =>  "while let",
152                         hir::ExprMatch(.., hir::MatchSource::ForLoopDesugar) =>  "for",
153                         hir::ExprMatch(..) => "match",
154                         _ => "expression",
155                     },
156                     Some(hir_map::NodeStmt(_)) => "statement",
157                     Some(hir_map::NodeItem(it)) => item_scope_tag(&it),
158                     Some(hir_map::NodeTraitItem(it)) => trait_item_scope_tag(&it),
159                     Some(hir_map::NodeImplItem(it)) => impl_item_scope_tag(&it),
160                     Some(_) | None => {
161                         err.span_note(span, &unknown_scope());
162                         return;
163                     }
164                 };
165                 let scope_decorated_tag = match self.region_maps.code_extent_data(scope) {
166                     region::CodeExtentData::Misc(_) => tag,
167                     region::CodeExtentData::CallSiteScope { .. } => {
168                         "scope of call-site for function"
169                     }
170                     region::CodeExtentData::ParameterScope { .. } => {
171                         "scope of function body"
172                     }
173                     region::CodeExtentData::DestructionScope(_) => {
174                         new_string = format!("destruction scope surrounding {}", tag);
175                         &new_string[..]
176                     }
177                     region::CodeExtentData::Remainder(r) => {
178                         new_string = format!("block suffix following statement {}",
179                                              r.first_statement_index);
180                         &new_string[..]
181                     }
182                 };
183                 explain_span(self, scope_decorated_tag, span)
184             }
185
186             ty::ReFree(ref fr) => {
187                 let prefix = match fr.bound_region {
188                     ty::BrAnon(idx) => {
189                         format!("the anonymous lifetime #{} defined on", idx + 1)
190                     }
191                     ty::BrFresh(_) => "an anonymous lifetime defined on".to_owned(),
192                     _ => {
193                         format!("the lifetime {} as defined on",
194                                 fr.bound_region)
195                     }
196                 };
197
198                 let node = fr.scope.node_id(&self.region_maps);
199                 let unknown;
200                 let tag = match self.hir.find(node) {
201                     Some(hir_map::NodeBlock(_)) |
202                     Some(hir_map::NodeExpr(_)) => "body",
203                     Some(hir_map::NodeItem(it)) => item_scope_tag(&it),
204                     Some(hir_map::NodeTraitItem(it)) => trait_item_scope_tag(&it),
205                     Some(hir_map::NodeImplItem(it)) => impl_item_scope_tag(&it),
206
207                     // this really should not happen, but it does:
208                     // FIXME(#27942)
209                     Some(_) => {
210                         unknown = format!("unexpected node ({}) for scope {:?}.  \
211                                            Please report a bug.",
212                                           self.hir.node_to_string(node), fr.scope);
213                         &unknown
214                     }
215                     None => {
216                         unknown = format!("unknown node for scope {:?}.  \
217                                            Please report a bug.", fr.scope);
218                         &unknown
219                     }
220                 };
221                 let (msg, opt_span) = explain_span(self, tag, self.hir.span(node));
222                 (format!("{} {}", prefix, msg), opt_span)
223             }
224
225             ty::ReStatic => ("the static lifetime".to_owned(), None),
226
227             ty::ReEmpty => ("the empty lifetime".to_owned(), None),
228
229             ty::ReEarlyBound(ref data) => (data.name.to_string(), None),
230
231             // FIXME(#13998) ReSkolemized should probably print like
232             // ReFree rather than dumping Debug output on the user.
233             //
234             // We shouldn't really be having unification failures with ReVar
235             // and ReLateBound though.
236             ty::ReSkolemized(..) |
237             ty::ReVar(_) |
238             ty::ReLateBound(..) |
239             ty::ReErased => {
240                 (format!("lifetime {:?}", region), None)
241             }
242         };
243         let message = format!("{}{}{}", prefix, description, suffix);
244         if let Some(span) = span {
245             err.span_note(span, &message);
246         } else {
247             err.note(&message);
248         }
249     }
250 }
251
252 impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
253     pub fn report_region_errors(&self,
254                                 errors: &Vec<RegionResolutionError<'tcx>>) {
255         debug!("report_region_errors(): {} errors to start", errors.len());
256
257         // try to pre-process the errors, which will group some of them
258         // together into a `ProcessedErrors` group:
259         let processed_errors = self.process_errors(errors);
260         let errors = processed_errors.as_ref().unwrap_or(errors);
261
262         debug!("report_region_errors: {} errors after preprocessing", errors.len());
263
264         for error in errors {
265             debug!("report_region_errors: error = {:?}", error);
266             match error.clone() {
267                 ConcreteFailure(origin, sub, sup) => {
268                     self.report_concrete_failure(origin, sub, sup).emit();
269                 }
270
271                 GenericBoundFailure(kind, param_ty, sub) => {
272                     self.report_generic_bound_failure(kind, param_ty, sub);
273                 }
274
275                 SubSupConflict(var_origin,
276                                sub_origin, sub_r,
277                                sup_origin, sup_r) => {
278                     self.report_sub_sup_conflict(var_origin,
279                                                  sub_origin, sub_r,
280                                                  sup_origin, sup_r);
281                 }
282
283                 ProcessedErrors(ref origins,
284                                 ref same_regions) => {
285                     if !same_regions.is_empty() {
286                         self.report_processed_errors(origins);
287                     }
288                 }
289             }
290         }
291     }
292
293     // This method goes through all the errors and try to group certain types
294     // of error together, for the purpose of suggesting explicit lifetime
295     // parameters to the user. This is done so that we can have a more
296     // complete view of what lifetimes should be the same.
297     // If the return value is an empty vector, it means that processing
298     // failed (so the return value of this method should not be used).
299     //
300     // The method also attempts to weed out messages that seem like
301     // duplicates that will be unhelpful to the end-user. But
302     // obviously it never weeds out ALL errors.
303     fn process_errors(&self, errors: &Vec<RegionResolutionError<'tcx>>)
304                       -> Option<Vec<RegionResolutionError<'tcx>>> {
305         debug!("process_errors()");
306         let mut origins = Vec::new();
307
308         // we collect up ConcreteFailures and SubSupConflicts that are
309         // relating free-regions bound on the fn-header and group them
310         // together into this vector
311         let mut same_regions = Vec::new();
312
313         // here we put errors that we will not be able to process nicely
314         let mut other_errors = Vec::new();
315
316         // we collect up GenericBoundFailures in here.
317         let mut bound_failures = Vec::new();
318
319         for error in errors {
320             // Check whether we can process this error into some other
321             // form; if not, fall through.
322             match *error {
323                 ConcreteFailure(ref origin, sub, sup) => {
324                     debug!("processing ConcreteFailure");
325                     if let SubregionOrigin::CompareImplMethodObligation { .. } = *origin {
326                         // When comparing an impl method against a
327                         // trait method, it is not helpful to suggest
328                         // changes to the impl method.  This is
329                         // because the impl method signature is being
330                         // checked using the trait's environment, so
331                         // usually the changes we suggest would
332                         // actually have to be applied to the *trait*
333                         // method (and it's not clear that the trait
334                         // method is even under the user's control).
335                     } else if let Some(same_frs) = free_regions_from_same_fn(self.tcx, sub, sup) {
336                         origins.push(
337                             ProcessedErrorOrigin::ConcreteFailure(
338                                 origin.clone(),
339                                 sub,
340                                 sup));
341                         append_to_same_regions(&mut same_regions, &same_frs);
342                         continue;
343                     }
344                 }
345                 SubSupConflict(ref var_origin, ref sub_origin, sub, ref sup_origin, sup) => {
346                     debug!("processing SubSupConflict sub: {:?} sup: {:?}", sub, sup);
347                     match (sub_origin, sup_origin) {
348                         (&SubregionOrigin::CompareImplMethodObligation { .. }, _) => {
349                             // As above, when comparing an impl method
350                             // against a trait method, it is not helpful
351                             // to suggest changes to the impl method.
352                         }
353                         (_, &SubregionOrigin::CompareImplMethodObligation { .. }) => {
354                             // See above.
355                         }
356                         _ => {
357                             if let Some(same_frs) = free_regions_from_same_fn(self.tcx, sub, sup) {
358                                 origins.push(
359                                     ProcessedErrorOrigin::VariableFailure(
360                                         var_origin.clone()));
361                                 append_to_same_regions(&mut same_regions, &same_frs);
362                                 continue;
363                             }
364                         }
365                     }
366                 }
367                 GenericBoundFailure(ref origin, ref kind, region) => {
368                     bound_failures.push((origin.clone(), kind.clone(), region));
369                     continue;
370                 }
371                 ProcessedErrors(..) => {
372                     bug!("should not encounter a `ProcessedErrors` yet: {:?}", error)
373                 }
374             }
375
376             // No changes to this error.
377             other_errors.push(error.clone());
378         }
379
380         // ok, let's pull together the errors, sorted in an order that
381         // we think will help user the best
382         let mut processed_errors = vec![];
383
384         // first, put the processed errors, if any
385         if !same_regions.is_empty() {
386             let common_scope_id = same_regions[0].scope_id;
387             for sr in &same_regions {
388                 // Since ProcessedErrors is used to reconstruct the function
389                 // declaration, we want to make sure that they are, in fact,
390                 // from the same scope
391                 if sr.scope_id != common_scope_id {
392                     debug!("returning empty result from process_errors because
393                             {} != {}", sr.scope_id, common_scope_id);
394                     return None;
395                 }
396             }
397             assert!(origins.len() > 0);
398             let pe = ProcessedErrors(origins, same_regions);
399             debug!("errors processed: {:?}", pe);
400             processed_errors.push(pe);
401         }
402
403         // next, put the other misc errors
404         processed_errors.extend(other_errors);
405
406         // finally, put the `T: 'a` errors, but only if there were no
407         // other errors. otherwise, these have a very high rate of
408         // being unhelpful in practice. This is because they are
409         // basically secondary checks that test the state of the
410         // region graph after the rest of inference is done, and the
411         // other kinds of errors indicate that the region constraint
412         // graph is internally inconsistent, so these test results are
413         // likely to be meaningless.
414         if processed_errors.is_empty() {
415             for (origin, kind, region) in bound_failures {
416                 processed_errors.push(GenericBoundFailure(origin, kind, region));
417             }
418         }
419
420         // we should always wind up with SOME errors, unless there were no
421         // errors to start
422         assert!(if errors.len() > 0 {processed_errors.len() > 0} else {true});
423
424         return Some(processed_errors);
425
426         #[derive(Debug)]
427         struct FreeRegionsFromSameFn {
428             sub_fr: ty::FreeRegion,
429             sup_fr: ty::FreeRegion,
430             scope_id: ast::NodeId
431         }
432
433         impl FreeRegionsFromSameFn {
434             fn new(sub_fr: ty::FreeRegion,
435                    sup_fr: ty::FreeRegion,
436                    scope_id: ast::NodeId)
437                    -> FreeRegionsFromSameFn {
438                 FreeRegionsFromSameFn {
439                     sub_fr: sub_fr,
440                     sup_fr: sup_fr,
441                     scope_id: scope_id
442                 }
443             }
444         }
445
446         fn free_regions_from_same_fn<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>,
447                                                      sub: &'tcx Region,
448                                                      sup: &'tcx Region)
449                                                      -> Option<FreeRegionsFromSameFn> {
450             debug!("free_regions_from_same_fn(sub={:?}, sup={:?})", sub, sup);
451             let (scope_id, fr1, fr2) = match (sub, sup) {
452                 (&ReFree(fr1), &ReFree(fr2)) => {
453                     if fr1.scope != fr2.scope {
454                         return None
455                     }
456                     assert!(fr1.scope == fr2.scope);
457                     (fr1.scope.node_id(&tcx.region_maps), fr1, fr2)
458                 },
459                 _ => return None
460             };
461             let parent = tcx.hir.get_parent(scope_id);
462             let parent_node = tcx.hir.find(parent);
463             match parent_node {
464                 Some(node) => match node {
465                     hir_map::NodeItem(item) => match item.node {
466                         hir::ItemFn(..) => {
467                             Some(FreeRegionsFromSameFn::new(fr1, fr2, scope_id))
468                         },
469                         _ => None
470                     },
471                     hir_map::NodeImplItem(..) |
472                     hir_map::NodeTraitItem(..) => {
473                         Some(FreeRegionsFromSameFn::new(fr1, fr2, scope_id))
474                     },
475                     _ => None
476                 },
477                 None => {
478                     debug!("no parent node of scope_id {}", scope_id);
479                     None
480                 }
481             }
482         }
483
484         fn append_to_same_regions(same_regions: &mut Vec<SameRegions>,
485                                   same_frs: &FreeRegionsFromSameFn) {
486             debug!("append_to_same_regions(same_regions={:?}, same_frs={:?})",
487                    same_regions, same_frs);
488             let scope_id = same_frs.scope_id;
489             let (sub_fr, sup_fr) = (same_frs.sub_fr, same_frs.sup_fr);
490             for sr in same_regions.iter_mut() {
491                 if sr.contains(&sup_fr.bound_region) && scope_id == sr.scope_id {
492                     sr.push(sub_fr.bound_region);
493                     return
494                 }
495             }
496             same_regions.push(SameRegions {
497                 scope_id: scope_id,
498                 regions: vec![sub_fr.bound_region, sup_fr.bound_region]
499             })
500         }
501     }
502
503     /// Adds a note if the types come from similarly named crates
504     fn check_and_note_conflicting_crates(&self,
505                                          err: &mut DiagnosticBuilder,
506                                          terr: &TypeError<'tcx>,
507                                          sp: Span) {
508         let report_path_match = |err: &mut DiagnosticBuilder, did1: DefId, did2: DefId| {
509             // Only external crates, if either is from a local
510             // module we could have false positives
511             if !(did1.is_local() || did2.is_local()) && did1.krate != did2.krate {
512                 let exp_path = self.tcx.item_path_str(did1);
513                 let found_path = self.tcx.item_path_str(did2);
514                 // We compare strings because DefPath can be different
515                 // for imported and non-imported crates
516                 if exp_path == found_path {
517                     let crate_name = self.tcx.sess.cstore.crate_name(did1.krate);
518                     err.span_note(sp, &format!("Perhaps two different versions \
519                                                 of crate `{}` are being used?",
520                                                crate_name));
521                 }
522             }
523         };
524         match *terr {
525             TypeError::Sorts(ref exp_found) => {
526                 // if they are both "path types", there's a chance of ambiguity
527                 // due to different versions of the same crate
528                 match (&exp_found.expected.sty, &exp_found.found.sty) {
529                     (&ty::TyAdt(exp_adt, _), &ty::TyAdt(found_adt, _)) => {
530                         report_path_match(err, exp_adt.did, found_adt.did);
531                     },
532                     _ => ()
533                 }
534             },
535             TypeError::Traits(ref exp_found) => {
536                 report_path_match(err, exp_found.expected, exp_found.found);
537             },
538             _ => () // FIXME(#22750) handle traits and stuff
539         }
540     }
541
542     fn note_error_origin(&self,
543                          err: &mut DiagnosticBuilder<'tcx>,
544                          cause: &ObligationCause<'tcx>)
545     {
546         match cause.code {
547             ObligationCauseCode::MatchExpressionArm { arm_span, source } => match source {
548                 hir::MatchSource::IfLetDesugar {..} => {
549                     err.span_note(arm_span, "`if let` arm with an incompatible type");
550                 }
551                 _ => {
552                     err.span_note(arm_span, "match arm with an incompatible type");
553                 }
554             },
555             _ => ()
556         }
557     }
558
559     pub fn note_type_err(&self,
560                          diag: &mut DiagnosticBuilder<'tcx>,
561                          cause: &ObligationCause<'tcx>,
562                          secondary_span: Option<(Span, String)>,
563                          values: Option<ValuePairs<'tcx>>,
564                          terr: &TypeError<'tcx>)
565     {
566         let expected_found = match values {
567             None => None,
568             Some(values) => match self.values_str(&values) {
569                 Some((expected, found)) => Some((expected, found)),
570                 None => {
571                     // Derived error. Cancel the emitter.
572                     self.tcx.sess.diagnostic().cancel(diag);
573                     return
574                 }
575             }
576         };
577
578         let span = cause.span;
579
580         if let Some((expected, found)) = expected_found {
581             let is_simple_error = if let &TypeError::Sorts(ref values) = terr {
582                 values.expected.is_primitive() && values.found.is_primitive()
583             } else {
584                 false
585             };
586
587             if !is_simple_error {
588                 if expected == found {
589                     if let &TypeError::Sorts(ref values) = terr {
590                         diag.note_expected_found_extra(
591                             &"type", &expected, &found,
592                             &format!(" ({})", values.expected.sort_string(self.tcx)),
593                             &format!(" ({})", values.found.sort_string(self.tcx)));
594                     } else {
595                         diag.note_expected_found(&"type", &expected, &found);
596                     }
597                 } else {
598                     diag.note_expected_found(&"type", &expected, &found);
599                 }
600             }
601         }
602
603         diag.span_label(span, &terr);
604         if let Some((sp, msg)) = secondary_span {
605             diag.span_label(sp, &msg);
606         }
607
608         self.note_error_origin(diag, &cause);
609         self.check_and_note_conflicting_crates(diag, terr, span);
610         self.tcx.note_and_explain_type_err(diag, terr, span);
611     }
612
613     pub fn report_and_explain_type_error(&self,
614                                          trace: TypeTrace<'tcx>,
615                                          terr: &TypeError<'tcx>)
616                                          -> DiagnosticBuilder<'tcx>
617     {
618         let span = trace.cause.span;
619         let failure_str = trace.cause.as_failure_str();
620         let mut diag = match trace.cause.code {
621             ObligationCauseCode::IfExpressionWithNoElse => {
622                 struct_span_err!(self.tcx.sess, span, E0317, "{}", failure_str)
623             }
624             ObligationCauseCode::MainFunctionType => {
625                 struct_span_err!(self.tcx.sess, span, E0580, "{}", failure_str)
626             }
627             _ => {
628                 struct_span_err!(self.tcx.sess, span, E0308, "{}", failure_str)
629             }
630         };
631         self.note_type_err(&mut diag, &trace.cause, None, Some(trace.values), terr);
632         diag
633     }
634
635     /// Returns a string of the form "expected `{}`, found `{}`".
636     fn values_str(&self, values: &ValuePairs<'tcx>) -> Option<(String, String)> {
637         match *values {
638             infer::Types(ref exp_found) => self.expected_found_str(exp_found),
639             infer::TraitRefs(ref exp_found) => self.expected_found_str(exp_found),
640             infer::PolyTraitRefs(ref exp_found) => self.expected_found_str(exp_found),
641         }
642     }
643
644     fn expected_found_str<T: fmt::Display + TypeFoldable<'tcx>>(
645         &self,
646         exp_found: &ty::error::ExpectedFound<T>)
647         -> Option<(String, String)>
648     {
649         let exp_found = self.resolve_type_vars_if_possible(exp_found);
650         if exp_found.references_error() {
651             return None;
652         }
653
654         Some((format!("{}", exp_found.expected), format!("{}", exp_found.found)))
655     }
656
657     fn report_generic_bound_failure(&self,
658                                     origin: SubregionOrigin<'tcx>,
659                                     bound_kind: GenericKind<'tcx>,
660                                     sub: &'tcx Region)
661     {
662         // FIXME: it would be better to report the first error message
663         // with the span of the parameter itself, rather than the span
664         // where the error was detected. But that span is not readily
665         // accessible.
666
667         let labeled_user_string = match bound_kind {
668             GenericKind::Param(ref p) =>
669                 format!("the parameter type `{}`", p),
670             GenericKind::Projection(ref p) =>
671                 format!("the associated type `{}`", p),
672         };
673
674         if let SubregionOrigin::CompareImplMethodObligation {
675             span, item_name, impl_item_def_id, trait_item_def_id, lint_id
676         } = origin {
677             self.report_extra_impl_obligation(span,
678                                               item_name,
679                                               impl_item_def_id,
680                                               trait_item_def_id,
681                                               &format!("`{}: {}`", bound_kind, sub),
682                                               lint_id)
683                 .emit();
684             return;
685         }
686
687         let mut err = match *sub {
688             ty::ReFree(ty::FreeRegion {bound_region: ty::BrNamed(..), ..}) => {
689                 // Does the required lifetime have a nice name we can print?
690                 let mut err = struct_span_err!(self.tcx.sess,
691                                                origin.span(),
692                                                E0309,
693                                                "{} may not live long enough",
694                                                labeled_user_string);
695                 err.help(&format!("consider adding an explicit lifetime bound `{}: {}`...",
696                          bound_kind,
697                          sub));
698                 err
699             }
700
701             ty::ReStatic => {
702                 // Does the required lifetime have a nice name we can print?
703                 let mut err = struct_span_err!(self.tcx.sess,
704                                                origin.span(),
705                                                E0310,
706                                                "{} may not live long enough",
707                                                labeled_user_string);
708                 err.help(&format!("consider adding an explicit lifetime \
709                                    bound `{}: 'static`...",
710                                   bound_kind));
711                 err
712             }
713
714             _ => {
715                 // If not, be less specific.
716                 let mut err = struct_span_err!(self.tcx.sess,
717                                                origin.span(),
718                                                E0311,
719                                                "{} may not live long enough",
720                                                labeled_user_string);
721                 err.help(&format!("consider adding an explicit lifetime bound for `{}`",
722                                   bound_kind));
723                 self.tcx.note_and_explain_region(
724                     &mut err,
725                     &format!("{} must be valid for ", labeled_user_string),
726                     sub,
727                     "...");
728                 err
729             }
730         };
731
732         self.note_region_origin(&mut err, &origin);
733         err.emit();
734     }
735
736     fn report_concrete_failure(&self,
737                                origin: SubregionOrigin<'tcx>,
738                                sub: &'tcx Region,
739                                sup: &'tcx Region)
740                                 -> DiagnosticBuilder<'tcx> {
741         match origin {
742             infer::Subtype(trace) => {
743                 let terr = TypeError::RegionsDoesNotOutlive(sup, sub);
744                 self.report_and_explain_type_error(trace, &terr)
745             }
746             infer::Reborrow(span) => {
747                 let mut err = struct_span_err!(self.tcx.sess, span, E0312,
748                     "lifetime of reference outlives \
749                      lifetime of borrowed content...");
750                 self.tcx.note_and_explain_region(&mut err,
751                     "...the reference is valid for ",
752                     sub,
753                     "...");
754                 self.tcx.note_and_explain_region(&mut err,
755                     "...but the borrowed content is only valid for ",
756                     sup,
757                     "");
758                 err
759             }
760             infer::ReborrowUpvar(span, ref upvar_id) => {
761                 let mut err = struct_span_err!(self.tcx.sess, span, E0313,
762                     "lifetime of borrowed pointer outlives \
763                             lifetime of captured variable `{}`...",
764                             self.tcx.local_var_name_str(upvar_id.var_id));
765                 self.tcx.note_and_explain_region(&mut err,
766                     "...the borrowed pointer is valid for ",
767                     sub,
768                     "...");
769                 self.tcx.note_and_explain_region(&mut err,
770                     &format!("...but `{}` is only valid for ",
771                              self.tcx.local_var_name_str(upvar_id.var_id)),
772                     sup,
773                     "");
774                 err
775             }
776             infer::InfStackClosure(span) => {
777                 let mut err = struct_span_err!(self.tcx.sess, span, E0314,
778                     "closure outlives stack frame");
779                 self.tcx.note_and_explain_region(&mut err,
780                     "...the closure must be valid for ",
781                     sub,
782                     "...");
783                 self.tcx.note_and_explain_region(&mut err,
784                     "...but the closure's stack frame is only valid for ",
785                     sup,
786                     "");
787                 err
788             }
789             infer::InvokeClosure(span) => {
790                 let mut err = struct_span_err!(self.tcx.sess, span, E0315,
791                     "cannot invoke closure outside of its lifetime");
792                 self.tcx.note_and_explain_region(&mut err,
793                     "the closure is only valid for ",
794                     sup,
795                     "");
796                 err
797             }
798             infer::DerefPointer(span) => {
799                 let mut err = struct_span_err!(self.tcx.sess, span, E0473,
800                           "dereference of reference outside its lifetime");
801                 self.tcx.note_and_explain_region(&mut err,
802                     "the reference is only valid for ",
803                     sup,
804                     "");
805                 err
806             }
807             infer::FreeVariable(span, id) => {
808                 let mut err = struct_span_err!(self.tcx.sess, span, E0474,
809                           "captured variable `{}` does not outlive the enclosing closure",
810                           self.tcx.local_var_name_str(id));
811                 self.tcx.note_and_explain_region(&mut err,
812                     "captured variable is valid for ",
813                     sup,
814                     "");
815                 self.tcx.note_and_explain_region(&mut err,
816                     "closure is valid for ",
817                     sub,
818                     "");
819                 err
820             }
821             infer::IndexSlice(span) => {
822                 let mut err = struct_span_err!(self.tcx.sess, span, E0475,
823                           "index of slice outside its lifetime");
824                 self.tcx.note_and_explain_region(&mut err,
825                     "the slice is only valid for ",
826                     sup,
827                     "");
828                 err
829             }
830             infer::RelateObjectBound(span) => {
831                 let mut err = struct_span_err!(self.tcx.sess, span, E0476,
832                           "lifetime of the source pointer does not outlive \
833                            lifetime bound of the object type");
834                 self.tcx.note_and_explain_region(&mut err,
835                     "object type is valid for ",
836                     sub,
837                     "");
838                 self.tcx.note_and_explain_region(&mut err,
839                     "source pointer is only valid for ",
840                     sup,
841                     "");
842                 err
843             }
844             infer::RelateParamBound(span, ty) => {
845                 let mut err = struct_span_err!(self.tcx.sess, span, E0477,
846                           "the type `{}` does not fulfill the required lifetime",
847                           self.ty_to_string(ty));
848                 self.tcx.note_and_explain_region(&mut err,
849                                         "type must outlive ",
850                                         sub,
851                                         "");
852                 err
853             }
854             infer::RelateRegionParamBound(span) => {
855                 let mut err = struct_span_err!(self.tcx.sess, span, E0478,
856                           "lifetime bound not satisfied");
857                 self.tcx.note_and_explain_region(&mut err,
858                     "lifetime parameter instantiated with ",
859                     sup,
860                     "");
861                 self.tcx.note_and_explain_region(&mut err,
862                     "but lifetime parameter must outlive ",
863                     sub,
864                     "");
865                 err
866             }
867             infer::RelateDefaultParamBound(span, ty) => {
868                 let mut err = struct_span_err!(self.tcx.sess, span, E0479,
869                           "the type `{}` (provided as the value of \
870                            a type parameter) is not valid at this point",
871                           self.ty_to_string(ty));
872                 self.tcx.note_and_explain_region(&mut err,
873                                         "type must outlive ",
874                                         sub,
875                                         "");
876                 err
877             }
878             infer::CallRcvr(span) => {
879                 let mut err = struct_span_err!(self.tcx.sess, span, E0480,
880                           "lifetime of method receiver does not outlive \
881                            the method call");
882                 self.tcx.note_and_explain_region(&mut err,
883                     "the receiver is only valid for ",
884                     sup,
885                     "");
886                 err
887             }
888             infer::CallArg(span) => {
889                 let mut err = struct_span_err!(self.tcx.sess, span, E0481,
890                           "lifetime of function argument does not outlive \
891                            the function call");
892                 self.tcx.note_and_explain_region(&mut err,
893                     "the function argument is only valid for ",
894                     sup,
895                     "");
896                 err
897             }
898             infer::CallReturn(span) => {
899                 let mut err = struct_span_err!(self.tcx.sess, span, E0482,
900                           "lifetime of return value does not outlive \
901                            the function call");
902                 self.tcx.note_and_explain_region(&mut err,
903                     "the return value is only valid for ",
904                     sup,
905                     "");
906                 err
907             }
908             infer::Operand(span) => {
909                 let mut err = struct_span_err!(self.tcx.sess, span, E0483,
910                           "lifetime of operand does not outlive \
911                            the operation");
912                 self.tcx.note_and_explain_region(&mut err,
913                     "the operand is only valid for ",
914                     sup,
915                     "");
916                 err
917             }
918             infer::AddrOf(span) => {
919                 let mut err = struct_span_err!(self.tcx.sess, span, E0484,
920                           "reference is not valid at the time of borrow");
921                 self.tcx.note_and_explain_region(&mut err,
922                     "the borrow is only valid for ",
923                     sup,
924                     "");
925                 err
926             }
927             infer::AutoBorrow(span) => {
928                 let mut err = struct_span_err!(self.tcx.sess, span, E0485,
929                           "automatically reference is not valid \
930                            at the time of borrow");
931                 self.tcx.note_and_explain_region(&mut err,
932                     "the automatic borrow is only valid for ",
933                     sup,
934                     "");
935                 err
936             }
937             infer::ExprTypeIsNotInScope(t, span) => {
938                 let mut err = struct_span_err!(self.tcx.sess, span, E0486,
939                           "type of expression contains references \
940                            that are not valid during the expression: `{}`",
941                           self.ty_to_string(t));
942                 self.tcx.note_and_explain_region(&mut err,
943                     "type is only valid for ",
944                     sup,
945                     "");
946                 err
947             }
948             infer::SafeDestructor(span) => {
949                 let mut err = struct_span_err!(self.tcx.sess, span, E0487,
950                           "unsafe use of destructor: destructor might be called \
951                            while references are dead");
952                 // FIXME (22171): terms "super/subregion" are suboptimal
953                 self.tcx.note_and_explain_region(&mut err,
954                     "superregion: ",
955                     sup,
956                     "");
957                 self.tcx.note_and_explain_region(&mut err,
958                     "subregion: ",
959                     sub,
960                     "");
961                 err
962             }
963             infer::BindingTypeIsNotValidAtDecl(span) => {
964                 let mut err = struct_span_err!(self.tcx.sess, span, E0488,
965                           "lifetime of variable does not enclose its declaration");
966                 self.tcx.note_and_explain_region(&mut err,
967                     "the variable is only valid for ",
968                     sup,
969                     "");
970                 err
971             }
972             infer::ParameterInScope(_, span) => {
973                 let mut err = struct_span_err!(self.tcx.sess, span, E0489,
974                           "type/lifetime parameter not in scope here");
975                 self.tcx.note_and_explain_region(&mut err,
976                     "the parameter is only valid for ",
977                     sub,
978                     "");
979                 err
980             }
981             infer::DataBorrowed(ty, span) => {
982                 let mut err = struct_span_err!(self.tcx.sess, span, E0490,
983                           "a value of type `{}` is borrowed for too long",
984                           self.ty_to_string(ty));
985                 self.tcx.note_and_explain_region(&mut err, "the type is valid for ", sub, "");
986                 self.tcx.note_and_explain_region(&mut err, "but the borrow lasts for ", sup, "");
987                 err
988             }
989             infer::ReferenceOutlivesReferent(ty, span) => {
990                 let mut err = struct_span_err!(self.tcx.sess, span, E0491,
991                           "in type `{}`, reference has a longer lifetime \
992                            than the data it references",
993                           self.ty_to_string(ty));
994                 self.tcx.note_and_explain_region(&mut err,
995                     "the pointer is valid for ",
996                     sub,
997                     "");
998                 self.tcx.note_and_explain_region(&mut err,
999                     "but the referenced data is only valid for ",
1000                     sup,
1001                     "");
1002                 err
1003             }
1004             infer::CompareImplMethodObligation { span,
1005                                                  item_name,
1006                                                  impl_item_def_id,
1007                                                  trait_item_def_id,
1008                                                  lint_id } => {
1009                 self.report_extra_impl_obligation(span,
1010                                                   item_name,
1011                                                   impl_item_def_id,
1012                                                   trait_item_def_id,
1013                                                   &format!("`{}: {}`", sup, sub),
1014                                                   lint_id)
1015             }
1016         }
1017     }
1018
1019     fn report_sub_sup_conflict(&self,
1020                                var_origin: RegionVariableOrigin,
1021                                sub_origin: SubregionOrigin<'tcx>,
1022                                sub_region: &'tcx Region,
1023                                sup_origin: SubregionOrigin<'tcx>,
1024                                sup_region: &'tcx Region) {
1025         let mut err = self.report_inference_failure(var_origin);
1026
1027         self.tcx.note_and_explain_region(&mut err,
1028             "first, the lifetime cannot outlive ",
1029             sup_region,
1030             "...");
1031
1032         self.note_region_origin(&mut err, &sup_origin);
1033
1034         self.tcx.note_and_explain_region(&mut err,
1035             "but, the lifetime must be valid for ",
1036             sub_region,
1037             "...");
1038
1039         self.note_region_origin(&mut err, &sub_origin);
1040         err.emit();
1041     }
1042
1043     fn report_processed_errors(&self,
1044                                origins: &[ProcessedErrorOrigin<'tcx>]) {
1045         for origin in origins.iter() {
1046             let mut err = match *origin {
1047                 ProcessedErrorOrigin::VariableFailure(ref var_origin) =>
1048                     self.report_inference_failure(var_origin.clone()),
1049                 ProcessedErrorOrigin::ConcreteFailure(ref sr_origin, sub, sup) =>
1050                     self.report_concrete_failure(sr_origin.clone(), sub, sup),
1051             };
1052
1053             err.emit();
1054         }
1055     }
1056
1057     pub fn issue_32330_warnings(&self, span: Span, issue32330s: &[ty::Issue32330]) {
1058         for issue32330 in issue32330s {
1059             match *issue32330 {
1060                 ty::Issue32330::WontChange => { }
1061                 ty::Issue32330::WillChange { fn_def_id, region_name } => {
1062                     self.tcx.sess.add_lint(
1063                         lint::builtin::HR_LIFETIME_IN_ASSOC_TYPE,
1064                         ast::CRATE_NODE_ID,
1065                         span,
1066                         format!("lifetime parameter `{0}` declared on fn `{1}` \
1067                                  appears only in the return type, \
1068                                  but here is required to be higher-ranked, \
1069                                  which means that `{0}` must appear in both \
1070                                  argument and return types",
1071                                 region_name,
1072                                 self.tcx.item_path_str(fn_def_id)));
1073                 }
1074             }
1075         }
1076     }
1077 }
1078
1079 impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
1080     fn report_inference_failure(&self,
1081                                 var_origin: RegionVariableOrigin)
1082                                 -> DiagnosticBuilder<'tcx> {
1083         let br_string = |br: ty::BoundRegion| {
1084             let mut s = br.to_string();
1085             if !s.is_empty() {
1086                 s.push_str(" ");
1087             }
1088             s
1089         };
1090         let var_description = match var_origin {
1091             infer::MiscVariable(_) => "".to_string(),
1092             infer::PatternRegion(_) => " for pattern".to_string(),
1093             infer::AddrOfRegion(_) => " for borrow expression".to_string(),
1094             infer::Autoref(_) => " for autoref".to_string(),
1095             infer::Coercion(_) => " for automatic coercion".to_string(),
1096             infer::LateBoundRegion(_, br, infer::FnCall) => {
1097                 format!(" for lifetime parameter {}in function call",
1098                         br_string(br))
1099             }
1100             infer::LateBoundRegion(_, br, infer::HigherRankedType) => {
1101                 format!(" for lifetime parameter {}in generic type", br_string(br))
1102             }
1103             infer::LateBoundRegion(_, br, infer::AssocTypeProjection(type_name)) => {
1104                 format!(" for lifetime parameter {}in trait containing associated type `{}`",
1105                         br_string(br), type_name)
1106             }
1107             infer::EarlyBoundRegion(_, name) => {
1108                 format!(" for lifetime parameter `{}`",
1109                         name)
1110             }
1111             infer::BoundRegionInCoherence(name) => {
1112                 format!(" for lifetime parameter `{}` in coherence check",
1113                         name)
1114             }
1115             infer::UpvarRegion(ref upvar_id, _) => {
1116                 format!(" for capture of `{}` by closure",
1117                         self.tcx.local_var_name_str(upvar_id.var_id).to_string())
1118             }
1119         };
1120
1121         struct_span_err!(self.tcx.sess, var_origin.span(), E0495,
1122                   "cannot infer an appropriate lifetime{} \
1123                    due to conflicting requirements",
1124                   var_description)
1125     }
1126
1127     fn note_region_origin(&self, err: &mut DiagnosticBuilder, origin: &SubregionOrigin<'tcx>) {
1128         match *origin {
1129             infer::Subtype(ref trace) => {
1130                 if let Some((expected, found)) = self.values_str(&trace.values) {
1131                     // FIXME: do we want a "the" here?
1132                     err.span_note(
1133                         trace.cause.span,
1134                         &format!("...so that {} (expected {}, found {})",
1135                                  trace.cause.as_requirement_str(), expected, found));
1136                 } else {
1137                     // FIXME: this really should be handled at some earlier stage. Our
1138                     // handling of region checking when type errors are present is
1139                     // *terrible*.
1140
1141                     err.span_note(
1142                         trace.cause.span,
1143                         &format!("...so that {}",
1144                                  trace.cause.as_requirement_str()));
1145                 }
1146             }
1147             infer::Reborrow(span) => {
1148                 err.span_note(
1149                     span,
1150                     "...so that reference does not outlive \
1151                     borrowed content");
1152             }
1153             infer::ReborrowUpvar(span, ref upvar_id) => {
1154                 err.span_note(
1155                     span,
1156                     &format!(
1157                         "...so that closure can access `{}`",
1158                         self.tcx.local_var_name_str(upvar_id.var_id)
1159                             .to_string()));
1160             }
1161             infer::InfStackClosure(span) => {
1162                 err.span_note(
1163                     span,
1164                     "...so that closure does not outlive its stack frame");
1165             }
1166             infer::InvokeClosure(span) => {
1167                 err.span_note(
1168                     span,
1169                     "...so that closure is not invoked outside its lifetime");
1170             }
1171             infer::DerefPointer(span) => {
1172                 err.span_note(
1173                     span,
1174                     "...so that pointer is not dereferenced \
1175                     outside its lifetime");
1176             }
1177             infer::FreeVariable(span, id) => {
1178                 err.span_note(
1179                     span,
1180                     &format!("...so that captured variable `{}` \
1181                             does not outlive the enclosing closure",
1182                             self.tcx.local_var_name_str(id)));
1183             }
1184             infer::IndexSlice(span) => {
1185                 err.span_note(
1186                     span,
1187                     "...so that slice is not indexed outside the lifetime");
1188             }
1189             infer::RelateObjectBound(span) => {
1190                 err.span_note(
1191                     span,
1192                     "...so that it can be closed over into an object");
1193             }
1194             infer::CallRcvr(span) => {
1195                 err.span_note(
1196                     span,
1197                     "...so that method receiver is valid for the method call");
1198             }
1199             infer::CallArg(span) => {
1200                 err.span_note(
1201                     span,
1202                     "...so that argument is valid for the call");
1203             }
1204             infer::CallReturn(span) => {
1205                 err.span_note(
1206                     span,
1207                     "...so that return value is valid for the call");
1208             }
1209             infer::Operand(span) => {
1210                 err.span_note(
1211                     span,
1212                     "...so that operand is valid for operation");
1213             }
1214             infer::AddrOf(span) => {
1215                 err.span_note(
1216                     span,
1217                     "...so that reference is valid \
1218                      at the time of borrow");
1219             }
1220             infer::AutoBorrow(span) => {
1221                 err.span_note(
1222                     span,
1223                     "...so that auto-reference is valid \
1224                      at the time of borrow");
1225             }
1226             infer::ExprTypeIsNotInScope(t, span) => {
1227                 err.span_note(
1228                     span,
1229                     &format!("...so type `{}` of expression is valid during the \
1230                              expression",
1231                             self.ty_to_string(t)));
1232             }
1233             infer::BindingTypeIsNotValidAtDecl(span) => {
1234                 err.span_note(
1235                     span,
1236                     "...so that variable is valid at time of its declaration");
1237             }
1238             infer::ParameterInScope(_, span) => {
1239                 err.span_note(
1240                     span,
1241                     "...so that a type/lifetime parameter is in scope here");
1242             }
1243             infer::DataBorrowed(ty, span) => {
1244                 err.span_note(
1245                     span,
1246                     &format!("...so that the type `{}` is not borrowed for too long",
1247                              self.ty_to_string(ty)));
1248             }
1249             infer::ReferenceOutlivesReferent(ty, span) => {
1250                 err.span_note(
1251                     span,
1252                     &format!("...so that the reference type `{}` \
1253                              does not outlive the data it points at",
1254                             self.ty_to_string(ty)));
1255             }
1256             infer::RelateParamBound(span, t) => {
1257                 err.span_note(
1258                     span,
1259                     &format!("...so that the type `{}` \
1260                              will meet its required lifetime bounds",
1261                             self.ty_to_string(t)));
1262             }
1263             infer::RelateDefaultParamBound(span, t) => {
1264                 err.span_note(
1265                     span,
1266                     &format!("...so that type parameter \
1267                              instantiated with `{}`, \
1268                              will meet its declared lifetime bounds",
1269                             self.ty_to_string(t)));
1270             }
1271             infer::RelateRegionParamBound(span) => {
1272                 err.span_note(
1273                     span,
1274                     "...so that the declared lifetime parameter bounds \
1275                                 are satisfied");
1276             }
1277             infer::SafeDestructor(span) => {
1278                 err.span_note(
1279                     span,
1280                     "...so that references are valid when the destructor \
1281                      runs");
1282             }
1283             infer::CompareImplMethodObligation { span, .. } => {
1284                 err.span_note(
1285                     span,
1286                     "...so that the definition in impl matches the definition from the trait");
1287             }
1288         }
1289     }
1290 }
1291
1292 impl<'tcx> ObligationCause<'tcx> {
1293     fn as_failure_str(&self) -> &'static str {
1294         use traits::ObligationCauseCode::*;
1295         match self.code {
1296             CompareImplMethodObligation { .. } => "method not compatible with trait",
1297             MatchExpressionArm { source, .. } => match source {
1298                 hir::MatchSource::IfLetDesugar{..} => "`if let` arms have incompatible types",
1299                 _ => "match arms have incompatible types",
1300             },
1301             IfExpression => "if and else have incompatible types",
1302             IfExpressionWithNoElse => "if may be missing an else clause",
1303             EquatePredicate => "equality predicate not satisfied",
1304             MainFunctionType => "main function has wrong type",
1305             StartFunctionType => "start function has wrong type",
1306             IntrinsicType => "intrinsic has wrong type",
1307             MethodReceiver => "mismatched method receiver",
1308             _ => "mismatched types",
1309         }
1310     }
1311
1312     fn as_requirement_str(&self) -> &'static str {
1313         use traits::ObligationCauseCode::*;
1314         match self.code {
1315             CompareImplMethodObligation { .. } => "method type is compatible with trait",
1316             ExprAssignable => "expression is assignable",
1317             MatchExpressionArm { source, .. } => match source {
1318                 hir::MatchSource::IfLetDesugar{..} => "`if let` arms have compatible types",
1319                 _ => "match arms have compatible types",
1320             },
1321             IfExpression => "if and else have compatible types",
1322             IfExpressionWithNoElse => "if missing an else returns ()",
1323             EquatePredicate => "equality where clause is satisfied",
1324             MainFunctionType => "`main` function has the correct type",
1325             StartFunctionType => "`start` function has the correct type",
1326             IntrinsicType => "intrinsic has the correct type",
1327             MethodReceiver => "method receiver has the correct type",
1328             _ => "types are compatible",
1329         }
1330     }
1331 }