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::traits::error_reporting::report_object_safety_error;
55 IfExpressionCause, MatchExpressionArmCause, ObligationCause, ObligationCauseCode,
58 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
59 use rustc_errors::{pluralize, struct_span_err};
60 use rustc_errors::{Applicability, DiagnosticBuilder, DiagnosticStyledString};
62 use rustc_hir::def_id::DefId;
63 use rustc_hir::{Item, ItemKind, Node};
64 use rustc_middle::ty::error::TypeError;
65 use rustc_middle::ty::{
67 subst::{Subst, SubstsRef},
68 Region, Ty, TyCtxt, TypeFoldable,
70 use rustc_span::{DesugaringKind, Pos, Span};
71 use rustc_target::spec::abi;
77 pub use need_type_info::TypeAnnotationNeeded;
79 pub mod nice_region_error;
81 pub(super) fn note_and_explain_region(
83 err: &mut DiagnosticBuilder<'_>,
85 region: ty::Region<'tcx>,
88 let (description, span) = match *region {
89 ty::ReEarlyBound(_) | ty::ReFree(_) | ty::ReStatic => {
90 msg_span_from_free_region(tcx, region)
93 ty::ReEmpty(ty::UniverseIndex::ROOT) => ("the empty lifetime".to_owned(), None),
95 // uh oh, hope no user ever sees THIS
96 ty::ReEmpty(ui) => (format!("the empty lifetime in universe {:?}", ui), None),
98 ty::RePlaceholder(_) => ("any other region".to_string(), None),
100 // FIXME(#13998) RePlaceholder should probably print like
101 // ReFree rather than dumping Debug output on the user.
103 // We shouldn't really be having unification failures with ReVar
104 // and ReLateBound though.
105 ty::ReVar(_) | ty::ReLateBound(..) | ty::ReErased => {
106 (format!("lifetime {:?}", region), None)
110 emit_msg_span(err, prefix, description, span, suffix);
113 pub(super) fn note_and_explain_free_region(
115 err: &mut DiagnosticBuilder<'_>,
117 region: ty::Region<'tcx>,
120 let (description, span) = msg_span_from_free_region(tcx, region);
122 emit_msg_span(err, prefix, description, span, suffix);
125 fn msg_span_from_free_region(
127 region: ty::Region<'tcx>,
128 ) -> (String, Option<Span>) {
130 ty::ReEarlyBound(_) | ty::ReFree(_) => {
131 msg_span_from_early_bound_and_free_regions(tcx, region)
133 ty::ReStatic => ("the static lifetime".to_owned(), None),
134 ty::ReEmpty(ty::UniverseIndex::ROOT) => ("an empty lifetime".to_owned(), None),
135 ty::ReEmpty(ui) => (format!("an empty lifetime in universe {:?}", ui), None),
136 _ => bug!("{:?}", region),
140 fn msg_span_from_early_bound_and_free_regions(
142 region: ty::Region<'tcx>,
143 ) -> (String, Option<Span>) {
144 let sm = tcx.sess.source_map();
146 let scope = region.free_region_binding_scope(tcx);
147 let node = tcx.hir().as_local_hir_id(scope.expect_local());
148 let tag = match tcx.hir().find(node) {
149 Some(Node::Block(_) | Node::Expr(_)) => "body",
150 Some(Node::Item(it)) => item_scope_tag(&it),
151 Some(Node::TraitItem(it)) => trait_item_scope_tag(&it),
152 Some(Node::ImplItem(it)) => impl_item_scope_tag(&it),
155 let (prefix, span) = match *region {
156 ty::ReEarlyBound(ref br) => {
157 let mut sp = sm.guess_head_span(tcx.hir().span(node));
159 tcx.hir().get_generics(scope).and_then(|generics| generics.get_named(br.name))
163 (format!("the lifetime `{}` as defined on", br.name), sp)
165 ty::ReFree(ty::FreeRegion { bound_region: ty::BoundRegion::BrNamed(_, name), .. }) => {
166 let mut sp = sm.guess_head_span(tcx.hir().span(node));
168 tcx.hir().get_generics(scope).and_then(|generics| generics.get_named(name))
172 (format!("the lifetime `{}` as defined on", name), sp)
174 ty::ReFree(ref fr) => match fr.bound_region {
176 (format!("the anonymous lifetime #{} defined on", idx + 1), tcx.hir().span(node))
179 format!("the lifetime `{}` as defined on", region),
180 sm.guess_head_span(tcx.hir().span(node)),
185 let (msg, opt_span) = explain_span(tcx, tag, span);
186 (format!("{} {}", prefix, msg), opt_span)
190 err: &mut DiagnosticBuilder<'_>,
196 let message = format!("{}{}{}", prefix, description, suffix);
198 if let Some(span) = span {
199 err.span_note(span, &message);
205 fn item_scope_tag(item: &hir::Item<'_>) -> &'static str {
207 hir::ItemKind::Impl { .. } => "impl",
208 hir::ItemKind::Struct(..) => "struct",
209 hir::ItemKind::Union(..) => "union",
210 hir::ItemKind::Enum(..) => "enum",
211 hir::ItemKind::Trait(..) => "trait",
212 hir::ItemKind::Fn(..) => "function body",
217 fn trait_item_scope_tag(item: &hir::TraitItem<'_>) -> &'static str {
219 hir::TraitItemKind::Fn(..) => "method body",
220 hir::TraitItemKind::Const(..) | hir::TraitItemKind::Type(..) => "associated item",
224 fn impl_item_scope_tag(item: &hir::ImplItem<'_>) -> &'static str {
226 hir::ImplItemKind::Fn(..) => "method body",
227 hir::ImplItemKind::Const(..) | hir::ImplItemKind::TyAlias(..) => "associated item",
231 fn explain_span(tcx: TyCtxt<'tcx>, heading: &str, span: Span) -> (String, Option<Span>) {
232 let lo = tcx.sess.source_map().lookup_char_pos(span.lo());
233 (format!("the {} at {}:{}", heading, lo.line, lo.col.to_usize() + 1), Some(span))
236 pub fn unexpected_hidden_region_diagnostic(
240 hidden_region: ty::Region<'tcx>,
241 ) -> DiagnosticBuilder<'tcx> {
242 let mut err = struct_span_err!(
246 "hidden type for `impl Trait` captures lifetime that does not appear in bounds",
249 // Explain the region we are capturing.
250 match hidden_region {
251 ty::ReEmpty(ty::UniverseIndex::ROOT) => {
252 // All lifetimes shorter than the function body are `empty` in
253 // lexical region resolution. The default explanation of "an empty
254 // lifetime" isn't really accurate here.
255 let message = format!(
256 "hidden type `{}` captures lifetime smaller than the function body",
259 err.span_note(span, &message);
261 ty::ReEarlyBound(_) | ty::ReFree(_) | ty::ReStatic | ty::ReEmpty(_) => {
262 // Assuming regionck succeeded (*), we ought to always be
263 // capturing *some* region from the fn header, and hence it
264 // ought to be free. So under normal circumstances, we will go
265 // down this path which gives a decent human readable
268 // (*) if not, the `tainted_by_errors` field would be set to
269 // `Some(ErrorReported)` in any case, so we wouldn't be here at all.
270 note_and_explain_free_region(
273 &format!("hidden type `{}` captures ", hidden_ty),
279 // Ugh. This is a painful case: the hidden region is not one
280 // that we can easily summarize or explain. This can happen
282 // `src/test/ui/multiple-lifetimes/ordinary-bounds-unsuited.rs`:
285 // fn upper_bounds<'a, 'b>(a: Ordinary<'a>, b: Ordinary<'b>) -> impl Trait<'a, 'b> {
286 // if condition() { a } else { b }
290 // Here the captured lifetime is the intersection of `'a` and
291 // `'b`, which we can't quite express.
293 // We can at least report a really cryptic error for now.
294 note_and_explain_region(
297 &format!("hidden type `{}` captures ", hidden_ty),
307 impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
308 pub fn report_region_errors(&self, errors: &Vec<RegionResolutionError<'tcx>>) {
309 debug!("report_region_errors(): {} errors to start", errors.len());
311 // try to pre-process the errors, which will group some of them
312 // together into a `ProcessedErrors` group:
313 let errors = self.process_errors(errors);
315 debug!("report_region_errors: {} errors after preprocessing", errors.len());
317 for error in errors {
318 debug!("report_region_errors: error = {:?}", error);
320 if !self.try_report_nice_region_error(&error) {
321 match error.clone() {
322 // These errors could indicate all manner of different
323 // problems with many different solutions. Rather
324 // than generate a "one size fits all" error, what we
325 // attempt to do is go through a number of specific
326 // scenarios and try to find the best way to present
327 // the error. If all of these fails, we fall back to a rather
328 // general bit of code that displays the error information
329 RegionResolutionError::ConcreteFailure(origin, sub, sup) => {
330 if sub.is_placeholder() || sup.is_placeholder() {
331 self.report_placeholder_failure(origin, sub, sup).emit();
333 self.report_concrete_failure(origin, sub, sup).emit();
337 RegionResolutionError::GenericBoundFailure(origin, param_ty, sub) => {
338 self.report_generic_bound_failure(
346 RegionResolutionError::SubSupConflict(
354 if sub_r.is_placeholder() {
355 self.report_placeholder_failure(sub_origin, sub_r, sup_r).emit();
356 } else if sup_r.is_placeholder() {
357 self.report_placeholder_failure(sup_origin, sub_r, sup_r).emit();
359 self.report_sub_sup_conflict(
360 var_origin, sub_origin, sub_r, sup_origin, sup_r,
365 RegionResolutionError::UpperBoundUniverseConflict(
372 assert!(sup_r.is_placeholder());
374 // Make a dummy value for the "sub region" --
375 // this is the initial value of the
376 // placeholder. In practice, we expect more
377 // tailored errors that don't really use this
379 let sub_r = self.tcx.mk_region(ty::ReEmpty(var_universe));
381 self.report_placeholder_failure(sup_origin, sub_r, sup_r).emit();
384 RegionResolutionError::MemberConstraintFailure {
389 let hidden_ty = self.resolve_vars_if_possible(&hidden_ty);
390 unexpected_hidden_region_diagnostic(
403 // This method goes through all the errors and try to group certain types
404 // of error together, for the purpose of suggesting explicit lifetime
405 // parameters to the user. This is done so that we can have a more
406 // complete view of what lifetimes should be the same.
407 // If the return value is an empty vector, it means that processing
408 // failed (so the return value of this method should not be used).
410 // The method also attempts to weed out messages that seem like
411 // duplicates that will be unhelpful to the end-user. But
412 // obviously it never weeds out ALL errors.
415 errors: &Vec<RegionResolutionError<'tcx>>,
416 ) -> Vec<RegionResolutionError<'tcx>> {
417 debug!("process_errors()");
419 // We want to avoid reporting generic-bound failures if we can
420 // avoid it: these have a very high rate of being unhelpful in
421 // practice. This is because they are basically secondary
422 // checks that test the state of the region graph after the
423 // rest of inference is done, and the other kinds of errors
424 // indicate that the region constraint graph is internally
425 // inconsistent, so these test results are likely to be
428 // Therefore, we filter them out of the list unless they are
429 // the only thing in the list.
431 let is_bound_failure = |e: &RegionResolutionError<'tcx>| match *e {
432 RegionResolutionError::GenericBoundFailure(..) => true,
433 RegionResolutionError::ConcreteFailure(..)
434 | RegionResolutionError::SubSupConflict(..)
435 | RegionResolutionError::UpperBoundUniverseConflict(..)
436 | RegionResolutionError::MemberConstraintFailure { .. } => false,
439 let mut errors = if errors.iter().all(|e| is_bound_failure(e)) {
442 errors.iter().filter(|&e| !is_bound_failure(e)).cloned().collect()
445 // sort the errors by span, for better error message stability.
446 errors.sort_by_key(|u| match *u {
447 RegionResolutionError::ConcreteFailure(ref sro, _, _) => sro.span(),
448 RegionResolutionError::GenericBoundFailure(ref sro, _, _) => sro.span(),
449 RegionResolutionError::SubSupConflict(_, ref rvo, _, _, _, _) => rvo.span(),
450 RegionResolutionError::UpperBoundUniverseConflict(_, ref rvo, _, _, _) => rvo.span(),
451 RegionResolutionError::MemberConstraintFailure { span, .. } => span,
456 /// Adds a note if the types come from similarly named crates
457 fn check_and_note_conflicting_crates(
459 err: &mut DiagnosticBuilder<'_>,
460 terr: &TypeError<'tcx>,
462 use hir::def_id::CrateNum;
463 use rustc_hir::definitions::DisambiguatedDefPathData;
464 use ty::print::Printer;
465 use ty::subst::GenericArg;
467 struct AbsolutePathPrinter<'tcx> {
471 struct NonTrivialPath;
473 impl<'tcx> Printer<'tcx> for AbsolutePathPrinter<'tcx> {
474 type Error = NonTrivialPath;
476 type Path = Vec<String>;
479 type DynExistential = !;
482 fn tcx<'a>(&'a self) -> TyCtxt<'tcx> {
486 fn print_region(self, _region: ty::Region<'_>) -> Result<Self::Region, Self::Error> {
490 fn print_type(self, _ty: Ty<'tcx>) -> Result<Self::Type, Self::Error> {
494 fn print_dyn_existential(
496 _predicates: &'tcx ty::List<ty::ExistentialPredicate<'tcx>>,
497 ) -> Result<Self::DynExistential, Self::Error> {
501 fn print_const(self, _ct: &'tcx ty::Const<'tcx>) -> Result<Self::Const, Self::Error> {
505 fn path_crate(self, cnum: CrateNum) -> Result<Self::Path, Self::Error> {
506 Ok(vec![self.tcx.original_crate_name(cnum).to_string()])
511 _trait_ref: Option<ty::TraitRef<'tcx>>,
512 ) -> Result<Self::Path, Self::Error> {
518 _print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
519 _disambiguated_data: &DisambiguatedDefPathData,
521 _trait_ref: Option<ty::TraitRef<'tcx>>,
522 ) -> Result<Self::Path, Self::Error> {
527 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
528 disambiguated_data: &DisambiguatedDefPathData,
529 ) -> Result<Self::Path, Self::Error> {
530 let mut path = print_prefix(self)?;
531 path.push(disambiguated_data.data.as_symbol().to_string());
534 fn path_generic_args(
536 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
537 _args: &[GenericArg<'tcx>],
538 ) -> Result<Self::Path, Self::Error> {
543 let report_path_match = |err: &mut DiagnosticBuilder<'_>, did1: DefId, did2: DefId| {
544 // Only external crates, if either is from a local
545 // module we could have false positives
546 if !(did1.is_local() || did2.is_local()) && did1.krate != did2.krate {
548 |def_id| AbsolutePathPrinter { tcx: self.tcx }.print_def_path(def_id, &[]);
550 // We compare strings because DefPath can be different
551 // for imported and non-imported crates
552 let same_path = || -> Result<_, NonTrivialPath> {
553 Ok(self.tcx.def_path_str(did1) == self.tcx.def_path_str(did2)
554 || abs_path(did1)? == abs_path(did2)?)
556 if same_path().unwrap_or(false) {
557 let crate_name = self.tcx.crate_name(did1.krate);
559 "perhaps two different versions of crate `{}` are being used?",
566 TypeError::Sorts(ref exp_found) => {
567 // if they are both "path types", there's a chance of ambiguity
568 // due to different versions of the same crate
569 if let (&ty::Adt(exp_adt, _), &ty::Adt(found_adt, _)) =
570 (&exp_found.expected.kind, &exp_found.found.kind)
572 report_path_match(err, exp_adt.did, found_adt.did);
575 TypeError::Traits(ref exp_found) => {
576 report_path_match(err, exp_found.expected, exp_found.found);
578 _ => (), // FIXME(#22750) handle traits and stuff
582 fn note_error_origin(
584 err: &mut DiagnosticBuilder<'tcx>,
585 cause: &ObligationCause<'tcx>,
586 exp_found: Option<ty::error::ExpectedFound<Ty<'tcx>>>,
589 ObligationCauseCode::Pattern { origin_expr: true, span: Some(span), root_ty } => {
590 let ty = self.resolve_vars_if_possible(&root_ty);
591 if ty.is_suggestable() {
592 // don't show type `_`
593 err.span_label(span, format!("this expression has type `{}`", ty));
595 if let Some(ty::error::ExpectedFound { found, .. }) = exp_found {
596 if ty.is_box() && ty.boxed_ty() == found {
597 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
600 "consider dereferencing the boxed value",
601 format!("*{}", snippet),
602 Applicability::MachineApplicable,
608 ObligationCauseCode::Pattern { origin_expr: false, span: Some(span), .. } => {
609 err.span_label(span, "expected due to this");
611 ObligationCauseCode::MatchExpressionArm(box MatchExpressionArmCause {
618 hir::MatchSource::IfLetDesugar { .. } => {
619 let msg = "`if let` arms have incompatible types";
620 err.span_label(cause.span, msg);
622 hir::MatchSource::TryDesugar => {
623 if let Some(ty::error::ExpectedFound { expected, .. }) = exp_found {
624 let scrut_expr = self.tcx.hir().expect_expr(scrut_hir_id);
625 let scrut_ty = if let hir::ExprKind::Call(_, args) = &scrut_expr.kind {
626 let arg_expr = args.first().expect("try desugaring call w/out arg");
627 self.in_progress_typeck_results.and_then(|typeck_results| {
628 typeck_results.borrow().expr_ty_opt(arg_expr)
631 bug!("try desugaring w/out call expr as scrutinee");
635 Some(ty) if expected == ty => {
636 let source_map = self.tcx.sess.source_map();
638 source_map.end_point(cause.span),
639 "try removing this `?`",
641 Applicability::MachineApplicable,
649 // `last_ty` can be `!`, `expected` will have better info when present.
650 let t = self.resolve_vars_if_possible(&match exp_found {
651 Some(ty::error::ExpectedFound { expected, .. }) => expected,
654 let msg = "`match` arms have incompatible types";
655 err.span_label(cause.span, msg);
656 if prior_arms.len() <= 4 {
657 for sp in prior_arms {
658 err.span_label(*sp, format!("this is found to be of type `{}`", t));
660 } else if let Some(sp) = prior_arms.last() {
663 format!("this and all prior arms are found to be of type `{}`", t),
668 ObligationCauseCode::IfExpression(box IfExpressionCause { then, outer, semicolon }) => {
669 err.span_label(then, "expected because of this");
670 if let Some(sp) = outer {
671 err.span_label(sp, "`if` and `else` have incompatible types");
673 if let Some(sp) = semicolon {
674 err.span_suggestion_short(
676 "consider removing this semicolon",
678 Applicability::MachineApplicable,
686 /// Given that `other_ty` is the same as a type argument for `name` in `sub`, populate `value`
687 /// highlighting `name` and every type argument that isn't at `pos` (which is `other_ty`), and
688 /// populate `other_value` with `other_ty`.
692 /// ^^^^--------^ this is highlighted
694 /// | this type argument is exactly the same as the other type, not highlighted
695 /// this is highlighted
697 /// -------- this type is the same as a type argument in the other type, not highlighted
701 value: &mut DiagnosticStyledString,
702 other_value: &mut DiagnosticStyledString,
704 sub: ty::subst::SubstsRef<'tcx>,
708 // `value` and `other_value` hold two incomplete type representation for display.
709 // `name` is the path of both types being compared. `sub`
710 value.push_highlighted(name);
713 value.push_highlighted("<");
716 // Output the lifetimes for the first type
720 let s = lifetime.to_string();
721 if s.is_empty() { "'_".to_string() } else { s }
725 if !lifetimes.is_empty() {
726 if sub.regions().count() < len {
727 value.push_normal(lifetimes + ", ");
729 value.push_normal(lifetimes);
733 // Highlight all the type arguments that aren't at `pos` and compare the type argument at
734 // `pos` and `other_ty`.
735 for (i, type_arg) in sub.types().enumerate() {
737 let values = self.cmp(type_arg, other_ty);
738 value.0.extend((values.0).0);
739 other_value.0.extend((values.1).0);
741 value.push_highlighted(type_arg.to_string());
744 if len > 0 && i != len - 1 {
745 value.push_normal(", ");
749 value.push_highlighted(">");
753 /// If `other_ty` is the same as a type argument present in `sub`, highlight `path` in `t1_out`,
754 /// as that is the difference to the other type.
756 /// For the following code:
759 /// let x: Foo<Bar<Qux>> = foo::<Bar<Qux>>();
762 /// The type error output will behave in the following way:
766 /// ^^^^--------^ this is highlighted
768 /// | this type argument is exactly the same as the other type, not highlighted
769 /// this is highlighted
771 /// -------- this type is the same as a type argument in the other type, not highlighted
775 mut t1_out: &mut DiagnosticStyledString,
776 mut t2_out: &mut DiagnosticStyledString,
778 sub: ty::subst::SubstsRef<'tcx>,
782 for (i, ta) in sub.types().enumerate() {
784 self.highlight_outer(&mut t1_out, &mut t2_out, path, sub, i, &other_ty);
787 if let &ty::Adt(def, _) = &ta.kind {
788 let path_ = self.tcx.def_path_str(def.did);
789 if path_ == other_path {
790 self.highlight_outer(&mut t1_out, &mut t2_out, path, sub, i, &other_ty);
798 /// Adds a `,` to the type representation only if it is appropriate.
801 value: &mut DiagnosticStyledString,
802 other_value: &mut DiagnosticStyledString,
806 if len > 0 && pos != len - 1 {
807 value.push_normal(", ");
808 other_value.push_normal(", ");
812 /// For generic types with parameters with defaults, remove the parameters corresponding to
813 /// the defaults. This repeats a lot of the logic found in `ty::print::pretty`.
814 fn strip_generic_default_params(
817 substs: ty::subst::SubstsRef<'tcx>,
818 ) -> SubstsRef<'tcx> {
819 let generics = self.tcx.generics_of(def_id);
820 let mut num_supplied_defaults = 0;
821 let mut type_params = generics
825 .filter_map(|param| match param.kind {
826 ty::GenericParamDefKind::Lifetime => None,
827 ty::GenericParamDefKind::Type { has_default, .. } => {
828 Some((param.def_id, has_default))
830 ty::GenericParamDefKind::Const => None, // FIXME(const_generics:defaults)
834 let has_default = type_params.peek().map(|(_, has_default)| has_default);
835 *has_default.unwrap_or(&false)
838 let types = substs.types().rev();
839 for ((def_id, has_default), actual) in type_params.zip(types) {
843 if self.tcx.type_of(def_id).subst(self.tcx, substs) != actual {
846 num_supplied_defaults += 1;
849 let len = generics.params.len();
850 let mut generics = generics.clone();
851 generics.params.truncate(len - num_supplied_defaults);
852 substs.truncate_to(self.tcx, &generics)
855 /// Given two `fn` signatures highlight only sub-parts that are different.
858 sig1: &ty::PolyFnSig<'tcx>,
859 sig2: &ty::PolyFnSig<'tcx>,
860 ) -> (DiagnosticStyledString, DiagnosticStyledString) {
861 let get_lifetimes = |sig| {
862 use rustc_hir::def::Namespace;
863 let mut s = String::new();
864 let (_, (sig, reg)) = ty::print::FmtPrinter::new(self.tcx, &mut s, Namespace::TypeNS)
865 .name_all_regions(sig)
867 let lts: Vec<String> = reg.into_iter().map(|(_, kind)| kind.to_string()).collect();
868 (if lts.is_empty() { String::new() } else { format!("for<{}> ", lts.join(", ")) }, sig)
871 let (lt1, sig1) = get_lifetimes(sig1);
872 let (lt2, sig2) = get_lifetimes(sig2);
874 // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
876 DiagnosticStyledString::normal("".to_string()),
877 DiagnosticStyledString::normal("".to_string()),
880 // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
882 values.0.push(sig1.unsafety.prefix_str(), sig1.unsafety != sig2.unsafety);
883 values.1.push(sig2.unsafety.prefix_str(), sig1.unsafety != sig2.unsafety);
885 // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
887 if sig1.abi != abi::Abi::Rust {
888 values.0.push(format!("extern {} ", sig1.abi), sig1.abi != sig2.abi);
890 if sig2.abi != abi::Abi::Rust {
891 values.1.push(format!("extern {} ", sig2.abi), sig1.abi != sig2.abi);
894 // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
896 let lifetime_diff = lt1 != lt2;
897 values.0.push(lt1, lifetime_diff);
898 values.1.push(lt2, lifetime_diff);
900 // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
902 values.0.push_normal("fn(");
903 values.1.push_normal("fn(");
905 // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
907 let len1 = sig1.inputs().len();
908 let len2 = sig2.inputs().len();
910 for (i, (l, r)) in sig1.inputs().iter().zip(sig2.inputs().iter()).enumerate() {
911 let (x1, x2) = self.cmp(l, r);
912 (values.0).0.extend(x1.0);
913 (values.1).0.extend(x2.0);
914 self.push_comma(&mut values.0, &mut values.1, len1, i);
917 for (i, l) in sig1.inputs().iter().enumerate() {
918 values.0.push_highlighted(l.to_string());
920 values.0.push_highlighted(", ");
923 for (i, r) in sig2.inputs().iter().enumerate() {
924 values.1.push_highlighted(r.to_string());
926 values.1.push_highlighted(", ");
933 values.0.push_normal(", ");
935 values.0.push("...", !sig2.c_variadic);
939 values.1.push_normal(", ");
941 values.1.push("...", !sig1.c_variadic);
944 // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
946 values.0.push_normal(")");
947 values.1.push_normal(")");
949 // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
951 let output1 = sig1.output();
952 let output2 = sig2.output();
953 let (x1, x2) = self.cmp(output1, output2);
954 if !output1.is_unit() {
955 values.0.push_normal(" -> ");
956 (values.0).0.extend(x1.0);
958 if !output2.is_unit() {
959 values.1.push_normal(" -> ");
960 (values.1).0.extend(x2.0);
965 /// Compares two given types, eliding parts that are the same between them and highlighting
966 /// relevant differences, and return two representation of those types for highlighted printing.
967 fn cmp(&self, t1: Ty<'tcx>, t2: Ty<'tcx>) -> (DiagnosticStyledString, DiagnosticStyledString) {
968 debug!("cmp(t1={}, t1.kind={:?}, t2={}, t2.kind={:?})", t1, t1.kind, t2, t2.kind);
971 fn equals<'tcx>(a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
972 match (&a.kind, &b.kind) {
973 (a, b) if *a == *b => true,
974 (&ty::Int(_), &ty::Infer(ty::InferTy::IntVar(_)))
976 &ty::Infer(ty::InferTy::IntVar(_)),
977 &ty::Int(_) | &ty::Infer(ty::InferTy::IntVar(_)),
979 | (&ty::Float(_), &ty::Infer(ty::InferTy::FloatVar(_)))
981 &ty::Infer(ty::InferTy::FloatVar(_)),
982 &ty::Float(_) | &ty::Infer(ty::InferTy::FloatVar(_)),
988 fn push_ty_ref<'tcx>(
989 region: &ty::Region<'tcx>,
991 mutbl: hir::Mutability,
992 s: &mut DiagnosticStyledString,
994 let mut r = region.to_string();
1000 s.push_highlighted(format!("&{}{}", r, mutbl.prefix_str()));
1001 s.push_normal(ty.to_string());
1004 // process starts here
1005 match (&t1.kind, &t2.kind) {
1006 (&ty::Adt(def1, sub1), &ty::Adt(def2, sub2)) => {
1007 let sub_no_defaults_1 = self.strip_generic_default_params(def1.did, sub1);
1008 let sub_no_defaults_2 = self.strip_generic_default_params(def2.did, sub2);
1009 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
1010 let path1 = self.tcx.def_path_str(def1.did);
1011 let path2 = self.tcx.def_path_str(def2.did);
1012 if def1.did == def2.did {
1013 // Easy case. Replace same types with `_` to shorten the output and highlight
1014 // the differing ones.
1015 // let x: Foo<Bar, Qux> = y::<Foo<Quz, Qux>>();
1018 // --- ^ type argument elided
1020 // highlighted in output
1021 values.0.push_normal(path1);
1022 values.1.push_normal(path2);
1024 // Avoid printing out default generic parameters that are common to both
1026 let len1 = sub_no_defaults_1.len();
1027 let len2 = sub_no_defaults_2.len();
1028 let common_len = cmp::min(len1, len2);
1029 let remainder1: Vec<_> = sub1.types().skip(common_len).collect();
1030 let remainder2: Vec<_> = sub2.types().skip(common_len).collect();
1031 let common_default_params = remainder1
1034 .zip(remainder2.iter().rev())
1035 .filter(|(a, b)| a == b)
1037 let len = sub1.len() - common_default_params;
1038 let consts_offset = len - sub1.consts().count();
1040 // Only draw `<...>` if there're lifetime/type arguments.
1042 values.0.push_normal("<");
1043 values.1.push_normal("<");
1046 fn lifetime_display(lifetime: Region<'_>) -> String {
1047 let s = lifetime.to_string();
1048 if s.is_empty() { "'_".to_string() } else { s }
1050 // At one point we'd like to elide all lifetimes here, they are irrelevant for
1051 // all diagnostics that use this output
1055 // ^^ ^^ --- type arguments are not elided
1057 // | elided as they were the same
1058 // not elided, they were different, but irrelevant
1059 let lifetimes = sub1.regions().zip(sub2.regions());
1060 for (i, lifetimes) in lifetimes.enumerate() {
1061 let l1 = lifetime_display(lifetimes.0);
1062 let l2 = lifetime_display(lifetimes.1);
1063 if lifetimes.0 == lifetimes.1 {
1064 values.0.push_normal("'_");
1065 values.1.push_normal("'_");
1067 values.0.push_highlighted(l1);
1068 values.1.push_highlighted(l2);
1070 self.push_comma(&mut values.0, &mut values.1, len, i);
1073 // We're comparing two types with the same path, so we compare the type
1074 // arguments for both. If they are the same, do not highlight and elide from the
1078 // ^ elided type as this type argument was the same in both sides
1079 let type_arguments = sub1.types().zip(sub2.types());
1080 let regions_len = sub1.regions().count();
1081 let num_display_types = consts_offset - regions_len;
1082 for (i, (ta1, ta2)) in type_arguments.take(num_display_types).enumerate() {
1083 let i = i + regions_len;
1085 values.0.push_normal("_");
1086 values.1.push_normal("_");
1088 let (x1, x2) = self.cmp(ta1, ta2);
1089 (values.0).0.extend(x1.0);
1090 (values.1).0.extend(x2.0);
1092 self.push_comma(&mut values.0, &mut values.1, len, i);
1095 // Do the same for const arguments, if they are equal, do not highlight and
1096 // elide them from the output.
1097 let const_arguments = sub1.consts().zip(sub2.consts());
1098 for (i, (ca1, ca2)) in const_arguments.enumerate() {
1099 let i = i + consts_offset;
1101 values.0.push_normal("_");
1102 values.1.push_normal("_");
1104 values.0.push_highlighted(ca1.to_string());
1105 values.1.push_highlighted(ca2.to_string());
1107 self.push_comma(&mut values.0, &mut values.1, len, i);
1110 // Close the type argument bracket.
1111 // Only draw `<...>` if there're lifetime/type arguments.
1113 values.0.push_normal(">");
1114 values.1.push_normal(">");
1119 // let x: Foo<Bar<Qux> = foo::<Bar<Qux>>();
1121 // ------- this type argument is exactly the same as the other type
1137 // let x: Bar<Qux> = y:<Foo<Bar<Qux>>>();
1140 // ------- this type argument is exactly the same as the other type
1155 // We can't find anything in common, highlight relevant part of type path.
1156 // let x: foo::bar::Baz<Qux> = y:<foo::bar::Bar<Zar>>();
1157 // foo::bar::Baz<Qux>
1158 // foo::bar::Bar<Zar>
1159 // -------- this part of the path is different
1161 let t1_str = t1.to_string();
1162 let t2_str = t2.to_string();
1163 let min_len = t1_str.len().min(t2_str.len());
1165 const SEPARATOR: &str = "::";
1166 let separator_len = SEPARATOR.len();
1167 let split_idx: usize = t1_str
1169 .zip(t2_str.split(SEPARATOR))
1170 .take_while(|(mod1_str, mod2_str)| mod1_str == mod2_str)
1171 .map(|(mod_str, _)| mod_str.len() + separator_len)
1175 "cmp: separator_len={}, split_idx={}, min_len={}",
1176 separator_len, split_idx, min_len
1179 if split_idx >= min_len {
1180 // paths are identical, highlight everything
1182 DiagnosticStyledString::highlighted(t1_str),
1183 DiagnosticStyledString::highlighted(t2_str),
1186 let (common, uniq1) = t1_str.split_at(split_idx);
1187 let (_, uniq2) = t2_str.split_at(split_idx);
1188 debug!("cmp: common={}, uniq1={}, uniq2={}", common, uniq1, uniq2);
1190 values.0.push_normal(common);
1191 values.0.push_highlighted(uniq1);
1192 values.1.push_normal(common);
1193 values.1.push_highlighted(uniq2);
1200 // When finding T != &T, highlight only the borrow
1201 (&ty::Ref(r1, ref_ty1, mutbl1), _) if equals(&ref_ty1, &t2) => {
1202 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
1203 push_ty_ref(&r1, ref_ty1, mutbl1, &mut values.0);
1204 values.1.push_normal(t2.to_string());
1207 (_, &ty::Ref(r2, ref_ty2, mutbl2)) if equals(&t1, &ref_ty2) => {
1208 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
1209 values.0.push_normal(t1.to_string());
1210 push_ty_ref(&r2, ref_ty2, mutbl2, &mut values.1);
1214 // When encountering &T != &mut T, highlight only the borrow
1215 (&ty::Ref(r1, ref_ty1, mutbl1), &ty::Ref(r2, ref_ty2, mutbl2))
1216 if equals(&ref_ty1, &ref_ty2) =>
1218 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
1219 push_ty_ref(&r1, ref_ty1, mutbl1, &mut values.0);
1220 push_ty_ref(&r2, ref_ty2, mutbl2, &mut values.1);
1224 // When encountering tuples of the same size, highlight only the differing types
1225 (&ty::Tuple(substs1), &ty::Tuple(substs2)) if substs1.len() == substs2.len() => {
1227 (DiagnosticStyledString::normal("("), DiagnosticStyledString::normal("("));
1228 let len = substs1.len();
1229 for (i, (left, right)) in substs1.types().zip(substs2.types()).enumerate() {
1230 let (x1, x2) = self.cmp(left, right);
1231 (values.0).0.extend(x1.0);
1232 (values.1).0.extend(x2.0);
1233 self.push_comma(&mut values.0, &mut values.1, len, i);
1236 // Keep the output for single element tuples as `(ty,)`.
1237 values.0.push_normal(",");
1238 values.1.push_normal(",");
1240 values.0.push_normal(")");
1241 values.1.push_normal(")");
1245 (ty::FnDef(did1, substs1), ty::FnDef(did2, substs2)) => {
1246 let sig1 = self.tcx.fn_sig(*did1).subst(self.tcx, substs1);
1247 let sig2 = self.tcx.fn_sig(*did2).subst(self.tcx, substs2);
1248 let mut values = self.cmp_fn_sig(&sig1, &sig2);
1249 let path1 = format!(" {{{}}}", self.tcx.def_path_str_with_substs(*did1, substs1));
1250 let path2 = format!(" {{{}}}", self.tcx.def_path_str_with_substs(*did2, substs2));
1251 let same_path = path1 == path2;
1252 values.0.push(path1, !same_path);
1253 values.1.push(path2, !same_path);
1257 (ty::FnDef(did1, substs1), ty::FnPtr(sig2)) => {
1258 let sig1 = self.tcx.fn_sig(*did1).subst(self.tcx, substs1);
1259 let mut values = self.cmp_fn_sig(&sig1, sig2);
1260 values.0.push_highlighted(format!(
1262 self.tcx.def_path_str_with_substs(*did1, substs1)
1267 (ty::FnPtr(sig1), ty::FnDef(did2, substs2)) => {
1268 let sig2 = self.tcx.fn_sig(*did2).subst(self.tcx, substs2);
1269 let mut values = self.cmp_fn_sig(sig1, &sig2);
1270 values.1.push_normal(format!(
1272 self.tcx.def_path_str_with_substs(*did2, substs2)
1277 (ty::FnPtr(sig1), ty::FnPtr(sig2)) => self.cmp_fn_sig(sig1, sig2),
1281 // The two types are the same, elide and don't highlight.
1282 (DiagnosticStyledString::normal("_"), DiagnosticStyledString::normal("_"))
1284 // We couldn't find anything in common, highlight everything.
1286 DiagnosticStyledString::highlighted(t1.to_string()),
1287 DiagnosticStyledString::highlighted(t2.to_string()),
1294 pub fn note_type_err(
1296 diag: &mut DiagnosticBuilder<'tcx>,
1297 cause: &ObligationCause<'tcx>,
1298 secondary_span: Option<(Span, String)>,
1299 mut values: Option<ValuePairs<'tcx>>,
1300 terr: &TypeError<'tcx>,
1302 let span = cause.span(self.tcx);
1303 debug!("note_type_err cause={:?} values={:?}, terr={:?}", cause, values, terr);
1305 // For some types of errors, expected-found does not make
1306 // sense, so just ignore the values we were given.
1307 if let TypeError::CyclicTy(_) = terr {
1310 struct OpaqueTypesVisitor<'tcx> {
1311 types: FxHashMap<TyCategory, FxHashSet<Span>>,
1312 expected: FxHashMap<TyCategory, FxHashSet<Span>>,
1313 found: FxHashMap<TyCategory, FxHashSet<Span>>,
1318 impl<'tcx> OpaqueTypesVisitor<'tcx> {
1319 fn visit_expected_found(
1325 let mut types_visitor = OpaqueTypesVisitor {
1326 types: Default::default(),
1327 expected: Default::default(),
1328 found: Default::default(),
1332 // The visitor puts all the relevant encountered types in `self.types`, but in
1333 // here we want to visit two separate types with no relation to each other, so we
1334 // move the results from `types` to `expected` or `found` as appropriate.
1335 expected.visit_with(&mut types_visitor);
1336 std::mem::swap(&mut types_visitor.expected, &mut types_visitor.types);
1337 found.visit_with(&mut types_visitor);
1338 std::mem::swap(&mut types_visitor.found, &mut types_visitor.types);
1342 fn report(&self, err: &mut DiagnosticBuilder<'_>) {
1343 self.add_labels_for_types(err, "expected", &self.expected);
1344 self.add_labels_for_types(err, "found", &self.found);
1347 fn add_labels_for_types(
1349 err: &mut DiagnosticBuilder<'_>,
1351 types: &FxHashMap<TyCategory, FxHashSet<Span>>,
1353 for (key, values) in types.iter() {
1354 let count = values.len();
1355 let kind = key.descr();
1361 if sp.is_desugaring(DesugaringKind::Async) {
1362 "the `Output` of this `async fn`'s "
1363 } else if count == 1 {
1368 if count > 1 { "one of the " } else { "" },
1379 impl<'tcx> ty::fold::TypeVisitor<'tcx> for OpaqueTypesVisitor<'tcx> {
1380 fn visit_ty(&mut self, t: Ty<'tcx>) -> bool {
1381 if let Some((kind, def_id)) = TyCategory::from_ty(t) {
1382 let span = self.tcx.def_span(def_id);
1383 // Avoid cluttering the output when the "found" and error span overlap:
1385 // error[E0308]: mismatched types
1386 // --> $DIR/issue-20862.rs:2:5
1391 // | the found closure
1392 // | expected `()`, found closure
1394 // = note: expected unit type `()`
1395 // found closure `[closure@$DIR/issue-20862.rs:2:5: 2:14 x:_]`
1396 if !self.ignore_span.overlaps(span) {
1397 self.types.entry(kind).or_default().insert(span);
1400 t.super_visit_with(self)
1404 debug!("note_type_err(diag={:?})", diag);
1405 let (expected_found, exp_found, is_simple_error) = match values {
1406 None => (None, None, false),
1408 let (is_simple_error, exp_found) = match values {
1409 ValuePairs::Types(exp_found) => {
1411 exp_found.expected.is_simple_text() && exp_found.found.is_simple_text();
1412 OpaqueTypesVisitor::visit_expected_found(
1420 (is_simple_err, Some(exp_found))
1424 let vals = match self.values_str(&values) {
1425 Some((expected, found)) => Some((expected, found)),
1427 // Derived error. Cancel the emitter.
1432 (vals, exp_found, is_simple_error)
1436 // Ignore msg for object safe coercion
1437 // since E0038 message will be printed
1439 TypeError::ObjectUnsafeCoercion(_) => {}
1441 diag.span_label(span, terr.to_string());
1442 if let Some((sp, msg)) = secondary_span {
1443 diag.span_label(sp, msg);
1447 if let Some((expected, found)) = expected_found {
1448 let expected_label = exp_found.map_or("type".into(), |ef| ef.expected.prefix_string());
1449 let found_label = exp_found.map_or("type".into(), |ef| ef.found.prefix_string());
1450 match (&terr, expected == found) {
1451 (TypeError::Sorts(values), extra) => {
1452 let sort_string = |ty: Ty<'tcx>| match (extra, &ty.kind) {
1453 (true, ty::Opaque(def_id, _)) => format!(
1454 " (opaque type at {})",
1458 .mk_substr_filename(self.tcx.def_span(*def_id)),
1460 (true, _) => format!(" ({})", ty.sort_string(self.tcx)),
1461 (false, _) => "".to_string(),
1463 if !(values.expected.is_simple_text() && values.found.is_simple_text())
1464 || (exp_found.map_or(false, |ef| {
1465 // This happens when the type error is a subset of the expectation,
1466 // like when you have two references but one is `usize` and the other
1467 // is `f32`. In those cases we still want to show the `note`. If the
1468 // value from `ef` is `Infer(_)`, then we ignore it.
1469 if !ef.expected.is_ty_infer() {
1470 ef.expected != values.expected
1471 } else if !ef.found.is_ty_infer() {
1472 ef.found != values.found
1478 diag.note_expected_found_extra(
1483 &sort_string(values.expected),
1484 &sort_string(values.found),
1488 (TypeError::ObjectUnsafeCoercion(_), _) => {
1489 diag.note_unsuccessfull_coercion(found, expected);
1493 "note_type_err: exp_found={:?}, expected={:?} found={:?}",
1494 exp_found, expected, found
1496 if !is_simple_error || terr.must_include_note() {
1497 diag.note_expected_found(&expected_label, expected, &found_label, found);
1502 if let Some(exp_found) = exp_found {
1503 self.suggest_as_ref_where_appropriate(span, &exp_found, diag);
1506 // In some (most?) cases cause.body_id points to actual body, but in some cases
1507 // it's a actual definition. According to the comments (e.g. in
1508 // librustc_typeck/check/compare_method.rs:compare_predicate_entailment) the latter
1509 // is relied upon by some other code. This might (or might not) need cleanup.
1510 let body_owner_def_id =
1511 self.tcx.hir().opt_local_def_id(cause.body_id).unwrap_or_else(|| {
1512 self.tcx.hir().body_owner_def_id(hir::BodyId { hir_id: cause.body_id })
1514 self.check_and_note_conflicting_crates(diag, terr);
1515 self.tcx.note_and_explain_type_err(diag, terr, cause, span, body_owner_def_id.to_def_id());
1517 // It reads better to have the error origin as the final
1519 self.note_error_origin(diag, cause, exp_found);
1522 /// When encountering a case where `.as_ref()` on a `Result` or `Option` would be appropriate,
1524 fn suggest_as_ref_where_appropriate(
1527 exp_found: &ty::error::ExpectedFound<Ty<'tcx>>,
1528 diag: &mut DiagnosticBuilder<'tcx>,
1530 if let (ty::Adt(exp_def, exp_substs), ty::Ref(_, found_ty, _)) =
1531 (&exp_found.expected.kind, &exp_found.found.kind)
1533 if let ty::Adt(found_def, found_substs) = found_ty.kind {
1534 let path_str = format!("{:?}", exp_def);
1535 if exp_def == &found_def {
1536 let opt_msg = "you can convert from `&Option<T>` to `Option<&T>` using \
1538 let result_msg = "you can convert from `&Result<T, E>` to \
1539 `Result<&T, &E>` using `.as_ref()`";
1540 let have_as_ref = &[
1541 ("std::option::Option", opt_msg),
1542 ("core::option::Option", opt_msg),
1543 ("std::result::Result", result_msg),
1544 ("core::result::Result", result_msg),
1546 if let Some(msg) = have_as_ref
1548 .find_map(|(path, msg)| (&path_str == path).then_some(msg))
1550 let mut show_suggestion = true;
1551 for (exp_ty, found_ty) in exp_substs.types().zip(found_substs.types()) {
1553 ty::Ref(_, exp_ty, _) => {
1554 match (&exp_ty.kind, &found_ty.kind) {
1558 | (ty::Infer(_), _) => {}
1559 _ if ty::TyS::same_type(exp_ty, found_ty) => {}
1560 _ => show_suggestion = false,
1563 ty::Param(_) | ty::Infer(_) => {}
1564 _ => show_suggestion = false,
1567 if let (Ok(snippet), true) =
1568 (self.tcx.sess.source_map().span_to_snippet(span), show_suggestion)
1570 diag.span_suggestion(
1573 format!("{}.as_ref()", snippet),
1574 Applicability::MachineApplicable,
1583 pub fn report_and_explain_type_error(
1585 trace: TypeTrace<'tcx>,
1586 terr: &TypeError<'tcx>,
1587 ) -> DiagnosticBuilder<'tcx> {
1588 debug!("report_and_explain_type_error(trace={:?}, terr={:?})", trace, terr);
1590 let span = trace.cause.span(self.tcx);
1591 let failure_code = trace.cause.as_failure_code(terr);
1592 let mut diag = match failure_code {
1593 FailureCode::Error0038(did) => {
1594 let violations = self.tcx.object_safety_violations(did);
1595 report_object_safety_error(self.tcx, span, did, violations)
1597 FailureCode::Error0317(failure_str) => {
1598 struct_span_err!(self.tcx.sess, span, E0317, "{}", failure_str)
1600 FailureCode::Error0580(failure_str) => {
1601 struct_span_err!(self.tcx.sess, span, E0580, "{}", failure_str)
1603 FailureCode::Error0308(failure_str) => {
1604 struct_span_err!(self.tcx.sess, span, E0308, "{}", failure_str)
1606 FailureCode::Error0644(failure_str) => {
1607 struct_span_err!(self.tcx.sess, span, E0644, "{}", failure_str)
1610 self.note_type_err(&mut diag, &trace.cause, None, Some(trace.values), terr);
1616 values: &ValuePairs<'tcx>,
1617 ) -> Option<(DiagnosticStyledString, DiagnosticStyledString)> {
1619 infer::Types(ref exp_found) => self.expected_found_str_ty(exp_found),
1620 infer::Regions(ref exp_found) => self.expected_found_str(exp_found),
1621 infer::Consts(ref exp_found) => self.expected_found_str(exp_found),
1622 infer::TraitRefs(ref exp_found) => {
1623 let pretty_exp_found = ty::error::ExpectedFound {
1624 expected: exp_found.expected.print_only_trait_path(),
1625 found: exp_found.found.print_only_trait_path(),
1627 self.expected_found_str(&pretty_exp_found)
1629 infer::PolyTraitRefs(ref exp_found) => {
1630 let pretty_exp_found = ty::error::ExpectedFound {
1631 expected: exp_found.expected.print_only_trait_path(),
1632 found: exp_found.found.print_only_trait_path(),
1634 self.expected_found_str(&pretty_exp_found)
1639 fn expected_found_str_ty(
1641 exp_found: &ty::error::ExpectedFound<Ty<'tcx>>,
1642 ) -> Option<(DiagnosticStyledString, DiagnosticStyledString)> {
1643 let exp_found = self.resolve_vars_if_possible(exp_found);
1644 if exp_found.references_error() {
1648 Some(self.cmp(exp_found.expected, exp_found.found))
1651 /// Returns a string of the form "expected `{}`, found `{}`".
1652 fn expected_found_str<T: fmt::Display + TypeFoldable<'tcx>>(
1654 exp_found: &ty::error::ExpectedFound<T>,
1655 ) -> Option<(DiagnosticStyledString, DiagnosticStyledString)> {
1656 let exp_found = self.resolve_vars_if_possible(exp_found);
1657 if exp_found.references_error() {
1662 DiagnosticStyledString::highlighted(exp_found.expected.to_string()),
1663 DiagnosticStyledString::highlighted(exp_found.found.to_string()),
1667 pub fn report_generic_bound_failure(
1670 origin: Option<SubregionOrigin<'tcx>>,
1671 bound_kind: GenericKind<'tcx>,
1674 self.construct_generic_bound_failure(span, origin, bound_kind, sub).emit();
1677 pub fn construct_generic_bound_failure(
1680 origin: Option<SubregionOrigin<'tcx>>,
1681 bound_kind: GenericKind<'tcx>,
1683 ) -> DiagnosticBuilder<'a> {
1684 let hir = &self.tcx.hir();
1685 // Attempt to obtain the span of the parameter so we can
1686 // suggest adding an explicit lifetime bound to it.
1688 .in_progress_typeck_results
1689 .map(|typeck_results| typeck_results.borrow().hir_owner)
1691 let hir_id = hir.as_local_hir_id(owner);
1692 let parent_id = hir.get_parent_item(hir_id);
1694 // Parent item could be a `mod`, so we check the HIR before calling:
1695 if let Some(Node::Item(Item {
1696 kind: ItemKind::Trait(..) | ItemKind::Impl { .. },
1698 })) = hir.find(parent_id)
1700 Some(self.tcx.generics_of(hir.local_def_id(parent_id).to_def_id()))
1704 self.tcx.generics_of(owner.to_def_id()),
1707 let type_param_span = match (generics, bound_kind) {
1708 (Some((_, ref generics)), GenericKind::Param(ref param)) => {
1709 // Account for the case where `param` corresponds to `Self`,
1710 // which doesn't have the expected type argument.
1711 if !(generics.has_self && param.index == 0) {
1712 let type_param = generics.type_param(param, self.tcx);
1713 type_param.def_id.as_local().map(|def_id| {
1714 // Get the `hir::Param` to verify whether it already has any bounds.
1715 // We do this to avoid suggesting code that ends up as `T: 'a'b`,
1716 // instead we suggest `T: 'a + 'b` in that case.
1717 let id = hir.as_local_hir_id(def_id);
1718 let mut has_bounds = false;
1719 if let Node::GenericParam(param) = hir.get(id) {
1720 has_bounds = !param.bounds.is_empty();
1722 let sp = hir.span(id);
1723 // `sp` only covers `T`, change it so that it covers
1724 // `T:` when appropriate
1725 let is_impl_trait = bound_kind.to_string().starts_with("impl ");
1726 let sp = if has_bounds && !is_impl_trait {
1731 .next_point(self.tcx.sess.source_map().next_point(sp)))
1735 (sp, has_bounds, is_impl_trait)
1743 let new_lt = generics
1745 .and_then(|(parent_g, g)| {
1746 let possible: Vec<_> = (b'a'..=b'z').map(|c| format!("'{}", c as char)).collect();
1747 let mut lts_names = g
1750 .filter(|p| matches!(p.kind, ty::GenericParamDefKind::Lifetime))
1751 .map(|p| p.name.as_str())
1752 .collect::<Vec<_>>();
1753 if let Some(g) = parent_g {
1757 .filter(|p| matches!(p.kind, ty::GenericParamDefKind::Lifetime))
1758 .map(|p| p.name.as_str()),
1761 let lts = lts_names.iter().map(|s| -> &str { &*s }).collect::<Vec<_>>();
1762 possible.into_iter().find(|candidate| !lts.contains(&candidate.as_str()))
1764 .unwrap_or("'lt".to_string());
1765 let add_lt_sugg = generics
1767 .and_then(|(_, g)| g.params.first())
1768 .and_then(|param| param.def_id.as_local())
1770 (hir.span(hir.as_local_hir_id(def_id)).shrink_to_lo(), format!("{}, ", new_lt))
1773 let labeled_user_string = match bound_kind {
1774 GenericKind::Param(ref p) => format!("the parameter type `{}`", p),
1775 GenericKind::Projection(ref p) => format!("the associated type `{}`", p),
1778 if let Some(SubregionOrigin::CompareImplMethodObligation {
1785 return self.report_extra_impl_obligation(
1790 &format!("`{}: {}`", bound_kind, sub),
1794 fn binding_suggestion<'tcx, S: fmt::Display>(
1795 err: &mut DiagnosticBuilder<'tcx>,
1796 type_param_span: Option<(Span, bool, bool)>,
1797 bound_kind: GenericKind<'tcx>,
1800 let msg = "consider adding an explicit lifetime bound";
1801 if let Some((sp, has_lifetimes, is_impl_trait)) = type_param_span {
1802 let suggestion = if is_impl_trait {
1803 format!("{} + {}", bound_kind, sub)
1805 let tail = if has_lifetimes { " + " } else { "" };
1806 format!("{}: {}{}", bound_kind, sub, tail)
1808 err.span_suggestion(
1810 &format!("{}...", msg),
1812 Applicability::MaybeIncorrect, // Issue #41966
1815 let consider = format!(
1818 if type_param_span.map(|(_, _, is_impl_trait)| is_impl_trait).unwrap_or(false) {
1819 format!(" `{}` to `{}`", sub, bound_kind)
1821 format!("`{}: {}`", bound_kind, sub)
1824 err.help(&consider);
1828 let new_binding_suggestion =
1829 |err: &mut DiagnosticBuilder<'tcx>,
1830 type_param_span: Option<(Span, bool, bool)>,
1831 bound_kind: GenericKind<'tcx>| {
1832 let msg = "consider introducing an explicit lifetime bound";
1833 if let Some((sp, has_lifetimes, is_impl_trait)) = type_param_span {
1834 let suggestion = if is_impl_trait {
1835 (sp.shrink_to_hi(), format!(" + {}", new_lt))
1837 let tail = if has_lifetimes { " +" } else { "" };
1838 (sp, format!("{}: {}{}", bound_kind, new_lt, tail))
1841 vec![suggestion, (span.shrink_to_hi(), format!(" + {}", new_lt))];
1842 if let Some(lt) = add_lt_sugg {
1844 sugg.rotate_right(1);
1846 // `MaybeIncorrect` due to issue #41966.
1847 err.multipart_suggestion(msg, sugg, Applicability::MaybeIncorrect);
1851 let mut err = match *sub {
1852 ty::ReEarlyBound(ty::EarlyBoundRegion { name, .. })
1853 | ty::ReFree(ty::FreeRegion { bound_region: ty::BrNamed(_, name), .. }) => {
1854 // Does the required lifetime have a nice name we can print?
1855 let mut err = struct_span_err!(
1859 "{} may not live long enough",
1862 // Explicitly use the name instead of `sub`'s `Display` impl. The `Display` impl
1863 // for the bound is not suitable for suggestions when `-Zverbose` is set because it
1864 // uses `Debug` output, so we handle it specially here so that suggestions are
1866 binding_suggestion(&mut err, type_param_span, bound_kind, name);
1871 // Does the required lifetime have a nice name we can print?
1872 let mut err = struct_span_err!(
1876 "{} may not live long enough",
1879 binding_suggestion(&mut err, type_param_span, bound_kind, "'static");
1884 // If not, be less specific.
1885 let mut err = struct_span_err!(
1889 "{} may not live long enough",
1892 note_and_explain_region(
1895 &format!("{} must be valid for ", labeled_user_string),
1899 if let Some(infer::RelateParamBound(_, t)) = origin {
1900 let t = self.resolve_vars_if_possible(&t);
1903 // fn get_later<G, T>(g: G, dest: &mut T) -> impl FnOnce() + '_
1905 // fn get_later<'a, G: 'a, T>(g: G, dest: &mut T) -> impl FnOnce() + '_ + 'a
1906 ty::Closure(_, _substs) | ty::Opaque(_, _substs) => {
1907 new_binding_suggestion(&mut err, type_param_span, bound_kind);
1910 binding_suggestion(&mut err, type_param_span, bound_kind, new_lt);
1918 if let Some(origin) = origin {
1919 self.note_region_origin(&mut err, &origin);
1924 fn report_sub_sup_conflict(
1926 var_origin: RegionVariableOrigin,
1927 sub_origin: SubregionOrigin<'tcx>,
1928 sub_region: Region<'tcx>,
1929 sup_origin: SubregionOrigin<'tcx>,
1930 sup_region: Region<'tcx>,
1932 let mut err = self.report_inference_failure(var_origin);
1934 note_and_explain_region(
1937 "first, the lifetime cannot outlive ",
1942 debug!("report_sub_sup_conflict: var_origin={:?}", var_origin);
1943 debug!("report_sub_sup_conflict: sub_region={:?}", sub_region);
1944 debug!("report_sub_sup_conflict: sub_origin={:?}", sub_origin);
1945 debug!("report_sub_sup_conflict: sup_region={:?}", sup_region);
1946 debug!("report_sub_sup_conflict: sup_origin={:?}", sup_origin);
1948 if let (&infer::Subtype(ref sup_trace), &infer::Subtype(ref sub_trace)) =
1949 (&sup_origin, &sub_origin)
1951 debug!("report_sub_sup_conflict: sup_trace={:?}", sup_trace);
1952 debug!("report_sub_sup_conflict: sub_trace={:?}", sub_trace);
1953 debug!("report_sub_sup_conflict: sup_trace.values={:?}", sup_trace.values);
1954 debug!("report_sub_sup_conflict: sub_trace.values={:?}", sub_trace.values);
1956 if let (Some((sup_expected, sup_found)), Some((sub_expected, sub_found))) =
1957 (self.values_str(&sup_trace.values), self.values_str(&sub_trace.values))
1959 if sub_expected == sup_expected && sub_found == sup_found {
1960 note_and_explain_region(
1963 "...but the lifetime must also be valid for ",
1968 sup_trace.cause.span,
1969 &format!("...so that the {}", sup_trace.cause.as_requirement_str()),
1972 err.note_expected_found(&"", sup_expected, &"", sup_found);
1979 self.note_region_origin(&mut err, &sup_origin);
1981 note_and_explain_region(
1984 "but, the lifetime must be valid for ",
1989 self.note_region_origin(&mut err, &sub_origin);
1994 impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
1995 fn report_inference_failure(
1997 var_origin: RegionVariableOrigin,
1998 ) -> DiagnosticBuilder<'tcx> {
1999 let br_string = |br: ty::BoundRegion| {
2000 let mut s = match br {
2001 ty::BrNamed(_, name) => name.to_string(),
2009 let var_description = match var_origin {
2010 infer::MiscVariable(_) => String::new(),
2011 infer::PatternRegion(_) => " for pattern".to_string(),
2012 infer::AddrOfRegion(_) => " for borrow expression".to_string(),
2013 infer::Autoref(_, _) => " for autoref".to_string(),
2014 infer::Coercion(_) => " for automatic coercion".to_string(),
2015 infer::LateBoundRegion(_, br, infer::FnCall) => {
2016 format!(" for lifetime parameter {}in function call", br_string(br))
2018 infer::LateBoundRegion(_, br, infer::HigherRankedType) => {
2019 format!(" for lifetime parameter {}in generic type", br_string(br))
2021 infer::LateBoundRegion(_, br, infer::AssocTypeProjection(def_id)) => format!(
2022 " for lifetime parameter {}in trait containing associated type `{}`",
2024 self.tcx.associated_item(def_id).ident
2026 infer::EarlyBoundRegion(_, name) => format!(" for lifetime parameter `{}`", name),
2027 infer::BoundRegionInCoherence(name) => {
2028 format!(" for lifetime parameter `{}` in coherence check", name)
2030 infer::UpvarRegion(ref upvar_id, _) => {
2031 let var_name = self.tcx.hir().name(upvar_id.var_path.hir_id);
2032 format!(" for capture of `{}` by closure", var_name)
2034 infer::NLL(..) => bug!("NLL variable found in lexical phase"),
2041 "cannot infer an appropriate lifetime{} due to conflicting requirements",
2049 Error0317(&'static str),
2050 Error0580(&'static str),
2051 Error0308(&'static str),
2052 Error0644(&'static str),
2055 trait ObligationCauseExt<'tcx> {
2056 fn as_failure_code(&self, terr: &TypeError<'tcx>) -> FailureCode;
2057 fn as_requirement_str(&self) -> &'static str;
2060 impl<'tcx> ObligationCauseExt<'tcx> for ObligationCause<'tcx> {
2061 fn as_failure_code(&self, terr: &TypeError<'tcx>) -> FailureCode {
2062 use self::FailureCode::*;
2063 use crate::traits::ObligationCauseCode::*;
2065 CompareImplMethodObligation { .. } => Error0308("method not compatible with trait"),
2066 CompareImplTypeObligation { .. } => Error0308("type not compatible with trait"),
2067 MatchExpressionArm(box MatchExpressionArmCause { source, .. }) => {
2068 Error0308(match source {
2069 hir::MatchSource::IfLetDesugar { .. } => {
2070 "`if let` arms have incompatible types"
2072 hir::MatchSource::TryDesugar => {
2073 "try expression alternatives have incompatible types"
2075 _ => "`match` arms have incompatible types",
2078 IfExpression { .. } => Error0308("`if` and `else` have incompatible types"),
2079 IfExpressionWithNoElse => Error0317("`if` may be missing an `else` clause"),
2080 MainFunctionType => Error0580("`main` function has wrong type"),
2081 StartFunctionType => Error0308("`#[start]` function has wrong type"),
2082 IntrinsicType => Error0308("intrinsic has wrong type"),
2083 MethodReceiver => Error0308("mismatched `self` parameter type"),
2085 // In the case where we have no more specific thing to
2086 // say, also take a look at the error code, maybe we can
2089 TypeError::CyclicTy(ty) if ty.is_closure() || ty.is_generator() => {
2090 Error0644("closure/generator type that references itself")
2092 TypeError::IntrinsicCast => {
2093 Error0308("cannot coerce intrinsics to function pointers")
2095 TypeError::ObjectUnsafeCoercion(did) => Error0038(*did),
2096 _ => Error0308("mismatched types"),
2101 fn as_requirement_str(&self) -> &'static str {
2102 use crate::traits::ObligationCauseCode::*;
2104 CompareImplMethodObligation { .. } => "method type is compatible with trait",
2105 CompareImplTypeObligation { .. } => "associated type is compatible with trait",
2106 ExprAssignable => "expression is assignable",
2107 MatchExpressionArm(box MatchExpressionArmCause { source, .. }) => match source {
2108 hir::MatchSource::IfLetDesugar { .. } => "`if let` arms have compatible types",
2109 _ => "`match` arms have compatible types",
2111 IfExpression { .. } => "`if` and `else` have incompatible types",
2112 IfExpressionWithNoElse => "`if` missing an `else` returns `()`",
2113 MainFunctionType => "`main` function has the correct type",
2114 StartFunctionType => "`#[start]` function has the correct type",
2115 IntrinsicType => "intrinsic has the correct type",
2116 MethodReceiver => "method receiver has the correct type",
2117 _ => "types are compatible",
2122 /// This is a bare signal of what kind of type we're dealing with. `ty::TyKind` tracks
2123 /// extra information about each type, but we only care about the category.
2124 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
2125 pub enum TyCategory {
2133 fn descr(&self) -> &'static str {
2135 Self::Closure => "closure",
2136 Self::Opaque => "opaque type",
2137 Self::Generator => "generator",
2138 Self::Foreign => "foreign type",
2142 pub fn from_ty(ty: Ty<'_>) -> Option<(Self, DefId)> {
2144 ty::Closure(def_id, _) => Some((Self::Closure, def_id)),
2145 ty::Opaque(def_id, _) => Some((Self::Opaque, def_id)),
2146 ty::Generator(def_id, ..) => Some((Self::Generator, def_id)),
2147 ty::Foreign(def_id) => Some((Self::Foreign, def_id)),