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};
53 use crate::infer::error_reporting::nice_region_error::find_anon_type::find_anon_type;
54 use crate::traits::error_reporting::report_object_safety_error;
56 IfExpressionCause, MatchExpressionArmCause, ObligationCause, ObligationCauseCode,
57 StatementAsExpression,
60 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
61 use rustc_errors::{pluralize, struct_span_err};
62 use rustc_errors::{Applicability, DiagnosticBuilder, DiagnosticStyledString};
64 use rustc_hir::def_id::DefId;
65 use rustc_hir::lang_items::LangItem;
66 use rustc_hir::{Item, ItemKind, Node};
67 use rustc_middle::dep_graph::DepContext;
68 use rustc_middle::ty::error::TypeError;
69 use rustc_middle::ty::{
71 subst::{GenericArgKind, Subst, SubstsRef},
72 Region, Ty, TyCtxt, TypeFoldable,
74 use rustc_span::{sym, BytePos, DesugaringKind, Pos, Span};
75 use rustc_target::spec::abi;
76 use std::ops::ControlFlow;
77 use std::{cmp, fmt, iter};
82 pub use need_type_info::TypeAnnotationNeeded;
84 pub mod nice_region_error;
86 pub(super) fn note_and_explain_region(
88 err: &mut DiagnosticBuilder<'_>,
90 region: ty::Region<'tcx>,
93 let (description, span) = match *region {
94 ty::ReEarlyBound(_) | ty::ReFree(_) | ty::ReStatic => {
95 msg_span_from_free_region(tcx, region)
98 ty::ReEmpty(ty::UniverseIndex::ROOT) => ("the empty lifetime".to_owned(), None),
100 // uh oh, hope no user ever sees THIS
101 ty::ReEmpty(ui) => (format!("the empty lifetime in universe {:?}", ui), None),
103 ty::RePlaceholder(_) => return,
105 // FIXME(#13998) RePlaceholder should probably print like
106 // ReFree rather than dumping Debug output on the user.
108 // We shouldn't really be having unification failures with ReVar
109 // and ReLateBound though.
110 ty::ReVar(_) | ty::ReLateBound(..) | ty::ReErased => {
111 (format!("lifetime {:?}", region), None)
115 emit_msg_span(err, prefix, description, span, suffix);
118 pub(super) fn note_and_explain_free_region(
120 err: &mut DiagnosticBuilder<'_>,
122 region: ty::Region<'tcx>,
125 let (description, span) = msg_span_from_free_region(tcx, region);
127 emit_msg_span(err, prefix, description, span, suffix);
130 fn msg_span_from_free_region(
132 region: ty::Region<'tcx>,
133 ) -> (String, Option<Span>) {
135 ty::ReEarlyBound(_) | ty::ReFree(_) => {
136 msg_span_from_early_bound_and_free_regions(tcx, region)
138 ty::ReStatic => ("the static lifetime".to_owned(), None),
139 ty::ReEmpty(ty::UniverseIndex::ROOT) => ("an empty lifetime".to_owned(), None),
140 ty::ReEmpty(ui) => (format!("an empty lifetime in universe {:?}", ui), None),
141 _ => bug!("{:?}", region),
145 fn msg_span_from_early_bound_and_free_regions(
147 region: ty::Region<'tcx>,
148 ) -> (String, Option<Span>) {
149 let sm = tcx.sess.source_map();
151 let scope = region.free_region_binding_scope(tcx);
152 let node = tcx.hir().local_def_id_to_hir_id(scope.expect_local());
153 let tag = match tcx.hir().find(node) {
154 Some(Node::Block(_) | Node::Expr(_)) => "body",
155 Some(Node::Item(it)) => item_scope_tag(&it),
156 Some(Node::TraitItem(it)) => trait_item_scope_tag(&it),
157 Some(Node::ImplItem(it)) => impl_item_scope_tag(&it),
158 Some(Node::ForeignItem(it)) => foreign_item_scope_tag(&it),
161 let (prefix, span) = match *region {
162 ty::ReEarlyBound(ref br) => {
163 let mut sp = sm.guess_head_span(tcx.hir().span(node));
165 tcx.hir().get_generics(scope).and_then(|generics| generics.get_named(br.name))
169 (format!("the lifetime `{}` as defined on", br.name), sp)
171 ty::ReFree(ty::FreeRegion {
172 bound_region: ty::BoundRegionKind::BrNamed(_, name), ..
174 let mut sp = sm.guess_head_span(tcx.hir().span(node));
176 tcx.hir().get_generics(scope).and_then(|generics| generics.get_named(name))
180 (format!("the lifetime `{}` as defined on", name), sp)
182 ty::ReFree(ref fr) => match fr.bound_region {
184 if let Some((ty, _)) = find_anon_type(tcx, region, &fr.bound_region) {
185 ("the anonymous lifetime defined on".to_string(), ty.span)
188 format!("the anonymous lifetime #{} defined on", idx + 1),
189 tcx.hir().span(node),
194 format!("the lifetime `{}` as defined on", region),
195 sm.guess_head_span(tcx.hir().span(node)),
200 let (msg, opt_span) = explain_span(tcx, tag, span);
201 (format!("{} {}", prefix, msg), opt_span)
205 err: &mut DiagnosticBuilder<'_>,
211 let message = format!("{}{}{}", prefix, description, suffix);
213 if let Some(span) = span {
214 err.span_note(span, &message);
220 fn item_scope_tag(item: &hir::Item<'_>) -> &'static str {
222 hir::ItemKind::Impl { .. } => "impl",
223 hir::ItemKind::Struct(..) => "struct",
224 hir::ItemKind::Union(..) => "union",
225 hir::ItemKind::Enum(..) => "enum",
226 hir::ItemKind::Trait(..) => "trait",
227 hir::ItemKind::Fn(..) => "function body",
232 fn trait_item_scope_tag(item: &hir::TraitItem<'_>) -> &'static str {
234 hir::TraitItemKind::Fn(..) => "method body",
235 hir::TraitItemKind::Const(..) | hir::TraitItemKind::Type(..) => "associated item",
239 fn impl_item_scope_tag(item: &hir::ImplItem<'_>) -> &'static str {
241 hir::ImplItemKind::Fn(..) => "method body",
242 hir::ImplItemKind::Const(..) | hir::ImplItemKind::TyAlias(..) => "associated item",
246 fn foreign_item_scope_tag(item: &hir::ForeignItem<'_>) -> &'static str {
248 hir::ForeignItemKind::Fn(..) => "method body",
249 hir::ForeignItemKind::Static(..) | hir::ForeignItemKind::Type => "associated item",
253 fn explain_span(tcx: TyCtxt<'tcx>, heading: &str, span: Span) -> (String, Option<Span>) {
254 let lo = tcx.sess.source_map().lookup_char_pos(span.lo());
255 (format!("the {} at {}:{}", heading, lo.line, lo.col.to_usize() + 1), Some(span))
258 pub fn unexpected_hidden_region_diagnostic(
262 hidden_region: ty::Region<'tcx>,
263 ) -> DiagnosticBuilder<'tcx> {
264 let mut err = struct_span_err!(
268 "hidden type for `impl Trait` captures lifetime that does not appear in bounds",
271 // Explain the region we are capturing.
272 match hidden_region {
273 ty::ReEmpty(ty::UniverseIndex::ROOT) => {
274 // All lifetimes shorter than the function body are `empty` in
275 // lexical region resolution. The default explanation of "an empty
276 // lifetime" isn't really accurate here.
277 let message = format!(
278 "hidden type `{}` captures lifetime smaller than the function body",
281 err.span_note(span, &message);
283 ty::ReEarlyBound(_) | ty::ReFree(_) | ty::ReStatic | ty::ReEmpty(_) => {
284 // Assuming regionck succeeded (*), we ought to always be
285 // capturing *some* region from the fn header, and hence it
286 // ought to be free. So under normal circumstances, we will go
287 // down this path which gives a decent human readable
290 // (*) if not, the `tainted_by_errors` field would be set to
291 // `Some(ErrorReported)` in any case, so we wouldn't be here at all.
292 note_and_explain_free_region(
295 &format!("hidden type `{}` captures ", hidden_ty),
301 // Ugh. This is a painful case: the hidden region is not one
302 // that we can easily summarize or explain. This can happen
304 // `src/test/ui/multiple-lifetimes/ordinary-bounds-unsuited.rs`:
307 // fn upper_bounds<'a, 'b>(a: Ordinary<'a>, b: Ordinary<'b>) -> impl Trait<'a, 'b> {
308 // if condition() { a } else { b }
312 // Here the captured lifetime is the intersection of `'a` and
313 // `'b`, which we can't quite express.
315 // We can at least report a really cryptic error for now.
316 note_and_explain_region(
319 &format!("hidden type `{}` captures ", hidden_ty),
329 impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
330 pub fn report_region_errors(&self, errors: &Vec<RegionResolutionError<'tcx>>) {
331 debug!("report_region_errors(): {} errors to start", errors.len());
333 // try to pre-process the errors, which will group some of them
334 // together into a `ProcessedErrors` group:
335 let errors = self.process_errors(errors);
337 debug!("report_region_errors: {} errors after preprocessing", errors.len());
339 for error in errors {
340 debug!("report_region_errors: error = {:?}", error);
342 if !self.try_report_nice_region_error(&error) {
343 match error.clone() {
344 // These errors could indicate all manner of different
345 // problems with many different solutions. Rather
346 // than generate a "one size fits all" error, what we
347 // attempt to do is go through a number of specific
348 // scenarios and try to find the best way to present
349 // the error. If all of these fails, we fall back to a rather
350 // general bit of code that displays the error information
351 RegionResolutionError::ConcreteFailure(origin, sub, sup) => {
352 if sub.is_placeholder() || sup.is_placeholder() {
353 self.report_placeholder_failure(origin, sub, sup).emit();
355 self.report_concrete_failure(origin, sub, sup).emit();
359 RegionResolutionError::GenericBoundFailure(origin, param_ty, sub) => {
360 self.report_generic_bound_failure(
368 RegionResolutionError::SubSupConflict(
376 if sub_r.is_placeholder() {
377 self.report_placeholder_failure(sub_origin, sub_r, sup_r).emit();
378 } else if sup_r.is_placeholder() {
379 self.report_placeholder_failure(sup_origin, sub_r, sup_r).emit();
381 self.report_sub_sup_conflict(
382 var_origin, sub_origin, sub_r, sup_origin, sup_r,
387 RegionResolutionError::UpperBoundUniverseConflict(
394 assert!(sup_r.is_placeholder());
396 // Make a dummy value for the "sub region" --
397 // this is the initial value of the
398 // placeholder. In practice, we expect more
399 // tailored errors that don't really use this
401 let sub_r = self.tcx.mk_region(ty::ReEmpty(var_universe));
403 self.report_placeholder_failure(sup_origin, sub_r, sup_r).emit();
406 RegionResolutionError::MemberConstraintFailure {
411 let hidden_ty = self.resolve_vars_if_possible(hidden_ty);
412 unexpected_hidden_region_diagnostic(
425 // This method goes through all the errors and try to group certain types
426 // of error together, for the purpose of suggesting explicit lifetime
427 // parameters to the user. This is done so that we can have a more
428 // complete view of what lifetimes should be the same.
429 // If the return value is an empty vector, it means that processing
430 // failed (so the return value of this method should not be used).
432 // The method also attempts to weed out messages that seem like
433 // duplicates that will be unhelpful to the end-user. But
434 // obviously it never weeds out ALL errors.
437 errors: &[RegionResolutionError<'tcx>],
438 ) -> Vec<RegionResolutionError<'tcx>> {
439 debug!("process_errors()");
441 // We want to avoid reporting generic-bound failures if we can
442 // avoid it: these have a very high rate of being unhelpful in
443 // practice. This is because they are basically secondary
444 // checks that test the state of the region graph after the
445 // rest of inference is done, and the other kinds of errors
446 // indicate that the region constraint graph is internally
447 // inconsistent, so these test results are likely to be
450 // Therefore, we filter them out of the list unless they are
451 // the only thing in the list.
453 let is_bound_failure = |e: &RegionResolutionError<'tcx>| match *e {
454 RegionResolutionError::GenericBoundFailure(..) => true,
455 RegionResolutionError::ConcreteFailure(..)
456 | RegionResolutionError::SubSupConflict(..)
457 | RegionResolutionError::UpperBoundUniverseConflict(..)
458 | RegionResolutionError::MemberConstraintFailure { .. } => false,
461 let mut errors = if errors.iter().all(|e| is_bound_failure(e)) {
464 errors.iter().filter(|&e| !is_bound_failure(e)).cloned().collect()
467 // sort the errors by span, for better error message stability.
468 errors.sort_by_key(|u| match *u {
469 RegionResolutionError::ConcreteFailure(ref sro, _, _) => sro.span(),
470 RegionResolutionError::GenericBoundFailure(ref sro, _, _) => sro.span(),
471 RegionResolutionError::SubSupConflict(_, ref rvo, _, _, _, _) => rvo.span(),
472 RegionResolutionError::UpperBoundUniverseConflict(_, ref rvo, _, _, _) => rvo.span(),
473 RegionResolutionError::MemberConstraintFailure { span, .. } => span,
478 /// Adds a note if the types come from similarly named crates
479 fn check_and_note_conflicting_crates(
481 err: &mut DiagnosticBuilder<'_>,
482 terr: &TypeError<'tcx>,
484 use hir::def_id::CrateNum;
485 use rustc_hir::definitions::DisambiguatedDefPathData;
486 use ty::print::Printer;
487 use ty::subst::GenericArg;
489 struct AbsolutePathPrinter<'tcx> {
493 struct NonTrivialPath;
495 impl<'tcx> Printer<'tcx> for AbsolutePathPrinter<'tcx> {
496 type Error = NonTrivialPath;
498 type Path = Vec<String>;
501 type DynExistential = !;
504 fn tcx<'a>(&'a self) -> TyCtxt<'tcx> {
508 fn print_region(self, _region: ty::Region<'_>) -> Result<Self::Region, Self::Error> {
512 fn print_type(self, _ty: Ty<'tcx>) -> Result<Self::Type, Self::Error> {
516 fn print_dyn_existential(
518 _predicates: &'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>,
519 ) -> Result<Self::DynExistential, Self::Error> {
523 fn print_const(self, _ct: &'tcx ty::Const<'tcx>) -> Result<Self::Const, Self::Error> {
527 fn path_crate(self, cnum: CrateNum) -> Result<Self::Path, Self::Error> {
528 Ok(vec![self.tcx.crate_name(cnum).to_string()])
533 _trait_ref: Option<ty::TraitRef<'tcx>>,
534 ) -> Result<Self::Path, Self::Error> {
540 _print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
541 _disambiguated_data: &DisambiguatedDefPathData,
543 _trait_ref: Option<ty::TraitRef<'tcx>>,
544 ) -> Result<Self::Path, Self::Error> {
549 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
550 disambiguated_data: &DisambiguatedDefPathData,
551 ) -> Result<Self::Path, Self::Error> {
552 let mut path = print_prefix(self)?;
553 path.push(disambiguated_data.to_string());
556 fn path_generic_args(
558 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
559 _args: &[GenericArg<'tcx>],
560 ) -> Result<Self::Path, Self::Error> {
565 let report_path_match = |err: &mut DiagnosticBuilder<'_>, did1: DefId, did2: DefId| {
566 // Only external crates, if either is from a local
567 // module we could have false positives
568 if !(did1.is_local() || did2.is_local()) && did1.krate != did2.krate {
570 |def_id| AbsolutePathPrinter { tcx: self.tcx }.print_def_path(def_id, &[]);
572 // We compare strings because DefPath can be different
573 // for imported and non-imported crates
574 let same_path = || -> Result<_, NonTrivialPath> {
575 Ok(self.tcx.def_path_str(did1) == self.tcx.def_path_str(did2)
576 || abs_path(did1)? == abs_path(did2)?)
578 if same_path().unwrap_or(false) {
579 let crate_name = self.tcx.crate_name(did1.krate);
581 "perhaps two different versions of crate `{}` are being used?",
588 TypeError::Sorts(ref exp_found) => {
589 // if they are both "path types", there's a chance of ambiguity
590 // due to different versions of the same crate
591 if let (&ty::Adt(exp_adt, _), &ty::Adt(found_adt, _)) =
592 (exp_found.expected.kind(), exp_found.found.kind())
594 report_path_match(err, exp_adt.did, found_adt.did);
597 TypeError::Traits(ref exp_found) => {
598 report_path_match(err, exp_found.expected, exp_found.found);
600 _ => (), // FIXME(#22750) handle traits and stuff
604 fn note_error_origin(
606 err: &mut DiagnosticBuilder<'tcx>,
607 cause: &ObligationCause<'tcx>,
608 exp_found: Option<ty::error::ExpectedFound<Ty<'tcx>>>,
611 ObligationCauseCode::Pattern { origin_expr: true, span: Some(span), root_ty } => {
612 let ty = self.resolve_vars_if_possible(root_ty);
613 if ty.is_suggestable() {
614 // don't show type `_`
615 err.span_label(span, format!("this 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::Pattern { origin_expr: false, span: Some(span), .. } => {
631 err.span_label(span, "expected due to this");
633 ObligationCauseCode::MatchExpressionArm(box MatchExpressionArmCause {
639 opt_suggest_box_span,
644 hir::MatchSource::IfLetDesugar { .. } => {
645 let msg = "`if let` arms have incompatible types";
646 err.span_label(cause.span, msg);
647 if let Some(ret_sp) = opt_suggest_box_span {
648 self.suggest_boxing_for_return_impl_trait(
651 prior_arms.iter().chain(std::iter::once(&arm_span)).map(|s| *s),
655 hir::MatchSource::TryDesugar => {
656 if let Some(ty::error::ExpectedFound { expected, .. }) = exp_found {
657 let scrut_expr = self.tcx.hir().expect_expr(scrut_hir_id);
658 let scrut_ty = if let hir::ExprKind::Call(_, args) = &scrut_expr.kind {
659 let arg_expr = args.first().expect("try desugaring call w/out arg");
660 self.in_progress_typeck_results.and_then(|typeck_results| {
661 typeck_results.borrow().expr_ty_opt(arg_expr)
664 bug!("try desugaring w/out call expr as scrutinee");
668 Some(ty) if expected == ty => {
669 let source_map = self.tcx.sess.source_map();
671 source_map.end_point(cause.span),
672 "try removing this `?`",
674 Applicability::MachineApplicable,
682 // `last_ty` can be `!`, `expected` will have better info when present.
683 let t = self.resolve_vars_if_possible(match exp_found {
684 Some(ty::error::ExpectedFound { expected, .. }) => expected,
687 let source_map = self.tcx.sess.source_map();
688 let mut any_multiline_arm = source_map.is_multiline(arm_span);
689 if prior_arms.len() <= 4 {
690 for sp in prior_arms {
691 any_multiline_arm |= source_map.is_multiline(*sp);
692 err.span_label(*sp, format!("this is found to be of type `{}`", t));
694 } else if let Some(sp) = prior_arms.last() {
695 any_multiline_arm |= source_map.is_multiline(*sp);
698 format!("this and all prior arms are found to be of type `{}`", t),
701 let outer_error_span = if any_multiline_arm {
702 // Cover just `match` and the scrutinee expression, not
703 // the entire match body, to reduce diagram noise.
704 cause.span.shrink_to_lo().to(scrut_span)
708 let msg = "`match` arms have incompatible types";
709 err.span_label(outer_error_span, msg);
710 if let Some((sp, boxed)) = semi_span {
711 if let (StatementAsExpression::NeedsBoxing, [.., prior_arm]) =
712 (boxed, &prior_arms[..])
714 err.multipart_suggestion(
715 "consider removing this semicolon and boxing the expressions",
717 (prior_arm.shrink_to_lo(), "Box::new(".to_string()),
718 (prior_arm.shrink_to_hi(), ")".to_string()),
719 (arm_span.shrink_to_lo(), "Box::new(".to_string()),
720 (arm_span.shrink_to_hi(), ")".to_string()),
723 Applicability::HasPlaceholders,
725 } else if matches!(boxed, StatementAsExpression::NeedsBoxing) {
726 err.span_suggestion_short(
728 "consider removing this semicolon and boxing the expressions",
730 Applicability::MachineApplicable,
733 err.span_suggestion_short(
735 "consider removing this semicolon",
737 Applicability::MachineApplicable,
741 if let Some(ret_sp) = opt_suggest_box_span {
742 // Get return type span and point to it.
743 self.suggest_boxing_for_return_impl_trait(
746 prior_arms.iter().chain(std::iter::once(&arm_span)).map(|s| *s),
751 ObligationCauseCode::IfExpression(box IfExpressionCause {
756 opt_suggest_box_span,
758 err.span_label(then, "expected because of this");
759 if let Some(sp) = outer {
760 err.span_label(sp, "`if` and `else` have incompatible types");
762 if let Some((sp, boxed)) = semicolon {
763 if matches!(boxed, StatementAsExpression::NeedsBoxing) {
764 err.multipart_suggestion(
765 "consider removing this semicolon and boxing the expression",
767 (then.shrink_to_lo(), "Box::new(".to_string()),
768 (then.shrink_to_hi(), ")".to_string()),
769 (else_sp.shrink_to_lo(), "Box::new(".to_string()),
770 (else_sp.shrink_to_hi(), ")".to_string()),
773 Applicability::MachineApplicable,
776 err.span_suggestion_short(
778 "consider removing this semicolon",
780 Applicability::MachineApplicable,
784 if let Some(ret_sp) = opt_suggest_box_span {
785 self.suggest_boxing_for_return_impl_trait(
788 vec![then, else_sp].into_iter(),
796 fn suggest_boxing_for_return_impl_trait(
798 err: &mut DiagnosticBuilder<'tcx>,
800 arm_spans: impl Iterator<Item = Span>,
802 err.multipart_suggestion(
803 "you could change the return type to be a boxed trait object",
805 (return_sp.with_hi(return_sp.lo() + BytePos(4)), "Box<dyn".to_string()),
806 (return_sp.shrink_to_hi(), ">".to_string()),
808 Applicability::MaybeIncorrect,
813 (sp.shrink_to_lo(), "Box::new(".to_string()),
814 (sp.shrink_to_hi(), ")".to_string()),
818 .collect::<Vec<_>>();
819 err.multipart_suggestion(
820 "if you change the return type to expect trait objects, box the returned expressions",
822 Applicability::MaybeIncorrect,
826 /// Given that `other_ty` is the same as a type argument for `name` in `sub`, populate `value`
827 /// highlighting `name` and every type argument that isn't at `pos` (which is `other_ty`), and
828 /// populate `other_value` with `other_ty`.
832 /// ^^^^--------^ this is highlighted
834 /// | this type argument is exactly the same as the other type, not highlighted
835 /// this is highlighted
837 /// -------- this type is the same as a type argument in the other type, not highlighted
841 value: &mut DiagnosticStyledString,
842 other_value: &mut DiagnosticStyledString,
844 sub: ty::subst::SubstsRef<'tcx>,
848 // `value` and `other_value` hold two incomplete type representation for display.
849 // `name` is the path of both types being compared. `sub`
850 value.push_highlighted(name);
853 value.push_highlighted("<");
856 // Output the lifetimes for the first type
860 let s = lifetime.to_string();
861 if s.is_empty() { "'_".to_string() } else { s }
865 if !lifetimes.is_empty() {
866 if sub.regions().count() < len {
867 value.push_normal(lifetimes + ", ");
869 value.push_normal(lifetimes);
873 // Highlight all the type arguments that aren't at `pos` and compare the type argument at
874 // `pos` and `other_ty`.
875 for (i, type_arg) in sub.types().enumerate() {
877 let values = self.cmp(type_arg, other_ty);
878 value.0.extend((values.0).0);
879 other_value.0.extend((values.1).0);
881 value.push_highlighted(type_arg.to_string());
884 if len > 0 && i != len - 1 {
885 value.push_normal(", ");
889 value.push_highlighted(">");
893 /// If `other_ty` is the same as a type argument present in `sub`, highlight `path` in `t1_out`,
894 /// as that is the difference to the other type.
896 /// For the following code:
899 /// let x: Foo<Bar<Qux>> = foo::<Bar<Qux>>();
902 /// The type error output will behave in the following way:
906 /// ^^^^--------^ this is highlighted
908 /// | this type argument is exactly the same as the other type, not highlighted
909 /// this is highlighted
911 /// -------- this type is the same as a type argument in the other type, not highlighted
915 mut t1_out: &mut DiagnosticStyledString,
916 mut t2_out: &mut DiagnosticStyledString,
918 sub: ty::subst::SubstsRef<'tcx>,
922 for (i, ta) in sub.types().enumerate() {
924 self.highlight_outer(&mut t1_out, &mut t2_out, path, sub, i, &other_ty);
927 if let ty::Adt(def, _) = ta.kind() {
928 let path_ = self.tcx.def_path_str(def.did);
929 if path_ == other_path {
930 self.highlight_outer(&mut t1_out, &mut t2_out, path, sub, i, &other_ty);
938 /// Adds a `,` to the type representation only if it is appropriate.
941 value: &mut DiagnosticStyledString,
942 other_value: &mut DiagnosticStyledString,
946 if len > 0 && pos != len - 1 {
947 value.push_normal(", ");
948 other_value.push_normal(", ");
952 /// For generic types with parameters with defaults, remove the parameters corresponding to
953 /// the defaults. This repeats a lot of the logic found in `ty::print::pretty`.
954 fn strip_generic_default_params(
957 substs: ty::subst::SubstsRef<'tcx>,
958 ) -> SubstsRef<'tcx> {
959 let generics = self.tcx.generics_of(def_id);
960 let mut num_supplied_defaults = 0;
962 let default_params = generics.params.iter().rev().filter_map(|param| match param.kind {
963 ty::GenericParamDefKind::Type { has_default: true, .. } => Some(param.def_id),
964 ty::GenericParamDefKind::Const { has_default: true } => Some(param.def_id),
967 for (def_id, actual) in iter::zip(default_params, substs.iter().rev()) {
968 match actual.unpack() {
969 GenericArgKind::Const(c) => {
970 if self.tcx.const_param_default(def_id).subst(self.tcx, substs) != c {
974 GenericArgKind::Type(ty) => {
975 if self.tcx.type_of(def_id).subst(self.tcx, substs) != ty {
981 num_supplied_defaults += 1;
983 let len = generics.params.len();
984 let mut generics = generics.clone();
985 generics.params.truncate(len - num_supplied_defaults);
986 substs.truncate_to(self.tcx, &generics)
989 /// Given two `fn` signatures highlight only sub-parts that are different.
992 sig1: &ty::PolyFnSig<'tcx>,
993 sig2: &ty::PolyFnSig<'tcx>,
994 ) -> (DiagnosticStyledString, DiagnosticStyledString) {
995 let get_lifetimes = |sig| {
996 use rustc_hir::def::Namespace;
997 let mut s = String::new();
998 let (_, sig, reg) = ty::print::FmtPrinter::new(self.tcx, &mut s, Namespace::TypeNS)
999 .name_all_regions(sig)
1001 let lts: Vec<String> = reg.into_iter().map(|(_, kind)| kind.to_string()).collect();
1002 (if lts.is_empty() { String::new() } else { format!("for<{}> ", lts.join(", ")) }, sig)
1005 let (lt1, sig1) = get_lifetimes(sig1);
1006 let (lt2, sig2) = get_lifetimes(sig2);
1008 // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
1010 DiagnosticStyledString::normal("".to_string()),
1011 DiagnosticStyledString::normal("".to_string()),
1014 // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
1016 values.0.push(sig1.unsafety.prefix_str(), sig1.unsafety != sig2.unsafety);
1017 values.1.push(sig2.unsafety.prefix_str(), sig1.unsafety != sig2.unsafety);
1019 // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
1021 if sig1.abi != abi::Abi::Rust {
1022 values.0.push(format!("extern {} ", sig1.abi), sig1.abi != sig2.abi);
1024 if sig2.abi != abi::Abi::Rust {
1025 values.1.push(format!("extern {} ", sig2.abi), sig1.abi != sig2.abi);
1028 // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
1030 let lifetime_diff = lt1 != lt2;
1031 values.0.push(lt1, lifetime_diff);
1032 values.1.push(lt2, lifetime_diff);
1034 // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
1036 values.0.push_normal("fn(");
1037 values.1.push_normal("fn(");
1039 // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
1041 let len1 = sig1.inputs().len();
1042 let len2 = sig2.inputs().len();
1044 for (i, (l, r)) in iter::zip(sig1.inputs(), sig2.inputs()).enumerate() {
1045 let (x1, x2) = self.cmp(l, r);
1046 (values.0).0.extend(x1.0);
1047 (values.1).0.extend(x2.0);
1048 self.push_comma(&mut values.0, &mut values.1, len1, i);
1051 for (i, l) in sig1.inputs().iter().enumerate() {
1052 values.0.push_highlighted(l.to_string());
1054 values.0.push_highlighted(", ");
1057 for (i, r) in sig2.inputs().iter().enumerate() {
1058 values.1.push_highlighted(r.to_string());
1060 values.1.push_highlighted(", ");
1065 if sig1.c_variadic {
1067 values.0.push_normal(", ");
1069 values.0.push("...", !sig2.c_variadic);
1071 if sig2.c_variadic {
1073 values.1.push_normal(", ");
1075 values.1.push("...", !sig1.c_variadic);
1078 // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
1080 values.0.push_normal(")");
1081 values.1.push_normal(")");
1083 // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
1085 let output1 = sig1.output();
1086 let output2 = sig2.output();
1087 let (x1, x2) = self.cmp(output1, output2);
1088 if !output1.is_unit() {
1089 values.0.push_normal(" -> ");
1090 (values.0).0.extend(x1.0);
1092 if !output2.is_unit() {
1093 values.1.push_normal(" -> ");
1094 (values.1).0.extend(x2.0);
1099 /// Compares two given types, eliding parts that are the same between them and highlighting
1100 /// relevant differences, and return two representation of those types for highlighted printing.
1101 fn cmp(&self, t1: Ty<'tcx>, t2: Ty<'tcx>) -> (DiagnosticStyledString, DiagnosticStyledString) {
1102 debug!("cmp(t1={}, t1.kind={:?}, t2={}, t2.kind={:?})", t1, t1.kind(), t2, t2.kind());
1105 fn equals<'tcx>(a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
1106 match (a.kind(), b.kind()) {
1107 (a, b) if *a == *b => true,
1108 (&ty::Int(_), &ty::Infer(ty::InferTy::IntVar(_)))
1110 &ty::Infer(ty::InferTy::IntVar(_)),
1111 &ty::Int(_) | &ty::Infer(ty::InferTy::IntVar(_)),
1113 | (&ty::Float(_), &ty::Infer(ty::InferTy::FloatVar(_)))
1115 &ty::Infer(ty::InferTy::FloatVar(_)),
1116 &ty::Float(_) | &ty::Infer(ty::InferTy::FloatVar(_)),
1122 fn push_ty_ref<'tcx>(
1123 region: &ty::Region<'tcx>,
1125 mutbl: hir::Mutability,
1126 s: &mut DiagnosticStyledString,
1128 let mut r = region.to_string();
1134 s.push_highlighted(format!("&{}{}", r, mutbl.prefix_str()));
1135 s.push_normal(ty.to_string());
1138 // process starts here
1139 match (t1.kind(), t2.kind()) {
1140 (&ty::Adt(def1, sub1), &ty::Adt(def2, sub2)) => {
1141 let sub_no_defaults_1 = self.strip_generic_default_params(def1.did, sub1);
1142 let sub_no_defaults_2 = self.strip_generic_default_params(def2.did, sub2);
1143 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
1144 let path1 = self.tcx.def_path_str(def1.did);
1145 let path2 = self.tcx.def_path_str(def2.did);
1146 if def1.did == def2.did {
1147 // Easy case. Replace same types with `_` to shorten the output and highlight
1148 // the differing ones.
1149 // let x: Foo<Bar, Qux> = y::<Foo<Quz, Qux>>();
1152 // --- ^ type argument elided
1154 // highlighted in output
1155 values.0.push_normal(path1);
1156 values.1.push_normal(path2);
1158 // Avoid printing out default generic parameters that are common to both
1160 let len1 = sub_no_defaults_1.len();
1161 let len2 = sub_no_defaults_2.len();
1162 let common_len = cmp::min(len1, len2);
1163 let remainder1: Vec<_> = sub1.types().skip(common_len).collect();
1164 let remainder2: Vec<_> = sub2.types().skip(common_len).collect();
1165 let common_default_params =
1166 iter::zip(remainder1.iter().rev(), remainder2.iter().rev())
1167 .filter(|(a, b)| a == b)
1169 let len = sub1.len() - common_default_params;
1170 let consts_offset = len - sub1.consts().count();
1172 // Only draw `<...>` if there're lifetime/type arguments.
1174 values.0.push_normal("<");
1175 values.1.push_normal("<");
1178 fn lifetime_display(lifetime: Region<'_>) -> String {
1179 let s = lifetime.to_string();
1180 if s.is_empty() { "'_".to_string() } else { s }
1182 // At one point we'd like to elide all lifetimes here, they are irrelevant for
1183 // all diagnostics that use this output
1187 // ^^ ^^ --- type arguments are not elided
1189 // | elided as they were the same
1190 // not elided, they were different, but irrelevant
1191 let lifetimes = sub1.regions().zip(sub2.regions());
1192 for (i, lifetimes) in lifetimes.enumerate() {
1193 let l1 = lifetime_display(lifetimes.0);
1194 let l2 = lifetime_display(lifetimes.1);
1195 if lifetimes.0 == lifetimes.1 {
1196 values.0.push_normal("'_");
1197 values.1.push_normal("'_");
1199 values.0.push_highlighted(l1);
1200 values.1.push_highlighted(l2);
1202 self.push_comma(&mut values.0, &mut values.1, len, i);
1205 // We're comparing two types with the same path, so we compare the type
1206 // arguments for both. If they are the same, do not highlight and elide from the
1210 // ^ elided type as this type argument was the same in both sides
1211 let type_arguments = sub1.types().zip(sub2.types());
1212 let regions_len = sub1.regions().count();
1213 let num_display_types = consts_offset - regions_len;
1214 for (i, (ta1, ta2)) in type_arguments.take(num_display_types).enumerate() {
1215 let i = i + regions_len;
1217 values.0.push_normal("_");
1218 values.1.push_normal("_");
1220 let (x1, x2) = self.cmp(ta1, ta2);
1221 (values.0).0.extend(x1.0);
1222 (values.1).0.extend(x2.0);
1224 self.push_comma(&mut values.0, &mut values.1, len, i);
1227 // Do the same for const arguments, if they are equal, do not highlight and
1228 // elide them from the output.
1229 let const_arguments = sub1.consts().zip(sub2.consts());
1230 for (i, (ca1, ca2)) in const_arguments.enumerate() {
1231 let i = i + consts_offset;
1233 values.0.push_normal("_");
1234 values.1.push_normal("_");
1236 values.0.push_highlighted(ca1.to_string());
1237 values.1.push_highlighted(ca2.to_string());
1239 self.push_comma(&mut values.0, &mut values.1, len, i);
1242 // Close the type argument bracket.
1243 // Only draw `<...>` if there're lifetime/type arguments.
1245 values.0.push_normal(">");
1246 values.1.push_normal(">");
1251 // let x: Foo<Bar<Qux> = foo::<Bar<Qux>>();
1253 // ------- this type argument is exactly the same as the other type
1269 // let x: Bar<Qux> = y:<Foo<Bar<Qux>>>();
1272 // ------- this type argument is exactly the same as the other type
1287 // We can't find anything in common, highlight relevant part of type path.
1288 // let x: foo::bar::Baz<Qux> = y:<foo::bar::Bar<Zar>>();
1289 // foo::bar::Baz<Qux>
1290 // foo::bar::Bar<Zar>
1291 // -------- this part of the path is different
1293 let t1_str = t1.to_string();
1294 let t2_str = t2.to_string();
1295 let min_len = t1_str.len().min(t2_str.len());
1297 const SEPARATOR: &str = "::";
1298 let separator_len = SEPARATOR.len();
1299 let split_idx: usize =
1300 iter::zip(t1_str.split(SEPARATOR), t2_str.split(SEPARATOR))
1301 .take_while(|(mod1_str, mod2_str)| mod1_str == mod2_str)
1302 .map(|(mod_str, _)| mod_str.len() + separator_len)
1306 "cmp: separator_len={}, split_idx={}, min_len={}",
1307 separator_len, split_idx, min_len
1310 if split_idx >= min_len {
1311 // paths are identical, highlight everything
1313 DiagnosticStyledString::highlighted(t1_str),
1314 DiagnosticStyledString::highlighted(t2_str),
1317 let (common, uniq1) = t1_str.split_at(split_idx);
1318 let (_, uniq2) = t2_str.split_at(split_idx);
1319 debug!("cmp: common={}, uniq1={}, uniq2={}", common, uniq1, uniq2);
1321 values.0.push_normal(common);
1322 values.0.push_highlighted(uniq1);
1323 values.1.push_normal(common);
1324 values.1.push_highlighted(uniq2);
1331 // When finding T != &T, highlight only the borrow
1332 (&ty::Ref(r1, ref_ty1, mutbl1), _) if equals(&ref_ty1, &t2) => {
1333 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
1334 push_ty_ref(&r1, ref_ty1, mutbl1, &mut values.0);
1335 values.1.push_normal(t2.to_string());
1338 (_, &ty::Ref(r2, ref_ty2, mutbl2)) if equals(&t1, &ref_ty2) => {
1339 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
1340 values.0.push_normal(t1.to_string());
1341 push_ty_ref(&r2, ref_ty2, mutbl2, &mut values.1);
1345 // When encountering &T != &mut T, highlight only the borrow
1346 (&ty::Ref(r1, ref_ty1, mutbl1), &ty::Ref(r2, ref_ty2, mutbl2))
1347 if equals(&ref_ty1, &ref_ty2) =>
1349 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
1350 push_ty_ref(&r1, ref_ty1, mutbl1, &mut values.0);
1351 push_ty_ref(&r2, ref_ty2, mutbl2, &mut values.1);
1355 // When encountering tuples of the same size, highlight only the differing types
1356 (&ty::Tuple(substs1), &ty::Tuple(substs2)) if substs1.len() == substs2.len() => {
1358 (DiagnosticStyledString::normal("("), DiagnosticStyledString::normal("("));
1359 let len = substs1.len();
1360 for (i, (left, right)) in substs1.types().zip(substs2.types()).enumerate() {
1361 let (x1, x2) = self.cmp(left, right);
1362 (values.0).0.extend(x1.0);
1363 (values.1).0.extend(x2.0);
1364 self.push_comma(&mut values.0, &mut values.1, len, i);
1367 // Keep the output for single element tuples as `(ty,)`.
1368 values.0.push_normal(",");
1369 values.1.push_normal(",");
1371 values.0.push_normal(")");
1372 values.1.push_normal(")");
1376 (ty::FnDef(did1, substs1), ty::FnDef(did2, substs2)) => {
1377 let sig1 = self.tcx.fn_sig(*did1).subst(self.tcx, substs1);
1378 let sig2 = self.tcx.fn_sig(*did2).subst(self.tcx, substs2);
1379 let mut values = self.cmp_fn_sig(&sig1, &sig2);
1380 let path1 = format!(" {{{}}}", self.tcx.def_path_str_with_substs(*did1, substs1));
1381 let path2 = format!(" {{{}}}", self.tcx.def_path_str_with_substs(*did2, substs2));
1382 let same_path = path1 == path2;
1383 values.0.push(path1, !same_path);
1384 values.1.push(path2, !same_path);
1388 (ty::FnDef(did1, substs1), ty::FnPtr(sig2)) => {
1389 let sig1 = self.tcx.fn_sig(*did1).subst(self.tcx, substs1);
1390 let mut values = self.cmp_fn_sig(&sig1, sig2);
1391 values.0.push_highlighted(format!(
1393 self.tcx.def_path_str_with_substs(*did1, substs1)
1398 (ty::FnPtr(sig1), ty::FnDef(did2, substs2)) => {
1399 let sig2 = self.tcx.fn_sig(*did2).subst(self.tcx, substs2);
1400 let mut values = self.cmp_fn_sig(sig1, &sig2);
1401 values.1.push_normal(format!(
1403 self.tcx.def_path_str_with_substs(*did2, substs2)
1408 (ty::FnPtr(sig1), ty::FnPtr(sig2)) => self.cmp_fn_sig(sig1, sig2),
1412 // The two types are the same, elide and don't highlight.
1413 (DiagnosticStyledString::normal("_"), DiagnosticStyledString::normal("_"))
1415 // We couldn't find anything in common, highlight everything.
1417 DiagnosticStyledString::highlighted(t1.to_string()),
1418 DiagnosticStyledString::highlighted(t2.to_string()),
1425 pub fn note_type_err(
1427 diag: &mut DiagnosticBuilder<'tcx>,
1428 cause: &ObligationCause<'tcx>,
1429 secondary_span: Option<(Span, String)>,
1430 mut values: Option<ValuePairs<'tcx>>,
1431 terr: &TypeError<'tcx>,
1433 let span = cause.span(self.tcx);
1434 debug!("note_type_err cause={:?} values={:?}, terr={:?}", cause, values, terr);
1436 // For some types of errors, expected-found does not make
1437 // sense, so just ignore the values we were given.
1438 if let TypeError::CyclicTy(_) = terr {
1441 struct OpaqueTypesVisitor<'tcx> {
1442 types: FxHashMap<TyCategory, FxHashSet<Span>>,
1443 expected: FxHashMap<TyCategory, FxHashSet<Span>>,
1444 found: FxHashMap<TyCategory, FxHashSet<Span>>,
1449 impl<'tcx> OpaqueTypesVisitor<'tcx> {
1450 fn visit_expected_found(
1456 let mut types_visitor = OpaqueTypesVisitor {
1457 types: Default::default(),
1458 expected: Default::default(),
1459 found: Default::default(),
1463 // The visitor puts all the relevant encountered types in `self.types`, but in
1464 // here we want to visit two separate types with no relation to each other, so we
1465 // move the results from `types` to `expected` or `found` as appropriate.
1466 expected.visit_with(&mut types_visitor);
1467 std::mem::swap(&mut types_visitor.expected, &mut types_visitor.types);
1468 found.visit_with(&mut types_visitor);
1469 std::mem::swap(&mut types_visitor.found, &mut types_visitor.types);
1473 fn report(&self, err: &mut DiagnosticBuilder<'_>) {
1474 self.add_labels_for_types(err, "expected", &self.expected);
1475 self.add_labels_for_types(err, "found", &self.found);
1478 fn add_labels_for_types(
1480 err: &mut DiagnosticBuilder<'_>,
1482 types: &FxHashMap<TyCategory, FxHashSet<Span>>,
1484 for (key, values) in types.iter() {
1485 let count = values.len();
1486 let kind = key.descr();
1487 let mut returned_async_output_error = false;
1493 if sp.is_desugaring(DesugaringKind::Async)
1494 && !returned_async_output_error
1496 "checked the `Output` of this `async fn`, "
1497 } else if count == 1 {
1502 if count > 1 { "one of the " } else { "" },
1508 if sp.is_desugaring(DesugaringKind::Async)
1509 && returned_async_output_error == false
1511 err.note("while checking the return type of the `async fn`");
1512 returned_async_output_error = true;
1519 impl<'tcx> ty::fold::TypeVisitor<'tcx> for OpaqueTypesVisitor<'tcx> {
1520 fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
1521 if let Some((kind, def_id)) = TyCategory::from_ty(self.tcx, t) {
1522 let span = self.tcx.def_span(def_id);
1523 // Avoid cluttering the output when the "found" and error span overlap:
1525 // error[E0308]: mismatched types
1526 // --> $DIR/issue-20862.rs:2:5
1531 // | the found closure
1532 // | expected `()`, found closure
1534 // = note: expected unit type `()`
1535 // found closure `[closure@$DIR/issue-20862.rs:2:5: 2:14 x:_]`
1536 if !self.ignore_span.overlaps(span) {
1537 self.types.entry(kind).or_default().insert(span);
1540 t.super_visit_with(self)
1544 debug!("note_type_err(diag={:?})", diag);
1546 Variable(ty::error::ExpectedFound<Ty<'a>>),
1547 Fixed(&'static str),
1549 let (expected_found, exp_found, is_simple_error) = match values {
1550 None => (None, Mismatch::Fixed("type"), false),
1552 let (is_simple_error, exp_found) = match values {
1553 ValuePairs::Types(exp_found) => {
1555 exp_found.expected.is_simple_text() && exp_found.found.is_simple_text();
1556 OpaqueTypesVisitor::visit_expected_found(
1564 (is_simple_err, Mismatch::Variable(exp_found))
1566 ValuePairs::TraitRefs(_) => (false, Mismatch::Fixed("trait")),
1567 _ => (false, Mismatch::Fixed("type")),
1569 let vals = match self.values_str(values) {
1570 Some((expected, found)) => Some((expected, found)),
1572 // Derived error. Cancel the emitter.
1577 (vals, exp_found, is_simple_error)
1581 // Ignore msg for object safe coercion
1582 // since E0038 message will be printed
1584 TypeError::ObjectUnsafeCoercion(_) => {}
1586 diag.span_label(span, terr.to_string());
1587 if let Some((sp, msg)) = secondary_span {
1588 diag.span_label(sp, msg);
1592 if let Some((expected, found)) = expected_found {
1593 let (expected_label, found_label, exp_found) = match exp_found {
1594 Mismatch::Variable(ef) => (
1595 ef.expected.prefix_string(self.tcx),
1596 ef.found.prefix_string(self.tcx),
1599 Mismatch::Fixed(s) => (s.into(), s.into(), None),
1601 match (&terr, expected == found) {
1602 (TypeError::Sorts(values), extra) => {
1603 let sort_string = |ty: Ty<'tcx>| match (extra, ty.kind()) {
1604 (true, ty::Opaque(def_id, _)) => {
1609 .lookup_char_pos(self.tcx.def_span(*def_id).lo());
1611 " (opaque type at <{}:{}:{}>)",
1612 pos.file.name.prefer_local(),
1614 pos.col.to_usize() + 1,
1617 (true, _) => format!(" ({})", ty.sort_string(self.tcx)),
1618 (false, _) => "".to_string(),
1620 if !(values.expected.is_simple_text() && values.found.is_simple_text())
1621 || (exp_found.map_or(false, |ef| {
1622 // This happens when the type error is a subset of the expectation,
1623 // like when you have two references but one is `usize` and the other
1624 // is `f32`. In those cases we still want to show the `note`. If the
1625 // value from `ef` is `Infer(_)`, then we ignore it.
1626 if !ef.expected.is_ty_infer() {
1627 ef.expected != values.expected
1628 } else if !ef.found.is_ty_infer() {
1629 ef.found != values.found
1635 diag.note_expected_found_extra(
1640 &sort_string(values.expected),
1641 &sort_string(values.found),
1645 (TypeError::ObjectUnsafeCoercion(_), _) => {
1646 diag.note_unsuccessful_coercion(found, expected);
1650 "note_type_err: exp_found={:?}, expected={:?} found={:?}",
1651 exp_found, expected, found
1653 if !is_simple_error || terr.must_include_note() {
1654 diag.note_expected_found(&expected_label, expected, &found_label, found);
1659 let exp_found = match exp_found {
1660 Mismatch::Variable(exp_found) => Some(exp_found),
1661 Mismatch::Fixed(_) => None,
1663 let exp_found = match terr {
1664 // `terr` has more accurate type information than `exp_found` in match expressions.
1665 ty::error::TypeError::Sorts(terr)
1666 if exp_found.map_or(false, |ef| terr.found == ef.found) =>
1672 debug!("exp_found {:?} terr {:?}", exp_found, terr);
1673 if let Some(exp_found) = exp_found {
1674 self.suggest_as_ref_where_appropriate(span, &exp_found, diag);
1675 self.suggest_accessing_field_where_appropriate(cause, &exp_found, diag);
1676 self.suggest_await_on_expect_found(cause, span, &exp_found, diag);
1679 // In some (most?) cases cause.body_id points to actual body, but in some cases
1680 // it's a actual definition. According to the comments (e.g. in
1681 // librustc_typeck/check/compare_method.rs:compare_predicate_entailment) the latter
1682 // is relied upon by some other code. This might (or might not) need cleanup.
1683 let body_owner_def_id =
1684 self.tcx.hir().opt_local_def_id(cause.body_id).unwrap_or_else(|| {
1685 self.tcx.hir().body_owner_def_id(hir::BodyId { hir_id: cause.body_id })
1687 self.check_and_note_conflicting_crates(diag, terr);
1688 self.tcx.note_and_explain_type_err(diag, terr, cause, span, body_owner_def_id.to_def_id());
1690 if let Some(ValuePairs::PolyTraitRefs(exp_found)) = values {
1691 if let ty::Closure(def_id, _) = exp_found.expected.skip_binder().self_ty().kind() {
1692 if let Some(def_id) = def_id.as_local() {
1693 let hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id);
1694 let span = self.tcx.hir().span(hir_id);
1695 diag.span_note(span, "this closure does not fulfill the lifetime requirements");
1700 // It reads better to have the error origin as the final
1702 self.note_error_origin(diag, cause, exp_found);
1705 pub fn get_impl_future_output_ty(&self, ty: Ty<'tcx>) -> Option<Ty<'tcx>> {
1706 if let ty::Opaque(def_id, substs) = ty.kind() {
1707 let future_trait = self.tcx.require_lang_item(LangItem::Future, None);
1709 let item_def_id = self
1711 .associated_items(future_trait)
1712 .in_definition_order()
1717 let bounds = self.tcx.explicit_item_bounds(*def_id);
1719 for (predicate, _) in bounds {
1720 let predicate = predicate.subst(self.tcx, substs);
1721 if let ty::PredicateKind::Projection(projection_predicate) =
1722 predicate.kind().skip_binder()
1724 if projection_predicate.projection_ty.item_def_id == item_def_id {
1725 // We don't account for multiple `Future::Output = Ty` contraints.
1726 return Some(projection_predicate.ty);
1734 /// A possible error is to forget to add `.await` when using futures:
1737 /// async fn make_u32() -> u32 {
1741 /// fn take_u32(x: u32) {}
1743 /// async fn foo() {
1744 /// let x = make_u32();
1749 /// This routine checks if the found type `T` implements `Future<Output=U>` where `U` is the
1750 /// expected type. If this is the case, and we are inside of an async body, it suggests adding
1751 /// `.await` to the tail of the expression.
1752 fn suggest_await_on_expect_found(
1754 cause: &ObligationCause<'tcx>,
1756 exp_found: &ty::error::ExpectedFound<Ty<'tcx>>,
1757 diag: &mut DiagnosticBuilder<'tcx>,
1760 "suggest_await_on_expect_found: exp_span={:?}, expected_ty={:?}, found_ty={:?}",
1761 exp_span, exp_found.expected, exp_found.found,
1764 if let ObligationCauseCode::CompareImplMethodObligation { .. } = &cause.code {
1769 self.get_impl_future_output_ty(exp_found.expected),
1770 self.get_impl_future_output_ty(exp_found.found),
1772 (Some(exp), Some(found)) if ty::TyS::same_type(exp, found) => match &cause.code {
1773 ObligationCauseCode::IfExpression(box IfExpressionCause { then, .. }) => {
1774 diag.multipart_suggestion(
1775 "consider `await`ing on both `Future`s",
1777 (then.shrink_to_hi(), ".await".to_string()),
1778 (exp_span.shrink_to_hi(), ".await".to_string()),
1780 Applicability::MaybeIncorrect,
1783 ObligationCauseCode::MatchExpressionArm(box MatchExpressionArmCause {
1787 if let [.., arm_span] = &prior_arms[..] {
1788 diag.multipart_suggestion(
1789 "consider `await`ing on both `Future`s",
1791 (arm_span.shrink_to_hi(), ".await".to_string()),
1792 (exp_span.shrink_to_hi(), ".await".to_string()),
1794 Applicability::MaybeIncorrect,
1797 diag.help("consider `await`ing on both `Future`s");
1801 diag.help("consider `await`ing on both `Future`s");
1804 (_, Some(ty)) if ty::TyS::same_type(exp_found.expected, ty) => {
1805 let span = match cause.code {
1807 ObligationCauseCode::Pattern { span: Some(span), .. } => span,
1810 diag.span_suggestion_verbose(
1811 span.shrink_to_hi(),
1812 "consider `await`ing on the `Future`",
1813 ".await".to_string(),
1814 Applicability::MaybeIncorrect,
1817 (Some(ty), _) if ty::TyS::same_type(ty, exp_found.found) => {
1818 let span = match cause.code {
1820 ObligationCauseCode::Pattern { span: Some(span), .. } => span,
1823 diag.span_suggestion_verbose(
1824 span.shrink_to_hi(),
1825 "consider `await`ing on the `Future`",
1826 ".await".to_string(),
1827 Applicability::MaybeIncorrect,
1834 fn suggest_accessing_field_where_appropriate(
1836 cause: &ObligationCause<'tcx>,
1837 exp_found: &ty::error::ExpectedFound<Ty<'tcx>>,
1838 diag: &mut DiagnosticBuilder<'tcx>,
1841 "suggest_accessing_field_where_appropriate(cause={:?}, exp_found={:?})",
1844 if let ty::Adt(expected_def, expected_substs) = exp_found.expected.kind() {
1845 if expected_def.is_enum() {
1849 if let Some((name, ty)) = expected_def
1853 .filter(|field| field.vis.is_accessible_from(field.did, self.tcx))
1854 .map(|field| (field.ident.name, field.ty(self.tcx, expected_substs)))
1855 .find(|(_, ty)| ty::TyS::same_type(ty, exp_found.found))
1857 if let ObligationCauseCode::Pattern { span: Some(span), .. } = cause.code {
1858 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
1859 let suggestion = if expected_def.is_struct() {
1860 format!("{}.{}", snippet, name)
1861 } else if expected_def.is_union() {
1862 format!("unsafe {{ {}.{} }}", snippet, name)
1866 diag.span_suggestion(
1869 "you might have meant to use field `{}` whose type is `{}`",
1873 Applicability::MaybeIncorrect,
1881 /// When encountering a case where `.as_ref()` on a `Result` or `Option` would be appropriate,
1883 fn suggest_as_ref_where_appropriate(
1886 exp_found: &ty::error::ExpectedFound<Ty<'tcx>>,
1887 diag: &mut DiagnosticBuilder<'tcx>,
1889 if let (ty::Adt(exp_def, exp_substs), ty::Ref(_, found_ty, _)) =
1890 (exp_found.expected.kind(), exp_found.found.kind())
1892 if let ty::Adt(found_def, found_substs) = *found_ty.kind() {
1893 let path_str = format!("{:?}", exp_def);
1894 if exp_def == &found_def {
1895 let opt_msg = "you can convert from `&Option<T>` to `Option<&T>` using \
1897 let result_msg = "you can convert from `&Result<T, E>` to \
1898 `Result<&T, &E>` using `.as_ref()`";
1899 let have_as_ref = &[
1900 ("std::option::Option", opt_msg),
1901 ("core::option::Option", opt_msg),
1902 ("std::result::Result", result_msg),
1903 ("core::result::Result", result_msg),
1905 if let Some(msg) = have_as_ref
1907 .find_map(|(path, msg)| (&path_str == path).then_some(msg))
1909 let mut show_suggestion = true;
1910 for (exp_ty, found_ty) in
1911 iter::zip(exp_substs.types(), found_substs.types())
1913 match *exp_ty.kind() {
1914 ty::Ref(_, exp_ty, _) => {
1915 match (exp_ty.kind(), found_ty.kind()) {
1919 | (ty::Infer(_), _) => {}
1920 _ if ty::TyS::same_type(exp_ty, found_ty) => {}
1921 _ => show_suggestion = false,
1924 ty::Param(_) | ty::Infer(_) => {}
1925 _ => show_suggestion = false,
1928 if let (Ok(snippet), true) =
1929 (self.tcx.sess.source_map().span_to_snippet(span), show_suggestion)
1931 diag.span_suggestion(
1934 format!("{}.as_ref()", snippet),
1935 Applicability::MachineApplicable,
1944 pub fn report_and_explain_type_error(
1946 trace: TypeTrace<'tcx>,
1947 terr: &TypeError<'tcx>,
1948 ) -> DiagnosticBuilder<'tcx> {
1949 debug!("report_and_explain_type_error(trace={:?}, terr={:?})", trace, terr);
1951 let span = trace.cause.span(self.tcx);
1952 let failure_code = trace.cause.as_failure_code(terr);
1953 let mut diag = match failure_code {
1954 FailureCode::Error0038(did) => {
1955 let violations = self.tcx.object_safety_violations(did);
1956 report_object_safety_error(self.tcx, span, did, violations)
1958 FailureCode::Error0317(failure_str) => {
1959 struct_span_err!(self.tcx.sess, span, E0317, "{}", failure_str)
1961 FailureCode::Error0580(failure_str) => {
1962 struct_span_err!(self.tcx.sess, span, E0580, "{}", failure_str)
1964 FailureCode::Error0308(failure_str) => {
1965 let mut err = struct_span_err!(self.tcx.sess, span, E0308, "{}", failure_str);
1966 if let ValuePairs::Types(ty::error::ExpectedFound { expected, found }) =
1969 // If a tuple of length one was expected and the found expression has
1970 // parentheses around it, perhaps the user meant to write `(expr,)` to
1971 // build a tuple (issue #86100)
1972 match (expected.kind(), found.kind()) {
1973 (ty::Tuple(_), ty::Tuple(_)) => {}
1974 (ty::Tuple(_), _) if expected.tuple_fields().count() == 1 => {
1975 if let Ok(code) = self.tcx.sess().source_map().span_to_snippet(span) {
1977 code.strip_prefix('(').and_then(|s| s.strip_suffix(')'))
1979 err.span_suggestion(
1981 "use a trailing comma to create a tuple with one element",
1982 format!("({},)", code),
1983 Applicability::MaybeIncorrect,
1993 FailureCode::Error0644(failure_str) => {
1994 struct_span_err!(self.tcx.sess, span, E0644, "{}", failure_str)
1997 self.note_type_err(&mut diag, &trace.cause, None, Some(trace.values), terr);
2003 values: ValuePairs<'tcx>,
2004 ) -> Option<(DiagnosticStyledString, DiagnosticStyledString)> {
2006 infer::Types(exp_found) => self.expected_found_str_ty(exp_found),
2007 infer::Regions(exp_found) => self.expected_found_str(exp_found),
2008 infer::Consts(exp_found) => self.expected_found_str(exp_found),
2009 infer::TraitRefs(exp_found) => {
2010 let pretty_exp_found = ty::error::ExpectedFound {
2011 expected: exp_found.expected.print_only_trait_path(),
2012 found: exp_found.found.print_only_trait_path(),
2014 self.expected_found_str(pretty_exp_found)
2016 infer::PolyTraitRefs(exp_found) => {
2017 let pretty_exp_found = ty::error::ExpectedFound {
2018 expected: exp_found.expected.print_only_trait_path(),
2019 found: exp_found.found.print_only_trait_path(),
2021 self.expected_found_str(pretty_exp_found)
2026 fn expected_found_str_ty(
2028 exp_found: ty::error::ExpectedFound<Ty<'tcx>>,
2029 ) -> Option<(DiagnosticStyledString, DiagnosticStyledString)> {
2030 let exp_found = self.resolve_vars_if_possible(exp_found);
2031 if exp_found.references_error() {
2035 Some(self.cmp(exp_found.expected, exp_found.found))
2038 /// Returns a string of the form "expected `{}`, found `{}`".
2039 fn expected_found_str<T: fmt::Display + TypeFoldable<'tcx>>(
2041 exp_found: ty::error::ExpectedFound<T>,
2042 ) -> Option<(DiagnosticStyledString, DiagnosticStyledString)> {
2043 let exp_found = self.resolve_vars_if_possible(exp_found);
2044 if exp_found.references_error() {
2049 DiagnosticStyledString::highlighted(exp_found.expected.to_string()),
2050 DiagnosticStyledString::highlighted(exp_found.found.to_string()),
2054 pub fn report_generic_bound_failure(
2057 origin: Option<SubregionOrigin<'tcx>>,
2058 bound_kind: GenericKind<'tcx>,
2061 self.construct_generic_bound_failure(span, origin, bound_kind, sub).emit();
2064 pub fn construct_generic_bound_failure(
2067 origin: Option<SubregionOrigin<'tcx>>,
2068 bound_kind: GenericKind<'tcx>,
2070 ) -> DiagnosticBuilder<'a> {
2071 let hir = &self.tcx.hir();
2072 // Attempt to obtain the span of the parameter so we can
2073 // suggest adding an explicit lifetime bound to it.
2075 .in_progress_typeck_results
2076 .map(|typeck_results| typeck_results.borrow().hir_owner)
2078 let hir_id = hir.local_def_id_to_hir_id(owner);
2079 let parent_id = hir.get_parent_item(hir_id);
2081 // Parent item could be a `mod`, so we check the HIR before calling:
2082 if let Some(Node::Item(Item {
2083 kind: ItemKind::Trait(..) | ItemKind::Impl { .. },
2085 })) = hir.find(parent_id)
2087 Some(self.tcx.generics_of(hir.local_def_id(parent_id).to_def_id()))
2091 self.tcx.generics_of(owner.to_def_id()),
2094 let type_param_span = match (generics, bound_kind) {
2095 (Some((_, ref generics)), GenericKind::Param(ref param)) => {
2096 // Account for the case where `param` corresponds to `Self`,
2097 // which doesn't have the expected type argument.
2098 if !(generics.has_self && param.index == 0) {
2099 let type_param = generics.type_param(param, self.tcx);
2100 type_param.def_id.as_local().map(|def_id| {
2101 // Get the `hir::Param` to verify whether it already has any bounds.
2102 // We do this to avoid suggesting code that ends up as `T: 'a'b`,
2103 // instead we suggest `T: 'a + 'b` in that case.
2104 let id = hir.local_def_id_to_hir_id(def_id);
2105 let mut has_bounds = false;
2106 if let Node::GenericParam(param) = hir.get(id) {
2107 has_bounds = !param.bounds.is_empty();
2109 let sp = hir.span(id);
2110 // `sp` only covers `T`, change it so that it covers
2111 // `T:` when appropriate
2112 let is_impl_trait = bound_kind.to_string().starts_with("impl ");
2113 let sp = if has_bounds && !is_impl_trait {
2118 .next_point(self.tcx.sess.source_map().next_point(sp)))
2122 (sp, has_bounds, is_impl_trait)
2130 let new_lt = generics
2132 .and_then(|(parent_g, g)| {
2133 let mut possible = (b'a'..=b'z').map(|c| format!("'{}", c as char));
2134 let mut lts_names = g
2137 .filter(|p| matches!(p.kind, ty::GenericParamDefKind::Lifetime))
2138 .map(|p| p.name.as_str())
2139 .collect::<Vec<_>>();
2140 if let Some(g) = parent_g {
2144 .filter(|p| matches!(p.kind, ty::GenericParamDefKind::Lifetime))
2145 .map(|p| p.name.as_str()),
2148 let lts = lts_names.iter().map(|s| -> &str { &*s }).collect::<Vec<_>>();
2149 possible.find(|candidate| !lts.contains(&candidate.as_str()))
2151 .unwrap_or("'lt".to_string());
2152 let add_lt_sugg = generics
2154 .and_then(|(_, g)| g.params.first())
2155 .and_then(|param| param.def_id.as_local())
2158 hir.span(hir.local_def_id_to_hir_id(def_id)).shrink_to_lo(),
2159 format!("{}, ", new_lt),
2163 let labeled_user_string = match bound_kind {
2164 GenericKind::Param(ref p) => format!("the parameter type `{}`", p),
2165 GenericKind::Projection(ref p) => format!("the associated type `{}`", p),
2168 if let Some(SubregionOrigin::CompareImplMethodObligation {
2175 return self.report_extra_impl_obligation(
2180 &format!("`{}: {}`", bound_kind, sub),
2184 fn binding_suggestion<'tcx, S: fmt::Display>(
2185 err: &mut DiagnosticBuilder<'tcx>,
2186 type_param_span: Option<(Span, bool, bool)>,
2187 bound_kind: GenericKind<'tcx>,
2190 let msg = "consider adding an explicit lifetime bound";
2191 if let Some((sp, has_lifetimes, is_impl_trait)) = type_param_span {
2192 let suggestion = if is_impl_trait {
2193 format!("{} + {}", bound_kind, sub)
2195 let tail = if has_lifetimes { " + " } else { "" };
2196 format!("{}: {}{}", bound_kind, sub, tail)
2198 err.span_suggestion(
2200 &format!("{}...", msg),
2202 Applicability::MaybeIncorrect, // Issue #41966
2205 let consider = format!(
2208 if type_param_span.map_or(false, |(_, _, is_impl_trait)| is_impl_trait) {
2209 format!(" `{}` to `{}`", sub, bound_kind)
2211 format!("`{}: {}`", bound_kind, sub)
2214 err.help(&consider);
2218 let new_binding_suggestion =
2219 |err: &mut DiagnosticBuilder<'tcx>,
2220 type_param_span: Option<(Span, bool, bool)>,
2221 bound_kind: GenericKind<'tcx>| {
2222 let msg = "consider introducing an explicit lifetime bound";
2223 if let Some((sp, has_lifetimes, is_impl_trait)) = type_param_span {
2224 let suggestion = if is_impl_trait {
2225 (sp.shrink_to_hi(), format!(" + {}", new_lt))
2227 let tail = if has_lifetimes { " +" } else { "" };
2228 (sp, format!("{}: {}{}", bound_kind, new_lt, tail))
2231 vec![suggestion, (span.shrink_to_hi(), format!(" + {}", new_lt))];
2232 if let Some(lt) = add_lt_sugg {
2234 sugg.rotate_right(1);
2236 // `MaybeIncorrect` due to issue #41966.
2237 err.multipart_suggestion(msg, sugg, Applicability::MaybeIncorrect);
2241 let mut err = match *sub {
2242 ty::ReEarlyBound(ty::EarlyBoundRegion { name, .. })
2243 | ty::ReFree(ty::FreeRegion { bound_region: ty::BrNamed(_, name), .. }) => {
2244 // Does the required lifetime have a nice name we can print?
2245 let mut err = struct_span_err!(
2249 "{} may not live long enough",
2252 // Explicitly use the name instead of `sub`'s `Display` impl. The `Display` impl
2253 // for the bound is not suitable for suggestions when `-Zverbose` is set because it
2254 // uses `Debug` output, so we handle it specially here so that suggestions are
2256 binding_suggestion(&mut err, type_param_span, bound_kind, name);
2261 // Does the required lifetime have a nice name we can print?
2262 let mut err = struct_span_err!(
2266 "{} may not live long enough",
2269 binding_suggestion(&mut err, type_param_span, bound_kind, "'static");
2274 // If not, be less specific.
2275 let mut err = struct_span_err!(
2279 "{} may not live long enough",
2282 note_and_explain_region(
2285 &format!("{} must be valid for ", labeled_user_string),
2289 if let Some(infer::RelateParamBound(_, t)) = origin {
2290 let return_impl_trait = self
2291 .in_progress_typeck_results
2292 .map(|typeck_results| typeck_results.borrow().hir_owner)
2293 .and_then(|owner| self.tcx.return_type_impl_trait(owner))
2295 let t = self.resolve_vars_if_possible(t);
2298 // fn get_later<G, T>(g: G, dest: &mut T) -> impl FnOnce() + '_
2300 // fn get_later<'a, G: 'a, T>(g: G, dest: &mut T) -> impl FnOnce() + '_ + 'a
2301 ty::Closure(_, _substs) | ty::Opaque(_, _substs) if return_impl_trait => {
2302 new_binding_suggestion(&mut err, type_param_span, bound_kind);
2305 binding_suggestion(&mut err, type_param_span, bound_kind, new_lt);
2313 if let Some(origin) = origin {
2314 self.note_region_origin(&mut err, &origin);
2319 fn report_sub_sup_conflict(
2321 var_origin: RegionVariableOrigin,
2322 sub_origin: SubregionOrigin<'tcx>,
2323 sub_region: Region<'tcx>,
2324 sup_origin: SubregionOrigin<'tcx>,
2325 sup_region: Region<'tcx>,
2327 let mut err = self.report_inference_failure(var_origin);
2329 note_and_explain_region(
2332 "first, the lifetime cannot outlive ",
2337 debug!("report_sub_sup_conflict: var_origin={:?}", var_origin);
2338 debug!("report_sub_sup_conflict: sub_region={:?}", sub_region);
2339 debug!("report_sub_sup_conflict: sub_origin={:?}", sub_origin);
2340 debug!("report_sub_sup_conflict: sup_region={:?}", sup_region);
2341 debug!("report_sub_sup_conflict: sup_origin={:?}", sup_origin);
2343 if let (&infer::Subtype(ref sup_trace), &infer::Subtype(ref sub_trace)) =
2344 (&sup_origin, &sub_origin)
2346 debug!("report_sub_sup_conflict: sup_trace={:?}", sup_trace);
2347 debug!("report_sub_sup_conflict: sub_trace={:?}", sub_trace);
2348 debug!("report_sub_sup_conflict: sup_trace.values={:?}", sup_trace.values);
2349 debug!("report_sub_sup_conflict: sub_trace.values={:?}", sub_trace.values);
2351 if let (Some((sup_expected, sup_found)), Some((sub_expected, sub_found))) =
2352 (self.values_str(sup_trace.values), self.values_str(sub_trace.values))
2354 if sub_expected == sup_expected && sub_found == sup_found {
2355 note_and_explain_region(
2358 "...but the lifetime must also be valid for ",
2363 sup_trace.cause.span,
2364 &format!("...so that the {}", sup_trace.cause.as_requirement_str()),
2367 err.note_expected_found(&"", sup_expected, &"", sup_found);
2374 self.note_region_origin(&mut err, &sup_origin);
2376 note_and_explain_region(
2379 "but, the lifetime must be valid for ",
2384 self.note_region_origin(&mut err, &sub_origin);
2388 /// Determine whether an error associated with the given span and definition
2389 /// should be treated as being caused by the implicit `From` conversion
2390 /// within `?` desugaring.
2391 pub fn is_try_conversion(&self, span: Span, trait_def_id: DefId) -> bool {
2392 span.is_desugaring(DesugaringKind::QuestionMark)
2393 && self.tcx.is_diagnostic_item(sym::from_trait, trait_def_id)
2397 impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
2398 fn report_inference_failure(
2400 var_origin: RegionVariableOrigin,
2401 ) -> DiagnosticBuilder<'tcx> {
2402 let br_string = |br: ty::BoundRegionKind| {
2403 let mut s = match br {
2404 ty::BrNamed(_, name) => name.to_string(),
2412 let var_description = match var_origin {
2413 infer::MiscVariable(_) => String::new(),
2414 infer::PatternRegion(_) => " for pattern".to_string(),
2415 infer::AddrOfRegion(_) => " for borrow expression".to_string(),
2416 infer::Autoref(_, _) => " for autoref".to_string(),
2417 infer::Coercion(_) => " for automatic coercion".to_string(),
2418 infer::LateBoundRegion(_, br, infer::FnCall) => {
2419 format!(" for lifetime parameter {}in function call", br_string(br))
2421 infer::LateBoundRegion(_, br, infer::HigherRankedType) => {
2422 format!(" for lifetime parameter {}in generic type", br_string(br))
2424 infer::LateBoundRegion(_, br, infer::AssocTypeProjection(def_id)) => format!(
2425 " for lifetime parameter {}in trait containing associated type `{}`",
2427 self.tcx.associated_item(def_id).ident
2429 infer::EarlyBoundRegion(_, name) => format!(" for lifetime parameter `{}`", name),
2430 infer::UpvarRegion(ref upvar_id, _) => {
2431 let var_name = self.tcx.hir().name(upvar_id.var_path.hir_id);
2432 format!(" for capture of `{}` by closure", var_name)
2434 infer::Nll(..) => bug!("NLL variable found in lexical phase"),
2441 "cannot infer an appropriate lifetime{} due to conflicting requirements",
2449 Error0317(&'static str),
2450 Error0580(&'static str),
2451 Error0308(&'static str),
2452 Error0644(&'static str),
2455 trait ObligationCauseExt<'tcx> {
2456 fn as_failure_code(&self, terr: &TypeError<'tcx>) -> FailureCode;
2457 fn as_requirement_str(&self) -> &'static str;
2460 impl<'tcx> ObligationCauseExt<'tcx> for ObligationCause<'tcx> {
2461 fn as_failure_code(&self, terr: &TypeError<'tcx>) -> FailureCode {
2462 use self::FailureCode::*;
2463 use crate::traits::ObligationCauseCode::*;
2465 CompareImplMethodObligation { .. } => Error0308("method not compatible with trait"),
2466 CompareImplTypeObligation { .. } => Error0308("type not compatible with trait"),
2467 MatchExpressionArm(box MatchExpressionArmCause { source, .. }) => {
2468 Error0308(match source {
2469 hir::MatchSource::IfLetDesugar { .. } => {
2470 "`if let` arms have incompatible types"
2472 hir::MatchSource::TryDesugar => {
2473 "try expression alternatives have incompatible types"
2475 _ => "`match` arms have incompatible types",
2478 IfExpression { .. } => Error0308("`if` and `else` have incompatible types"),
2479 IfExpressionWithNoElse => Error0317("`if` may be missing an `else` clause"),
2480 MainFunctionType => Error0580("`main` function has wrong type"),
2481 StartFunctionType => Error0308("`#[start]` function has wrong type"),
2482 IntrinsicType => Error0308("intrinsic has wrong type"),
2483 MethodReceiver => Error0308("mismatched `self` parameter type"),
2485 // In the case where we have no more specific thing to
2486 // say, also take a look at the error code, maybe we can
2489 TypeError::CyclicTy(ty) if ty.is_closure() || ty.is_generator() => {
2490 Error0644("closure/generator type that references itself")
2492 TypeError::IntrinsicCast => {
2493 Error0308("cannot coerce intrinsics to function pointers")
2495 TypeError::ObjectUnsafeCoercion(did) => Error0038(*did),
2496 _ => Error0308("mismatched types"),
2501 fn as_requirement_str(&self) -> &'static str {
2502 use crate::traits::ObligationCauseCode::*;
2504 CompareImplMethodObligation { .. } => "method type is compatible with trait",
2505 CompareImplTypeObligation { .. } => "associated type is compatible with trait",
2506 ExprAssignable => "expression is assignable",
2507 MatchExpressionArm(box MatchExpressionArmCause { source, .. }) => match source {
2508 hir::MatchSource::IfLetDesugar { .. } => "`if let` arms have compatible types",
2509 _ => "`match` arms have compatible types",
2511 IfExpression { .. } => "`if` and `else` have incompatible types",
2512 IfExpressionWithNoElse => "`if` missing an `else` returns `()`",
2513 MainFunctionType => "`main` function has the correct type",
2514 StartFunctionType => "`#[start]` function has the correct type",
2515 IntrinsicType => "intrinsic has the correct type",
2516 MethodReceiver => "method receiver has the correct type",
2517 _ => "types are compatible",
2522 /// This is a bare signal of what kind of type we're dealing with. `ty::TyKind` tracks
2523 /// extra information about each type, but we only care about the category.
2524 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
2525 pub enum TyCategory {
2528 Generator(hir::GeneratorKind),
2533 fn descr(&self) -> &'static str {
2535 Self::Closure => "closure",
2536 Self::Opaque => "opaque type",
2537 Self::Generator(gk) => gk.descr(),
2538 Self::Foreign => "foreign type",
2542 pub fn from_ty(tcx: TyCtxt<'_>, ty: Ty<'_>) -> Option<(Self, DefId)> {
2544 ty::Closure(def_id, _) => Some((Self::Closure, def_id)),
2545 ty::Opaque(def_id, _) => Some((Self::Opaque, def_id)),
2546 ty::Generator(def_id, ..) => {
2547 Some((Self::Generator(tcx.generator_kind(def_id).unwrap()), def_id))
2549 ty::Foreign(def_id) => Some((Self::Foreign, def_id)),