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 system is based around a set of "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}
;
52 use crate::errors
::{self, ObligationCauseFailureCode, TypeErrorAdditionalDiags}
;
54 use crate::infer
::error_reporting
::nice_region_error
::find_anon_type
::find_anon_type
;
55 use crate::infer
::ExpectedFound
;
57 IfExpressionCause
, MatchExpressionArmCause
, ObligationCause
, ObligationCauseCode
,
61 use rustc_data_structures
::fx
::{FxIndexMap, FxIndexSet}
;
62 use rustc_errors
::{error_code, Applicability, DiagnosticBuilder, DiagnosticStyledString}
;
63 use rustc_errors
::{pluralize, struct_span_err, Diagnostic, ErrorGuaranteed, IntoDiagnosticArg}
;
65 use rustc_hir
::def
::DefKind
;
66 use rustc_hir
::def_id
::{DefId, LocalDefId}
;
67 use rustc_hir
::intravisit
::Visitor
;
68 use rustc_hir
::lang_items
::LangItem
;
69 use rustc_middle
::dep_graph
::DepContext
;
70 use rustc_middle
::ty
::print
::{with_forced_trimmed_paths, PrintError}
;
71 use rustc_middle
::ty
::relate
::{self, RelateResult, TypeRelation}
;
72 use rustc_middle
::ty
::{
73 self, error
::TypeError
, IsSuggestable
, List
, Region
, Ty
, TyCtxt
, TypeFoldable
,
74 TypeSuperVisitable
, TypeVisitable
, TypeVisitableExt
,
76 use rustc_span
::{sym, symbol::kw, BytePos, DesugaringKind, Pos, Span}
;
77 use rustc_target
::spec
::abi
;
79 use std
::ops
::{ControlFlow, Deref}
;
80 use std
::path
::PathBuf
;
81 use std
::{cmp, fmt, iter}
;
87 pub(crate) mod need_type_info
;
88 pub use need_type_info
::TypeAnnotationNeeded
;
90 pub mod nice_region_error
;
92 /// Makes a valid string literal from a string by escaping special characters (" and \),
93 /// unless they are already escaped.
94 fn escape_literal(s
: &str) -> String
{
95 let mut escaped
= String
::with_capacity(s
.len());
96 let mut chrs
= s
.chars().peekable();
97 while let Some(first
) = chrs
.next() {
98 match (first
, chrs
.peek()) {
99 ('
\\'
, Some(&delim @ '
"') | Some(&delim @ '\'')) => {
108 (c
, _
) => escaped
.push(c
),
114 /// A helper for building type related errors. The `typeck_results`
115 /// field is only populated during an in-progress typeck.
116 /// Get an instance by calling `InferCtxt::err_ctxt` or `FnCtxt::err_ctxt`.
118 /// You must only create this if you intend to actually emit an error.
119 /// This provides a lot of utility methods which should not be used
120 /// during the happy path.
121 pub struct TypeErrCtxt
<'a
, 'tcx
> {
122 pub infcx
: &'a InferCtxt
<'tcx
>,
123 pub typeck_results
: Option
<std
::cell
::Ref
<'a
, ty
::TypeckResults
<'tcx
>>>,
124 pub fallback_has_occurred
: bool
,
126 pub normalize_fn_sig
: Box
<dyn Fn(ty
::PolyFnSig
<'tcx
>) -> ty
::PolyFnSig
<'tcx
> + 'a
>,
129 Box
<dyn Fn(Ty
<'tcx
>) -> Vec
<(Ty
<'tcx
>, Vec
<PredicateObligation
<'tcx
>>)> + 'a
>,
132 impl Drop
for TypeErrCtxt
<'_
, '_
> {
134 if let Some(_
) = self.infcx
.tcx
.sess
.has_errors_or_delayed_span_bugs() {
135 // ok, emitted an error.
140 .delay_good_path_bug("used a `TypeErrCtxt` without raising an error or lint");
145 impl TypeErrCtxt
<'_
, '_
> {
146 /// This is just to avoid a potential footgun of accidentally
147 /// dropping `typeck_results` by calling `InferCtxt::err_ctxt`
148 #[deprecated(note = "you already have a `TypeErrCtxt`")]
150 pub fn err_ctxt(&self) -> ! {
151 bug
!("called `err_ctxt` on `TypeErrCtxt`. Try removing the call");
155 impl<'tcx
> Deref
for TypeErrCtxt
<'_
, 'tcx
> {
156 type Target
= InferCtxt
<'tcx
>;
157 fn deref(&self) -> &InferCtxt
<'tcx
> {
162 pub(super) fn note_and_explain_region
<'tcx
>(
164 err
: &mut Diagnostic
,
166 region
: ty
::Region
<'tcx
>,
168 alt_span
: Option
<Span
>,
170 let (description
, span
) = match *region
{
171 ty
::ReEarlyBound(_
) | ty
::ReFree(_
) | ty
::RePlaceholder(_
) | ty
::ReStatic
=> {
172 msg_span_from_named_region(tcx
, region
, alt_span
)
175 ty
::ReError(_
) => return,
177 // We shouldn't really be having unification failures with ReVar
178 // and ReLateBound though.
179 ty
::ReVar(_
) | ty
::ReLateBound(..) | ty
::ReErased
=> {
180 (format
!("lifetime `{region}`"), alt_span
)
184 emit_msg_span(err
, prefix
, description
, span
, suffix
);
187 fn explain_free_region
<'tcx
>(
189 err
: &mut Diagnostic
,
191 region
: ty
::Region
<'tcx
>,
194 let (description
, span
) = msg_span_from_named_region(tcx
, region
, None
);
196 label_msg_span(err
, prefix
, description
, span
, suffix
);
199 fn msg_span_from_named_region
<'tcx
>(
201 region
: ty
::Region
<'tcx
>,
202 alt_span
: Option
<Span
>,
203 ) -> (String
, Option
<Span
>) {
205 ty
::ReEarlyBound(ref br
) => {
206 let scope
= region
.free_region_binding_scope(tcx
).expect_local();
207 let span
= if let Some(param
) =
208 tcx
.hir().get_generics(scope
).and_then(|generics
| generics
.get_named(br
.name
))
214 let text
= if br
.has_name() {
215 format
!("the lifetime `{}` as defined here", br
.name
)
217 "the anonymous lifetime as defined here".to_string()
221 ty
::ReFree(ref fr
) => {
222 if !fr
.bound_region
.is_named()
223 && let Some((ty
, _
)) = find_anon_type(tcx
, region
, &fr
.bound_region
)
225 ("the anonymous lifetime defined here".to_string(), Some(ty
.span
))
227 let scope
= region
.free_region_binding_scope(tcx
).expect_local();
228 match fr
.bound_region
{
229 ty
::BoundRegionKind
::BrNamed(_
, name
) => {
230 let span
= if let Some(param
) = tcx
233 .and_then(|generics
| generics
.get_named(name
))
239 let text
= if name
== kw
::UnderscoreLifetime
{
240 "the anonymous lifetime as defined here".to_string()
242 format
!("the lifetime `{name}` as defined here")
247 "the anonymous lifetime as defined here".to_string(),
248 Some(tcx
.def_span(scope
)),
251 format
!("the lifetime `{region}` as defined here"),
252 Some(tcx
.def_span(scope
)),
257 ty
::ReStatic
=> ("the static lifetime".to_owned(), alt_span
),
258 ty
::RePlaceholder(ty
::PlaceholderRegion
{
259 bound
: ty
::BoundRegion { kind: ty::BoundRegionKind::BrNamed(def_id, name), .. }
,
261 }) => (format
!("the lifetime `{name}` as defined here"), Some(tcx
.def_span(def_id
))),
262 ty
::RePlaceholder(ty
::PlaceholderRegion
{
263 bound
: ty
::BoundRegion { kind: ty::BoundRegionKind::BrAnon, .. }
,
265 }) => ("an anonymous lifetime".to_owned(), None
),
266 _
=> bug
!("{:?}", region
),
271 err
: &mut Diagnostic
,
277 let message
= format
!("{prefix}{description}{suffix}");
279 if let Some(span
) = span
{
280 err
.span_note(span
, message
);
287 err
: &mut Diagnostic
,
293 let message
= format
!("{prefix}{description}{suffix}");
295 if let Some(span
) = span
{
296 err
.span_label(span
, message
);
302 #[instrument(level = "trace", skip(tcx))]
303 pub fn unexpected_hidden_region_diagnostic
<'tcx
>(
307 hidden_region
: ty
::Region
<'tcx
>,
308 opaque_ty_key
: ty
::OpaqueTypeKey
<'tcx
>,
309 ) -> DiagnosticBuilder
<'tcx
, ErrorGuaranteed
> {
310 let mut err
= tcx
.sess
.create_err(errors
::OpaqueCapturesLifetime
{
312 opaque_ty
: Ty
::new_opaque(tcx
, opaque_ty_key
.def_id
.to_def_id(), opaque_ty_key
.args
),
313 opaque_ty_span
: tcx
.def_span(opaque_ty_key
.def_id
),
316 // Explain the region we are capturing.
317 match *hidden_region
{
318 ty
::ReEarlyBound(_
) | ty
::ReFree(_
) | ty
::ReStatic
=> {
319 // Assuming regionck succeeded (*), we ought to always be
320 // capturing *some* region from the fn header, and hence it
321 // ought to be free. So under normal circumstances, we will go
322 // down this path which gives a decent human readable
325 // (*) if not, the `tainted_by_errors` field would be set to
326 // `Some(ErrorGuaranteed)` in any case, so we wouldn't be here at all.
330 &format
!("hidden type `{hidden_ty}` captures "),
334 if let Some(reg_info
) = tcx
.is_suitable_region(hidden_region
) {
335 let fn_returns
= tcx
.return_type_impl_or_dyn_traits(reg_info
.def_id
);
336 nice_region_error
::suggest_new_region_bound(
340 hidden_region
.to_string(),
342 format
!("captures `{hidden_region}`"),
344 Some(reg_info
.def_id
),
348 ty
::RePlaceholder(_
) => {
352 &format
!("hidden type `{}` captures ", hidden_ty
),
361 // Ugh. This is a painful case: the hidden region is not one
362 // that we can easily summarize or explain. This can happen
364 // `tests/ui/multiple-lifetimes/ordinary-bounds-unsuited.rs`:
367 // fn upper_bounds<'a, 'b>(a: Ordinary<'a>, b: Ordinary<'b>) -> impl Trait<'a, 'b> {
368 // if condition() { a } else { b }
372 // Here the captured lifetime is the intersection of `'a` and
373 // `'b`, which we can't quite express.
375 // We can at least report a really cryptic error for now.
376 note_and_explain_region(
379 &format
!("hidden type `{hidden_ty}` captures "),
390 impl<'tcx
> InferCtxt
<'tcx
> {
391 pub fn get_impl_future_output_ty(&self, ty
: Ty
<'tcx
>) -> Option
<Ty
<'tcx
>> {
392 let (def_id
, args
) = match *ty
.kind() {
393 ty
::Alias(_
, ty
::AliasTy { def_id, args, .. }
)
394 if matches
!(self.tcx
.def_kind(def_id
), DefKind
::OpaqueTy
) =>
398 ty
::Alias(_
, ty
::AliasTy { def_id, args, .. }
)
399 if self.tcx
.is_impl_trait_in_trait(def_id
) =>
406 let future_trait
= self.tcx
.require_lang_item(LangItem
::Future
, None
);
407 let item_def_id
= self.tcx
.associated_item_def_ids(future_trait
)[0];
409 self.tcx
.explicit_item_bounds(def_id
).iter_instantiated_copied(self.tcx
, args
).find_map(
413 .map_bound(|kind
| match kind
{
414 ty
::ClauseKind
::Projection(projection_predicate
)
415 if projection_predicate
.projection_ty
.def_id
== item_def_id
=>
417 projection_predicate
.term
.ty()
428 impl<'tcx
> TypeErrCtxt
<'_
, 'tcx
> {
429 pub fn report_region_errors(
431 generic_param_scope
: LocalDefId
,
432 errors
: &[RegionResolutionError
<'tcx
>],
433 ) -> ErrorGuaranteed
{
434 if let Some(guaranteed
) = self.infcx
.tainted_by_errors() {
438 debug
!("report_region_errors(): {} errors to start", errors
.len());
440 // try to pre-process the errors, which will group some of them
441 // together into a `ProcessedErrors` group:
442 let errors
= self.process_errors(errors
);
444 debug
!("report_region_errors: {} errors after preprocessing", errors
.len());
446 for error
in errors
{
447 debug
!("report_region_errors: error = {:?}", error
);
449 if !self.try_report_nice_region_error(&error
) {
450 match error
.clone() {
451 // These errors could indicate all manner of different
452 // problems with many different solutions. Rather
453 // than generate a "one size fits all" error, what we
454 // attempt to do is go through a number of specific
455 // scenarios and try to find the best way to present
456 // the error. If all of these fails, we fall back to a rather
457 // general bit of code that displays the error information
458 RegionResolutionError
::ConcreteFailure(origin
, sub
, sup
) => {
459 if sub
.is_placeholder() || sup
.is_placeholder() {
460 self.report_placeholder_failure(origin
, sub
, sup
).emit();
462 self.report_concrete_failure(origin
, sub
, sup
).emit();
466 RegionResolutionError
::GenericBoundFailure(origin
, param_ty
, sub
) => {
467 self.report_generic_bound_failure(
476 RegionResolutionError
::SubSupConflict(
485 if sub_r
.is_placeholder() {
486 self.report_placeholder_failure(sub_origin
, sub_r
, sup_r
).emit();
487 } else if sup_r
.is_placeholder() {
488 self.report_placeholder_failure(sup_origin
, sub_r
, sup_r
).emit();
490 self.report_sub_sup_conflict(
491 var_origin
, sub_origin
, sub_r
, sup_origin
, sup_r
,
496 RegionResolutionError
::UpperBoundUniverseConflict(
503 assert
!(sup_r
.is_placeholder());
505 // Make a dummy value for the "sub region" --
506 // this is the initial value of the
507 // placeholder. In practice, we expect more
508 // tailored errors that don't really use this
510 let sub_r
= self.tcx
.lifetimes
.re_erased
;
512 self.report_placeholder_failure(sup_origin
, sub_r
, sup_r
).emit();
520 .delay_span_bug(self.tcx
.def_span(generic_param_scope
), "expected region errors")
523 // This method goes through all the errors and try to group certain types
524 // of error together, for the purpose of suggesting explicit lifetime
525 // parameters to the user. This is done so that we can have a more
526 // complete view of what lifetimes should be the same.
527 // If the return value is an empty vector, it means that processing
528 // failed (so the return value of this method should not be used).
530 // The method also attempts to weed out messages that seem like
531 // duplicates that will be unhelpful to the end-user. But
532 // obviously it never weeds out ALL errors.
535 errors
: &[RegionResolutionError
<'tcx
>],
536 ) -> Vec
<RegionResolutionError
<'tcx
>> {
537 debug
!("process_errors()");
539 // We want to avoid reporting generic-bound failures if we can
540 // avoid it: these have a very high rate of being unhelpful in
541 // practice. This is because they are basically secondary
542 // checks that test the state of the region graph after the
543 // rest of inference is done, and the other kinds of errors
544 // indicate that the region constraint graph is internally
545 // inconsistent, so these test results are likely to be
548 // Therefore, we filter them out of the list unless they are
549 // the only thing in the list.
551 let is_bound_failure
= |e
: &RegionResolutionError
<'tcx
>| match *e
{
552 RegionResolutionError
::GenericBoundFailure(..) => true,
553 RegionResolutionError
::ConcreteFailure(..)
554 | RegionResolutionError
::SubSupConflict(..)
555 | RegionResolutionError
::UpperBoundUniverseConflict(..) => false,
558 let mut errors
= if errors
.iter().all(|e
| is_bound_failure(e
)) {
561 errors
.iter().filter(|&e
| !is_bound_failure(e
)).cloned().collect()
564 // sort the errors by span, for better error message stability.
565 errors
.sort_by_key(|u
| match *u
{
566 RegionResolutionError
::ConcreteFailure(ref sro
, _
, _
) => sro
.span(),
567 RegionResolutionError
::GenericBoundFailure(ref sro
, _
, _
) => sro
.span(),
568 RegionResolutionError
::SubSupConflict(_
, ref rvo
, _
, _
, _
, _
, _
) => rvo
.span(),
569 RegionResolutionError
::UpperBoundUniverseConflict(_
, ref rvo
, _
, _
, _
) => rvo
.span(),
574 /// Adds a note if the types come from similarly named crates
575 fn check_and_note_conflicting_crates(&self, err
: &mut Diagnostic
, terr
: TypeError
<'tcx
>) {
576 use hir
::def_id
::CrateNum
;
577 use rustc_hir
::definitions
::DisambiguatedDefPathData
;
578 use ty
::print
::Printer
;
581 struct AbsolutePathPrinter
<'tcx
> {
583 segments
: Vec
<String
>,
586 impl<'tcx
> Printer
<'tcx
> for AbsolutePathPrinter
<'tcx
> {
587 fn tcx
<'a
>(&'a
self) -> TyCtxt
<'tcx
> {
591 fn print_region(&mut self, _region
: ty
::Region
<'_
>) -> Result
<(), PrintError
> {
595 fn print_type(&mut self, _ty
: Ty
<'tcx
>) -> Result
<(), PrintError
> {
599 fn print_dyn_existential(
601 _predicates
: &'tcx ty
::List
<ty
::PolyExistentialPredicate
<'tcx
>>,
602 ) -> Result
<(), PrintError
> {
606 fn print_const(&mut self, _ct
: ty
::Const
<'tcx
>) -> Result
<(), PrintError
> {
610 fn path_crate(&mut self, cnum
: CrateNum
) -> Result
<(), PrintError
> {
611 self.segments
= vec
![self.tcx
.crate_name(cnum
).to_string()];
617 _trait_ref
: Option
<ty
::TraitRef
<'tcx
>>,
618 ) -> Result
<(), PrintError
> {
624 _print_prefix
: impl FnOnce(&mut Self) -> Result
<(), PrintError
>,
625 _disambiguated_data
: &DisambiguatedDefPathData
,
627 _trait_ref
: Option
<ty
::TraitRef
<'tcx
>>,
628 ) -> Result
<(), PrintError
> {
633 print_prefix
: impl FnOnce(&mut Self) -> Result
<(), PrintError
>,
634 disambiguated_data
: &DisambiguatedDefPathData
,
635 ) -> Result
<(), PrintError
> {
637 self.segments
.push(disambiguated_data
.to_string());
640 fn path_generic_args(
642 print_prefix
: impl FnOnce(&mut Self) -> Result
<(), PrintError
>,
643 _args
: &[GenericArg
<'tcx
>],
644 ) -> Result
<(), PrintError
> {
649 let report_path_match
= |err
: &mut Diagnostic
, did1
: DefId
, did2
: DefId
| {
650 // Only report definitions from different crates. If both definitions
651 // are from a local module we could have false positives, e.g.
652 // let _ = [{struct Foo; Foo}, {struct Foo; Foo}];
653 if did1
.krate
!= did2
.krate
{
654 let abs_path
= |def_id
| {
655 let mut printer
= AbsolutePathPrinter { tcx: self.tcx, segments: vec![] }
;
656 printer
.print_def_path(def_id
, &[]).map(|_
| printer
.segments
)
659 // We compare strings because DefPath can be different
660 // for imported and non-imported crates
661 let same_path
= || -> Result
<_
, PrintError
> {
662 Ok(self.tcx
.def_path_str(did1
) == self.tcx
.def_path_str(did2
)
663 || abs_path(did1
)?
== abs_path(did2
)?
)
665 if same_path().unwrap_or(false) {
666 let crate_name
= self.tcx
.crate_name(did1
.krate
);
667 let msg
= if did1
.is_local() || did2
.is_local() {
669 "the crate `{crate_name}` is compiled multiple times, possibly with different configurations"
673 "perhaps two different versions of crate `{crate_name}` are being used?"
681 TypeError
::Sorts(ref exp_found
) => {
682 // if they are both "path types", there's a chance of ambiguity
683 // due to different versions of the same crate
684 if let (&ty
::Adt(exp_adt
, _
), &ty
::Adt(found_adt
, _
)) =
685 (exp_found
.expected
.kind(), exp_found
.found
.kind())
687 report_path_match(err
, exp_adt
.did(), found_adt
.did());
690 TypeError
::Traits(ref exp_found
) => {
691 report_path_match(err
, exp_found
.expected
, exp_found
.found
);
693 _
=> (), // FIXME(#22750) handle traits and stuff
697 fn note_error_origin(
699 err
: &mut Diagnostic
,
700 cause
: &ObligationCause
<'tcx
>,
701 exp_found
: Option
<ty
::error
::ExpectedFound
<Ty
<'tcx
>>>,
702 terr
: TypeError
<'tcx
>,
704 match *cause
.code() {
705 ObligationCauseCode
::Pattern { origin_expr: true, span: Some(span), root_ty }
=> {
706 let ty
= self.resolve_vars_if_possible(root_ty
);
707 if !matches
!(ty
.kind(), ty
::Infer(ty
::InferTy
::TyVar(_
) | ty
::InferTy
::FreshTy(_
)))
709 // don't show type `_`
710 if span
.desugaring_kind() == Some(DesugaringKind
::ForLoop
)
711 && let ty
::Adt(def
, args
) = ty
.kind()
712 && Some(def
.did()) == self.tcx
.get_diagnostic_item(sym
::Option
)
716 format
!("this is an iterator with items of type `{}`", args
.type_at(0)),
719 err
.span_label(span
, format
!("this expression has type `{ty}`"));
722 if let Some(ty
::error
::ExpectedFound { found, .. }
) = exp_found
724 && ty
.boxed_ty() == found
725 && let Ok(snippet
) = self.tcx
.sess
.source_map().span_to_snippet(span
)
729 "consider dereferencing the boxed value",
730 format
!("*{snippet}"),
731 Applicability
::MachineApplicable
,
735 ObligationCauseCode
::Pattern { origin_expr: false, span: Some(span), .. }
=> {
736 err
.span_label(span
, "expected due to this");
738 ObligationCauseCode
::BlockTailExpression(
740 hir
::MatchSource
::TryDesugar(scrut_hir_id
),
742 if let Some(ty
::error
::ExpectedFound { expected, .. }
) = exp_found
{
743 let scrut_expr
= self.tcx
.hir().expect_expr(scrut_hir_id
);
744 let scrut_ty
= if let hir
::ExprKind
::Call(_
, args
) = &scrut_expr
.kind
{
745 let arg_expr
= args
.first().expect("try desugaring call w/out arg");
748 .and_then(|typeck_results
| typeck_results
.expr_ty_opt(arg_expr
))
750 bug
!("try desugaring w/out call expr as scrutinee");
754 Some(ty
) if expected
== ty
=> {
755 let source_map
= self.tcx
.sess
.source_map();
757 source_map
.end_point(cause
.span()),
758 "try removing this `?`",
760 Applicability
::MachineApplicable
,
767 ObligationCauseCode
::MatchExpressionArm(box MatchExpressionArmCause
{
776 opt_suggest_box_span
,
781 hir
::MatchSource
::TryDesugar(scrut_hir_id
) => {
782 if let Some(ty
::error
::ExpectedFound { expected, .. }
) = exp_found
{
783 let scrut_expr
= self.tcx
.hir().expect_expr(scrut_hir_id
);
784 let scrut_ty
= if let hir
::ExprKind
::Call(_
, args
) = &scrut_expr
.kind
{
785 let arg_expr
= args
.first().expect("try desugaring call w/out arg");
788 .and_then(|typeck_results
| typeck_results
.expr_ty_opt(arg_expr
))
790 bug
!("try desugaring w/out call expr as scrutinee");
794 Some(ty
) if expected
== ty
=> {
795 let source_map
= self.tcx
.sess
.source_map();
797 source_map
.end_point(cause
.span()),
798 "try removing this `?`",
800 Applicability
::MachineApplicable
,
808 // `prior_arm_ty` can be `!`, `expected` will have better info when present.
809 let t
= self.resolve_vars_if_possible(match exp_found
{
810 Some(ty
::error
::ExpectedFound { expected, .. }
) => expected
,
813 let source_map
= self.tcx
.sess
.source_map();
814 let mut any_multiline_arm
= source_map
.is_multiline(arm_span
);
815 if prior_arms
.len() <= 4 {
816 for sp
in prior_arms
{
817 any_multiline_arm
|= source_map
.is_multiline(*sp
);
818 err
.span_label(*sp
, format
!("this is found to be of type `{t}`"));
820 } else if let Some(sp
) = prior_arms
.last() {
821 any_multiline_arm
|= source_map
.is_multiline(*sp
);
824 format
!("this and all prior arms are found to be of type `{t}`"),
827 let outer
= if any_multiline_arm
|| !source_map
.is_multiline(cause
.span
) {
828 // Cover just `match` and the scrutinee expression, not
829 // the entire match body, to reduce diagram noise.
830 cause
.span
.shrink_to_lo().to(scrut_span
)
834 let msg
= "`match` arms have incompatible types";
835 err
.span_label(outer
, msg
);
836 if let Some(subdiag
) = self.suggest_remove_semi_or_return_binding(
844 err
.subdiagnostic(subdiag
);
846 if let Some(hir
::Node
::Expr(m
)) = self.tcx
.hir().find_parent(scrut_hir_id
)
847 && let Some(hir
::Node
::Stmt(stmt
)) = self.tcx
.hir().find_parent(m
.hir_id
)
848 && let hir
::StmtKind
::Expr(_
) = stmt
.kind
850 err
.span_suggestion_verbose(
851 stmt
.span
.shrink_to_hi(),
852 "consider using a semicolon here, but this will discard any values \
855 Applicability
::MaybeIncorrect
,
858 if let Some(ret_sp
) = opt_suggest_box_span
{
859 // Get return type span and point to it.
860 self.suggest_boxing_for_return_impl_trait(
863 prior_arms
.iter().chain(std
::iter
::once(&arm_span
)).map(|s
| *s
),
868 ObligationCauseCode
::IfExpression(box IfExpressionCause
{
874 opt_suggest_box_span
,
876 let then_span
= self.find_block_span_from_hir_id(then_id
);
877 let else_span
= self.find_block_span_from_hir_id(else_id
);
878 err
.span_label(then_span
, "expected because of this");
879 if let Some(sp
) = outer_span
{
880 err
.span_label(sp
, "`if` and `else` have incompatible types");
882 if let Some(subdiag
) = self.suggest_remove_semi_or_return_binding(
890 err
.subdiagnostic(subdiag
);
892 // don't suggest wrapping either blocks in `if .. {} else {}`
893 let is_empty_arm
= |id
| {
894 let hir
::Node
::Block(blk
) = self.tcx
.hir().get(id
) else {
897 if blk
.expr
.is_some() || !blk
.stmts
.is_empty() {
900 let Some((_
, hir
::Node
::Expr(expr
))) = self.tcx
.hir().parent_iter(id
).nth(1)
904 matches
!(expr
.kind
, hir
::ExprKind
::If(..))
906 if let Some(ret_sp
) = opt_suggest_box_span
907 && !is_empty_arm(then_id
)
908 && !is_empty_arm(else_id
)
910 self.suggest_boxing_for_return_impl_trait(
913 [then_span
, else_span
].into_iter(),
917 ObligationCauseCode
::LetElse
=> {
918 err
.help("try adding a diverging expression, such as `return` or `panic!(..)`");
919 err
.help("...or use `match` instead of `let...else`");
922 if let ObligationCauseCode
::BindingObligation(_
, span
)
923 | ObligationCauseCode
::ExprBindingObligation(_
, span
, ..) =
924 cause
.code().peel_derives()
925 && let TypeError
::RegionsPlaceholderMismatch
= terr
927 err
.span_note(*span
, "the lifetime requirement is introduced here");
933 /// Given that `other_ty` is the same as a type argument for `name` in `sub`, populate `value`
934 /// highlighting `name` and every type argument that isn't at `pos` (which is `other_ty`), and
935 /// populate `other_value` with `other_ty`.
939 /// ^^^^--------^ this is highlighted
941 /// | this type argument is exactly the same as the other type, not highlighted
942 /// this is highlighted
944 /// -------- this type is the same as a type argument in the other type, not highlighted
948 value
: &mut DiagnosticStyledString
,
949 other_value
: &mut DiagnosticStyledString
,
951 sub
: ty
::GenericArgsRef
<'tcx
>,
955 // `value` and `other_value` hold two incomplete type representation for display.
956 // `name` is the path of both types being compared. `sub`
957 value
.push_highlighted(name
);
960 value
.push_highlighted("<");
963 // Output the lifetimes for the first type
967 let s
= lifetime
.to_string();
968 if s
.is_empty() { "'_".to_string() }
else { s }
972 if !lifetimes
.is_empty() {
973 if sub
.regions().count() < len
{
974 value
.push_normal(lifetimes
+ ", ");
976 value
.push_normal(lifetimes
);
980 // Highlight all the type arguments that aren't at `pos` and compare the type argument at
981 // `pos` and `other_ty`.
982 for (i
, type_arg
) in sub
.types().enumerate() {
984 let values
= self.cmp(type_arg
, other_ty
);
985 value
.0.extend((values
.0).0);
986 other_value
.0.extend((values
.1).0);
988 value
.push_highlighted(type_arg
.to_string());
991 if len
> 0 && i
!= len
- 1 {
992 value
.push_normal(", ");
996 value
.push_highlighted(">");
1000 /// If `other_ty` is the same as a type argument present in `sub`, highlight `path` in `t1_out`,
1001 /// as that is the difference to the other type.
1003 /// For the following code:
1005 /// ```ignore (illustrative)
1006 /// let x: Foo<Bar<Qux>> = foo::<Bar<Qux>>();
1009 /// The type error output will behave in the following way:
1013 /// ^^^^--------^ this is highlighted
1015 /// | this type argument is exactly the same as the other type, not highlighted
1016 /// this is highlighted
1018 /// -------- this type is the same as a type argument in the other type, not highlighted
1022 mut t1_out
: &mut DiagnosticStyledString
,
1023 mut t2_out
: &mut DiagnosticStyledString
,
1025 sub
: &'tcx
[ty
::GenericArg
<'tcx
>],
1029 // FIXME/HACK: Go back to `GenericArgsRef` to use its inherent methods,
1030 // ideally that shouldn't be necessary.
1031 let sub
= self.tcx
.mk_args(sub
);
1032 for (i
, ta
) in sub
.types().enumerate() {
1034 self.highlight_outer(&mut t1_out
, &mut t2_out
, path
, sub
, i
, other_ty
);
1037 if let ty
::Adt(def
, _
) = ta
.kind() {
1038 let path_
= self.tcx
.def_path_str(def
.did());
1039 if path_
== other_path
{
1040 self.highlight_outer(&mut t1_out
, &mut t2_out
, path
, sub
, i
, other_ty
);
1048 /// Adds a `,` to the type representation only if it is appropriate.
1051 value
: &mut DiagnosticStyledString
,
1052 other_value
: &mut DiagnosticStyledString
,
1056 if len
> 0 && pos
!= len
- 1 {
1057 value
.push_normal(", ");
1058 other_value
.push_normal(", ");
1062 /// Given two `fn` signatures highlight only sub-parts that are different.
1065 sig1
: &ty
::PolyFnSig
<'tcx
>,
1066 sig2
: &ty
::PolyFnSig
<'tcx
>,
1067 ) -> (DiagnosticStyledString
, DiagnosticStyledString
) {
1068 let sig1
= &(self.normalize_fn_sig
)(*sig1
);
1069 let sig2
= &(self.normalize_fn_sig
)(*sig2
);
1071 let get_lifetimes
= |sig
| {
1072 use rustc_hir
::def
::Namespace
;
1073 let (sig
, reg
) = ty
::print
::FmtPrinter
::new(self.tcx
, Namespace
::TypeNS
)
1074 .name_all_regions(sig
)
1076 let lts
: Vec
<String
> = reg
.into_values().map(|kind
| kind
.to_string()).collect();
1077 (if lts
.is_empty() { String::new() }
else { format!("for<{}
> ", lts.join(", ")) }, sig)
1080 let (lt1, sig1) = get_lifetimes(sig1);
1081 let (lt2, sig2) = get_lifetimes(sig2);
1083 // unsafe extern "C
" for<'a> fn(&'a T) -> &'a T
1085 DiagnosticStyledString::normal("".to_string()),
1086 DiagnosticStyledString::normal("".to_string()),
1089 // unsafe extern "C
" for<'a> fn(&'a T) -> &'a T
1091 values.0.push(sig1.unsafety.prefix_str(), sig1.unsafety != sig2.unsafety);
1092 values.1.push(sig2.unsafety.prefix_str(), sig1.unsafety != sig2.unsafety);
1094 // unsafe extern "C
" for<'a> fn(&'a T) -> &'a T
1096 if sig1.abi != abi::Abi::Rust {
1097 values.0.push(format!("extern {}
", sig1.abi), sig1.abi != sig2.abi);
1099 if sig2.abi != abi::Abi::Rust {
1100 values.1.push(format!("extern {}
", sig2.abi), sig1.abi != sig2.abi);
1103 // unsafe extern "C
" for<'a> fn(&'a T) -> &'a T
1105 let lifetime_diff = lt1 != lt2;
1106 values.0.push(lt1, lifetime_diff);
1107 values.1.push(lt2, lifetime_diff);
1109 // unsafe extern "C
" for<'a> fn(&'a T) -> &'a T
1111 values.0.push_normal("fn(");
1112 values.1.push_normal("fn(");
1114 // unsafe extern "C
" for<'a> fn(&'a T) -> &'a T
1116 let len1 = sig1.inputs().len();
1117 let len2 = sig2.inputs().len();
1119 for (i, (l, r)) in iter::zip(sig1.inputs(), sig2.inputs()).enumerate() {
1120 let (x1, x2) = self.cmp(*l, *r);
1121 (values.0).0.extend(x1.0);
1122 (values.1).0.extend(x2.0);
1123 self.push_comma(&mut values.0, &mut values.1, len1, i);
1126 for (i, l) in sig1.inputs().iter().enumerate() {
1127 values.0.push_highlighted(l.to_string());
1129 values.0.push_highlighted(", ");
1132 for (i, r) in sig2.inputs().iter().enumerate() {
1133 values.1.push_highlighted(r.to_string());
1135 values.1.push_highlighted(", ");
1140 if sig1.c_variadic {
1142 values.0.push_normal(", ");
1144 values.0.push("...", !sig2.c_variadic);
1146 if sig2.c_variadic {
1148 values.1.push_normal(", ");
1150 values.1.push("...", !sig1.c_variadic);
1153 // unsafe extern "C
" for<'a> fn(&'a T) -> &'a T
1155 values.0.push_normal(")");
1156 values.1.push_normal(")");
1158 // unsafe extern "C
" for<'a> fn(&'a T) -> &'a T
1160 let output1 = sig1.output();
1161 let output2 = sig2.output();
1162 let (x1, x2) = self.cmp(output1, output2);
1163 if !output1.is_unit() {
1164 values.0.push_normal(" -> ");
1165 (values.0).0.extend(x1.0);
1167 if !output2.is_unit() {
1168 values.1.push_normal(" -> ");
1169 (values.1).0.extend(x2.0);
1174 /// Compares two given types, eliding parts that are the same between them and highlighting
1175 /// relevant differences, and return two representation of those types for highlighted printing.
1180 ) -> (DiagnosticStyledString, DiagnosticStyledString) {
1181 debug!("cmp(t1
={}
, t1
.kind
={:?}
, t2
={}
, t2
.kind
={:?}
)", t1, t1.kind(), t2, t2.kind());
1184 fn equals<'tcx>(a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
1185 match (a.kind(), b.kind()) {
1186 (a, b) if *a == *b => true,
1187 (&ty::Int(_), &ty::Infer(ty::InferTy::IntVar(_)))
1189 &ty::Infer(ty::InferTy::IntVar(_)),
1190 &ty::Int(_) | &ty::Infer(ty::InferTy::IntVar(_)),
1192 | (&ty::Float(_), &ty::Infer(ty::InferTy::FloatVar(_)))
1194 &ty::Infer(ty::InferTy::FloatVar(_)),
1195 &ty::Float(_) | &ty::Infer(ty::InferTy::FloatVar(_)),
1201 fn push_ty_ref<'tcx>(
1202 region: ty::Region<'tcx>,
1204 mutbl: hir::Mutability,
1205 s: &mut DiagnosticStyledString,
1207 let mut r = region.to_string();
1213 s.push_highlighted(format!("&{}{}
", r, mutbl.prefix_str()));
1214 s.push_normal(ty.to_string());
1217 // process starts here
1218 match (t1.kind(), t2.kind()) {
1219 (&ty::Adt(def1, sub1), &ty::Adt(def2, sub2)) => {
1220 let did1 = def1.did();
1221 let did2 = def2.did();
1222 let sub_no_defaults_1 =
1223 self.tcx.generics_of(did1).own_args_no_defaults(self.tcx, sub1);
1224 let sub_no_defaults_2 =
1225 self.tcx.generics_of(did2).own_args_no_defaults(self.tcx, sub2);
1226 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
1227 let path1 = self.tcx.def_path_str(did1);
1228 let path2 = self.tcx.def_path_str(did2);
1230 // Easy case. Replace same types with `_` to shorten the output and highlight
1231 // the differing ones.
1232 // let x: Foo<Bar, Qux> = y::<Foo<Quz, Qux>>();
1235 // --- ^ type argument elided
1237 // highlighted in output
1238 values.0.push_normal(path1);
1239 values.1.push_normal(path2);
1241 // Avoid printing out default generic parameters that are common to both
1243 let len1 = sub_no_defaults_1.len();
1244 let len2 = sub_no_defaults_2.len();
1245 let common_len = cmp::min(len1, len2);
1246 let remainder1: Vec<_> = sub1.types().skip(common_len).collect();
1247 let remainder2: Vec<_> = sub2.types().skip(common_len).collect();
1248 let common_default_params =
1249 iter::zip(remainder1.iter().rev(), remainder2.iter().rev())
1250 .filter(|(a, b)| a == b)
1252 let len = sub1.len() - common_default_params;
1253 let consts_offset = len - sub1.consts().count();
1255 // Only draw `<...>` if there are lifetime/type arguments.
1257 values.0.push_normal("<");
1258 values.1.push_normal("<");
1261 fn lifetime_display(lifetime: Region<'_>) -> String {
1262 let s = lifetime.to_string();
1263 if s.is_empty() { "'_".to_string() } else { s }
1265 // At one point we'd like to elide all lifetimes here, they are irrelevant for
1266 // all diagnostics that use this output
1270 // ^^ ^^ --- type arguments are not elided
1272 // | elided as they were the same
1273 // not elided, they were different, but irrelevant
1275 // For bound lifetimes, keep the names of the lifetimes,
1276 // even if they are the same so that it's clear what's happening
1277 // if we have something like
1279 // for<'r, 's> fn(Inv<'r>, Inv<'s>)
1280 // for<'r> fn(Inv<'r>, Inv<'r>)
1281 let lifetimes = sub1.regions().zip(sub2.regions());
1282 for (i, lifetimes) in lifetimes.enumerate() {
1283 let l1 = lifetime_display(lifetimes.0);
1284 let l2 = lifetime_display(lifetimes.1);
1285 if lifetimes.0 != lifetimes.1 {
1286 values.0.push_highlighted(l1);
1287 values.1.push_highlighted(l2);
1288 } else if lifetimes.0.is_late_bound() {
1289 values.0.push_normal(l1);
1290 values.1.push_normal(l2);
1292 values.0.push_normal("'_
");
1293 values.1.push_normal("'_
");
1295 self.push_comma(&mut values.0, &mut values.1, len, i);
1298 // We're comparing two types with the same path, so we compare the type
1299 // arguments for both. If they are the same, do not highlight and elide from the
1303 // ^ elided type as this type argument was the same in both sides
1304 let type_arguments = sub1.types().zip(sub2.types());
1305 let regions_len = sub1.regions().count();
1306 let num_display_types = consts_offset - regions_len;
1307 for (i, (ta1, ta2)) in type_arguments.take(num_display_types).enumerate() {
1308 let i = i + regions_len;
1309 if ta1 == ta2 && !self.tcx.sess.verbose() {
1310 values.0.push_normal("_
");
1311 values.1.push_normal("_
");
1313 let (x1, x2) = self.cmp(ta1, ta2);
1314 (values.0).0.extend(x1.0);
1315 (values.1).0.extend(x2.0);
1317 self.push_comma(&mut values.0, &mut values.1, len, i);
1320 // Do the same for const arguments, if they are equal, do not highlight and
1321 // elide them from the output.
1322 let const_arguments = sub1.consts().zip(sub2.consts());
1323 for (i, (ca1, ca2)) in const_arguments.enumerate() {
1324 let i = i + consts_offset;
1325 if ca1 == ca2 && !self.tcx.sess.verbose() {
1326 values.0.push_normal("_
");
1327 values.1.push_normal("_
");
1329 values.0.push_highlighted(ca1.to_string());
1330 values.1.push_highlighted(ca2.to_string());
1332 self.push_comma(&mut values.0, &mut values.1, len, i);
1335 // Close the type argument bracket.
1336 // Only draw `<...>` if there are lifetime/type arguments.
1338 values.0.push_normal(">");
1339 values.1.push_normal(">");
1344 // let x: Foo<Bar<Qux> = foo::<Bar<Qux>>();
1346 // ------- this type argument is exactly the same as the other type
1362 // let x: Bar<Qux> = y:<Foo<Bar<Qux>>>();
1365 // ------- this type argument is exactly the same as the other type
1380 // We can't find anything in common, highlight relevant part of type path.
1381 // let x: foo::bar::Baz<Qux> = y:<foo::bar::Bar<Zar>>();
1382 // foo::bar::Baz<Qux>
1383 // foo::bar::Bar<Zar>
1384 // -------- this part of the path is different
1386 let t1_str = t1.to_string();
1387 let t2_str = t2.to_string();
1388 let min_len = t1_str.len().min(t2_str.len());
1390 const SEPARATOR: &str = "::";
1391 let separator_len = SEPARATOR.len();
1392 let split_idx: usize =
1393 iter::zip(t1_str.split(SEPARATOR), t2_str.split(SEPARATOR))
1394 .take_while(|(mod1_str, mod2_str)| mod1_str == mod2_str)
1395 .map(|(mod_str, _)| mod_str.len() + separator_len)
1398 debug!(?separator_len, ?split_idx, ?min_len, "cmp
");
1400 if split_idx >= min_len {
1401 // paths are identical, highlight everything
1403 DiagnosticStyledString::highlighted(t1_str),
1404 DiagnosticStyledString::highlighted(t2_str),
1407 let (common, uniq1) = t1_str.split_at(split_idx);
1408 let (_, uniq2) = t2_str.split_at(split_idx);
1409 debug!(?common, ?uniq1, ?uniq2, "cmp
");
1411 values.0.push_normal(common);
1412 values.0.push_highlighted(uniq1);
1413 values.1.push_normal(common);
1414 values.1.push_highlighted(uniq2);
1421 // When finding T != &T, highlight only the borrow
1422 (&ty::Ref(r1, ref_ty1, mutbl1), _) if equals(ref_ty1, t2) => {
1423 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
1424 push_ty_ref(r1, ref_ty1, mutbl1, &mut values.0);
1425 values.1.push_normal(t2.to_string());
1428 (_, &ty::Ref(r2, ref_ty2, mutbl2)) if equals(t1, ref_ty2) => {
1429 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
1430 values.0.push_normal(t1.to_string());
1431 push_ty_ref(r2, ref_ty2, mutbl2, &mut values.1);
1435 // When encountering &T != &mut T, highlight only the borrow
1436 (&ty::Ref(r1, ref_ty1, mutbl1), &ty::Ref(r2, ref_ty2, mutbl2))
1437 if equals(ref_ty1, ref_ty2) =>
1439 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
1440 push_ty_ref(r1, ref_ty1, mutbl1, &mut values.0);
1441 push_ty_ref(r2, ref_ty2, mutbl2, &mut values.1);
1445 // When encountering tuples of the same size, highlight only the differing types
1446 (&ty::Tuple(args1), &ty::Tuple(args2)) if args1.len() == args2.len() => {
1448 (DiagnosticStyledString::normal("("), DiagnosticStyledString::normal("("));
1449 let len = args1.len();
1450 for (i, (left, right)) in args1.iter().zip(args2).enumerate() {
1451 let (x1, x2) = self.cmp(left, right);
1452 (values.0).0.extend(x1.0);
1453 (values.1).0.extend(x2.0);
1454 self.push_comma(&mut values.0, &mut values.1, len, i);
1457 // Keep the output for single element tuples as `(ty,)`.
1458 values.0.push_normal(",");
1459 values.1.push_normal(",");
1461 values.0.push_normal(")");
1462 values.1.push_normal(")");
1466 (ty::FnDef(did1, args1), ty::FnDef(did2, args2)) => {
1467 let sig1 = self.tcx.fn_sig(*did1).instantiate(self.tcx, args1);
1468 let sig2 = self.tcx.fn_sig(*did2).instantiate(self.tcx, args2);
1469 let mut values = self.cmp_fn_sig(&sig1, &sig2);
1470 let path1 = format!(" {{{}
}}", self.tcx.def_path_str_with_args(*did1, args1));
1471 let path2 = format!(" {{{}
}}", self.tcx.def_path_str_with_args(*did2, args2));
1472 let same_path = path1 == path2;
1473 values.0.push(path1, !same_path);
1474 values.1.push(path2, !same_path);
1478 (ty::FnDef(did1, args1), ty::FnPtr(sig2)) => {
1479 let sig1 = self.tcx.fn_sig(*did1).instantiate(self.tcx, args1);
1480 let mut values = self.cmp_fn_sig(&sig1, sig2);
1481 values.0.push_highlighted(format!(
1483 self.tcx.def_path_str_with_args(*did1, args1)
1488 (ty::FnPtr(sig1), ty::FnDef(did2, args2)) => {
1489 let sig2 = self.tcx.fn_sig(*did2).instantiate(self.tcx, args2);
1490 let mut values = self.cmp_fn_sig(sig1, &sig2);
1493 .push_normal(format!(" {{{}
}}", self.tcx.def_path_str_with_args(*did2, args2)));
1497 (ty::FnPtr(sig1), ty::FnPtr(sig2)) => self.cmp_fn_sig(sig1, sig2),
1500 if t1 == t2 && !self.tcx.sess.verbose() {
1501 // The two types are the same, elide and don't highlight.
1502 (DiagnosticStyledString::normal("_
"), DiagnosticStyledString::normal("_
"))
1504 // We couldn't find anything in common, highlight everything.
1506 DiagnosticStyledString::highlighted(t1.to_string()),
1507 DiagnosticStyledString::highlighted(t2.to_string()),
1514 /// Extend a type error with extra labels pointing at "non
-trivial
" types, like closures and
1515 /// the return type of `async fn`s.
1517 /// `secondary_span` gives the caller the opportunity to expand `diag` with a `span_label`.
1519 /// `swap_secondary_and_primary` is used to make projection errors in particular nicer by using
1520 /// the message in `secondary_span` as the primary label, and apply the message that would
1521 /// otherwise be used for the primary label on the `secondary_span` `Span`. This applies on
1522 /// E0271, like `tests/ui/issues/issue-39970.stderr`.
1525 skip(self, diag, secondary_span, swap_secondary_and_primary, prefer_label)
1527 pub fn note_type_err(
1529 diag: &mut Diagnostic,
1530 cause: &ObligationCause<'tcx>,
1531 secondary_span: Option<(Span, Cow<'static, str>)>,
1532 mut values: Option<ValuePairs<'tcx>>,
1533 terr: TypeError<'tcx>,
1534 swap_secondary_and_primary: bool,
1537 let span = cause.span();
1539 // For some types of errors, expected-found does not make
1540 // sense, so just ignore the values we were given.
1541 if let TypeError::CyclicTy(_) = terr {
1544 struct OpaqueTypesVisitor<'tcx> {
1545 types: FxIndexMap<TyCategory, FxIndexSet<Span>>,
1546 expected: FxIndexMap<TyCategory, FxIndexSet<Span>>,
1547 found: FxIndexMap<TyCategory, FxIndexSet<Span>>,
1552 impl<'tcx> OpaqueTypesVisitor<'tcx> {
1553 fn visit_expected_found(
1555 expected: impl TypeVisitable<TyCtxt<'tcx>>,
1556 found: impl TypeVisitable<TyCtxt<'tcx>>,
1559 let mut types_visitor = OpaqueTypesVisitor {
1560 types: Default::default(),
1561 expected: Default::default(),
1562 found: Default::default(),
1566 // The visitor puts all the relevant encountered types in `self.types`, but in
1567 // here we want to visit two separate types with no relation to each other, so we
1568 // move the results from `types` to `expected` or `found` as appropriate.
1569 expected.visit_with(&mut types_visitor);
1570 std::mem::swap(&mut types_visitor.expected, &mut types_visitor.types);
1571 found.visit_with(&mut types_visitor);
1572 std::mem::swap(&mut types_visitor.found, &mut types_visitor.types);
1576 fn report(&self, err: &mut Diagnostic) {
1577 self.add_labels_for_types(err, "expected
", &self.expected);
1578 self.add_labels_for_types(err, "found
", &self.found);
1581 fn add_labels_for_types(
1583 err: &mut Diagnostic,
1585 types: &FxIndexMap<TyCategory, FxIndexSet<Span>>,
1587 for (kind, values) in types.iter() {
1588 let count = values.len();
1594 if count == 1 { "the " } else { "one of the " },
1605 impl<'tcx> ty::visit::TypeVisitor<TyCtxt<'tcx>> for OpaqueTypesVisitor<'tcx> {
1606 fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
1607 if let Some((kind, def_id)) = TyCategory::from_ty(self.tcx, t) {
1608 let span = self.tcx.def_span(def_id);
1609 // Avoid cluttering the output when the "found
" and error span overlap:
1611 // error[E0308]: mismatched types
1612 // --> $DIR/issue-20862.rs:2:5
1617 // | the found closure
1618 // | expected `()`, found closure
1620 // = note: expected unit type `()`
1621 // found closure `{closure@$DIR/issue-20862.rs:2:5: 2:14 x:_}`
1623 // Also ignore opaque `Future`s that come from async fns.
1624 if !self.ignore_span.overlaps(span)
1625 && !span.is_desugaring(DesugaringKind::Async)
1627 self.types.entry(kind).or_default().insert(span);
1630 t.super_visit_with(self)
1634 debug!("note_type_err(diag
={:?}
)", diag);
1636 Variable(ty::error::ExpectedFound<Ty<'a>>),
1637 Fixed(&'static str),
1639 let (expected_found, exp_found, is_simple_error, values) = match values {
1640 None => (None, Mismatch::Fixed("type"), false, None),
1642 let values = self.resolve_vars_if_possible(values);
1643 let (is_simple_error, exp_found) = match values {
1644 ValuePairs::Terms(infer::ExpectedFound { expected, found }) => {
1645 match (expected.unpack(), found.unpack()) {
1646 (ty::TermKind::Ty(expected), ty::TermKind::Ty(found)) => {
1647 let is_simple_err = expected.is_simple_text(self.tcx)
1648 && found.is_simple_text(self.tcx);
1649 OpaqueTypesVisitor::visit_expected_found(
1650 self.tcx, expected, found, span,
1656 Mismatch::Variable(infer::ExpectedFound { expected, found }),
1659 (ty::TermKind::Const(_), ty::TermKind::Const(_)) => {
1660 (false, Mismatch::Fixed("constant
"))
1662 _ => (false, Mismatch::Fixed("type")),
1665 ValuePairs::PolySigs(infer::ExpectedFound { expected, found }) => {
1666 OpaqueTypesVisitor::visit_expected_found(self.tcx, expected, found, span)
1668 (false, Mismatch::Fixed("signature
"))
1670 ValuePairs::TraitRefs(_) | ValuePairs::PolyTraitRefs(_) => {
1671 (false, Mismatch::Fixed("trait"))
1673 ValuePairs::Aliases(infer::ExpectedFound { expected, .. }) => {
1674 (false, Mismatch::Fixed(self.tcx.def_descr(expected.def_id)))
1676 ValuePairs::Regions(_) => (false, Mismatch::Fixed("lifetime
")),
1677 ValuePairs::ExistentialTraitRef(_) => {
1678 (false, Mismatch::Fixed("existential
trait ref"))
1680 ValuePairs::ExistentialProjection(_) => {
1681 (false, Mismatch::Fixed("existential projection
"))
1684 let Some(vals) = self.values_str(values) else {
1685 // Derived error. Cancel the emitter.
1686 // NOTE(eddyb) this was `.cancel()`, but `diag`
1687 // is borrowed, so we can't fully defuse it.
1688 diag.downgrade_to_delayed_bug();
1691 (Some(vals), exp_found, is_simple_error, Some(values))
1695 let mut label_or_note = |span: Span, msg: Cow<'static, str>| {
1696 if (prefer_label && is_simple_error) || &[span] == diag.span.primary_spans() {
1697 diag.span_label(span, msg);
1699 diag.span_note(span, msg);
1702 if let Some((sp, msg)) = secondary_span {
1703 if swap_secondary_and_primary {
1704 let terr = if let Some(infer::ValuePairs::Terms(infer::ExpectedFound {
1709 Cow::from(format!("expected this to be `{expected}`
"))
1711 terr.to_string(self.tcx)
1713 label_or_note(sp, terr);
1714 label_or_note(span, msg);
1716 label_or_note(span, terr.to_string(self.tcx));
1717 label_or_note(sp, msg);
1720 if let Some(values) = values
1721 && let Some((e, f)) = values.ty()
1722 && let TypeError::ArgumentSorts(..) | TypeError::Sorts(_) = terr
1724 let e = self.tcx.erase_regions(e);
1725 let f = self.tcx.erase_regions(f);
1726 let expected = with_forced_trimmed_paths!(e.sort_string(self.tcx));
1727 let found = with_forced_trimmed_paths!(f.sort_string(self.tcx));
1728 if expected == found {
1729 label_or_note(span, terr.to_string(self.tcx));
1731 label_or_note(span, Cow::from(format!("expected {expected}
, found {found}
")));
1734 label_or_note(span, terr.to_string(self.tcx));
1738 if let Some((expected, found, exp_p, found_p)) = expected_found {
1739 let (expected_label, found_label, exp_found) = match exp_found {
1740 Mismatch::Variable(ef) => (
1741 ef.expected.prefix_string(self.tcx),
1742 ef.found.prefix_string(self.tcx),
1745 Mismatch::Fixed(s) => (s.into(), s.into(), None),
1748 enum Similar<'tcx> {
1749 Adts { expected: ty::AdtDef<'tcx>, found: ty::AdtDef<'tcx> },
1750 PrimitiveFound { expected: ty::AdtDef<'tcx>, found: Ty<'tcx> },
1751 PrimitiveExpected { expected: Ty<'tcx>, found: ty::AdtDef<'tcx> },
1754 let similarity = |ExpectedFound { expected, found }: ExpectedFound<Ty<'tcx>>| {
1755 if let ty::Adt(expected, _) = expected.kind()
1756 && let Some(primitive) = found.primitive_symbol()
1758 let path = self.tcx.def_path(expected.did()).data;
1759 let name = path.last().unwrap().data.get_opt_name();
1760 if name == Some(primitive) {
1761 return Some(Similar::PrimitiveFound { expected: *expected, found });
1763 } else if let Some(primitive) = expected.primitive_symbol()
1764 && let ty::Adt(found, _) = found.kind()
1766 let path = self.tcx.def_path(found.did()).data;
1767 let name = path.last().unwrap().data.get_opt_name();
1768 if name == Some(primitive) {
1769 return Some(Similar::PrimitiveExpected { expected, found: *found });
1771 } else if let ty::Adt(expected, _) = expected.kind()
1772 && let ty::Adt(found, _) = found.kind()
1774 if !expected.did().is_local() && expected.did().krate == found.did().krate {
1775 // Most likely types from different versions of the same crate
1776 // are in play, in which case this message isn't so helpful.
1777 // A "perhaps two different versions
..." error is already emitted for that.
1780 let f_path = self.tcx.def_path(found.did()).data;
1781 let e_path = self.tcx.def_path(expected.did()).data;
1783 if let (Some(e_last), Some(f_last)) = (e_path.last(), f_path.last())
1786 return Some(Similar::Adts { expected: *expected, found: *found });
1793 // If two types mismatch but have similar names, mention that specifically.
1794 TypeError::Sorts(values) if let Some(s) = similarity(values) => {
1795 let diagnose_primitive =
1799 diagnostic: &mut Diagnostic| {
1800 let name = shadow.sort_string(self.tcx);
1801 diagnostic.note(format!(
1802 "{prim} and {name} have similar names
, but are actually distinct types
"
1805 .note(format!("{prim} is a primitive defined by the language
"));
1806 let def_span = self.tcx.def_span(defid);
1807 let msg = if defid.is_local() {
1808 format!("{name} is defined
in the current
crate")
1810 let crate_name = self.tcx.crate_name(defid.krate);
1811 format!("{name} is defined
in crate `{crate_name}`
")
1813 diagnostic.span_note(def_span, msg);
1817 |expected_adt: ty::AdtDef<'tcx>,
1818 found_adt: ty::AdtDef<'tcx>,
1819 diagnostic: &mut Diagnostic| {
1820 let found_name = values.found.sort_string(self.tcx);
1821 let expected_name = values.expected.sort_string(self.tcx);
1823 let found_defid = found_adt.did();
1824 let expected_defid = expected_adt.did();
1826 diagnostic.note(format!("{found_name} and {expected_name} have similar names
, but are actually distinct types
"));
1827 for (defid, name) in
1828 [(found_defid, found_name), (expected_defid, expected_name)]
1830 let def_span = self.tcx.def_span(defid);
1832 let msg = if found_defid.is_local() && expected_defid.is_local() {
1835 .parent_module_from_def_id(defid.expect_local())
1838 self.tcx.def_path(module).to_string_no_crate_verbose();
1840 "{name} is defined
in module `
crate{module_name}` of the current
crate"
1842 } else if defid.is_local() {
1843 format!("{name} is defined
in the current
crate")
1845 let crate_name = self.tcx.crate_name(defid.krate);
1846 format!("{name} is defined
in crate `{crate_name}`
")
1848 diagnostic.span_note(def_span, msg);
1853 Similar::Adts { expected, found } => diagnose_adts(expected, found, diag),
1854 Similar::PrimitiveFound { expected, found: prim } => {
1855 diagnose_primitive(prim, values.expected, expected.did(), diag)
1857 Similar::PrimitiveExpected { expected: prim, found } => {
1858 diagnose_primitive(prim, values.found, found.did(), diag)
1862 TypeError::Sorts(values) => {
1863 let extra = expected == found;
1864 let sort_string = |ty: Ty<'tcx>, path: Option<PathBuf>| {
1865 let mut s = match (extra, ty.kind()) {
1866 (true, ty::Alias(ty::Opaque, ty::AliasTy { def_id, .. })) => {
1867 let sm = self.tcx.sess.source_map();
1868 let pos = sm.lookup_char_pos(self.tcx.def_span(*def_id).lo());
1870 " (opaque
type at
<{}
:{}
:{}
>)",
1871 sm.filename_for_diagnostics(&pos.file.name),
1873 pos.col.to_usize() + 1,
1876 (true, ty::Alias(ty::Projection, proj))
1877 if self.tcx.is_impl_trait_in_trait(proj.def_id) =>
1879 let sm = self.tcx.sess.source_map();
1880 let pos = sm.lookup_char_pos(self.tcx.def_span(proj.def_id).lo());
1882 " (trait associated opaque
type at
<{}
:{}
:{}
>)",
1883 sm.filename_for_diagnostics(&pos.file.name),
1885 pos.col.to_usize() + 1,
1888 (true, _) => format!(" ({}
)", ty.sort_string(self.tcx)),
1889 (false, _) => "".to_string(),
1891 if let Some(path) = path {
1892 s.push_str(&format!(
1893 "\nthe full
type name has been written to '{}'
",
1899 if !(values.expected.is_simple_text(self.tcx)
1900 && values.found.is_simple_text(self.tcx))
1901 || (exp_found.is_some_and(|ef| {
1902 // This happens when the type error is a subset of the expectation,
1903 // like when you have two references but one is `usize` and the other
1904 // is `f32`. In those cases we still want to show the `note`. If the
1905 // value from `ef` is `Infer(_)`, then we ignore it.
1906 if !ef.expected.is_ty_or_numeric_infer() {
1907 ef.expected != values.expected
1908 } else if !ef.found.is_ty_or_numeric_infer() {
1909 ef.found != values.found
1915 if let Some(ExpectedFound { found: found_ty, .. }) = exp_found {
1916 // `Future` is a special opaque type that the compiler
1917 // will try to hide in some case such as `async fn`, so
1918 // to make an error more use friendly we will
1919 // avoid to suggest a mismatch type with a
1920 // type that the user usually are not using
1921 // directly such as `impl Future<Output = u8>`.
1922 if !self.tcx.ty_is_opaque_future(found_ty) {
1923 diag.note_expected_found_extra(
1928 &sort_string(values.expected, exp_p),
1929 &sort_string(values.found, found_p),
1937 "note_type_err
: exp_found
={:?}
, expected
={:?} found
={:?}
",
1938 exp_found, expected, found
1940 if !is_simple_error || terr.must_include_note() {
1941 diag.note_expected_found(&expected_label, expected, &found_label, found);
1946 let exp_found = match exp_found {
1947 Mismatch::Variable(exp_found) => Some(exp_found),
1948 Mismatch::Fixed(_) => None,
1950 let exp_found = match terr {
1951 // `terr` has more accurate type information than `exp_found` in match expressions.
1952 ty::error::TypeError::Sorts(terr)
1953 if exp_found.is_some_and(|ef| terr.found == ef.found) =>
1959 debug!("exp_found {:?} terr {:?} cause
.code {:?}
", exp_found, terr, cause.code());
1960 if let Some(exp_found) = exp_found {
1961 let should_suggest_fixes =
1962 if let ObligationCauseCode::Pattern { root_ty, .. } = cause.code() {
1963 // Skip if the root_ty of the pattern is not the same as the expected_ty.
1964 // If these types aren't equal then we've probably peeled off a layer of arrays.
1965 self.same_type_modulo_infer(*root_ty, exp_found.expected)
1970 // FIXME(#73154): For now, we do leak check when coercing function
1971 // pointers in typeck, instead of only during borrowck. This can lead
1972 // to these `RegionsInsufficientlyPolymorphic` errors that aren't helpful.
1973 if should_suggest_fixes
1974 && !matches!(terr, TypeError::RegionsInsufficientlyPolymorphic(..))
1976 self.suggest_tuple_pattern(cause, &exp_found, diag);
1977 self.suggest_accessing_field_where_appropriate(cause, &exp_found, diag);
1978 self.suggest_await_on_expect_found(cause, span, &exp_found, diag);
1979 self.suggest_function_pointers(cause, span, &exp_found, diag);
1983 self.check_and_note_conflicting_crates(diag, terr);
1985 self.note_and_explain_type_err(diag, terr, cause, span, cause.body_id.to_def_id());
1986 if let Some(exp_found) = exp_found
1987 && let exp_found = TypeError::Sorts(exp_found)
1988 && exp_found != terr
1990 self.note_and_explain_type_err(diag, exp_found, cause, span, cause.body_id.to_def_id());
1993 if let Some(ValuePairs::PolyTraitRefs(exp_found)) = values
1994 && let ty::Closure(def_id, _) = exp_found.expected.skip_binder().self_ty().kind()
1995 && let Some(def_id) = def_id.as_local()
1996 && terr.involves_regions()
1998 let span = self.tcx.def_span(def_id);
1999 diag.span_note(span, "this closure does not fulfill the lifetime requirements
");
2000 self.suggest_for_all_lifetime_closure(
2002 self.tcx.hir().get_by_def_id(def_id),
2008 // It reads better to have the error origin as the final
2010 self.note_error_origin(diag, cause, exp_found, terr);
2015 pub fn type_error_additional_suggestions(
2017 trace: &TypeTrace<'tcx>,
2018 terr: TypeError<'tcx>,
2019 ) -> Vec<TypeErrorAdditionalDiags> {
2020 use crate::traits::ObligationCauseCode::{BlockTailExpression, MatchExpressionArm};
2021 let mut suggestions = Vec::new();
2022 let span = trace.cause.span();
2023 let values = self.resolve_vars_if_possible(trace.values);
2024 if let Some((expected, found)) = values.ty() {
2025 match (expected.kind(), found.kind()) {
2026 (ty::Tuple(_), ty::Tuple(_)) => {}
2027 // If a tuple of length one was expected and the found expression has
2028 // parentheses around it, perhaps the user meant to write `(expr,)` to
2029 // build a tuple (issue #86100)
2030 (ty::Tuple(fields), _) => {
2031 suggestions.extend(self.suggest_wrap_to_build_a_tuple(span, found, fields))
2033 // If a byte was expected and the found expression is a char literal
2034 // containing a single ASCII character, perhaps the user meant to write `b'c'` to
2035 // specify a byte literal
2036 (ty::Uint(ty::UintTy::U8), ty::Char) => {
2037 if let Ok(code) = self.tcx.sess().source_map().span_to_snippet(span)
2039 code.strip_prefix('\'').and_then(|s| s.strip_suffix('\''))
2040 // forbid all Unicode escapes
2041 && !code.starts_with("\\u
")
2042 // forbids literal Unicode characters beyond ASCII
2043 && code.chars().next().is_some_and(|c| c.is_ascii())
2045 suggestions.push(TypeErrorAdditionalDiags::MeantByteLiteral {
2047 code: escape_literal(code),
2051 // If a character was expected and the found expression is a string literal
2052 // containing a single character, perhaps the user meant to write `'c'` to
2053 // specify a character literal (issue #92479)
2054 (ty::Char, ty::Ref(_, r, _)) if r.is_str() => {
2055 if let Ok(code) = self.tcx.sess().source_map().span_to_snippet(span)
2056 && let Some(code) = code.strip_prefix('"'
).and_then(|s
| s
.strip_suffix('
"'))
2057 && code.chars().count() == 1
2059 suggestions.push(TypeErrorAdditionalDiags::MeantCharLiteral {
2061 code: escape_literal(code),
2065 // If a string was expected and the found expression is a character literal,
2066 // perhaps the user meant to write `"s
"` to specify a string literal.
2067 (ty::Ref(_, r, _), ty::Char) if r.is_str() => {
2068 if let Ok(code) = self.tcx.sess().source_map().span_to_snippet(span) {
2070 code.strip_prefix('\'').and_then(|s| s.strip_suffix('\''))
2072 suggestions.push(TypeErrorAdditionalDiags::MeantStrLiteral {
2074 code: escape_literal(code),
2079 // For code `if Some(..) = expr `, the type mismatch may be expected `bool` but found `()`,
2080 // we try to suggest to add the missing `let` for `if let Some(..) = expr`
2081 (ty::Bool, ty::Tuple(list)) => {
2082 if list.len() == 0 {
2083 suggestions.extend(self.suggest_let_for_letchains(&trace.cause, span));
2086 (ty::Array(_, _), ty::Array(_, _)) => {
2087 suggestions.extend(self.suggest_specify_actual_length(terr, trace, span))
2092 let code = trace.cause.code();
2093 if let &(MatchExpressionArm(box MatchExpressionArmCause { source, .. })
2094 | BlockTailExpression(.., source)) = code
2095 && let hir::MatchSource::TryDesugar(_) = source
2096 && let Some((expected_ty, found_ty, _, _)) = self.values_str(trace.values)
2098 suggestions.push(TypeErrorAdditionalDiags::TryCannotConvert {
2099 found: found_ty.content(),
2100 expected: expected_ty.content(),
2106 fn suggest_specify_actual_length(
2108 terr: TypeError<'_>,
2109 trace: &TypeTrace<'_>,
2111 ) -> Option<TypeErrorAdditionalDiags> {
2112 let hir = self.tcx.hir();
2113 let TypeError::FixedArraySize(sz) = terr else {
2116 let tykind = match hir.find_by_def_id(trace.cause.body_id) {
2117 Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(_, _, body_id), .. })) => {
2118 let body = hir.body(*body_id);
2119 struct LetVisitor<'v> {
2121 result: Option<&'v hir::Ty<'v>>,
2123 impl<'v> Visitor<'v> for LetVisitor<'v> {
2124 fn visit_stmt(&mut self, s: &'v hir::Stmt<'v>) {
2125 if self.result.is_some() {
2128 // Find a local statement where the initializer has
2129 // the same span as the error and the type is specified.
2132 hir::StmtKind::Local(hir::Local {
2133 init: Some(hir::Expr { span: init_span, .. }),
2139 && init_span == &self.span
2141 self.result = Some(*array_ty);
2145 let mut visitor = LetVisitor { span, result: None };
2146 visitor.visit_body(body);
2147 visitor.result.map(|r| &r.peel_refs().kind)
2149 Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Const(ty, _, _), .. })) => {
2150 Some(&ty.peel_refs().kind)
2154 if let Some(tykind) = tykind
2155 && let hir::TyKind::Array(_, length) = tykind
2156 && let hir::ArrayLen::Body(hir::AnonConst { hir_id, .. }) = length
2157 && let Some(span) = self.tcx.hir().opt_span(*hir_id)
2159 Some(TypeErrorAdditionalDiags::ConsiderSpecifyingLength { span, length: sz.found })
2165 pub fn report_and_explain_type_error(
2167 trace: TypeTrace<'tcx>,
2168 terr: TypeError<'tcx>,
2169 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
2170 debug!("report_and_explain_type_error(trace
={:?}
, terr
={:?}
)", trace, terr);
2172 let span = trace.cause.span();
2173 let failure_code = trace.cause.as_failure_code_diag(
2176 self.type_error_additional_suggestions(&trace, terr),
2178 let mut diag = self.tcx.sess.create_err(failure_code);
2179 self.note_type_err(&mut diag, &trace.cause, None, Some(trace.values), terr, false, false);
2183 fn suggest_wrap_to_build_a_tuple(
2187 expected_fields: &List<Ty<'tcx>>,
2188 ) -> Option<TypeErrorAdditionalDiags> {
2189 let [expected_tup_elem] = expected_fields[..] else { return None };
2191 if !self.same_type_modulo_infer(expected_tup_elem, found) {
2195 let Ok(code) = self.tcx.sess().source_map().span_to_snippet(span) else { return None };
2197 let sugg = if code.starts_with('(') && code.ends_with(')') {
2198 let before_close = span.hi() - BytePos::from_u32(1);
2199 TypeErrorAdditionalDiags::TupleOnlyComma {
2200 span: span.with_hi(before_close).shrink_to_hi(),
2203 TypeErrorAdditionalDiags::TupleAlsoParentheses {
2204 span_low: span.shrink_to_lo(),
2205 span_high: span.shrink_to_hi(),
2213 values: ValuePairs<'tcx>,
2214 ) -> Option<(DiagnosticStyledString, DiagnosticStyledString, Option<PathBuf>, Option<PathBuf>)>
2217 infer::Regions(exp_found) => self.expected_found_str(exp_found),
2218 infer::Terms(exp_found) => self.expected_found_str_term(exp_found),
2219 infer::Aliases(exp_found) => self.expected_found_str(exp_found),
2220 infer::ExistentialTraitRef(exp_found) => self.expected_found_str(exp_found),
2221 infer::ExistentialProjection(exp_found) => self.expected_found_str(exp_found),
2222 infer::TraitRefs(exp_found) => {
2223 let pretty_exp_found = ty::error::ExpectedFound {
2224 expected: exp_found.expected.print_only_trait_path(),
2225 found: exp_found.found.print_only_trait_path(),
2227 match self.expected_found_str(pretty_exp_found) {
2228 Some((expected, found, _, _)) if expected == found => {
2229 self.expected_found_str(exp_found)
2234 infer::PolyTraitRefs(exp_found) => {
2235 let pretty_exp_found = ty::error::ExpectedFound {
2236 expected: exp_found.expected.print_only_trait_path(),
2237 found: exp_found.found.print_only_trait_path(),
2239 match self.expected_found_str(pretty_exp_found) {
2240 Some((expected, found, _, _)) if expected == found => {
2241 self.expected_found_str(exp_found)
2246 infer::PolySigs(exp_found) => {
2247 let exp_found = self.resolve_vars_if_possible(exp_found);
2248 if exp_found.references_error() {
2251 let (exp, fnd) = self.cmp_fn_sig(&exp_found.expected, &exp_found.found);
2252 Some((exp, fnd, None, None))
2257 fn expected_found_str_term(
2259 exp_found: ty::error::ExpectedFound<ty::Term<'tcx>>,
2260 ) -> Option<(DiagnosticStyledString, DiagnosticStyledString, Option<PathBuf>, Option<PathBuf>)>
2262 let exp_found = self.resolve_vars_if_possible(exp_found);
2263 if exp_found.references_error() {
2267 Some(match (exp_found.expected.unpack(), exp_found.found.unpack()) {
2268 (ty::TermKind::Ty(expected), ty::TermKind::Ty(found)) => {
2269 let (mut exp, mut fnd) = self.cmp(expected, found);
2270 // Use the terminal width as the basis to determine when to compress the printed
2271 // out type, but give ourselves some leeway to avoid ending up creating a file for
2272 // a type that is somewhat shorter than the path we'd write to.
2273 let len = self.tcx.sess().diagnostic_width() + 40;
2274 let exp_s = exp.content();
2275 let fnd_s = fnd.content();
2276 let mut exp_p = None;
2277 let mut fnd_p = None;
2278 if exp_s.len() > len {
2279 let (exp_s, exp_path) = self.tcx.short_ty_string(expected);
2280 exp = DiagnosticStyledString::highlighted(exp_s);
2283 if fnd_s.len() > len {
2284 let (fnd_s, fnd_path) = self.tcx.short_ty_string(found);
2285 fnd = DiagnosticStyledString::highlighted(fnd_s);
2288 (exp, fnd, exp_p, fnd_p)
2291 DiagnosticStyledString::highlighted(exp_found.expected.to_string()),
2292 DiagnosticStyledString::highlighted(exp_found.found.to_string()),
2299 /// Returns a string of the form "expected `{}`
, found `{}`
".
2300 fn expected_found_str<T: fmt::Display + TypeFoldable<TyCtxt<'tcx>>>(
2302 exp_found: ty::error::ExpectedFound<T>,
2303 ) -> Option<(DiagnosticStyledString, DiagnosticStyledString, Option<PathBuf>, Option<PathBuf>)>
2305 let exp_found = self.resolve_vars_if_possible(exp_found);
2306 if exp_found.references_error() {
2311 DiagnosticStyledString::highlighted(exp_found.expected.to_string()),
2312 DiagnosticStyledString::highlighted(exp_found.found.to_string()),
2318 pub fn report_generic_bound_failure(
2320 generic_param_scope: LocalDefId,
2322 origin: Option<SubregionOrigin<'tcx>>,
2323 bound_kind: GenericKind<'tcx>,
2326 self.construct_generic_bound_failure(generic_param_scope, span, origin, bound_kind, sub)
2330 pub fn construct_generic_bound_failure(
2332 generic_param_scope: LocalDefId,
2334 origin: Option<SubregionOrigin<'tcx>>,
2335 bound_kind: GenericKind<'tcx>,
2337 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
2338 if let Some(SubregionOrigin::CompareImplItemObligation {
2344 return self.report_extra_impl_obligation(
2348 &format!("`{bound_kind}
: {sub}`
"),
2352 let labeled_user_string = match bound_kind {
2353 GenericKind::Param(ref p) => format!("the parameter
type `{p}`
"),
2354 GenericKind::Alias(ref p) => match p.kind(self.tcx) {
2355 ty::AliasKind::Projection | ty::AliasKind::Inherent => {
2356 format!("the associated
type `{p}`
")
2358 ty::AliasKind::Weak => format!("the
type alias `{p}`
"),
2359 ty::AliasKind::Opaque => format!("the opaque
type `{p}`
"),
2363 let mut err = self.tcx.sess.struct_span_err_with_code(
2365 format!("{labeled_user_string} may not live long enough
"),
2367 ty::ReEarlyBound(_) | ty::ReFree(_) if sub.has_name() => error_code!(E0309),
2368 ty::ReStatic => error_code!(E0310),
2369 _ => error_code!(E0311),
2374 let (description, span) = match sub.kind() {
2375 ty::ReEarlyBound(_) | ty::ReFree(_) | ty::ReStatic => {
2376 msg_span_from_named_region(self.tcx, sub, Some(span))
2378 _ => (format!("lifetime `{sub}`
"), Some(span)),
2380 let prefix = format!("{labeled_user_string} must be valid
for ");
2381 label_msg_span(&mut err, &prefix, description, span, "...");
2382 if let Some(origin) = origin {
2383 self.note_region_origin(&mut err, &origin);
2388 let msg = "consider adding an explicit lifetime bound
";
2390 if (bound_kind, sub).has_infer_regions()
2391 || (bound_kind, sub).has_placeholders()
2392 || !bound_kind.is_suggestable(self.tcx, false)
2394 let lt_name = sub.get_name_or_anon().to_string();
2395 err.help(format!("{msg} `{bound_kind}
: {lt_name}`
..."));
2399 let mut generic_param_scope = generic_param_scope;
2400 while self.tcx.def_kind(generic_param_scope) == DefKind::OpaqueTy {
2401 generic_param_scope = self.tcx.local_parent(generic_param_scope);
2404 // type_param_sugg_span is (span, has_bounds)
2405 let (type_scope, type_param_sugg_span) = match bound_kind {
2406 GenericKind::Param(ref param) => {
2407 let generics = self.tcx.generics_of(generic_param_scope);
2408 let def_id = generics.type_param(param, self.tcx).def_id.expect_local();
2409 let scope = self.tcx.local_def_id_to_hir_id(def_id).owner.def_id;
2410 // Get the `hir::Param` to verify whether it already has any bounds.
2411 // We do this to avoid suggesting code that ends up as `T: 'a'b`,
2412 // instead we suggest `T: 'a + 'b` in that case.
2413 let hir_generics = self.tcx.hir().get_generics(scope).unwrap();
2414 let sugg_span = match hir_generics.bounds_span_for_suggestions(def_id) {
2415 Some(span) => Some((span, true)),
2416 // If `param` corresponds to `Self`, no usable suggestion span.
2417 None if generics.has_self && param.index == 0 => None,
2418 None => Some((self.tcx.def_span(def_id).shrink_to_hi(), false)),
2422 _ => (generic_param_scope, None),
2424 let suggestion_scope = {
2425 let lifetime_scope = match sub.kind() {
2426 ty::ReStatic => hir::def_id::CRATE_DEF_ID,
2427 _ => match self.tcx.is_suitable_region(sub) {
2428 Some(info) => info.def_id,
2429 None => generic_param_scope,
2432 match self.tcx.is_descendant_of(type_scope.into(), lifetime_scope.into()) {
2434 false => lifetime_scope,
2438 let mut suggs = vec![];
2439 let lt_name = self.suggest_name_region(sub, &mut suggs);
2441 if let Some((sp, has_lifetimes)) = type_param_sugg_span
2442 && suggestion_scope == type_scope
2445 if has_lifetimes { format!(" + {lt_name}") } else { format!(": {lt_name}
") };
2446 suggs.push((sp, suggestion))
2447 } else if let Some(generics) = self.tcx.hir().get_generics(suggestion_scope) {
2448 let pred = format!("{bound_kind}
: {lt_name}
");
2449 let suggestion = format!("{} {}
", generics.add_where_or_trailing_comma(), pred);
2450 suggs.push((generics.tail_span_for_predicate_suggestion(), suggestion))
2452 let consider = format!("{msg} `{bound_kind}
: {sub}`
...");
2456 if !suggs.is_empty() {
2457 err.multipart_suggestion_verbose(
2460 Applicability::MaybeIncorrect, // Issue #41966
2468 pub fn suggest_name_region(
2470 lifetime: Region<'tcx>,
2471 add_lt_suggs: &mut Vec<(Span, String)>,
2473 struct LifetimeReplaceVisitor<'tcx, 'a> {
2475 needle: hir::LifetimeName,
2477 add_lt_suggs: &'a mut Vec<(Span, String)>,
2480 impl<'hir, 'tcx> hir::intravisit::Visitor<'hir> for LifetimeReplaceVisitor<'tcx, '_> {
2481 fn visit_lifetime(&mut self, lt: &'hir hir::Lifetime) {
2482 if lt.res == self.needle {
2483 let (pos, span) = lt.suggestion_position();
2484 let new_lt = &self.new_lt;
2485 let sugg = match pos {
2486 hir::LifetimeSuggestionPosition::Normal => format!("{new_lt}
"),
2487 hir::LifetimeSuggestionPosition::Ampersand => format!("{new_lt}
"),
2488 hir::LifetimeSuggestionPosition::ElidedPath => format!("<{new_lt}
>"),
2489 hir::LifetimeSuggestionPosition::ElidedPathArgument => {
2490 format!("{new_lt}
, ")
2492 hir::LifetimeSuggestionPosition::ObjectDefault => format!("+ {new_lt}
"),
2494 self.add_lt_suggs.push((span, sugg));
2498 fn visit_ty(&mut self, ty: &'hir hir::Ty<'hir>) {
2499 let hir::TyKind::OpaqueDef(item_id, _, _) = ty.kind else {
2500 return hir::intravisit::walk_ty(self, ty);
2502 let opaque_ty = self.tcx.hir().item(item_id).expect_opaque_ty();
2503 if let Some(&(_, b)) =
2504 opaque_ty.lifetime_mapping.iter().find(|&(a, _)| a.res == self.needle)
2507 std::mem::replace(&mut self.needle, hir::LifetimeName::Param(b));
2508 for bound in opaque_ty.bounds {
2509 self.visit_param_bound(bound);
2511 self.needle = prev_needle;
2516 let (lifetime_def_id, lifetime_scope) = match self.tcx.is_suitable_region(lifetime) {
2517 Some(info) if !lifetime.has_name() => {
2518 (info.boundregion.get_id().unwrap().expect_local(), info.def_id)
2520 _ => return lifetime.get_name_or_anon().to_string(),
2524 let generics = self.tcx.generics_of(lifetime_scope);
2525 let mut used_names =
2526 iter::successors(Some(generics), |g| g.parent.map(|p| self.tcx.generics_of(p)))
2527 .flat_map(|g| &g.params)
2528 .filter(|p| matches!(p.kind, ty::GenericParamDefKind::Lifetime))
2530 .collect::<Vec<_>>();
2531 if let Some(hir_id) = self.tcx.opt_local_def_id_to_hir_id(lifetime_scope) {
2532 // consider late-bound lifetimes ...
2533 used_names.extend(self.tcx.late_bound_vars(hir_id).into_iter().filter_map(|p| {
2535 ty::BoundVariableKind::Region(lt) => lt.get_name(),
2541 .map(|c| format!("'{}
", c as char))
2542 .find(|candidate| !used_names.iter().any(|e| e.as_str() == candidate))
2543 .unwrap_or("'lt
".to_string())
2546 let mut visitor = LifetimeReplaceVisitor {
2548 needle: hir::LifetimeName::Param(lifetime_def_id),
2552 match self.tcx.hir().expect_owner(lifetime_scope) {
2553 hir::OwnerNode::Item(i) => visitor.visit_item(i),
2554 hir::OwnerNode::ForeignItem(i) => visitor.visit_foreign_item(i),
2555 hir::OwnerNode::ImplItem(i) => visitor.visit_impl_item(i),
2556 hir::OwnerNode::TraitItem(i) => visitor.visit_trait_item(i),
2557 hir::OwnerNode::Crate(_) => bug!("OwnerNode
::Crate doesn't not have generics
"),
2560 let ast_generics = self.tcx.hir().get_generics(lifetime_scope).unwrap();
2561 let sugg = ast_generics
2562 .span_for_lifetime_suggestion()
2563 .map(|span| (span, format!("{new_lt}
, ")))
2564 .unwrap_or_else(|| (ast_generics.span, format!("<{new_lt}
>")));
2565 add_lt_suggs.push(sugg);
2570 fn report_sub_sup_conflict(
2572 var_origin: RegionVariableOrigin,
2573 sub_origin: SubregionOrigin<'tcx>,
2574 sub_region: Region<'tcx>,
2575 sup_origin: SubregionOrigin<'tcx>,
2576 sup_region: Region<'tcx>,
2578 let mut err = self.report_inference_failure(var_origin);
2580 note_and_explain_region(
2583 "first
, the lifetime cannot outlive
",
2589 debug!("report_sub_sup_conflict
: var_origin
={:?}
", var_origin);
2590 debug!("report_sub_sup_conflict
: sub_region
={:?}
", sub_region);
2591 debug!("report_sub_sup_conflict
: sub_origin
={:?}
", sub_origin);
2592 debug!("report_sub_sup_conflict
: sup_region
={:?}
", sup_region);
2593 debug!("report_sub_sup_conflict
: sup_origin
={:?}
", sup_origin);
2595 if let infer::Subtype(ref sup_trace) = sup_origin
2596 && let infer::Subtype(ref sub_trace) = sub_origin
2597 && let Some((sup_expected, sup_found, _, _)) = self.values_str(sup_trace.values)
2598 && let Some((sub_expected, sub_found, _, _)) = self.values_str(sub_trace.values)
2599 && sub_expected == sup_expected
2600 && sub_found == sup_found
2602 note_and_explain_region(
2605 "...but the lifetime must also be valid
for ",
2611 sup_trace.cause.span,
2612 format!("...so that the {}
", sup_trace.cause.as_requirement_str()),
2615 err.note_expected_found(&"", sup_expected, &"", sup_found);
2616 if sub_region.is_error() | sup_region.is_error() {
2624 self.note_region_origin(&mut err, &sup_origin);
2626 note_and_explain_region(
2629 "but
, the lifetime must be valid
for ",
2635 self.note_region_origin(&mut err, &sub_origin);
2636 if sub_region.is_error() | sup_region.is_error() {
2643 /// Determine whether an error associated with the given span and definition
2644 /// should be treated as being caused by the implicit `From` conversion
2645 /// within `?` desugaring.
2646 pub fn is_try_conversion(&self, span: Span, trait_def_id: DefId) -> bool {
2647 span.is_desugaring(DesugaringKind::QuestionMark)
2648 && self.tcx.is_diagnostic_item(sym::From, trait_def_id)
2651 /// Structurally compares two types, modulo any inference variables.
2653 /// Returns `true` if two types are equal, or if one type is an inference variable compatible
2654 /// with the other type. A TyVar inference type is compatible with any type, and an IntVar or
2655 /// FloatVar inference type are compatible with themselves or their concrete types (Int and
2656 /// Float types, respectively). When comparing two ADTs, these rules apply recursively.
2657 pub fn same_type_modulo_infer<T: relate::Relate<'tcx>>(&self, a: T, b: T) -> bool {
2658 let (a, b) = self.resolve_vars_if_possible((a, b));
2659 SameTypeModuloInfer(self).relate(a, b).is_ok()
2663 struct SameTypeModuloInfer<'a, 'tcx>(&'a InferCtxt<'tcx>);
2665 impl<'tcx> TypeRelation<'tcx> for SameTypeModuloInfer<'_, 'tcx> {
2666 fn tcx(&self) -> TyCtxt<'tcx> {
2670 fn param_env(&self) -> ty::ParamEnv<'tcx> {
2671 // Unused, only for consts which we treat as always equal
2672 ty::ParamEnv::empty()
2675 fn tag(&self) -> &'static str {
2676 "SameTypeModuloInfer
"
2679 fn a_is_expected(&self) -> bool {
2683 fn relate_with_variance<T: relate::Relate<'tcx>>(
2685 _variance: ty::Variance,
2686 _info: ty::VarianceDiagInfo<'tcx>,
2689 ) -> relate::RelateResult<'tcx, T> {
2693 fn tys(&mut self, a: Ty<'tcx>, b: Ty<'tcx>) -> RelateResult<'tcx, Ty<'tcx>> {
2694 match (a.kind(), b.kind()) {
2695 (ty::Int(_) | ty::Uint(_), ty::Infer(ty::InferTy::IntVar(_)))
2697 ty::Infer(ty::InferTy::IntVar(_)),
2698 ty::Int(_) | ty::Uint(_) | ty::Infer(ty::InferTy::IntVar(_)),
2700 | (ty::Float(_), ty::Infer(ty::InferTy::FloatVar(_)))
2702 ty::Infer(ty::InferTy::FloatVar(_)),
2703 ty::Float(_) | ty::Infer(ty::InferTy::FloatVar(_)),
2705 | (ty::Infer(ty::InferTy::TyVar(_)), _)
2706 | (_, ty::Infer(ty::InferTy::TyVar(_))) => Ok(a),
2707 (ty::Infer(_), _) | (_, ty::Infer(_)) => Err(TypeError::Mismatch),
2708 _ => relate::structurally_relate_tys(self, a, b),
2714 a: ty::Region<'tcx>,
2715 b: ty::Region<'tcx>,
2716 ) -> RelateResult<'tcx, ty::Region<'tcx>> {
2717 if (a.is_var() && b.is_free_or_static())
2718 || (b.is_var() && a.is_free_or_static())
2719 || (a.is_var() && b.is_var())
2724 Err(TypeError::Mismatch)
2730 a: ty::Binder<'tcx, T>,
2731 b: ty::Binder<'tcx, T>,
2732 ) -> relate::RelateResult<'tcx, ty::Binder<'tcx, T>>
2734 T: relate::Relate<'tcx>,
2736 Ok(a.rebind(self.relate(a.skip_binder(), b.skip_binder())?))
2742 _b: ty::Const<'tcx>,
2743 ) -> relate::RelateResult<'tcx, ty::Const<'tcx>> {
2744 // FIXME(compiler-errors): This could at least do some first-order
2750 impl<'tcx> InferCtxt<'tcx> {
2751 fn report_inference_failure(
2753 var_origin: RegionVariableOrigin,
2754 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
2755 let br_string = |br: ty::BoundRegionKind| {
2756 let mut s = match br {
2757 ty::BrNamed(_, name) => name.to_string(),
2765 let var_description = match var_origin {
2766 infer::MiscVariable(_) => String::new(),
2767 infer::PatternRegion(_) => " for pattern
".to_string(),
2768 infer::AddrOfRegion(_) => " for borrow expression
".to_string(),
2769 infer::Autoref(_) => " for autoref
".to_string(),
2770 infer::Coercion(_) => " for automatic coercion
".to_string(),
2771 infer::LateBoundRegion(_, br, infer::FnCall) => {
2772 format!(" for lifetime parameter {}
in function call
", br_string(br))
2774 infer::LateBoundRegion(_, br, infer::HigherRankedType) => {
2775 format!(" for lifetime parameter {}
in generic
type", br_string(br))
2777 infer::LateBoundRegion(_, br, infer::AssocTypeProjection(def_id)) => format!(
2778 " for lifetime parameter {}
in trait containing associated
type `{}`
",
2780 self.tcx.associated_item(def_id).name
2782 infer::EarlyBoundRegion(_, name) => format!(" for lifetime parameter `{name}`
"),
2783 infer::UpvarRegion(ref upvar_id, _) => {
2784 let var_name = self.tcx.hir().name(upvar_id.var_path.hir_id);
2785 format!(" for capture of `{var_name}` by closure
")
2787 infer::Nll(..) => bug!("NLL variable found
in lexical phase
"),
2794 "cannot infer an appropriate lifetime{} due to conflicting requirements
",
2800 pub enum FailureCode {
2807 pub trait ObligationCauseExt<'tcx> {
2808 fn as_failure_code(&self, terr: TypeError<'tcx>) -> FailureCode;
2810 fn as_failure_code_diag(
2812 terr: TypeError<'tcx>,
2814 subdiags: Vec<TypeErrorAdditionalDiags>,
2815 ) -> ObligationCauseFailureCode;
2816 fn as_requirement_str(&self) -> &'static str;
2819 impl<'tcx> ObligationCauseExt<'tcx> for ObligationCause<'tcx> {
2820 fn as_failure_code(&self, terr: TypeError<'tcx>) -> FailureCode {
2821 use self::FailureCode::*;
2822 use crate::traits::ObligationCauseCode::*;
2824 IfExpressionWithNoElse => Error0317,
2825 MainFunctionType => Error0580,
2826 CompareImplItemObligation { .. }
2827 | MatchExpressionArm(_)
2828 | IfExpression { .. }
2831 | LangFunctionType(_)
2833 | MethodReceiver => Error0308,
2835 // In the case where we have no more specific thing to
2836 // say, also take a look at the error code, maybe we can
2839 TypeError::CyclicTy(ty) if ty.is_closure() || ty.is_coroutine() => Error0644,
2840 TypeError::IntrinsicCast => Error0308,
2845 fn as_failure_code_diag(
2847 terr: TypeError<'tcx>,
2849 subdiags: Vec<TypeErrorAdditionalDiags>,
2850 ) -> ObligationCauseFailureCode {
2851 use crate::traits::ObligationCauseCode::*;
2853 CompareImplItemObligation { kind: ty::AssocKind::Fn, .. } => {
2854 ObligationCauseFailureCode::MethodCompat { span, subdiags }
2856 CompareImplItemObligation { kind: ty::AssocKind::Type, .. } => {
2857 ObligationCauseFailureCode::TypeCompat { span, subdiags }
2859 CompareImplItemObligation { kind: ty::AssocKind::Const, .. } => {
2860 ObligationCauseFailureCode::ConstCompat { span, subdiags }
2862 BlockTailExpression(.., hir::MatchSource::TryDesugar(_)) => {
2863 ObligationCauseFailureCode::TryCompat { span, subdiags }
2865 MatchExpressionArm(box MatchExpressionArmCause { source, .. }) => match source {
2866 hir::MatchSource::TryDesugar(_) => {
2867 ObligationCauseFailureCode::TryCompat { span, subdiags }
2869 _ => ObligationCauseFailureCode::MatchCompat { span, subdiags },
2871 IfExpression { .. } => ObligationCauseFailureCode::IfElseDifferent { span, subdiags },
2872 IfExpressionWithNoElse => ObligationCauseFailureCode::NoElse { span },
2873 LetElse => ObligationCauseFailureCode::NoDiverge { span, subdiags },
2874 MainFunctionType => ObligationCauseFailureCode::FnMainCorrectType { span },
2875 StartFunctionType => ObligationCauseFailureCode::FnStartCorrectType { span, subdiags },
2876 &LangFunctionType(lang_item_name) => {
2877 ObligationCauseFailureCode::FnLangCorrectType { span, subdiags, lang_item_name }
2879 IntrinsicType => ObligationCauseFailureCode::IntrinsicCorrectType { span, subdiags },
2880 MethodReceiver => ObligationCauseFailureCode::MethodCorrectType { span, subdiags },
2882 // In the case where we have no more specific thing to
2883 // say, also take a look at the error code, maybe we can
2886 TypeError::CyclicTy(ty) if ty.is_closure() || ty.is_coroutine() => {
2887 ObligationCauseFailureCode::ClosureSelfref { span }
2889 TypeError::IntrinsicCast => {
2890 ObligationCauseFailureCode::CantCoerce { span, subdiags }
2892 _ => ObligationCauseFailureCode::Generic { span, subdiags },
2897 fn as_requirement_str(&self) -> &'static str {
2898 use crate::traits::ObligationCauseCode::*;
2900 CompareImplItemObligation { kind: ty::AssocKind::Fn, .. } => {
2901 "method
type is compatible with
trait"
2903 CompareImplItemObligation { kind: ty::AssocKind::Type, .. } => {
2904 "associated
type is compatible with
trait"
2906 CompareImplItemObligation { kind: ty::AssocKind::Const, .. } => {
2907 "const is compatible with
trait"
2909 ExprAssignable => "expression is assignable
",
2910 IfExpression { .. } => "`
if` and `
else` have incompatible types
",
2911 IfExpressionWithNoElse => "`
if` missing an `
else` returns `
()`
",
2912 MainFunctionType => "`main` function has the correct
type",
2913 StartFunctionType => "`
#[start]` function has the correct type",
2914 LangFunctionType(_) => "lang item function has the correct type",
2915 IntrinsicType => "intrinsic has the correct type",
2916 MethodReceiver => "method receiver has the correct type",
2917 _ => "types are compatible",
2922 /// Newtype to allow implementing IntoDiagnosticArg
2923 pub struct ObligationCauseAsDiagArg<'tcx>(pub ObligationCause<'tcx>);
2925 impl IntoDiagnosticArg for ObligationCauseAsDiagArg<'_> {
2926 fn into_diagnostic_arg(self) -> rustc_errors::DiagnosticArgValue<'static> {
2927 use crate::traits::ObligationCauseCode::*;
2928 let kind = match self.0.code() {
2929 CompareImplItemObligation { kind: ty::AssocKind::Fn, .. } => "method_compat",
2930 CompareImplItemObligation { kind: ty::AssocKind::Type, .. } => "type_compat",
2931 CompareImplItemObligation { kind: ty::AssocKind::Const, .. } => "const_compat",
2932 ExprAssignable => "expr_assignable",
2933 IfExpression { .. } => "if_else_different",
2934 IfExpressionWithNoElse => "no_else",
2935 MainFunctionType => "fn_main_correct_type",
2936 StartFunctionType => "fn_start_correct_type",
2937 LangFunctionType(_) => "fn_lang_correct_type",
2938 IntrinsicType => "intrinsic_correct_type",
2939 MethodReceiver => "method_correct_type",
2943 rustc_errors::DiagnosticArgValue::Str(kind)
2947 /// This is a bare signal of what kind of type we're dealing with. `ty::TyKind` tracks
2948 /// extra information about each type, but we only care about the category.
2949 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
2950 pub enum TyCategory {
2954 Coroutine(hir::CoroutineKind),
2958 impl fmt::Display for TyCategory {
2959 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2961 Self::Closure => "closure".fmt(f),
2962 Self::Opaque => "opaque type".fmt(f),
2963 Self::OpaqueFuture => "future".fmt(f),
2964 Self::Coroutine(gk) => gk.fmt(f),
2965 Self::Foreign => "foreign type".fmt(f),
2971 pub fn from_ty(tcx: TyCtxt<'_>, ty: Ty<'_>) -> Option<(Self, DefId)> {
2973 ty::Closure(def_id, _) => Some((Self::Closure, def_id)),
2974 ty::Alias(ty::Opaque, ty::AliasTy { def_id, .. }) => {
2976 if tcx.ty_is_opaque_future(ty) { Self::OpaqueFuture } else { Self::Opaque };
2977 Some((kind, def_id))
2979 ty::Coroutine(def_id, ..) => {
2980 Some((Self::Coroutine(tcx.coroutine_kind(def_id).unwrap()), def_id))
2982 ty::Foreign(def_id) => Some((Self::Foreign, def_id)),
2988 impl<'tcx> InferCtxt<'tcx> {
2989 /// Given a [`hir::Block`], get the span of its last expression or
2990 /// statement, peeling off any inner blocks.
2991 pub fn find_block_span(&self, block: &'tcx hir::Block<'tcx>) -> Span {
2992 let block = block.innermost_block();
2993 if let Some(expr) = &block.expr {
2995 } else if let Some(stmt) = block.stmts.last() {
2996 // possibly incorrect trailing `;` in the else arm
2999 // empty block; point at its entirety
3004 /// Given a [`hir::HirId`] for a block, get the span of its last expression
3005 /// or statement, peeling off any inner blocks.
3006 pub fn find_block_span_from_hir_id(&self, hir_id: hir::HirId) -> Span {
3007 match self.tcx.hir().get(hir_id) {
3008 hir::Node::Block(blk) => self.find_block_span(blk),
3009 // The parser was in a weird state if either of these happen, but
3010 // it's better not to panic.
3011 hir::Node::Expr(e) => e.span,
3012 _ => rustc_span::DUMMY_SP,