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
,
56 StatementAsExpression
,
59 use rustc_data_structures
::fx
::{FxHashMap, FxHashSet}
;
60 use rustc_errors
::{pluralize, struct_span_err}
;
61 use rustc_errors
::{Applicability, DiagnosticBuilder, DiagnosticStyledString}
;
63 use rustc_hir
::def_id
::DefId
;
64 use rustc_hir
::lang_items
::LangItem
;
65 use rustc_hir
::{Item, ItemKind, Node}
;
66 use rustc_middle
::ty
::error
::TypeError
;
67 use rustc_middle
::ty
::{
69 subst
::{Subst, SubstsRef}
,
70 Region
, Ty
, TyCtxt
, TypeFoldable
,
72 use rustc_span
::{BytePos, DesugaringKind, Pos, Span}
;
73 use rustc_target
::spec
::abi
;
74 use std
::ops
::ControlFlow
;
80 pub use need_type_info
::TypeAnnotationNeeded
;
82 pub mod nice_region_error
;
84 pub(super) fn note_and_explain_region(
86 err
: &mut DiagnosticBuilder
<'_
>,
88 region
: ty
::Region
<'tcx
>,
91 let (description
, span
) = match *region
{
92 ty
::ReEarlyBound(_
) | ty
::ReFree(_
) | ty
::ReStatic
=> {
93 msg_span_from_free_region(tcx
, region
)
96 ty
::ReEmpty(ty
::UniverseIndex
::ROOT
) => ("the empty lifetime".to_owned(), None
),
98 // uh oh, hope no user ever sees THIS
99 ty
::ReEmpty(ui
) => (format
!("the empty lifetime in universe {:?}", ui
), None
),
101 ty
::RePlaceholder(_
) => ("any other region".to_string(), None
),
103 // FIXME(#13998) RePlaceholder should probably print like
104 // ReFree rather than dumping Debug output on the user.
106 // We shouldn't really be having unification failures with ReVar
107 // and ReLateBound though.
108 ty
::ReVar(_
) | ty
::ReLateBound(..) | ty
::ReErased
=> {
109 (format
!("lifetime {:?}", region
), None
)
113 emit_msg_span(err
, prefix
, description
, span
, suffix
);
116 pub(super) fn note_and_explain_free_region(
118 err
: &mut DiagnosticBuilder
<'_
>,
120 region
: ty
::Region
<'tcx
>,
123 let (description
, span
) = msg_span_from_free_region(tcx
, region
);
125 emit_msg_span(err
, prefix
, description
, span
, suffix
);
128 fn msg_span_from_free_region(
130 region
: ty
::Region
<'tcx
>,
131 ) -> (String
, Option
<Span
>) {
133 ty
::ReEarlyBound(_
) | ty
::ReFree(_
) => {
134 msg_span_from_early_bound_and_free_regions(tcx
, region
)
136 ty
::ReStatic
=> ("the static lifetime".to_owned(), None
),
137 ty
::ReEmpty(ty
::UniverseIndex
::ROOT
) => ("an empty lifetime".to_owned(), None
),
138 ty
::ReEmpty(ui
) => (format
!("an empty lifetime in universe {:?}", ui
), None
),
139 _
=> bug
!("{:?}", region
),
143 fn msg_span_from_early_bound_and_free_regions(
145 region
: ty
::Region
<'tcx
>,
146 ) -> (String
, Option
<Span
>) {
147 let sm
= tcx
.sess
.source_map();
149 let scope
= region
.free_region_binding_scope(tcx
);
150 let node
= tcx
.hir().local_def_id_to_hir_id(scope
.expect_local());
151 let tag
= match tcx
.hir().find(node
) {
152 Some(Node
::Block(_
) | Node
::Expr(_
)) => "body",
153 Some(Node
::Item(it
)) => item_scope_tag(&it
),
154 Some(Node
::TraitItem(it
)) => trait_item_scope_tag(&it
),
155 Some(Node
::ImplItem(it
)) => impl_item_scope_tag(&it
),
158 let (prefix
, span
) = match *region
{
159 ty
::ReEarlyBound(ref br
) => {
160 let mut sp
= sm
.guess_head_span(tcx
.hir().span(node
));
162 tcx
.hir().get_generics(scope
).and_then(|generics
| generics
.get_named(br
.name
))
166 (format
!("the lifetime `{}` as defined on", br
.name
), sp
)
168 ty
::ReFree(ty
::FreeRegion { bound_region: ty::BoundRegion::BrNamed(_, name), .. }
) => {
169 let mut sp
= sm
.guess_head_span(tcx
.hir().span(node
));
171 tcx
.hir().get_generics(scope
).and_then(|generics
| generics
.get_named(name
))
175 (format
!("the lifetime `{}` as defined on", name
), sp
)
177 ty
::ReFree(ref fr
) => match fr
.bound_region
{
179 (format
!("the anonymous lifetime #{} defined on", idx
+ 1), tcx
.hir().span(node
))
182 format
!("the lifetime `{}` as defined on", region
),
183 sm
.guess_head_span(tcx
.hir().span(node
)),
188 let (msg
, opt_span
) = explain_span(tcx
, tag
, span
);
189 (format
!("{} {}", prefix
, msg
), opt_span
)
193 err
: &mut DiagnosticBuilder
<'_
>,
199 let message
= format
!("{}{}{}", prefix
, description
, suffix
);
201 if let Some(span
) = span
{
202 err
.span_note(span
, &message
);
208 fn item_scope_tag(item
: &hir
::Item
<'_
>) -> &'
static str {
210 hir
::ItemKind
::Impl { .. }
=> "impl",
211 hir
::ItemKind
::Struct(..) => "struct",
212 hir
::ItemKind
::Union(..) => "union",
213 hir
::ItemKind
::Enum(..) => "enum",
214 hir
::ItemKind
::Trait(..) => "trait",
215 hir
::ItemKind
::Fn(..) => "function body",
220 fn trait_item_scope_tag(item
: &hir
::TraitItem
<'_
>) -> &'
static str {
222 hir
::TraitItemKind
::Fn(..) => "method body",
223 hir
::TraitItemKind
::Const(..) | hir
::TraitItemKind
::Type(..) => "associated item",
227 fn impl_item_scope_tag(item
: &hir
::ImplItem
<'_
>) -> &'
static str {
229 hir
::ImplItemKind
::Fn(..) => "method body",
230 hir
::ImplItemKind
::Const(..) | hir
::ImplItemKind
::TyAlias(..) => "associated item",
234 fn explain_span(tcx
: TyCtxt
<'tcx
>, heading
: &str, span
: Span
) -> (String
, Option
<Span
>) {
235 let lo
= tcx
.sess
.source_map().lookup_char_pos(span
.lo());
236 (format
!("the {} at {}:{}", heading
, lo
.line
, lo
.col
.to_usize() + 1), Some(span
))
239 pub fn unexpected_hidden_region_diagnostic(
243 hidden_region
: ty
::Region
<'tcx
>,
244 ) -> DiagnosticBuilder
<'tcx
> {
245 let mut err
= struct_span_err
!(
249 "hidden type for `impl Trait` captures lifetime that does not appear in bounds",
252 // Explain the region we are capturing.
253 match hidden_region
{
254 ty
::ReEmpty(ty
::UniverseIndex
::ROOT
) => {
255 // All lifetimes shorter than the function body are `empty` in
256 // lexical region resolution. The default explanation of "an empty
257 // lifetime" isn't really accurate here.
258 let message
= format
!(
259 "hidden type `{}` captures lifetime smaller than the function body",
262 err
.span_note(span
, &message
);
264 ty
::ReEarlyBound(_
) | ty
::ReFree(_
) | ty
::ReStatic
| ty
::ReEmpty(_
) => {
265 // Assuming regionck succeeded (*), we ought to always be
266 // capturing *some* region from the fn header, and hence it
267 // ought to be free. So under normal circumstances, we will go
268 // down this path which gives a decent human readable
271 // (*) if not, the `tainted_by_errors` field would be set to
272 // `Some(ErrorReported)` in any case, so we wouldn't be here at all.
273 note_and_explain_free_region(
276 &format
!("hidden type `{}` captures ", hidden_ty
),
282 // Ugh. This is a painful case: the hidden region is not one
283 // that we can easily summarize or explain. This can happen
285 // `src/test/ui/multiple-lifetimes/ordinary-bounds-unsuited.rs`:
288 // fn upper_bounds<'a, 'b>(a: Ordinary<'a>, b: Ordinary<'b>) -> impl Trait<'a, 'b> {
289 // if condition() { a } else { b }
293 // Here the captured lifetime is the intersection of `'a` and
294 // `'b`, which we can't quite express.
296 // We can at least report a really cryptic error for now.
297 note_and_explain_region(
300 &format
!("hidden type `{}` captures ", hidden_ty
),
310 impl<'a
, 'tcx
> InferCtxt
<'a
, 'tcx
> {
311 pub fn report_region_errors(&self, errors
: &Vec
<RegionResolutionError
<'tcx
>>) {
312 debug
!("report_region_errors(): {} errors to start", errors
.len());
314 // try to pre-process the errors, which will group some of them
315 // together into a `ProcessedErrors` group:
316 let errors
= self.process_errors(errors
);
318 debug
!("report_region_errors: {} errors after preprocessing", errors
.len());
320 for error
in errors
{
321 debug
!("report_region_errors: error = {:?}", error
);
323 if !self.try_report_nice_region_error(&error
) {
324 match error
.clone() {
325 // These errors could indicate all manner of different
326 // problems with many different solutions. Rather
327 // than generate a "one size fits all" error, what we
328 // attempt to do is go through a number of specific
329 // scenarios and try to find the best way to present
330 // the error. If all of these fails, we fall back to a rather
331 // general bit of code that displays the error information
332 RegionResolutionError
::ConcreteFailure(origin
, sub
, sup
) => {
333 if sub
.is_placeholder() || sup
.is_placeholder() {
334 self.report_placeholder_failure(origin
, sub
, sup
).emit();
336 self.report_concrete_failure(origin
, sub
, sup
).emit();
340 RegionResolutionError
::GenericBoundFailure(origin
, param_ty
, sub
) => {
341 self.report_generic_bound_failure(
349 RegionResolutionError
::SubSupConflict(
357 if sub_r
.is_placeholder() {
358 self.report_placeholder_failure(sub_origin
, sub_r
, sup_r
).emit();
359 } else if sup_r
.is_placeholder() {
360 self.report_placeholder_failure(sup_origin
, sub_r
, sup_r
).emit();
362 self.report_sub_sup_conflict(
363 var_origin
, sub_origin
, sub_r
, sup_origin
, sup_r
,
368 RegionResolutionError
::UpperBoundUniverseConflict(
375 assert
!(sup_r
.is_placeholder());
377 // Make a dummy value for the "sub region" --
378 // this is the initial value of the
379 // placeholder. In practice, we expect more
380 // tailored errors that don't really use this
382 let sub_r
= self.tcx
.mk_region(ty
::ReEmpty(var_universe
));
384 self.report_placeholder_failure(sup_origin
, sub_r
, sup_r
).emit();
387 RegionResolutionError
::MemberConstraintFailure
{
392 let hidden_ty
= self.resolve_vars_if_possible(&hidden_ty
);
393 unexpected_hidden_region_diagnostic(
406 // This method goes through all the errors and try to group certain types
407 // of error together, for the purpose of suggesting explicit lifetime
408 // parameters to the user. This is done so that we can have a more
409 // complete view of what lifetimes should be the same.
410 // If the return value is an empty vector, it means that processing
411 // failed (so the return value of this method should not be used).
413 // The method also attempts to weed out messages that seem like
414 // duplicates that will be unhelpful to the end-user. But
415 // obviously it never weeds out ALL errors.
418 errors
: &Vec
<RegionResolutionError
<'tcx
>>,
419 ) -> Vec
<RegionResolutionError
<'tcx
>> {
420 debug
!("process_errors()");
422 // We want to avoid reporting generic-bound failures if we can
423 // avoid it: these have a very high rate of being unhelpful in
424 // practice. This is because they are basically secondary
425 // checks that test the state of the region graph after the
426 // rest of inference is done, and the other kinds of errors
427 // indicate that the region constraint graph is internally
428 // inconsistent, so these test results are likely to be
431 // Therefore, we filter them out of the list unless they are
432 // the only thing in the list.
434 let is_bound_failure
= |e
: &RegionResolutionError
<'tcx
>| match *e
{
435 RegionResolutionError
::GenericBoundFailure(..) => true,
436 RegionResolutionError
::ConcreteFailure(..)
437 | RegionResolutionError
::SubSupConflict(..)
438 | RegionResolutionError
::UpperBoundUniverseConflict(..)
439 | RegionResolutionError
::MemberConstraintFailure { .. }
=> false,
442 let mut errors
= if errors
.iter().all(|e
| is_bound_failure(e
)) {
445 errors
.iter().filter(|&e
| !is_bound_failure(e
)).cloned().collect()
448 // sort the errors by span, for better error message stability.
449 errors
.sort_by_key(|u
| match *u
{
450 RegionResolutionError
::ConcreteFailure(ref sro
, _
, _
) => sro
.span(),
451 RegionResolutionError
::GenericBoundFailure(ref sro
, _
, _
) => sro
.span(),
452 RegionResolutionError
::SubSupConflict(_
, ref rvo
, _
, _
, _
, _
) => rvo
.span(),
453 RegionResolutionError
::UpperBoundUniverseConflict(_
, ref rvo
, _
, _
, _
) => rvo
.span(),
454 RegionResolutionError
::MemberConstraintFailure { span, .. }
=> span
,
459 /// Adds a note if the types come from similarly named crates
460 fn check_and_note_conflicting_crates(
462 err
: &mut DiagnosticBuilder
<'_
>,
463 terr
: &TypeError
<'tcx
>,
465 use hir
::def_id
::CrateNum
;
466 use rustc_hir
::definitions
::DisambiguatedDefPathData
;
467 use ty
::print
::Printer
;
468 use ty
::subst
::GenericArg
;
470 struct AbsolutePathPrinter
<'tcx
> {
474 struct NonTrivialPath
;
476 impl<'tcx
> Printer
<'tcx
> for AbsolutePathPrinter
<'tcx
> {
477 type Error
= NonTrivialPath
;
479 type Path
= Vec
<String
>;
482 type DynExistential
= !;
485 fn tcx
<'a
>(&'a
self) -> TyCtxt
<'tcx
> {
489 fn print_region(self, _region
: ty
::Region
<'_
>) -> Result
<Self::Region
, Self::Error
> {
493 fn print_type(self, _ty
: Ty
<'tcx
>) -> Result
<Self::Type
, Self::Error
> {
497 fn print_dyn_existential(
499 _predicates
: &'tcx ty
::List
<ty
::ExistentialPredicate
<'tcx
>>,
500 ) -> Result
<Self::DynExistential
, Self::Error
> {
504 fn print_const(self, _ct
: &'tcx ty
::Const
<'tcx
>) -> Result
<Self::Const
, Self::Error
> {
508 fn path_crate(self, cnum
: CrateNum
) -> Result
<Self::Path
, Self::Error
> {
509 Ok(vec
![self.tcx
.original_crate_name(cnum
).to_string()])
514 _trait_ref
: Option
<ty
::TraitRef
<'tcx
>>,
515 ) -> Result
<Self::Path
, Self::Error
> {
521 _print_prefix
: impl FnOnce(Self) -> Result
<Self::Path
, Self::Error
>,
522 _disambiguated_data
: &DisambiguatedDefPathData
,
524 _trait_ref
: Option
<ty
::TraitRef
<'tcx
>>,
525 ) -> Result
<Self::Path
, Self::Error
> {
530 print_prefix
: impl FnOnce(Self) -> Result
<Self::Path
, Self::Error
>,
531 disambiguated_data
: &DisambiguatedDefPathData
,
532 ) -> Result
<Self::Path
, Self::Error
> {
533 let mut path
= print_prefix(self)?
;
534 path
.push(disambiguated_data
.to_string());
537 fn path_generic_args(
539 print_prefix
: impl FnOnce(Self) -> Result
<Self::Path
, Self::Error
>,
540 _args
: &[GenericArg
<'tcx
>],
541 ) -> Result
<Self::Path
, Self::Error
> {
546 let report_path_match
= |err
: &mut DiagnosticBuilder
<'_
>, did1
: DefId
, did2
: DefId
| {
547 // Only external crates, if either is from a local
548 // module we could have false positives
549 if !(did1
.is_local() || did2
.is_local()) && did1
.krate
!= did2
.krate
{
551 |def_id
| AbsolutePathPrinter { tcx: self.tcx }
.print_def_path(def_id
, &[]);
553 // We compare strings because DefPath can be different
554 // for imported and non-imported crates
555 let same_path
= || -> Result
<_
, NonTrivialPath
> {
556 Ok(self.tcx
.def_path_str(did1
) == self.tcx
.def_path_str(did2
)
557 || abs_path(did1
)?
== abs_path(did2
)?
)
559 if same_path().unwrap_or(false) {
560 let crate_name
= self.tcx
.crate_name(did1
.krate
);
562 "perhaps two different versions of crate `{}` are being used?",
569 TypeError
::Sorts(ref exp_found
) => {
570 // if they are both "path types", there's a chance of ambiguity
571 // due to different versions of the same crate
572 if let (&ty
::Adt(exp_adt
, _
), &ty
::Adt(found_adt
, _
)) =
573 (exp_found
.expected
.kind(), exp_found
.found
.kind())
575 report_path_match(err
, exp_adt
.did
, found_adt
.did
);
578 TypeError
::Traits(ref exp_found
) => {
579 report_path_match(err
, exp_found
.expected
, exp_found
.found
);
581 _
=> (), // FIXME(#22750) handle traits and stuff
585 fn note_error_origin(
587 err
: &mut DiagnosticBuilder
<'tcx
>,
588 cause
: &ObligationCause
<'tcx
>,
589 exp_found
: Option
<ty
::error
::ExpectedFound
<Ty
<'tcx
>>>,
592 ObligationCauseCode
::Pattern { origin_expr: true, span: Some(span), root_ty }
=> {
593 let ty
= self.resolve_vars_if_possible(&root_ty
);
594 if ty
.is_suggestable() {
595 // don't show type `_`
596 err
.span_label(span
, format
!("this expression has type `{}`", ty
));
598 if let Some(ty
::error
::ExpectedFound { found, .. }
) = exp_found
{
599 if ty
.is_box() && ty
.boxed_ty() == found
{
600 if let Ok(snippet
) = self.tcx
.sess
.source_map().span_to_snippet(span
) {
603 "consider dereferencing the boxed value",
604 format
!("*{}", snippet
),
605 Applicability
::MachineApplicable
,
611 ObligationCauseCode
::Pattern { origin_expr: false, span: Some(span), .. }
=> {
612 err
.span_label(span
, "expected due to this");
614 ObligationCauseCode
::MatchExpressionArm(box MatchExpressionArmCause
{
620 opt_suggest_box_span
,
625 hir
::MatchSource
::IfLetDesugar { .. }
=> {
626 let msg
= "`if let` arms have incompatible types";
627 err
.span_label(cause
.span
, msg
);
628 if let Some(ret_sp
) = opt_suggest_box_span
{
629 self.suggest_boxing_for_return_impl_trait(
632 prior_arms
.iter().chain(std
::iter
::once(&arm_span
)).map(|s
| *s
),
636 hir
::MatchSource
::TryDesugar
=> {
637 if let Some(ty
::error
::ExpectedFound { expected, .. }
) = exp_found
{
638 let scrut_expr
= self.tcx
.hir().expect_expr(scrut_hir_id
);
639 let scrut_ty
= if let hir
::ExprKind
::Call(_
, args
) = &scrut_expr
.kind
{
640 let arg_expr
= args
.first().expect("try desugaring call w/out arg");
641 self.in_progress_typeck_results
.and_then(|typeck_results
| {
642 typeck_results
.borrow().expr_ty_opt(arg_expr
)
645 bug
!("try desugaring w/out call expr as scrutinee");
649 Some(ty
) if expected
== ty
=> {
650 let source_map
= self.tcx
.sess
.source_map();
652 source_map
.end_point(cause
.span
),
653 "try removing this `?`",
655 Applicability
::MachineApplicable
,
663 // `last_ty` can be `!`, `expected` will have better info when present.
664 let t
= self.resolve_vars_if_possible(&match exp_found
{
665 Some(ty
::error
::ExpectedFound { expected, .. }
) => expected
,
668 let source_map
= self.tcx
.sess
.source_map();
669 let mut any_multiline_arm
= source_map
.is_multiline(arm_span
);
670 if prior_arms
.len() <= 4 {
671 for sp
in prior_arms
{
672 any_multiline_arm
|= source_map
.is_multiline(*sp
);
673 err
.span_label(*sp
, format
!("this is found to be of type `{}`", t
));
675 } else if let Some(sp
) = prior_arms
.last() {
676 any_multiline_arm
|= source_map
.is_multiline(*sp
);
679 format
!("this and all prior arms are found to be of type `{}`", t
),
682 let outer_error_span
= if any_multiline_arm
{
683 // Cover just `match` and the scrutinee expression, not
684 // the entire match body, to reduce diagram noise.
685 cause
.span
.shrink_to_lo().to(scrut_span
)
689 let msg
= "`match` arms have incompatible types";
690 err
.span_label(outer_error_span
, msg
);
691 if let Some((sp
, boxed
)) = semi_span
{
692 if let (StatementAsExpression
::NeedsBoxing
, [.., prior_arm
]) =
693 (boxed
, &prior_arms
[..])
695 err
.multipart_suggestion(
696 "consider removing this semicolon and boxing the expressions",
698 (prior_arm
.shrink_to_lo(), "Box::new(".to_string()),
699 (prior_arm
.shrink_to_hi(), ")".to_string()),
700 (arm_span
.shrink_to_lo(), "Box::new(".to_string()),
701 (arm_span
.shrink_to_hi(), ")".to_string()),
704 Applicability
::HasPlaceholders
,
706 } else if matches
!(boxed
, StatementAsExpression
::NeedsBoxing
) {
707 err
.span_suggestion_short(
709 "consider removing this semicolon and boxing the expressions",
711 Applicability
::MachineApplicable
,
714 err
.span_suggestion_short(
716 "consider removing this semicolon",
718 Applicability
::MachineApplicable
,
722 if let Some(ret_sp
) = opt_suggest_box_span
{
723 // Get return type span and point to it.
724 self.suggest_boxing_for_return_impl_trait(
727 prior_arms
.iter().chain(std
::iter
::once(&arm_span
)).map(|s
| *s
),
732 ObligationCauseCode
::IfExpression(box IfExpressionCause
{
737 opt_suggest_box_span
,
739 err
.span_label(then
, "expected because of this");
740 if let Some(sp
) = outer
{
741 err
.span_label(sp
, "`if` and `else` have incompatible types");
743 if let Some((sp
, boxed
)) = semicolon
{
744 if matches
!(boxed
, StatementAsExpression
::NeedsBoxing
) {
745 err
.multipart_suggestion(
746 "consider removing this semicolon and boxing the expression",
748 (then
.shrink_to_lo(), "Box::new(".to_string()),
749 (then
.shrink_to_hi(), ")".to_string()),
750 (else_sp
.shrink_to_lo(), "Box::new(".to_string()),
751 (else_sp
.shrink_to_hi(), ")".to_string()),
754 Applicability
::MachineApplicable
,
757 err
.span_suggestion_short(
759 "consider removing this semicolon",
761 Applicability
::MachineApplicable
,
765 if let Some(ret_sp
) = opt_suggest_box_span
{
766 self.suggest_boxing_for_return_impl_trait(
769 vec
![then
, else_sp
].into_iter(),
777 fn suggest_boxing_for_return_impl_trait(
779 err
: &mut DiagnosticBuilder
<'tcx
>,
781 arm_spans
: impl Iterator
<Item
= Span
>,
783 err
.multipart_suggestion(
784 "you could change the return type to be a boxed trait object",
786 (return_sp
.with_hi(return_sp
.lo() + BytePos(4)), "Box<dyn".to_string()),
787 (return_sp
.shrink_to_hi(), ">".to_string()),
789 Applicability
::MaybeIncorrect
,
794 (sp
.shrink_to_lo(), "Box::new(".to_string()),
795 (sp
.shrink_to_hi(), ")".to_string()),
799 .collect
::<Vec
<_
>>();
800 err
.multipart_suggestion(
801 "if you change the return type to expect trait objects, box the returned expressions",
803 Applicability
::MaybeIncorrect
,
807 /// Given that `other_ty` is the same as a type argument for `name` in `sub`, populate `value`
808 /// highlighting `name` and every type argument that isn't at `pos` (which is `other_ty`), and
809 /// populate `other_value` with `other_ty`.
813 /// ^^^^--------^ this is highlighted
815 /// | this type argument is exactly the same as the other type, not highlighted
816 /// this is highlighted
818 /// -------- this type is the same as a type argument in the other type, not highlighted
822 value
: &mut DiagnosticStyledString
,
823 other_value
: &mut DiagnosticStyledString
,
825 sub
: ty
::subst
::SubstsRef
<'tcx
>,
829 // `value` and `other_value` hold two incomplete type representation for display.
830 // `name` is the path of both types being compared. `sub`
831 value
.push_highlighted(name
);
834 value
.push_highlighted("<");
837 // Output the lifetimes for the first type
841 let s
= lifetime
.to_string();
842 if s
.is_empty() { "'_".to_string() }
else { s }
846 if !lifetimes
.is_empty() {
847 if sub
.regions().count() < len
{
848 value
.push_normal(lifetimes
+ ", ");
850 value
.push_normal(lifetimes
);
854 // Highlight all the type arguments that aren't at `pos` and compare the type argument at
855 // `pos` and `other_ty`.
856 for (i
, type_arg
) in sub
.types().enumerate() {
858 let values
= self.cmp(type_arg
, other_ty
);
859 value
.0.extend((values
.0).0);
860 other_value
.0.extend((values
.1).0);
862 value
.push_highlighted(type_arg
.to_string());
865 if len
> 0 && i
!= len
- 1 {
866 value
.push_normal(", ");
870 value
.push_highlighted(">");
874 /// If `other_ty` is the same as a type argument present in `sub`, highlight `path` in `t1_out`,
875 /// as that is the difference to the other type.
877 /// For the following code:
880 /// let x: Foo<Bar<Qux>> = foo::<Bar<Qux>>();
883 /// The type error output will behave in the following way:
887 /// ^^^^--------^ this is highlighted
889 /// | this type argument is exactly the same as the other type, not highlighted
890 /// this is highlighted
892 /// -------- this type is the same as a type argument in the other type, not highlighted
896 mut t1_out
: &mut DiagnosticStyledString
,
897 mut t2_out
: &mut DiagnosticStyledString
,
899 sub
: ty
::subst
::SubstsRef
<'tcx
>,
903 for (i
, ta
) in sub
.types().enumerate() {
905 self.highlight_outer(&mut t1_out
, &mut t2_out
, path
, sub
, i
, &other_ty
);
908 if let &ty
::Adt(def
, _
) = ta
.kind() {
909 let path_
= self.tcx
.def_path_str(def
.did
);
910 if path_
== other_path
{
911 self.highlight_outer(&mut t1_out
, &mut t2_out
, path
, sub
, i
, &other_ty
);
919 /// Adds a `,` to the type representation only if it is appropriate.
922 value
: &mut DiagnosticStyledString
,
923 other_value
: &mut DiagnosticStyledString
,
927 if len
> 0 && pos
!= len
- 1 {
928 value
.push_normal(", ");
929 other_value
.push_normal(", ");
933 /// For generic types with parameters with defaults, remove the parameters corresponding to
934 /// the defaults. This repeats a lot of the logic found in `ty::print::pretty`.
935 fn strip_generic_default_params(
938 substs
: ty
::subst
::SubstsRef
<'tcx
>,
939 ) -> SubstsRef
<'tcx
> {
940 let generics
= self.tcx
.generics_of(def_id
);
941 let mut num_supplied_defaults
= 0;
942 let mut type_params
= generics
946 .filter_map(|param
| match param
.kind
{
947 ty
::GenericParamDefKind
::Lifetime
=> None
,
948 ty
::GenericParamDefKind
::Type { has_default, .. }
=> {
949 Some((param
.def_id
, has_default
))
951 ty
::GenericParamDefKind
::Const
=> None
, // FIXME(const_generics:defaults)
955 let has_default
= type_params
.peek().map(|(_
, has_default
)| has_default
);
956 *has_default
.unwrap_or(&false)
959 let types
= substs
.types().rev();
960 for ((def_id
, has_default
), actual
) in type_params
.zip(types
) {
964 if self.tcx
.type_of(def_id
).subst(self.tcx
, substs
) != actual
{
967 num_supplied_defaults
+= 1;
970 let len
= generics
.params
.len();
971 let mut generics
= generics
.clone();
972 generics
.params
.truncate(len
- num_supplied_defaults
);
973 substs
.truncate_to(self.tcx
, &generics
)
976 /// Given two `fn` signatures highlight only sub-parts that are different.
979 sig1
: &ty
::PolyFnSig
<'tcx
>,
980 sig2
: &ty
::PolyFnSig
<'tcx
>,
981 ) -> (DiagnosticStyledString
, DiagnosticStyledString
) {
982 let get_lifetimes
= |sig
| {
983 use rustc_hir
::def
::Namespace
;
984 let mut s
= String
::new();
985 let (_
, (sig
, reg
)) = ty
::print
::FmtPrinter
::new(self.tcx
, &mut s
, Namespace
::TypeNS
)
986 .name_all_regions(sig
)
988 let lts
: Vec
<String
> = reg
.into_iter().map(|(_
, kind
)| kind
.to_string()).collect();
989 (if lts
.is_empty() { String::new() }
else { format!("for<{}
> ", lts.join(", ")) }, sig)
992 let (lt1, sig1) = get_lifetimes(sig1);
993 let (lt2, sig2) = get_lifetimes(sig2);
995 // unsafe extern "C
" for<'a> fn(&'a T) -> &'a T
997 DiagnosticStyledString::normal("".to_string()),
998 DiagnosticStyledString::normal("".to_string()),
1001 // unsafe extern "C
" for<'a> fn(&'a T) -> &'a T
1003 values.0.push(sig1.unsafety.prefix_str(), sig1.unsafety != sig2.unsafety);
1004 values.1.push(sig2.unsafety.prefix_str(), sig1.unsafety != sig2.unsafety);
1006 // unsafe extern "C
" for<'a> fn(&'a T) -> &'a T
1008 if sig1.abi != abi::Abi::Rust {
1009 values.0.push(format!("extern {}
", sig1.abi), sig1.abi != sig2.abi);
1011 if sig2.abi != abi::Abi::Rust {
1012 values.1.push(format!("extern {}
", sig2.abi), sig1.abi != sig2.abi);
1015 // unsafe extern "C
" for<'a> fn(&'a T) -> &'a T
1017 let lifetime_diff = lt1 != lt2;
1018 values.0.push(lt1, lifetime_diff);
1019 values.1.push(lt2, lifetime_diff);
1021 // unsafe extern "C
" for<'a> fn(&'a T) -> &'a T
1023 values.0.push_normal("fn(");
1024 values.1.push_normal("fn(");
1026 // unsafe extern "C
" for<'a> fn(&'a T) -> &'a T
1028 let len1 = sig1.inputs().len();
1029 let len2 = sig2.inputs().len();
1031 for (i, (l, r)) in sig1.inputs().iter().zip(sig2.inputs().iter()).enumerate() {
1032 let (x1, x2) = self.cmp(l, r);
1033 (values.0).0.extend(x1.0);
1034 (values.1).0.extend(x2.0);
1035 self.push_comma(&mut values.0, &mut values.1, len1, i);
1038 for (i, l) in sig1.inputs().iter().enumerate() {
1039 values.0.push_highlighted(l.to_string());
1041 values.0.push_highlighted(", ");
1044 for (i, r) in sig2.inputs().iter().enumerate() {
1045 values.1.push_highlighted(r.to_string());
1047 values.1.push_highlighted(", ");
1052 if sig1.c_variadic {
1054 values.0.push_normal(", ");
1056 values.0.push("...", !sig2.c_variadic);
1058 if sig2.c_variadic {
1060 values.1.push_normal(", ");
1062 values.1.push("...", !sig1.c_variadic);
1065 // unsafe extern "C
" for<'a> fn(&'a T) -> &'a T
1067 values.0.push_normal(")");
1068 values.1.push_normal(")");
1070 // unsafe extern "C
" for<'a> fn(&'a T) -> &'a T
1072 let output1 = sig1.output();
1073 let output2 = sig2.output();
1074 let (x1, x2) = self.cmp(output1, output2);
1075 if !output1.is_unit() {
1076 values.0.push_normal(" -> ");
1077 (values.0).0.extend(x1.0);
1079 if !output2.is_unit() {
1080 values.1.push_normal(" -> ");
1081 (values.1).0.extend(x2.0);
1086 /// Compares two given types, eliding parts that are the same between them and highlighting
1087 /// relevant differences, and return two representation of those types for highlighted printing.
1088 fn cmp(&self, t1: Ty<'tcx>, t2: Ty<'tcx>) -> (DiagnosticStyledString, DiagnosticStyledString) {
1089 debug!("cmp(t1
={}
, t1
.kind
={:?}
, t2
={}
, t2
.kind
={:?}
)", t1, t1.kind(), t2, t2.kind());
1092 fn equals<'tcx>(a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
1093 match (a.kind(), b.kind()) {
1094 (a, b) if *a == *b => true,
1095 (&ty::Int(_), &ty::Infer(ty::InferTy::IntVar(_)))
1097 &ty::Infer(ty::InferTy::IntVar(_)),
1098 &ty::Int(_) | &ty::Infer(ty::InferTy::IntVar(_)),
1100 | (&ty::Float(_), &ty::Infer(ty::InferTy::FloatVar(_)))
1102 &ty::Infer(ty::InferTy::FloatVar(_)),
1103 &ty::Float(_) | &ty::Infer(ty::InferTy::FloatVar(_)),
1109 fn push_ty_ref<'tcx>(
1110 region: &ty::Region<'tcx>,
1112 mutbl: hir::Mutability,
1113 s: &mut DiagnosticStyledString,
1115 let mut r = region.to_string();
1121 s.push_highlighted(format!("&{}{}
", r, mutbl.prefix_str()));
1122 s.push_normal(ty.to_string());
1125 // process starts here
1126 match (t1.kind(), t2.kind()) {
1127 (&ty::Adt(def1, sub1), &ty::Adt(def2, sub2)) => {
1128 let sub_no_defaults_1 = self.strip_generic_default_params(def1.did, sub1);
1129 let sub_no_defaults_2 = self.strip_generic_default_params(def2.did, sub2);
1130 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
1131 let path1 = self.tcx.def_path_str(def1.did);
1132 let path2 = self.tcx.def_path_str(def2.did);
1133 if def1.did == def2.did {
1134 // Easy case. Replace same types with `_` to shorten the output and highlight
1135 // the differing ones.
1136 // let x: Foo<Bar, Qux> = y::<Foo<Quz, Qux>>();
1139 // --- ^ type argument elided
1141 // highlighted in output
1142 values.0.push_normal(path1);
1143 values.1.push_normal(path2);
1145 // Avoid printing out default generic parameters that are common to both
1147 let len1 = sub_no_defaults_1.len();
1148 let len2 = sub_no_defaults_2.len();
1149 let common_len = cmp::min(len1, len2);
1150 let remainder1: Vec<_> = sub1.types().skip(common_len).collect();
1151 let remainder2: Vec<_> = sub2.types().skip(common_len).collect();
1152 let common_default_params = remainder1
1155 .zip(remainder2.iter().rev())
1156 .filter(|(a, b)| a == b)
1158 let len = sub1.len() - common_default_params;
1159 let consts_offset = len - sub1.consts().count();
1161 // Only draw `<...>` if there're lifetime/type arguments.
1163 values.0.push_normal("<");
1164 values.1.push_normal("<");
1167 fn lifetime_display(lifetime: Region<'_>) -> String {
1168 let s = lifetime.to_string();
1169 if s.is_empty() { "'_".to_string() } else { s }
1171 // At one point we'd like to elide all lifetimes here, they are irrelevant for
1172 // all diagnostics that use this output
1176 // ^^ ^^ --- type arguments are not elided
1178 // | elided as they were the same
1179 // not elided, they were different, but irrelevant
1180 let lifetimes = sub1.regions().zip(sub2.regions());
1181 for (i, lifetimes) in lifetimes.enumerate() {
1182 let l1 = lifetime_display(lifetimes.0);
1183 let l2 = lifetime_display(lifetimes.1);
1184 if lifetimes.0 == lifetimes.1 {
1185 values.0.push_normal("'_
");
1186 values.1.push_normal("'_
");
1188 values.0.push_highlighted(l1);
1189 values.1.push_highlighted(l2);
1191 self.push_comma(&mut values.0, &mut values.1, len, i);
1194 // We're comparing two types with the same path, so we compare the type
1195 // arguments for both. If they are the same, do not highlight and elide from the
1199 // ^ elided type as this type argument was the same in both sides
1200 let type_arguments = sub1.types().zip(sub2.types());
1201 let regions_len = sub1.regions().count();
1202 let num_display_types = consts_offset - regions_len;
1203 for (i, (ta1, ta2)) in type_arguments.take(num_display_types).enumerate() {
1204 let i = i + regions_len;
1206 values.0.push_normal("_
");
1207 values.1.push_normal("_
");
1209 let (x1, x2) = self.cmp(ta1, ta2);
1210 (values.0).0.extend(x1.0);
1211 (values.1).0.extend(x2.0);
1213 self.push_comma(&mut values.0, &mut values.1, len, i);
1216 // Do the same for const arguments, if they are equal, do not highlight and
1217 // elide them from the output.
1218 let const_arguments = sub1.consts().zip(sub2.consts());
1219 for (i, (ca1, ca2)) in const_arguments.enumerate() {
1220 let i = i + consts_offset;
1222 values.0.push_normal("_
");
1223 values.1.push_normal("_
");
1225 values.0.push_highlighted(ca1.to_string());
1226 values.1.push_highlighted(ca2.to_string());
1228 self.push_comma(&mut values.0, &mut values.1, len, i);
1231 // Close the type argument bracket.
1232 // Only draw `<...>` if there're lifetime/type arguments.
1234 values.0.push_normal(">");
1235 values.1.push_normal(">");
1240 // let x: Foo<Bar<Qux> = foo::<Bar<Qux>>();
1242 // ------- this type argument is exactly the same as the other type
1258 // let x: Bar<Qux> = y:<Foo<Bar<Qux>>>();
1261 // ------- this type argument is exactly the same as the other type
1276 // We can't find anything in common, highlight relevant part of type path.
1277 // let x: foo::bar::Baz<Qux> = y:<foo::bar::Bar<Zar>>();
1278 // foo::bar::Baz<Qux>
1279 // foo::bar::Bar<Zar>
1280 // -------- this part of the path is different
1282 let t1_str = t1.to_string();
1283 let t2_str = t2.to_string();
1284 let min_len = t1_str.len().min(t2_str.len());
1286 const SEPARATOR: &str = "::";
1287 let separator_len = SEPARATOR.len();
1288 let split_idx: usize = t1_str
1290 .zip(t2_str.split(SEPARATOR))
1291 .take_while(|(mod1_str, mod2_str)| mod1_str == mod2_str)
1292 .map(|(mod_str, _)| mod_str.len() + separator_len)
1296 "cmp
: separator_len
={}
, split_idx
={}
, min_len
={}
",
1297 separator_len, split_idx, min_len
1300 if split_idx >= min_len {
1301 // paths are identical, highlight everything
1303 DiagnosticStyledString::highlighted(t1_str),
1304 DiagnosticStyledString::highlighted(t2_str),
1307 let (common, uniq1) = t1_str.split_at(split_idx);
1308 let (_, uniq2) = t2_str.split_at(split_idx);
1309 debug!("cmp
: common
={}
, uniq1
={}
, uniq2
={}
", common, uniq1, uniq2);
1311 values.0.push_normal(common);
1312 values.0.push_highlighted(uniq1);
1313 values.1.push_normal(common);
1314 values.1.push_highlighted(uniq2);
1321 // When finding T != &T, highlight only the borrow
1322 (&ty::Ref(r1, ref_ty1, mutbl1), _) if equals(&ref_ty1, &t2) => {
1323 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
1324 push_ty_ref(&r1, ref_ty1, mutbl1, &mut values.0);
1325 values.1.push_normal(t2.to_string());
1328 (_, &ty::Ref(r2, ref_ty2, mutbl2)) if equals(&t1, &ref_ty2) => {
1329 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
1330 values.0.push_normal(t1.to_string());
1331 push_ty_ref(&r2, ref_ty2, mutbl2, &mut values.1);
1335 // When encountering &T != &mut T, highlight only the borrow
1336 (&ty::Ref(r1, ref_ty1, mutbl1), &ty::Ref(r2, ref_ty2, mutbl2))
1337 if equals(&ref_ty1, &ref_ty2) =>
1339 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
1340 push_ty_ref(&r1, ref_ty1, mutbl1, &mut values.0);
1341 push_ty_ref(&r2, ref_ty2, mutbl2, &mut values.1);
1345 // When encountering tuples of the same size, highlight only the differing types
1346 (&ty::Tuple(substs1), &ty::Tuple(substs2)) if substs1.len() == substs2.len() => {
1348 (DiagnosticStyledString::normal("("), DiagnosticStyledString::normal("("));
1349 let len = substs1.len();
1350 for (i, (left, right)) in substs1.types().zip(substs2.types()).enumerate() {
1351 let (x1, x2) = self.cmp(left, right);
1352 (values.0).0.extend(x1.0);
1353 (values.1).0.extend(x2.0);
1354 self.push_comma(&mut values.0, &mut values.1, len, i);
1357 // Keep the output for single element tuples as `(ty,)`.
1358 values.0.push_normal(",");
1359 values.1.push_normal(",");
1361 values.0.push_normal(")");
1362 values.1.push_normal(")");
1366 (ty::FnDef(did1, substs1), ty::FnDef(did2, substs2)) => {
1367 let sig1 = self.tcx.fn_sig(*did1).subst(self.tcx, substs1);
1368 let sig2 = self.tcx.fn_sig(*did2).subst(self.tcx, substs2);
1369 let mut values = self.cmp_fn_sig(&sig1, &sig2);
1370 let path1 = format!(" {{{}
}}", self.tcx.def_path_str_with_substs(*did1, substs1));
1371 let path2 = format!(" {{{}
}}", self.tcx.def_path_str_with_substs(*did2, substs2));
1372 let same_path = path1 == path2;
1373 values.0.push(path1, !same_path);
1374 values.1.push(path2, !same_path);
1378 (ty::FnDef(did1, substs1), ty::FnPtr(sig2)) => {
1379 let sig1 = self.tcx.fn_sig(*did1).subst(self.tcx, substs1);
1380 let mut values = self.cmp_fn_sig(&sig1, sig2);
1381 values.0.push_highlighted(format!(
1383 self.tcx.def_path_str_with_substs(*did1, substs1)
1388 (ty::FnPtr(sig1), ty::FnDef(did2, substs2)) => {
1389 let sig2 = self.tcx.fn_sig(*did2).subst(self.tcx, substs2);
1390 let mut values = self.cmp_fn_sig(sig1, &sig2);
1391 values.1.push_normal(format!(
1393 self.tcx.def_path_str_with_substs(*did2, substs2)
1398 (ty::FnPtr(sig1), ty::FnPtr(sig2)) => self.cmp_fn_sig(sig1, sig2),
1402 // The two types are the same, elide and don't highlight.
1403 (DiagnosticStyledString::normal("_
"), DiagnosticStyledString::normal("_
"))
1405 // We couldn't find anything in common, highlight everything.
1407 DiagnosticStyledString::highlighted(t1.to_string()),
1408 DiagnosticStyledString::highlighted(t2.to_string()),
1415 pub fn note_type_err(
1417 diag: &mut DiagnosticBuilder<'tcx>,
1418 cause: &ObligationCause<'tcx>,
1419 secondary_span: Option<(Span, String)>,
1420 mut values: Option<ValuePairs<'tcx>>,
1421 terr: &TypeError<'tcx>,
1423 let span = cause.span(self.tcx);
1424 debug!("note_type_err cause
={:?} values
={:?}
, terr
={:?}
", cause, values, terr);
1426 // For some types of errors, expected-found does not make
1427 // sense, so just ignore the values we were given.
1428 if let TypeError::CyclicTy(_) = terr {
1431 struct OpaqueTypesVisitor<'tcx> {
1432 types: FxHashMap<TyCategory, FxHashSet<Span>>,
1433 expected: FxHashMap<TyCategory, FxHashSet<Span>>,
1434 found: FxHashMap<TyCategory, FxHashSet<Span>>,
1439 impl<'tcx> OpaqueTypesVisitor<'tcx> {
1440 fn visit_expected_found(
1446 let mut types_visitor = OpaqueTypesVisitor {
1447 types: Default::default(),
1448 expected: Default::default(),
1449 found: Default::default(),
1453 // The visitor puts all the relevant encountered types in `self.types`, but in
1454 // here we want to visit two separate types with no relation to each other, so we
1455 // move the results from `types` to `expected` or `found` as appropriate.
1456 expected.visit_with(&mut types_visitor);
1457 std::mem::swap(&mut types_visitor.expected, &mut types_visitor.types);
1458 found.visit_with(&mut types_visitor);
1459 std::mem::swap(&mut types_visitor.found, &mut types_visitor.types);
1463 fn report(&self, err: &mut DiagnosticBuilder<'_>) {
1464 self.add_labels_for_types(err, "expected
", &self.expected);
1465 self.add_labels_for_types(err, "found
", &self.found);
1468 fn add_labels_for_types(
1470 err: &mut DiagnosticBuilder<'_>,
1472 types: &FxHashMap<TyCategory, FxHashSet<Span>>,
1474 for (key, values) in types.iter() {
1475 let count = values.len();
1476 let kind = key.descr();
1482 if sp.is_desugaring(DesugaringKind::Async) {
1483 "the `Output` of this `async
fn`'s
"
1484 } else if count == 1 {
1489 if count > 1 { "one of the " } else { "" },
1500 impl<'tcx> ty::fold::TypeVisitor<'tcx> for OpaqueTypesVisitor<'tcx> {
1501 fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<()> {
1502 if let Some((kind, def_id)) = TyCategory::from_ty(t) {
1503 let span = self.tcx.def_span(def_id);
1504 // Avoid cluttering the output when the "found
" and error span overlap:
1506 // error[E0308]: mismatched types
1507 // --> $DIR/issue-20862.rs:2:5
1512 // | the found closure
1513 // | expected `()`, found closure
1515 // = note: expected unit type `()`
1516 // found closure `[closure@$DIR/issue-20862.rs:2:5: 2:14 x:_]`
1517 if !self.ignore_span.overlaps(span) {
1518 self.types.entry(kind).or_default().insert(span);
1521 t.super_visit_with(self)
1525 debug!("note_type_err(diag
={:?}
)", diag);
1527 Variable(ty::error::ExpectedFound<Ty<'a>>),
1528 Fixed(&'static str),
1530 let (expected_found, exp_found, is_simple_error) = match values {
1531 None => (None, Mismatch::Fixed("type"), false),
1533 let (is_simple_error, exp_found) = match values {
1534 ValuePairs::Types(exp_found) => {
1536 exp_found.expected.is_simple_text() && exp_found.found.is_simple_text();
1537 OpaqueTypesVisitor::visit_expected_found(
1545 (is_simple_err, Mismatch::Variable(exp_found))
1547 ValuePairs::TraitRefs(_) => (false, Mismatch::Fixed("trait")),
1548 _ => (false, Mismatch::Fixed("type")),
1550 let vals = match self.values_str(&values) {
1551 Some((expected, found)) => Some((expected, found)),
1553 // Derived error. Cancel the emitter.
1558 (vals, exp_found, is_simple_error)
1562 // Ignore msg for object safe coercion
1563 // since E0038 message will be printed
1565 TypeError::ObjectUnsafeCoercion(_) => {}
1567 diag.span_label(span, terr.to_string());
1568 if let Some((sp, msg)) = secondary_span {
1569 diag.span_label(sp, msg);
1573 if let Some((expected, found)) = expected_found {
1574 let expected_label = match exp_found {
1575 Mismatch::Variable(ef) => ef.expected.prefix_string(),
1576 Mismatch::Fixed(s) => s.into(),
1578 let found_label = match exp_found {
1579 Mismatch::Variable(ef) => ef.found.prefix_string(),
1580 Mismatch::Fixed(s) => s.into(),
1582 let exp_found = match exp_found {
1583 Mismatch::Variable(exp_found) => Some(exp_found),
1584 Mismatch::Fixed(_) => None,
1586 match (&terr, expected == found) {
1587 (TypeError::Sorts(values), extra) => {
1588 let sort_string = |ty: Ty<'tcx>| match (extra, ty.kind()) {
1589 (true, ty::Opaque(def_id, _)) => format!(
1590 " (opaque
type at {}
)",
1594 .mk_substr_filename(self.tcx.def_span(*def_id)),
1596 (true, _) => format!(" ({}
)", ty.sort_string(self.tcx)),
1597 (false, _) => "".to_string(),
1599 if !(values.expected.is_simple_text() && values.found.is_simple_text())
1600 || (exp_found.map_or(false, |ef| {
1601 // This happens when the type error is a subset of the expectation,
1602 // like when you have two references but one is `usize` and the other
1603 // is `f32`. In those cases we still want to show the `note`. If the
1604 // value from `ef` is `Infer(_)`, then we ignore it.
1605 if !ef.expected.is_ty_infer() {
1606 ef.expected != values.expected
1607 } else if !ef.found.is_ty_infer() {
1608 ef.found != values.found
1614 diag.note_expected_found_extra(
1619 &sort_string(values.expected),
1620 &sort_string(values.found),
1624 (TypeError::ObjectUnsafeCoercion(_), _) => {
1625 diag.note_unsuccessfull_coercion(found, expected);
1629 "note_type_err
: exp_found
={:?}
, expected
={:?} found
={:?}
",
1630 exp_found, expected, found
1632 if !is_simple_error || terr.must_include_note() {
1633 diag.note_expected_found(&expected_label, expected, &found_label, found);
1638 let exp_found = match exp_found {
1639 Mismatch::Variable(exp_found) => Some(exp_found),
1640 Mismatch::Fixed(_) => None,
1642 let exp_found = match terr {
1643 // `terr` has more accurate type information than `exp_found` in match expressions.
1644 ty::error::TypeError::Sorts(terr)
1645 if exp_found.map_or(false, |ef| terr.found == ef.found) =>
1651 debug!("exp_found {:?} terr {:?}
", exp_found, terr);
1652 if let Some(exp_found) = exp_found {
1653 self.suggest_as_ref_where_appropriate(span, &exp_found, diag);
1654 self.suggest_await_on_expect_found(cause, span, &exp_found, diag);
1657 // In some (most?) cases cause.body_id points to actual body, but in some cases
1658 // it's a actual definition. According to the comments (e.g. in
1659 // librustc_typeck/check/compare_method.rs:compare_predicate_entailment) the latter
1660 // is relied upon by some other code. This might (or might not) need cleanup.
1661 let body_owner_def_id =
1662 self.tcx.hir().opt_local_def_id(cause.body_id).unwrap_or_else(|| {
1663 self.tcx.hir().body_owner_def_id(hir::BodyId { hir_id: cause.body_id })
1665 self.check_and_note_conflicting_crates(diag, terr);
1666 self.tcx.note_and_explain_type_err(diag, terr, cause, span, body_owner_def_id.to_def_id());
1668 // It reads better to have the error origin as the final
1670 self.note_error_origin(diag, cause, exp_found);
1673 pub fn get_impl_future_output_ty(&self, ty: Ty<'tcx>) -> Option<Ty<'tcx>> {
1674 if let ty::Opaque(def_id, substs) = ty.kind() {
1675 let future_trait = self.tcx.require_lang_item(LangItem::Future, None);
1677 let item_def_id = self
1679 .associated_items(future_trait)
1680 .in_definition_order()
1685 let bounds = self.tcx.explicit_item_bounds(*def_id);
1687 for (predicate, _) in bounds {
1688 let predicate = predicate.subst(self.tcx, substs);
1689 if let ty::PredicateAtom::Projection(projection_predicate) =
1690 predicate.skip_binders()
1692 if projection_predicate.projection_ty.item_def_id == item_def_id {
1693 // We don't account for multiple `Future::Output = Ty` contraints.
1694 return Some(projection_predicate.ty);
1702 /// A possible error is to forget to add `.await` when using futures:
1705 /// async fn make_u32() -> u32 {
1709 /// fn take_u32(x: u32) {}
1711 /// async fn foo() {
1712 /// let x = make_u32();
1717 /// This routine checks if the found type `T` implements `Future<Output=U>` where `U` is the
1718 /// expected type. If this is the case, and we are inside of an async body, it suggests adding
1719 /// `.await` to the tail of the expression.
1720 fn suggest_await_on_expect_found(
1722 cause: &ObligationCause<'tcx>,
1724 exp_found: &ty::error::ExpectedFound<Ty<'tcx>>,
1725 diag: &mut DiagnosticBuilder<'tcx>,
1728 "suggest_await_on_expect_found
: exp_span
={:?}
, expected_ty
={:?}
, found_ty
={:?}
",
1729 exp_span, exp_found.expected, exp_found.found,
1732 if let ObligationCauseCode::CompareImplMethodObligation { .. } = &cause.code {
1737 self.get_impl_future_output_ty(exp_found.expected),
1738 self.get_impl_future_output_ty(exp_found.found),
1740 (Some(exp), Some(found)) if ty::TyS::same_type(exp, found) => match &cause.code {
1741 ObligationCauseCode::IfExpression(box IfExpressionCause { then, .. }) => {
1742 diag.multipart_suggestion(
1743 "consider `await`ing on both `Future`s
",
1745 (then.shrink_to_hi(), ".await
".to_string()),
1746 (exp_span.shrink_to_hi(), ".await
".to_string()),
1748 Applicability::MaybeIncorrect,
1751 ObligationCauseCode::MatchExpressionArm(box MatchExpressionArmCause {
1755 if let [.., arm_span] = &prior_arms[..] {
1756 diag.multipart_suggestion(
1757 "consider `await`ing on both `Future`s
",
1759 (arm_span.shrink_to_hi(), ".await
".to_string()),
1760 (exp_span.shrink_to_hi(), ".await
".to_string()),
1762 Applicability::MaybeIncorrect,
1765 diag.help("consider `await`ing on both `Future`s
");
1769 diag.help("consider `await`ing on both `Future`s
");
1772 (_, Some(ty)) if ty::TyS::same_type(exp_found.expected, ty) => {
1773 let span = match cause.code {
1775 ObligationCauseCode::Pattern { span: Some(span), .. } => span,
1778 diag.span_suggestion_verbose(
1779 span.shrink_to_hi(),
1780 "consider `await`ing on the `Future`
",
1781 ".await
".to_string(),
1782 Applicability::MaybeIncorrect,
1785 (Some(ty), _) if ty::TyS::same_type(ty, exp_found.found) => {
1786 let span = match cause.code {
1788 ObligationCauseCode::Pattern { span: Some(span), .. } => span,
1791 diag.span_suggestion_verbose(
1792 span.shrink_to_hi(),
1793 "consider `await`ing on the `Future`
",
1794 ".await
".to_string(),
1795 Applicability::MaybeIncorrect,
1802 /// When encountering a case where `.as_ref()` on a `Result` or `Option` would be appropriate,
1804 fn suggest_as_ref_where_appropriate(
1807 exp_found: &ty::error::ExpectedFound<Ty<'tcx>>,
1808 diag: &mut DiagnosticBuilder<'tcx>,
1810 if let (ty::Adt(exp_def, exp_substs), ty::Ref(_, found_ty, _)) =
1811 (exp_found.expected.kind(), exp_found.found.kind())
1813 if let ty::Adt(found_def, found_substs) = *found_ty.kind() {
1814 let path_str = format!("{:?}
", exp_def);
1815 if exp_def == &found_def {
1816 let opt_msg = "you can convert from `
&Option
<T
>` to `Option
<&T
>` using
\
1818 let result_msg = "you can convert from `
&Result
<T
, E
>` to
\
1819 `Result
<&T
, &E
>` using `
.as_ref()`
";
1820 let have_as_ref = &[
1821 ("std
::option
::Option
", opt_msg),
1822 ("core
::option
::Option
", opt_msg),
1823 ("std
::result
::Result
", result_msg),
1824 ("core
::result
::Result
", result_msg),
1826 if let Some(msg) = have_as_ref
1828 .find_map(|(path, msg)| (&path_str == path).then_some(msg))
1830 let mut show_suggestion = true;
1831 for (exp_ty, found_ty) in exp_substs.types().zip(found_substs.types()) {
1832 match *exp_ty.kind() {
1833 ty::Ref(_, exp_ty, _) => {
1834 match (exp_ty.kind(), found_ty.kind()) {
1838 | (ty::Infer(_), _) => {}
1839 _ if ty::TyS::same_type(exp_ty, found_ty) => {}
1840 _ => show_suggestion = false,
1843 ty::Param(_) | ty::Infer(_) => {}
1844 _ => show_suggestion = false,
1847 if let (Ok(snippet), true) =
1848 (self.tcx.sess.source_map().span_to_snippet(span), show_suggestion)
1850 diag.span_suggestion(
1853 format!("{}
.as_ref()", snippet),
1854 Applicability::MachineApplicable,
1863 pub fn report_and_explain_type_error(
1865 trace: TypeTrace<'tcx>,
1866 terr: &TypeError<'tcx>,
1867 ) -> DiagnosticBuilder<'tcx> {
1868 debug!("report_and_explain_type_error(trace
={:?}
, terr
={:?}
)", trace, terr);
1870 let span = trace.cause.span(self.tcx);
1871 let failure_code = trace.cause.as_failure_code(terr);
1872 let mut diag = match failure_code {
1873 FailureCode::Error0038(did) => {
1874 let violations = self.tcx.object_safety_violations(did);
1875 report_object_safety_error(self.tcx, span, did, violations)
1877 FailureCode::Error0317(failure_str) => {
1878 struct_span_err!(self.tcx.sess, span, E0317, "{}
", failure_str)
1880 FailureCode::Error0580(failure_str) => {
1881 struct_span_err!(self.tcx.sess, span, E0580, "{}
", failure_str)
1883 FailureCode::Error0308(failure_str) => {
1884 struct_span_err!(self.tcx.sess, span, E0308, "{}
", failure_str)
1886 FailureCode::Error0644(failure_str) => {
1887 struct_span_err!(self.tcx.sess, span, E0644, "{}
", failure_str)
1890 self.note_type_err(&mut diag, &trace.cause, None, Some(trace.values), terr);
1896 values: &ValuePairs<'tcx>,
1897 ) -> Option<(DiagnosticStyledString, DiagnosticStyledString)> {
1899 infer::Types(ref exp_found) => self.expected_found_str_ty(exp_found),
1900 infer::Regions(ref exp_found) => self.expected_found_str(exp_found),
1901 infer::Consts(ref exp_found) => self.expected_found_str(exp_found),
1902 infer::TraitRefs(ref exp_found) => {
1903 let pretty_exp_found = ty::error::ExpectedFound {
1904 expected: exp_found.expected.print_only_trait_path(),
1905 found: exp_found.found.print_only_trait_path(),
1907 self.expected_found_str(&pretty_exp_found)
1909 infer::PolyTraitRefs(ref exp_found) => {
1910 let pretty_exp_found = ty::error::ExpectedFound {
1911 expected: exp_found.expected.print_only_trait_path(),
1912 found: exp_found.found.print_only_trait_path(),
1914 self.expected_found_str(&pretty_exp_found)
1919 fn expected_found_str_ty(
1921 exp_found: &ty::error::ExpectedFound<Ty<'tcx>>,
1922 ) -> Option<(DiagnosticStyledString, DiagnosticStyledString)> {
1923 let exp_found = self.resolve_vars_if_possible(exp_found);
1924 if exp_found.references_error() {
1928 Some(self.cmp(exp_found.expected, exp_found.found))
1931 /// Returns a string of the form "expected `{}`
, found `{}`
".
1932 fn expected_found_str<T: fmt::Display + TypeFoldable<'tcx>>(
1934 exp_found: &ty::error::ExpectedFound<T>,
1935 ) -> Option<(DiagnosticStyledString, DiagnosticStyledString)> {
1936 let exp_found = self.resolve_vars_if_possible(exp_found);
1937 if exp_found.references_error() {
1942 DiagnosticStyledString::highlighted(exp_found.expected.to_string()),
1943 DiagnosticStyledString::highlighted(exp_found.found.to_string()),
1947 pub fn report_generic_bound_failure(
1950 origin: Option<SubregionOrigin<'tcx>>,
1951 bound_kind: GenericKind<'tcx>,
1954 self.construct_generic_bound_failure(span, origin, bound_kind, sub).emit();
1957 pub fn construct_generic_bound_failure(
1960 origin: Option<SubregionOrigin<'tcx>>,
1961 bound_kind: GenericKind<'tcx>,
1963 ) -> DiagnosticBuilder<'a> {
1964 let hir = &self.tcx.hir();
1965 // Attempt to obtain the span of the parameter so we can
1966 // suggest adding an explicit lifetime bound to it.
1968 .in_progress_typeck_results
1969 .map(|typeck_results| typeck_results.borrow().hir_owner)
1971 let hir_id = hir.local_def_id_to_hir_id(owner);
1972 let parent_id = hir.get_parent_item(hir_id);
1974 // Parent item could be a `mod`, so we check the HIR before calling:
1975 if let Some(Node::Item(Item {
1976 kind: ItemKind::Trait(..) | ItemKind::Impl { .. },
1978 })) = hir.find(parent_id)
1980 Some(self.tcx.generics_of(hir.local_def_id(parent_id).to_def_id()))
1984 self.tcx.generics_of(owner.to_def_id()),
1987 let type_param_span = match (generics, bound_kind) {
1988 (Some((_, ref generics)), GenericKind::Param(ref param)) => {
1989 // Account for the case where `param` corresponds to `Self`,
1990 // which doesn't have the expected type argument.
1991 if !(generics.has_self && param.index == 0) {
1992 let type_param = generics.type_param(param, self.tcx);
1993 type_param.def_id.as_local().map(|def_id| {
1994 // Get the `hir::Param` to verify whether it already has any bounds.
1995 // We do this to avoid suggesting code that ends up as `T: 'a'b`,
1996 // instead we suggest `T: 'a + 'b` in that case.
1997 let id = hir.local_def_id_to_hir_id(def_id);
1998 let mut has_bounds = false;
1999 if let Node::GenericParam(param) = hir.get(id) {
2000 has_bounds = !param.bounds.is_empty();
2002 let sp = hir.span(id);
2003 // `sp` only covers `T`, change it so that it covers
2004 // `T:` when appropriate
2005 let is_impl_trait = bound_kind.to_string().starts_with("impl ");
2006 let sp = if has_bounds && !is_impl_trait {
2011 .next_point(self.tcx.sess.source_map().next_point(sp)))
2015 (sp, has_bounds, is_impl_trait)
2023 let new_lt = generics
2025 .and_then(|(parent_g, g)| {
2026 let possible: Vec<_> = (b'a'..=b'z').map(|c| format!("'{}
", c as char)).collect();
2027 let mut lts_names = g
2030 .filter(|p| matches!(p.kind, ty::GenericParamDefKind::Lifetime))
2031 .map(|p| p.name.as_str())
2032 .collect::<Vec<_>>();
2033 if let Some(g) = parent_g {
2037 .filter(|p| matches!(p.kind, ty::GenericParamDefKind::Lifetime))
2038 .map(|p| p.name.as_str()),
2041 let lts = lts_names.iter().map(|s| -> &str { &*s }).collect::<Vec<_>>();
2042 possible.into_iter().find(|candidate| !lts.contains(&candidate.as_str()))
2044 .unwrap_or("'lt
".to_string());
2045 let add_lt_sugg = generics
2047 .and_then(|(_, g)| g.params.first())
2048 .and_then(|param| param.def_id.as_local())
2051 hir.span(hir.local_def_id_to_hir_id(def_id)).shrink_to_lo(),
2052 format!("{}
, ", new_lt),
2056 let labeled_user_string = match bound_kind {
2057 GenericKind::Param(ref p) => format!("the parameter
type `{}`
", p),
2058 GenericKind::Projection(ref p) => format!("the associated
type `{}`
", p),
2061 if let Some(SubregionOrigin::CompareImplMethodObligation {
2068 return self.report_extra_impl_obligation(
2073 &format!("`{}
: {}`
", bound_kind, sub),
2077 fn binding_suggestion<'tcx, S: fmt::Display>(
2078 err: &mut DiagnosticBuilder<'tcx>,
2079 type_param_span: Option<(Span, bool, bool)>,
2080 bound_kind: GenericKind<'tcx>,
2083 let msg = "consider adding an explicit lifetime bound
";
2084 if let Some((sp, has_lifetimes, is_impl_trait)) = type_param_span {
2085 let suggestion = if is_impl_trait {
2086 format!("{}
+ {}
", bound_kind, sub)
2088 let tail = if has_lifetimes { " + " } else { "" };
2089 format!("{}
: {}{}
", bound_kind, sub, tail)
2091 err.span_suggestion(
2093 &format!("{}
...", msg),
2095 Applicability::MaybeIncorrect, // Issue #41966
2098 let consider = format!(
2101 if type_param_span.map(|(_, _, is_impl_trait)| is_impl_trait).unwrap_or(false) {
2102 format!(" `{}` to `{}`
", sub, bound_kind)
2104 format!("`{}
: {}`
", bound_kind, sub)
2107 err.help(&consider);
2111 let new_binding_suggestion =
2112 |err: &mut DiagnosticBuilder<'tcx>,
2113 type_param_span: Option<(Span, bool, bool)>,
2114 bound_kind: GenericKind<'tcx>| {
2115 let msg = "consider introducing an explicit lifetime bound
";
2116 if let Some((sp, has_lifetimes, is_impl_trait)) = type_param_span {
2117 let suggestion = if is_impl_trait {
2118 (sp.shrink_to_hi(), format!(" + {}
", new_lt))
2120 let tail = if has_lifetimes { " +" } else { "" };
2121 (sp, format!("{}
: {}{}
", bound_kind, new_lt, tail))
2124 vec![suggestion, (span.shrink_to_hi(), format!(" + {}
", new_lt))];
2125 if let Some(lt) = add_lt_sugg {
2127 sugg.rotate_right(1);
2129 // `MaybeIncorrect` due to issue #41966.
2130 err.multipart_suggestion(msg, sugg, Applicability::MaybeIncorrect);
2134 let mut err = match *sub {
2135 ty::ReEarlyBound(ty::EarlyBoundRegion { name, .. })
2136 | ty::ReFree(ty::FreeRegion { bound_region: ty::BrNamed(_, name), .. }) => {
2137 // Does the required lifetime have a nice name we can print?
2138 let mut err = struct_span_err!(
2142 "{} may not live long enough
",
2145 // Explicitly use the name instead of `sub`'s `Display` impl. The `Display` impl
2146 // for the bound is not suitable for suggestions when `-Zverbose` is set because it
2147 // uses `Debug` output, so we handle it specially here so that suggestions are
2149 binding_suggestion(&mut err, type_param_span, bound_kind, name);
2154 // Does the required lifetime have a nice name we can print?
2155 let mut err = struct_span_err!(
2159 "{} may not live long enough
",
2162 binding_suggestion(&mut err, type_param_span, bound_kind, "'
static");
2167 // If not, be less specific.
2168 let mut err = struct_span_err!(
2172 "{} may not live long enough
",
2175 note_and_explain_region(
2178 &format!("{} must be valid
for ", labeled_user_string),
2182 if let Some(infer::RelateParamBound(_, t)) = origin {
2183 let t = self.resolve_vars_if_possible(&t);
2186 // fn get_later<G, T>(g: G, dest: &mut T) -> impl FnOnce() + '_
2188 // fn get_later<'a, G: 'a, T>(g: G, dest: &mut T) -> impl FnOnce() + '_ + 'a
2189 ty::Closure(_, _substs) | ty::Opaque(_, _substs) => {
2190 new_binding_suggestion(&mut err, type_param_span, bound_kind);
2193 binding_suggestion(&mut err, type_param_span, bound_kind, new_lt);
2201 if let Some(origin) = origin {
2202 self.note_region_origin(&mut err, &origin);
2207 fn report_sub_sup_conflict(
2209 var_origin: RegionVariableOrigin,
2210 sub_origin: SubregionOrigin<'tcx>,
2211 sub_region: Region<'tcx>,
2212 sup_origin: SubregionOrigin<'tcx>,
2213 sup_region: Region<'tcx>,
2215 let mut err = self.report_inference_failure(var_origin);
2217 note_and_explain_region(
2220 "first
, the lifetime cannot outlive
",
2225 debug!("report_sub_sup_conflict
: var_origin
={:?}
", var_origin);
2226 debug!("report_sub_sup_conflict
: sub_region
={:?}
", sub_region);
2227 debug!("report_sub_sup_conflict
: sub_origin
={:?}
", sub_origin);
2228 debug!("report_sub_sup_conflict
: sup_region
={:?}
", sup_region);
2229 debug!("report_sub_sup_conflict
: sup_origin
={:?}
", sup_origin);
2231 if let (&infer::Subtype(ref sup_trace), &infer::Subtype(ref sub_trace)) =
2232 (&sup_origin, &sub_origin)
2234 debug!("report_sub_sup_conflict
: sup_trace
={:?}
", sup_trace);
2235 debug!("report_sub_sup_conflict
: sub_trace
={:?}
", sub_trace);
2236 debug!("report_sub_sup_conflict
: sup_trace
.values
={:?}
", sup_trace.values);
2237 debug!("report_sub_sup_conflict
: sub_trace
.values
={:?}
", sub_trace.values);
2239 if let (Some((sup_expected, sup_found)), Some((sub_expected, sub_found))) =
2240 (self.values_str(&sup_trace.values), self.values_str(&sub_trace.values))
2242 if sub_expected == sup_expected && sub_found == sup_found {
2243 note_and_explain_region(
2246 "...but the lifetime must also be valid
for ",
2251 sup_trace.cause.span,
2252 &format!("...so that the {}
", sup_trace.cause.as_requirement_str()),
2255 err.note_expected_found(&"", sup_expected, &"", sup_found);
2262 self.note_region_origin(&mut err, &sup_origin);
2264 note_and_explain_region(
2267 "but
, the lifetime must be valid
for ",
2272 self.note_region_origin(&mut err, &sub_origin);
2277 impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
2278 fn report_inference_failure(
2280 var_origin: RegionVariableOrigin,
2281 ) -> DiagnosticBuilder<'tcx> {
2282 let br_string = |br: ty::BoundRegion| {
2283 let mut s = match br {
2284 ty::BrNamed(_, name) => name.to_string(),
2292 let var_description = match var_origin {
2293 infer::MiscVariable(_) => String::new(),
2294 infer::PatternRegion(_) => " for pattern
".to_string(),
2295 infer::AddrOfRegion(_) => " for borrow expression
".to_string(),
2296 infer::Autoref(_, _) => " for autoref
".to_string(),
2297 infer::Coercion(_) => " for automatic coercion
".to_string(),
2298 infer::LateBoundRegion(_, br, infer::FnCall) => {
2299 format!(" for lifetime parameter {}
in function call
", br_string(br))
2301 infer::LateBoundRegion(_, br, infer::HigherRankedType) => {
2302 format!(" for lifetime parameter {}
in generic
type", br_string(br))
2304 infer::LateBoundRegion(_, br, infer::AssocTypeProjection(def_id)) => format!(
2305 " for lifetime parameter {}
in trait containing associated
type `{}`
",
2307 self.tcx.associated_item(def_id).ident
2309 infer::EarlyBoundRegion(_, name) => format!(" for lifetime parameter `{}`
", name),
2310 infer::BoundRegionInCoherence(name) => {
2311 format!(" for lifetime parameter `{}`
in coherence check
", name)
2313 infer::UpvarRegion(ref upvar_id, _) => {
2314 let var_name = self.tcx.hir().name(upvar_id.var_path.hir_id);
2315 format!(" for capture of `{}` by closure
", var_name)
2317 infer::NLL(..) => bug!("NLL variable found
in lexical phase
"),
2324 "cannot infer an appropriate lifetime{} due to conflicting requirements
",
2332 Error0317(&'static str),
2333 Error0580(&'static str),
2334 Error0308(&'static str),
2335 Error0644(&'static str),
2338 trait ObligationCauseExt<'tcx> {
2339 fn as_failure_code(&self, terr: &TypeError<'tcx>) -> FailureCode;
2340 fn as_requirement_str(&self) -> &'static str;
2343 impl<'tcx> ObligationCauseExt<'tcx> for ObligationCause<'tcx> {
2344 fn as_failure_code(&self, terr: &TypeError<'tcx>) -> FailureCode {
2345 use self::FailureCode::*;
2346 use crate::traits::ObligationCauseCode::*;
2348 CompareImplMethodObligation { .. } => Error0308("method not compatible with
trait"),
2349 CompareImplTypeObligation { .. } => Error0308("type not compatible with
trait"),
2350 MatchExpressionArm(box MatchExpressionArmCause { source, .. }) => {
2351 Error0308(match source {
2352 hir::MatchSource::IfLetDesugar { .. } => {
2353 "`
if let` arms have incompatible types
"
2355 hir::MatchSource::TryDesugar => {
2356 "try expression alternatives have incompatible types
"
2358 _ => "`
match` arms have incompatible types
",
2361 IfExpression { .. } => Error0308("`
if` and `
else` have incompatible types
"),
2362 IfExpressionWithNoElse => Error0317("`
if` may be missing an `
else` clause
"),
2363 MainFunctionType => Error0580("`main` function has wrong
type"),
2364 StartFunctionType => Error0308("`
#[start]` function has wrong type"),
2365 IntrinsicType => Error0308("intrinsic has wrong type"),
2366 MethodReceiver => Error0308("mismatched `self` parameter type"),
2368 // In the case where we have no more specific thing to
2369 // say, also take a look at the error code, maybe we can
2372 TypeError::CyclicTy(ty) if ty.is_closure() || ty.is_generator() => {
2373 Error0644("closure/generator type that references itself")
2375 TypeError::IntrinsicCast => {
2376 Error0308("cannot coerce intrinsics to function pointers")
2378 TypeError::ObjectUnsafeCoercion(did) => Error0038(*did),
2379 _ => Error0308("mismatched types"),
2384 fn as_requirement_str(&self) -> &'static str {
2385 use crate::traits::ObligationCauseCode::*;
2387 CompareImplMethodObligation { .. } => "method type is compatible with trait",
2388 CompareImplTypeObligation { .. } => "associated type is compatible with trait",
2389 ExprAssignable => "expression is assignable",
2390 MatchExpressionArm(box MatchExpressionArmCause { source, .. }) => match source {
2391 hir::MatchSource::IfLetDesugar { .. } => "`if let` arms have compatible types",
2392 _ => "`match` arms have compatible types",
2394 IfExpression { .. } => "`if` and `else` have incompatible types",
2395 IfExpressionWithNoElse => "`if` missing an `else` returns `()`",
2396 MainFunctionType => "`main` function has the correct type",
2397 StartFunctionType => "`#[start]` function has the correct type",
2398 IntrinsicType => "intrinsic has the correct type",
2399 MethodReceiver => "method receiver has the correct type",
2400 _ => "types are compatible",
2405 /// This is a bare signal of what kind of type we're dealing with. `ty::TyKind` tracks
2406 /// extra information about each type, but we only care about the category.
2407 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
2408 pub enum TyCategory {
2416 fn descr(&self) -> &'static str {
2418 Self::Closure => "closure",
2419 Self::Opaque => "opaque type",
2420 Self::Generator => "generator",
2421 Self::Foreign => "foreign type",
2425 pub fn from_ty(ty: Ty<'_>) -> Option<(Self, DefId)> {
2427 ty::Closure(def_id, _) => Some((Self::Closure, def_id)),
2428 ty::Opaque(def_id, _) => Some((Self::Opaque, def_id)),
2429 ty::Generator(def_id, ..) => Some((Self::Generator, def_id)),
2430 ty::Foreign(def_id) => Some((Self::Foreign, def_id)),