1 //! Error Reporting Code for the inference engine
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.
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
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.
21 //! # Region Inference
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.
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.
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.
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};
54 use crate::hir::def_id::DefId;
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};
64 use syntax_pos::{Pos, Span};
66 use rustc_error_codes::*;
72 pub mod nice_region_error;
74 impl<'tcx> TyCtxt<'tcx> {
75 pub fn note_and_explain_region(
77 region_scope_tree: ®ion::ScopeTree,
78 err: &mut DiagnosticBuilder<'_>,
80 region: ty::Region<'tcx>,
83 let (description, span) = match *region {
84 ty::ReScope(scope) => {
86 let unknown_scope = || {
88 "{}unknown scope: {:?}{}. Please report a bug.",
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",
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),
109 err.span_note(span, &unknown_scope());
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);
121 region::ScopeData::Remainder(first_statement_index) => {
122 new_string = format!(
123 "block suffix following statement {}",
124 first_statement_index.index()
129 self.explain_span(scope_decorated_tag, span)
132 ty::ReEarlyBound(_) | ty::ReFree(_) | ty::ReStatic => {
133 self.msg_span_from_free_region(region)
136 ty::ReEmpty => ("the empty lifetime".to_owned(), None),
138 ty::RePlaceholder(_) => (format!("any other region"), None),
140 // FIXME(#13998) RePlaceholder should probably print like
141 // ReFree rather than dumping Debug output on the user.
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)
149 // We shouldn't encounter an error message with ReClosureBound.
150 ty::ReClosureBound(..) => {
151 bug!("encountered unexpected ReClosureBound: {:?}", region,);
155 TyCtxt::emit_msg_span(err, prefix, description, span, suffix);
158 pub fn note_and_explain_free_region(
160 err: &mut DiagnosticBuilder<'_>,
162 region: ty::Region<'tcx>,
165 let (description, span) = self.msg_span_from_free_region(region);
167 TyCtxt::emit_msg_span(err, prefix, description, span, suffix);
170 fn msg_span_from_free_region(self, region: ty::Region<'tcx>) -> (String, Option<Span>) {
172 ty::ReEarlyBound(_) | ty::ReFree(_) => {
173 self.msg_span_from_early_bound_and_free_regions(region)
175 ty::ReStatic => ("the static lifetime".to_owned(), None),
176 ty::ReEmpty => ("an empty lifetime".to_owned(), None),
177 _ => bug!("{:?}", region),
181 fn msg_span_from_early_bound_and_free_regions(
183 region: ty::Region<'tcx>,
184 ) -> (String, Option<Span>) {
185 let cm = self.sess.source_map();
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),
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()
201 .and_then(|generics| generics.get_named(br.name))
205 (format!("the lifetime `{}` as defined on", br.name), sp)
207 ty::ReFree(ty::FreeRegion {
208 bound_region: ty::BoundRegion::BrNamed(_, name),
211 let mut sp = cm.def_span(self.hir().span(node));
212 if let Some(param) = self.hir()
214 .and_then(|generics| generics.get_named(name))
218 (format!("the lifetime `{}` as defined on", name), sp)
220 ty::ReFree(ref fr) => match fr.bound_region {
222 format!("the anonymous lifetime #{} defined on", idx + 1),
223 self.hir().span(node),
226 format!("the lifetime `{}` as defined on", region),
227 cm.def_span(self.hir().span(node)),
232 let (msg, opt_span) = self.explain_span(tag, span);
233 (format!("{} {}", prefix, msg), opt_span)
237 err: &mut DiagnosticBuilder<'_>,
243 let message = format!("{}{}{}", prefix, description, suffix);
245 if let Some(span) = span {
246 err.span_note(span, &message);
252 fn item_scope_tag(item: &hir::Item) -> &'static str {
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",
264 fn trait_item_scope_tag(item: &hir::TraitItem) -> &'static str {
266 hir::TraitItemKind::Method(..) => "method body",
267 hir::TraitItemKind::Const(..) | hir::TraitItemKind::Type(..) => "associated item",
271 fn impl_item_scope_tag(item: &hir::ImplItem) -> &'static str {
273 hir::ImplItemKind::Method(..) => "method body",
274 hir::ImplItemKind::Const(..)
275 | hir::ImplItemKind::OpaqueTy(..)
276 | hir::ImplItemKind::TyAlias(..) => "associated item",
280 fn explain_span(self, heading: &str, span: Span) -> (String, Option<Span>) {
281 let lo = self.sess.source_map().lookup_char_pos(span.lo());
283 format!("the {} at {}:{}", heading, lo.line, lo.col.to_usize() + 1),
289 impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
290 pub fn report_region_errors(
292 region_scope_tree: ®ion::ScopeTree,
293 errors: &Vec<RegionResolutionError<'tcx>>,
294 suppress: SuppressRegionErrors,
297 "report_region_errors(): {} errors to start, suppress = {:?}",
302 if suppress.suppressed() {
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);
311 "report_region_errors: {} errors after preprocessing",
315 for error in errors {
316 debug!("report_region_errors: error = {:?}", error);
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)
332 self.report_concrete_failure(region_scope_tree, origin, sub, sup)
337 RegionResolutionError::GenericBoundFailure(origin, param_ty, sub) => {
338 self.report_generic_bound_failure(
347 RegionResolutionError::SubSupConflict(
355 if sub_r.is_placeholder() {
356 self.report_placeholder_failure(
363 } else if sup_r.is_placeholder() {
364 self.report_placeholder_failure(
372 self.report_sub_sup_conflict(
383 RegionResolutionError::MemberConstraintFailure {
390 let hidden_ty = self.resolve_vars_if_possible(&hidden_ty);
391 opaque_types::unexpected_hidden_region_diagnostic(
393 Some(region_scope_tree),
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).
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.
416 errors: &Vec<RegionResolutionError<'tcx>>,
417 ) -> Vec<RegionResolutionError<'tcx>> {
418 debug!("process_errors()");
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
429 // Therefore, we filter them out of the list unless they are
430 // the only thing in the list.
432 let is_bound_failure = |e: &RegionResolutionError<'tcx>| match *e {
433 RegionResolutionError::GenericBoundFailure(..) => true,
434 RegionResolutionError::ConcreteFailure(..)
435 | RegionResolutionError::SubSupConflict(..)
436 | RegionResolutionError::MemberConstraintFailure { .. } => false,
439 let mut errors = if errors.iter().all(|e| is_bound_failure(e)) {
444 .filter(|&e| !is_bound_failure(e))
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,
459 /// Adds a note if the types come from similarly named crates
460 fn check_and_note_conflicting_crates(
462 err: &mut DiagnosticBuilder<'_>,
463 terr: &TypeError<'tcx>,
466 use hir::def_id::CrateNum;
467 use hir::map::DisambiguatedDefPathData;
468 use ty::print::Printer;
469 use ty::subst::GenericArg;
471 struct AbsolutePathPrinter<'tcx> {
475 struct NonTrivialPath;
477 impl<'tcx> Printer<'tcx> for AbsolutePathPrinter<'tcx> {
478 type Error = NonTrivialPath;
480 type Path = Vec<String>;
483 type DynExistential = !;
486 fn tcx<'a>(&'a self) -> TyCtxt<'tcx> {
492 _region: ty::Region<'_>,
493 ) -> Result<Self::Region, Self::Error> {
500 ) -> Result<Self::Type, Self::Error> {
504 fn print_dyn_existential(
506 _predicates: &'tcx ty::List<ty::ExistentialPredicate<'tcx>>,
507 ) -> Result<Self::DynExistential, Self::Error> {
513 _ct: &'tcx ty::Const<'tcx>,
514 ) -> Result<Self::Const, Self::Error> {
521 ) -> Result<Self::Path, Self::Error> {
522 Ok(vec![self.tcx.original_crate_name(cnum).to_string()])
527 _trait_ref: Option<ty::TraitRef<'tcx>>,
528 ) -> Result<Self::Path, Self::Error> {
534 _print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
535 _disambiguated_data: &DisambiguatedDefPathData,
537 _trait_ref: Option<ty::TraitRef<'tcx>>,
538 ) -> Result<Self::Path, Self::Error> {
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());
550 fn path_generic_args(
552 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
553 _args: &[GenericArg<'tcx>],
554 ) -> Result<Self::Path, Self::Error> {
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, &[])
568 // We compare strings because DefPath can be different
569 // for imported and non-imported crates
570 let same_path = || -> Result<_, NonTrivialPath> {
572 self.tcx.def_path_str(did1) == self.tcx.def_path_str(did2) ||
573 abs_path(did1)? == abs_path(did2)?
576 if same_path().unwrap_or(false) {
577 let crate_name = self.tcx.crate_name(did1.krate);
581 "Perhaps two different versions \
582 of crate `{}` are being used?",
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)
596 report_path_match(err, exp_adt.did, found_adt.did);
599 TypeError::Traits(ref exp_found) => {
600 report_path_match(err, exp_found.expected, exp_found.found);
602 _ => (), // FIXME(#22750) handle traits and stuff
606 fn note_error_origin(
608 err: &mut DiagnosticBuilder<'tcx>,
609 cause: &ObligationCause<'tcx>,
610 exp_found: Option<ty::error::ExpectedFound<Ty<'tcx>>>,
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));
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) {
622 "consider dereferencing the boxed value",
623 format!("*{}", snippet),
624 Applicability::MachineApplicable,
630 ObligationCauseCode::MatchExpressionArm(box MatchExpressionArmCause {
637 hir::MatchSource::IfLetDesugar { .. } => {
638 let msg = "`if let` arms have incompatible types";
639 err.span_label(cause.span, msg);
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)
650 bug!("try desugaring w/out call expr as discriminant");
654 Some(ty) if expected == ty => {
655 let source_map = self.tcx.sess.source_map();
657 source_map.end_point(cause.span),
658 "try removing this `?`",
660 Applicability::MachineApplicable,
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,
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));
679 } else if let Some(sp) = prior_arms.last() {
682 format!("this and all prior arms are found to be of type `{}`", t),
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(
693 "consider removing this semicolon",
695 Applicability::MachineApplicable,
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`.
709 /// ^^^^--------^ this is highlighted
711 /// | this type argument is exactly the same as the other type, not highlighted
712 /// this is highlighted
714 /// -------- this type is the same as a type argument in the other type, not highlighted
718 value: &mut DiagnosticStyledString,
719 other_value: &mut DiagnosticStyledString,
721 sub: ty::subst::SubstsRef<'tcx>,
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);
730 value.push_highlighted("<");
733 // Output the lifetimes for the first type
734 let lifetimes = sub.regions()
736 let s = lifetime.to_string();
745 if !lifetimes.is_empty() {
746 if sub.regions().count() < len {
747 value.push_normal(lifetimes + &", ");
749 value.push_normal(lifetimes);
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() {
757 let values = self.cmp(type_arg, other_ty);
758 value.0.extend((values.0).0);
759 other_value.0.extend((values.1).0);
761 value.push_highlighted(type_arg.to_string());
764 if len > 0 && i != len - 1 {
765 value.push_normal(", ");
767 //self.push_comma(&mut value, &mut other_value, len, i);
770 value.push_highlighted(">");
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.
777 /// For the following code:
780 /// let x: Foo<Bar<Qux>> = foo::<Bar<Qux>>();
783 /// The type error output will behave in the following way:
787 /// ^^^^--------^ this is highlighted
789 /// | this type argument is exactly the same as the other type, not highlighted
790 /// this is highlighted
792 /// -------- this type is the same as a type argument in the other type, not highlighted
796 mut t1_out: &mut DiagnosticStyledString,
797 mut t2_out: &mut DiagnosticStyledString,
799 sub: ty::subst::SubstsRef<'tcx>,
803 for (i, ta) in sub.types().enumerate() {
805 self.highlight_outer(&mut t1_out, &mut t2_out, path, sub, i, &other_ty);
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);
819 /// Adds a `,` to the type representation only if it is appropriate.
822 value: &mut DiagnosticStyledString,
823 other_value: &mut DiagnosticStyledString,
827 if len > 0 && pos != len - 1 {
828 value.push_normal(", ");
829 other_value.push_normal(", ");
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(
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)
848 let has_default = type_params.peek().map(|(_, has_default)| has_default);
849 *has_default.unwrap_or(&false)
852 let types = substs.types().rev();
853 for ((def_id, has_default), actual) in type_params.zip(types) {
857 if self.tcx.type_of(def_id).subst(self.tcx, substs) != actual {
860 num_supplied_defaults += 1;
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)
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);
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(_))) => {
890 fn push_ty_ref<'tcx>(
891 r: &ty::Region<'tcx>,
893 mutbl: hir::Mutability,
894 s: &mut DiagnosticStyledString,
896 let mut r = r.to_string();
902 s.push_highlighted(format!("&{}{}", r, mutbl.prefix_str()));
903 s.push_normal(ty.to_string());
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>>();
920 // --- ^ type argument elided
922 // highlighted in output
923 values.0.push_normal(path1);
924 values.1.push_normal(path2);
926 // Avoid printing out default generic parameters that are common to both
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
936 .zip(remainder2.iter().rev())
937 .filter(|(a, b)| a == b)
939 let len = sub1.len() - common_default_params;
940 let consts_offset = len - sub1.consts().count();
942 // Only draw `<...>` if there're lifetime/type arguments.
944 values.0.push_normal("<");
945 values.1.push_normal("<");
948 fn lifetime_display(lifetime: Region<'_>) -> String {
949 let s = lifetime.to_string();
956 // At one point we'd like to elide all lifetimes here, they are irrelevant for
957 // all diagnostics that use this output
961 // ^^ ^^ --- type arguments are not elided
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);
970 values.0.push_normal("'_");
971 values.1.push_normal("'_");
973 values.0.push_highlighted(l1);
974 values.1.push_highlighted(l2);
976 self.push_comma(&mut values.0, &mut values.1, len, i);
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
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;
991 values.0.push_normal("_");
992 values.1.push_normal("_");
994 let (x1, x2) = self.cmp(ta1, ta2);
995 (values.0).0.extend(x1.0);
996 (values.1).0.extend(x2.0);
998 self.push_comma(&mut values.0, &mut values.1, len, i);
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;
1007 values.0.push_normal("_");
1008 values.1.push_normal("_");
1010 values.0.push_highlighted(ca1.to_string());
1011 values.1.push_highlighted(ca2.to_string());
1013 self.push_comma(&mut values.0, &mut values.1, len, i);
1016 // Close the type argument bracket.
1017 // Only draw `<...>` if there're lifetime/type arguments.
1019 values.0.push_normal(">");
1020 values.1.push_normal(">");
1025 // let x: Foo<Bar<Qux> = foo::<Bar<Qux>>();
1027 // ------- this type argument is exactly the same as the other type
1029 if self.cmp_type_arg(
1041 // let x: Bar<Qux> = y:<Foo<Bar<Qux>>>();
1044 // ------- this type argument is exactly the same as the other type
1045 if self.cmp_type_arg(
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
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());
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)
1076 debug!("cmp: separator_len={}, split_idx={}, min_len={}",
1077 separator_len, split_idx, min_len
1080 if split_idx >= min_len {
1081 // paths are identical, highlight everything
1083 DiagnosticStyledString::highlighted(t1_str),
1084 DiagnosticStyledString::highlighted(t2_str)
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);
1091 values.0.push_normal(common);
1092 values.0.push_highlighted(uniq1);
1093 values.1.push_normal(common);
1094 values.1.push_highlighted(uniq2);
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());
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);
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) =>
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);
1127 // The two types are the same, elide and don't highlight.
1129 DiagnosticStyledString::normal("_"),
1130 DiagnosticStyledString::normal("_"),
1133 // We couldn't find anything in common, highlight everything.
1135 DiagnosticStyledString::highlighted(t1.to_string()),
1136 DiagnosticStyledString::highlighted(t2.to_string()),
1143 pub fn note_type_err(
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>,
1151 // For some types of errors, expected-found does not make
1152 // sense, so just ignore the values we were given.
1154 TypeError::CyclicTy(_) => {
1160 debug!("note_type_err(diag={:?})", diag);
1161 let (expected_found, exp_found, is_simple_error) = match values {
1162 None => (None, None, false),
1164 let (is_simple_error, exp_found) = match values {
1165 ValuePairs::Types(exp_found) => {
1167 exp_found.expected.is_primitive() && exp_found.found.is_primitive();
1169 (is_simple_err, Some(exp_found))
1173 let vals = match self.values_str(&values) {
1174 Some((expected, found)) => Some((expected, found)),
1176 // Derived error. Cancel the emitter.
1181 (vals, exp_found, is_simple_error)
1185 let span = cause.span(self.tcx);
1187 // Ignore msg for object safe coercion
1188 // since E0038 message will be printed
1190 TypeError::ObjectUnsafeCoercion(_) => {}
1192 diag.span_label(span, terr.to_string());
1193 if let Some((sp, msg)) = secondary_span {
1194 diag.span_label(sp, msg);
1199 if let Some((expected, found)) = expected_found {
1200 let expected_label = exp_found.map(|ef| ef.expected.prefix_string())
1201 .unwrap_or("type".into());
1202 let found_label = exp_found.map(|ef| ef.found.prefix_string())
1203 .unwrap_or("type".into());
1204 match (terr, is_simple_error, expected == found) {
1205 (&TypeError::Sorts(ref values), false, extra) => {
1206 let sort_string = |ty: Ty<'tcx>| match (extra, &ty.kind) {
1207 (true, ty::Opaque(def_id, _)) => format!(
1208 " (opaque type at {})",
1209 self.tcx.sess.source_map()
1210 .mk_substr_filename(self.tcx.def_span(*def_id)),
1212 (true, _) => format!(" ({})", ty.sort_string(self.tcx)),
1213 (false, _) => "".to_string(),
1215 diag.note_expected_found_extra(
1220 &sort_string(values.expected),
1221 &sort_string(values.found),
1224 (TypeError::ObjectUnsafeCoercion(_), ..) => {
1225 diag.note_unsuccessfull_coercion(found, expected);
1229 "note_type_err: exp_found={:?}, expected={:?} found={:?}",
1230 exp_found, expected, found
1232 diag.note_expected_found(&expected_label, expected, &found_label, found);
1237 if let Some(exp_found) = exp_found {
1238 self.suggest_as_ref_where_appropriate(span, &exp_found, diag);
1241 // In some (most?) cases cause.body_id points to actual body, but in some cases
1242 // it's a actual definition. According to the comments (e.g. in
1243 // librustc_typeck/check/compare_method.rs:compare_predicate_entailment) the latter
1244 // is relied upon by some other code. This might (or might not) need cleanup.
1245 let body_owner_def_id = self.tcx.hir().opt_local_def_id(cause.body_id)
1246 .unwrap_or_else(|| {
1247 self.tcx.hir().body_owner_def_id(hir::BodyId { hir_id: cause.body_id })
1249 self.check_and_note_conflicting_crates(diag, terr, span);
1250 self.tcx.note_and_explain_type_err(diag, terr, span, body_owner_def_id);
1252 // It reads better to have the error origin as the final
1254 self.note_error_origin(diag, &cause, exp_found);
1257 /// When encountering a case where `.as_ref()` on a `Result` or `Option` would be appropriate,
1259 fn suggest_as_ref_where_appropriate(
1262 exp_found: &ty::error::ExpectedFound<Ty<'tcx>>,
1263 diag: &mut DiagnosticBuilder<'tcx>,
1265 match (&exp_found.expected.kind, &exp_found.found.kind) {
1266 (ty::Adt(exp_def, exp_substs), ty::Ref(_, found_ty, _)) => {
1267 if let ty::Adt(found_def, found_substs) = found_ty.kind {
1268 let path_str = format!("{:?}", exp_def);
1269 if exp_def == &found_def {
1270 let opt_msg = "you can convert from `&Option<T>` to `Option<&T>` using \
1272 let result_msg = "you can convert from `&Result<T, E>` to \
1273 `Result<&T, &E>` using `.as_ref()`";
1274 let have_as_ref = &[
1275 ("std::option::Option", opt_msg),
1276 ("core::option::Option", opt_msg),
1277 ("std::result::Result", result_msg),
1278 ("core::result::Result", result_msg),
1280 if let Some(msg) = have_as_ref.iter()
1281 .filter_map(|(path, msg)| if &path_str == path {
1287 let mut show_suggestion = true;
1288 for (exp_ty, found_ty) in exp_substs.types().zip(found_substs.types()) {
1290 ty::Ref(_, exp_ty, _) => {
1291 match (&exp_ty.kind, &found_ty.kind) {
1295 (ty::Infer(_), _) => {}
1296 _ if ty::TyS::same_type(exp_ty, found_ty) => {}
1297 _ => show_suggestion = false,
1300 ty::Param(_) | ty::Infer(_) => {}
1301 _ => show_suggestion = false,
1304 if let (Ok(snippet), true) = (
1305 self.tcx.sess.source_map().span_to_snippet(span),
1308 diag.span_suggestion(
1311 format!("{}.as_ref()", snippet),
1312 Applicability::MachineApplicable,
1323 pub fn report_and_explain_type_error(
1325 trace: TypeTrace<'tcx>,
1326 terr: &TypeError<'tcx>,
1327 ) -> DiagnosticBuilder<'tcx> {
1329 "report_and_explain_type_error(trace={:?}, terr={:?})",
1333 let span = trace.cause.span(self.tcx);
1334 let failure_code = trace.cause.as_failure_code(terr);
1335 let mut diag = match failure_code {
1336 FailureCode::Error0038(did) => {
1337 let violations = self.tcx.object_safety_violations(did);
1338 self.tcx.report_object_safety_error(span, did, violations)
1340 FailureCode::Error0317(failure_str) => {
1341 struct_span_err!(self.tcx.sess, span, E0317, "{}", failure_str)
1343 FailureCode::Error0580(failure_str) => {
1344 struct_span_err!(self.tcx.sess, span, E0580, "{}", failure_str)
1346 FailureCode::Error0308(failure_str) => {
1347 struct_span_err!(self.tcx.sess, span, E0308, "{}", failure_str)
1349 FailureCode::Error0644(failure_str) => {
1350 struct_span_err!(self.tcx.sess, span, E0644, "{}", failure_str)
1353 self.note_type_err(&mut diag, &trace.cause, None, Some(trace.values), terr);
1359 values: &ValuePairs<'tcx>,
1360 ) -> Option<(DiagnosticStyledString, DiagnosticStyledString)> {
1362 infer::Types(ref exp_found) => self.expected_found_str_ty(exp_found),
1363 infer::Regions(ref exp_found) => self.expected_found_str(exp_found),
1364 infer::Consts(ref exp_found) => self.expected_found_str(exp_found),
1365 infer::TraitRefs(ref exp_found) => self.expected_found_str(exp_found),
1366 infer::PolyTraitRefs(ref exp_found) => self.expected_found_str(exp_found),
1370 fn expected_found_str_ty(
1372 exp_found: &ty::error::ExpectedFound<Ty<'tcx>>,
1373 ) -> Option<(DiagnosticStyledString, DiagnosticStyledString)> {
1374 let exp_found = self.resolve_vars_if_possible(exp_found);
1375 if exp_found.references_error() {
1379 Some(self.cmp(exp_found.expected, exp_found.found))
1382 /// Returns a string of the form "expected `{}`, found `{}`".
1383 fn expected_found_str<T: fmt::Display + TypeFoldable<'tcx>>(
1385 exp_found: &ty::error::ExpectedFound<T>,
1386 ) -> Option<(DiagnosticStyledString, DiagnosticStyledString)> {
1387 let exp_found = self.resolve_vars_if_possible(exp_found);
1388 if exp_found.references_error() {
1393 DiagnosticStyledString::highlighted(exp_found.expected.to_string()),
1394 DiagnosticStyledString::highlighted(exp_found.found.to_string()),
1398 pub fn report_generic_bound_failure(
1400 region_scope_tree: ®ion::ScopeTree,
1402 origin: Option<SubregionOrigin<'tcx>>,
1403 bound_kind: GenericKind<'tcx>,
1406 self.construct_generic_bound_failure(region_scope_tree, span, origin, bound_kind, sub)
1410 pub fn construct_generic_bound_failure(
1412 region_scope_tree: ®ion::ScopeTree,
1414 origin: Option<SubregionOrigin<'tcx>>,
1415 bound_kind: GenericKind<'tcx>,
1417 ) -> DiagnosticBuilder<'a> {
1418 // Attempt to obtain the span of the parameter so we can
1419 // suggest adding an explicit lifetime bound to it.
1420 let type_param_span = match (self.in_progress_tables, bound_kind) {
1421 (Some(ref table), GenericKind::Param(ref param)) => {
1422 let table = table.borrow();
1423 table.local_id_root.and_then(|did| {
1424 let generics = self.tcx.generics_of(did);
1425 // Account for the case where `did` corresponds to `Self`, which doesn't have
1426 // the expected type argument.
1427 if !(generics.has_self && param.index == 0) {
1428 let type_param = generics.type_param(param, self.tcx);
1429 let hir = &self.tcx.hir();
1430 hir.as_local_hir_id(type_param.def_id).map(|id| {
1431 // Get the `hir::Param` to verify whether it already has any bounds.
1432 // We do this to avoid suggesting code that ends up as `T: 'a'b`,
1433 // instead we suggest `T: 'a + 'b` in that case.
1434 let mut has_bounds = false;
1435 if let Node::GenericParam(param) = hir.get(id) {
1436 has_bounds = !param.bounds.is_empty();
1438 let sp = hir.span(id);
1439 // `sp` only covers `T`, change it so that it covers
1440 // `T:` when appropriate
1441 let is_impl_trait = bound_kind.to_string().starts_with("impl ");
1442 let sp = if has_bounds && !is_impl_trait {
1446 .next_point(self.tcx.sess.source_map().next_point(sp)))
1450 (sp, has_bounds, is_impl_trait)
1460 let labeled_user_string = match bound_kind {
1461 GenericKind::Param(ref p) => format!("the parameter type `{}`", p),
1462 GenericKind::Projection(ref p) => format!("the associated type `{}`", p),
1465 if let Some(SubregionOrigin::CompareImplMethodObligation {
1472 return self.report_extra_impl_obligation(
1477 &format!("`{}: {}`", bound_kind, sub),
1481 fn binding_suggestion<'tcx, S: fmt::Display>(
1482 err: &mut DiagnosticBuilder<'tcx>,
1483 type_param_span: Option<(Span, bool, bool)>,
1484 bound_kind: GenericKind<'tcx>,
1487 let consider = format!(
1488 "consider adding an explicit lifetime bound {}",
1489 if type_param_span.map(|(_, _, is_impl_trait)| is_impl_trait).unwrap_or(false) {
1490 format!(" `{}` to `{}`...", sub, bound_kind)
1492 format!("`{}: {}`...", bound_kind, sub)
1495 if let Some((sp, has_lifetimes, is_impl_trait)) = type_param_span {
1496 let suggestion = if is_impl_trait {
1497 format!("{} + {}", bound_kind, sub)
1499 let tail = if has_lifetimes { " + " } else { "" };
1500 format!("{}: {}{}", bound_kind, sub, tail)
1502 err.span_suggestion_short(
1506 Applicability::MaybeIncorrect, // Issue #41966
1509 err.help(&consider);
1513 let mut err = match *sub {
1515 | ty::ReFree(ty::FreeRegion {
1516 bound_region: ty::BrNamed(..),
1519 // Does the required lifetime have a nice name we can print?
1520 let mut err = struct_span_err!(
1524 "{} may not live long enough",
1527 binding_suggestion(&mut err, type_param_span, bound_kind, sub);
1532 // Does the required lifetime have a nice name we can print?
1533 let mut err = struct_span_err!(
1537 "{} may not live long enough",
1540 binding_suggestion(&mut err, type_param_span, bound_kind, "'static");
1545 // If not, be less specific.
1546 let mut err = struct_span_err!(
1550 "{} may not live long enough",
1554 "consider adding an explicit lifetime bound for `{}`",
1557 self.tcx.note_and_explain_region(
1560 &format!("{} must be valid for ", labeled_user_string),
1568 if let Some(origin) = origin {
1569 self.note_region_origin(&mut err, &origin);
1574 fn report_sub_sup_conflict(
1576 region_scope_tree: ®ion::ScopeTree,
1577 var_origin: RegionVariableOrigin,
1578 sub_origin: SubregionOrigin<'tcx>,
1579 sub_region: Region<'tcx>,
1580 sup_origin: SubregionOrigin<'tcx>,
1581 sup_region: Region<'tcx>,
1583 let mut err = self.report_inference_failure(var_origin);
1585 self.tcx.note_and_explain_region(
1588 "first, the lifetime cannot outlive ",
1593 match (&sup_origin, &sub_origin) {
1594 (&infer::Subtype(ref sup_trace), &infer::Subtype(ref sub_trace)) => {
1595 debug!("report_sub_sup_conflict: var_origin={:?}", var_origin);
1596 debug!("report_sub_sup_conflict: sub_region={:?}", sub_region);
1597 debug!("report_sub_sup_conflict: sub_origin={:?}", sub_origin);
1598 debug!("report_sub_sup_conflict: sup_region={:?}", sup_region);
1599 debug!("report_sub_sup_conflict: sup_origin={:?}", sup_origin);
1600 debug!("report_sub_sup_conflict: sup_trace={:?}", sup_trace);
1601 debug!("report_sub_sup_conflict: sub_trace={:?}", sub_trace);
1602 debug!("report_sub_sup_conflict: sup_trace.values={:?}", sup_trace.values);
1603 debug!("report_sub_sup_conflict: sub_trace.values={:?}", sub_trace.values);
1605 if let (Some((sup_expected, sup_found)), Some((sub_expected, sub_found))) = (
1606 self.values_str(&sup_trace.values),
1607 self.values_str(&sub_trace.values),
1609 if sub_expected == sup_expected && sub_found == sup_found {
1610 self.tcx.note_and_explain_region(
1613 "...but the lifetime must also be valid for ",
1618 "...so that the {}:\nexpected {}\n found {}",
1619 sup_trace.cause.as_requirement_str(),
1620 sup_expected.content(),
1631 self.note_region_origin(&mut err, &sup_origin);
1633 self.tcx.note_and_explain_region(
1636 "but, the lifetime must be valid for ",
1641 self.note_region_origin(&mut err, &sub_origin);
1646 impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
1647 fn report_inference_failure(
1649 var_origin: RegionVariableOrigin,
1650 ) -> DiagnosticBuilder<'tcx> {
1651 let br_string = |br: ty::BoundRegion| {
1652 let mut s = match br {
1653 ty::BrNamed(_, name) => name.to_string(),
1661 let var_description = match var_origin {
1662 infer::MiscVariable(_) => String::new(),
1663 infer::PatternRegion(_) => " for pattern".to_string(),
1664 infer::AddrOfRegion(_) => " for borrow expression".to_string(),
1665 infer::Autoref(_) => " for autoref".to_string(),
1666 infer::Coercion(_) => " for automatic coercion".to_string(),
1667 infer::LateBoundRegion(_, br, infer::FnCall) => {
1668 format!(" for lifetime parameter {}in function call", br_string(br))
1670 infer::LateBoundRegion(_, br, infer::HigherRankedType) => {
1671 format!(" for lifetime parameter {}in generic type", br_string(br))
1673 infer::LateBoundRegion(_, br, infer::AssocTypeProjection(def_id)) => format!(
1674 " for lifetime parameter {}in trait containing associated type `{}`",
1676 self.tcx.associated_item(def_id).ident
1678 infer::EarlyBoundRegion(_, name) => format!(" for lifetime parameter `{}`", name),
1679 infer::BoundRegionInCoherence(name) => {
1680 format!(" for lifetime parameter `{}` in coherence check", name)
1682 infer::UpvarRegion(ref upvar_id, _) => {
1683 let var_name = self.tcx.hir().name(upvar_id.var_path.hir_id);
1684 format!(" for capture of `{}` by closure", var_name)
1686 infer::NLL(..) => bug!("NLL variable found in lexical phase"),
1693 "cannot infer an appropriate lifetime{} \
1694 due to conflicting requirements",
1702 Error0317(&'static str),
1703 Error0580(&'static str),
1704 Error0308(&'static str),
1705 Error0644(&'static str),
1708 impl<'tcx> ObligationCause<'tcx> {
1709 fn as_failure_code(&self, terr: &TypeError<'tcx>) -> FailureCode {
1710 use self::FailureCode::*;
1711 use crate::traits::ObligationCauseCode::*;
1713 CompareImplMethodObligation { .. } => Error0308("method not compatible with trait"),
1714 MatchExpressionArm(box MatchExpressionArmCause { source, .. }) =>
1715 Error0308(match source {
1716 hir::MatchSource::IfLetDesugar { .. } =>
1717 "`if let` arms have incompatible types",
1718 hir::MatchSource::TryDesugar => {
1719 "try expression alternatives have incompatible types"
1721 _ => "match arms have incompatible types",
1723 IfExpression { .. } => Error0308("if and else have incompatible types"),
1724 IfExpressionWithNoElse => Error0317("if may be missing an else clause"),
1725 MainFunctionType => Error0580("main function has wrong type"),
1726 StartFunctionType => Error0308("start function has wrong type"),
1727 IntrinsicType => Error0308("intrinsic has wrong type"),
1728 MethodReceiver => Error0308("mismatched `self` parameter type"),
1730 // In the case where we have no more specific thing to
1731 // say, also take a look at the error code, maybe we can
1734 TypeError::CyclicTy(ty) if ty.is_closure() || ty.is_generator() => {
1735 Error0644("closure/generator type that references itself")
1737 TypeError::IntrinsicCast => {
1738 Error0308("cannot coerce intrinsics to function pointers")
1740 TypeError::ObjectUnsafeCoercion(did) => Error0038(did.clone()),
1741 _ => Error0308("mismatched types"),
1746 fn as_requirement_str(&self) -> &'static str {
1747 use crate::traits::ObligationCauseCode::*;
1749 CompareImplMethodObligation { .. } => "method type is compatible with trait",
1750 ExprAssignable => "expression is assignable",
1751 MatchExpressionArm(box MatchExpressionArmCause { source, .. }) => match source {
1752 hir::MatchSource::IfLetDesugar { .. } => "`if let` arms have compatible types",
1753 _ => "match arms have compatible types",
1755 IfExpression { .. } => "if and else have incompatible types",
1756 IfExpressionWithNoElse => "if missing an else returns ()",
1757 MainFunctionType => "`main` function has the correct type",
1758 StartFunctionType => "`start` function has the correct type",
1759 IntrinsicType => "intrinsic has the correct type",
1760 MethodReceiver => "method receiver has the correct type",
1761 _ => "types are compatible",