]> git.proxmox.com Git - rustc.git/blob - compiler/rustc_infer/src/infer/error_reporting/mod.rs
New upstream version 1.75.0+dfsg1
[rustc.git] / compiler / rustc_infer / src / infer / error_reporting / mod.rs
1 //! Error Reporting Code for the inference engine
2 //!
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.
9 //!
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
15 //! error message.
16 //!
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.
20 //!
21 //! # Region Inference
22 //!
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.
27 //!
28 //! # Subtype Trace
29 //!
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.
41 //!
42 //! # Reality vs plan
43 //!
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.
47
48 use super::lexical_region_resolve::RegionResolutionError;
49 use super::region_constraints::GenericKind;
50 use super::{InferCtxt, RegionVariableOrigin, SubregionOrigin, TypeTrace, ValuePairs};
51
52 use crate::errors::{self, ObligationCauseFailureCode, TypeErrorAdditionalDiags};
53 use crate::infer;
54 use crate::infer::error_reporting::nice_region_error::find_anon_type::find_anon_type;
55 use crate::infer::ExpectedFound;
56 use crate::traits::{
57 IfExpressionCause, MatchExpressionArmCause, ObligationCause, ObligationCauseCode,
58 PredicateObligation,
59 };
60
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};
64 use rustc_hir as hir;
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,
75 };
76 use rustc_span::{sym, symbol::kw, BytePos, DesugaringKind, Pos, Span};
77 use rustc_target::spec::abi;
78 use std::borrow::Cow;
79 use std::ops::{ControlFlow, Deref};
80 use std::path::PathBuf;
81 use std::{cmp, fmt, iter};
82
83 mod note;
84 mod note_and_explain;
85 mod suggest;
86
87 pub(crate) mod need_type_info;
88 pub use need_type_info::TypeAnnotationNeeded;
89
90 pub mod nice_region_error;
91
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 @ '\'')) => {
100 escaped.push('\\');
101 escaped.push(delim);
102 chrs.next();
103 }
104 ('"' | '\'', _) => {
105 escaped.push('\\');
106 escaped.push(first)
107 }
108 (c, _) => escaped.push(c),
109 };
110 }
111 escaped
112 }
113
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`.
117 ///
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,
125
126 pub normalize_fn_sig: Box<dyn Fn(ty::PolyFnSig<'tcx>) -> ty::PolyFnSig<'tcx> + 'a>,
127
128 pub autoderef_steps:
129 Box<dyn Fn(Ty<'tcx>) -> Vec<(Ty<'tcx>, Vec<PredicateObligation<'tcx>>)> + 'a>,
130 }
131
132 impl Drop for TypeErrCtxt<'_, '_> {
133 fn drop(&mut self) {
134 if let Some(_) = self.infcx.tcx.sess.has_errors_or_delayed_span_bugs() {
135 // ok, emitted an error.
136 } else {
137 self.infcx
138 .tcx
139 .sess
140 .delay_good_path_bug("used a `TypeErrCtxt` without raising an error or lint");
141 }
142 }
143 }
144
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`")]
149 #[allow(unused)]
150 pub fn err_ctxt(&self) -> ! {
151 bug!("called `err_ctxt` on `TypeErrCtxt`. Try removing the call");
152 }
153 }
154
155 impl<'tcx> Deref for TypeErrCtxt<'_, 'tcx> {
156 type Target = InferCtxt<'tcx>;
157 fn deref(&self) -> &InferCtxt<'tcx> {
158 &self.infcx
159 }
160 }
161
162 pub(super) fn note_and_explain_region<'tcx>(
163 tcx: TyCtxt<'tcx>,
164 err: &mut Diagnostic,
165 prefix: &str,
166 region: ty::Region<'tcx>,
167 suffix: &str,
168 alt_span: Option<Span>,
169 ) {
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)
173 }
174
175 ty::ReError(_) => return,
176
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)
181 }
182 };
183
184 emit_msg_span(err, prefix, description, span, suffix);
185 }
186
187 fn explain_free_region<'tcx>(
188 tcx: TyCtxt<'tcx>,
189 err: &mut Diagnostic,
190 prefix: &str,
191 region: ty::Region<'tcx>,
192 suffix: &str,
193 ) {
194 let (description, span) = msg_span_from_named_region(tcx, region, None);
195
196 label_msg_span(err, prefix, description, span, suffix);
197 }
198
199 fn msg_span_from_named_region<'tcx>(
200 tcx: TyCtxt<'tcx>,
201 region: ty::Region<'tcx>,
202 alt_span: Option<Span>,
203 ) -> (String, Option<Span>) {
204 match *region {
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))
209 {
210 param.span
211 } else {
212 tcx.def_span(scope)
213 };
214 let text = if br.has_name() {
215 format!("the lifetime `{}` as defined here", br.name)
216 } else {
217 "the anonymous lifetime as defined here".to_string()
218 };
219 (text, Some(span))
220 }
221 ty::ReFree(ref fr) => {
222 if !fr.bound_region.is_named()
223 && let Some((ty, _)) = find_anon_type(tcx, region, &fr.bound_region)
224 {
225 ("the anonymous lifetime defined here".to_string(), Some(ty.span))
226 } else {
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
231 .hir()
232 .get_generics(scope)
233 .and_then(|generics| generics.get_named(name))
234 {
235 param.span
236 } else {
237 tcx.def_span(scope)
238 };
239 let text = if name == kw::UnderscoreLifetime {
240 "the anonymous lifetime as defined here".to_string()
241 } else {
242 format!("the lifetime `{name}` as defined here")
243 };
244 (text, Some(span))
245 }
246 ty::BrAnon => (
247 "the anonymous lifetime as defined here".to_string(),
248 Some(tcx.def_span(scope)),
249 ),
250 _ => (
251 format!("the lifetime `{region}` as defined here"),
252 Some(tcx.def_span(scope)),
253 ),
254 }
255 }
256 }
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), .. },
260 ..
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, .. },
264 ..
265 }) => ("an anonymous lifetime".to_owned(), None),
266 _ => bug!("{:?}", region),
267 }
268 }
269
270 fn emit_msg_span(
271 err: &mut Diagnostic,
272 prefix: &str,
273 description: String,
274 span: Option<Span>,
275 suffix: &str,
276 ) {
277 let message = format!("{prefix}{description}{suffix}");
278
279 if let Some(span) = span {
280 err.span_note(span, message);
281 } else {
282 err.note(message);
283 }
284 }
285
286 fn label_msg_span(
287 err: &mut Diagnostic,
288 prefix: &str,
289 description: String,
290 span: Option<Span>,
291 suffix: &str,
292 ) {
293 let message = format!("{prefix}{description}{suffix}");
294
295 if let Some(span) = span {
296 err.span_label(span, message);
297 } else {
298 err.note(message);
299 }
300 }
301
302 #[instrument(level = "trace", skip(tcx))]
303 pub fn unexpected_hidden_region_diagnostic<'tcx>(
304 tcx: TyCtxt<'tcx>,
305 span: Span,
306 hidden_ty: Ty<'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 {
311 span,
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),
314 });
315
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
323 // explanation.
324 //
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.
327 explain_free_region(
328 tcx,
329 &mut err,
330 &format!("hidden type `{hidden_ty}` captures "),
331 hidden_region,
332 "",
333 );
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(
337 tcx,
338 &mut err,
339 fn_returns,
340 hidden_region.to_string(),
341 None,
342 format!("captures `{hidden_region}`"),
343 None,
344 Some(reg_info.def_id),
345 )
346 }
347 }
348 ty::RePlaceholder(_) => {
349 explain_free_region(
350 tcx,
351 &mut err,
352 &format!("hidden type `{}` captures ", hidden_ty),
353 hidden_region,
354 "",
355 );
356 }
357 ty::ReError(_) => {
358 err.delay_as_bug();
359 }
360 _ => {
361 // Ugh. This is a painful case: the hidden region is not one
362 // that we can easily summarize or explain. This can happen
363 // in a case like
364 // `tests/ui/multiple-lifetimes/ordinary-bounds-unsuited.rs`:
365 //
366 // ```
367 // fn upper_bounds<'a, 'b>(a: Ordinary<'a>, b: Ordinary<'b>) -> impl Trait<'a, 'b> {
368 // if condition() { a } else { b }
369 // }
370 // ```
371 //
372 // Here the captured lifetime is the intersection of `'a` and
373 // `'b`, which we can't quite express.
374
375 // We can at least report a really cryptic error for now.
376 note_and_explain_region(
377 tcx,
378 &mut err,
379 &format!("hidden type `{hidden_ty}` captures "),
380 hidden_region,
381 "",
382 None,
383 );
384 }
385 }
386
387 err
388 }
389
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) =>
395 {
396 (def_id, args)
397 }
398 ty::Alias(_, ty::AliasTy { def_id, args, .. })
399 if self.tcx.is_impl_trait_in_trait(def_id) =>
400 {
401 (def_id, args)
402 }
403 _ => return None,
404 };
405
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];
408
409 self.tcx.explicit_item_bounds(def_id).iter_instantiated_copied(self.tcx, args).find_map(
410 |(predicate, _)| {
411 predicate
412 .kind()
413 .map_bound(|kind| match kind {
414 ty::ClauseKind::Projection(projection_predicate)
415 if projection_predicate.projection_ty.def_id == item_def_id =>
416 {
417 projection_predicate.term.ty()
418 }
419 _ => None,
420 })
421 .no_bound_vars()
422 .flatten()
423 },
424 )
425 }
426 }
427
428 impl<'tcx> TypeErrCtxt<'_, 'tcx> {
429 pub fn report_region_errors(
430 &self,
431 generic_param_scope: LocalDefId,
432 errors: &[RegionResolutionError<'tcx>],
433 ) -> ErrorGuaranteed {
434 if let Some(guaranteed) = self.infcx.tainted_by_errors() {
435 return guaranteed;
436 }
437
438 debug!("report_region_errors(): {} errors to start", errors.len());
439
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);
443
444 debug!("report_region_errors: {} errors after preprocessing", errors.len());
445
446 for error in errors {
447 debug!("report_region_errors: error = {:?}", error);
448
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();
461 } else {
462 self.report_concrete_failure(origin, sub, sup).emit();
463 }
464 }
465
466 RegionResolutionError::GenericBoundFailure(origin, param_ty, sub) => {
467 self.report_generic_bound_failure(
468 generic_param_scope,
469 origin.span(),
470 Some(origin),
471 param_ty,
472 sub,
473 );
474 }
475
476 RegionResolutionError::SubSupConflict(
477 _,
478 var_origin,
479 sub_origin,
480 sub_r,
481 sup_origin,
482 sup_r,
483 _,
484 ) => {
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();
489 } else {
490 self.report_sub_sup_conflict(
491 var_origin, sub_origin, sub_r, sup_origin, sup_r,
492 );
493 }
494 }
495
496 RegionResolutionError::UpperBoundUniverseConflict(
497 _,
498 _,
499 _,
500 sup_origin,
501 sup_r,
502 ) => {
503 assert!(sup_r.is_placeholder());
504
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
509 // value.
510 let sub_r = self.tcx.lifetimes.re_erased;
511
512 self.report_placeholder_failure(sup_origin, sub_r, sup_r).emit();
513 }
514 }
515 }
516 }
517
518 self.tcx
519 .sess
520 .delay_span_bug(self.tcx.def_span(generic_param_scope), "expected region errors")
521 }
522
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).
529 //
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.
533 fn process_errors(
534 &self,
535 errors: &[RegionResolutionError<'tcx>],
536 ) -> Vec<RegionResolutionError<'tcx>> {
537 debug!("process_errors()");
538
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
546 // meaningless.
547 //
548 // Therefore, we filter them out of the list unless they are
549 // the only thing in the list.
550
551 let is_bound_failure = |e: &RegionResolutionError<'tcx>| match *e {
552 RegionResolutionError::GenericBoundFailure(..) => true,
553 RegionResolutionError::ConcreteFailure(..)
554 | RegionResolutionError::SubSupConflict(..)
555 | RegionResolutionError::UpperBoundUniverseConflict(..) => false,
556 };
557
558 let mut errors = if errors.iter().all(|e| is_bound_failure(e)) {
559 errors.to_owned()
560 } else {
561 errors.iter().filter(|&e| !is_bound_failure(e)).cloned().collect()
562 };
563
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(),
570 });
571 errors
572 }
573
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;
579 use ty::GenericArg;
580
581 struct AbsolutePathPrinter<'tcx> {
582 tcx: TyCtxt<'tcx>,
583 segments: Vec<String>,
584 }
585
586 impl<'tcx> Printer<'tcx> for AbsolutePathPrinter<'tcx> {
587 fn tcx<'a>(&'a self) -> TyCtxt<'tcx> {
588 self.tcx
589 }
590
591 fn print_region(&mut self, _region: ty::Region<'_>) -> Result<(), PrintError> {
592 Err(fmt::Error)
593 }
594
595 fn print_type(&mut self, _ty: Ty<'tcx>) -> Result<(), PrintError> {
596 Err(fmt::Error)
597 }
598
599 fn print_dyn_existential(
600 &mut self,
601 _predicates: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
602 ) -> Result<(), PrintError> {
603 Err(fmt::Error)
604 }
605
606 fn print_const(&mut self, _ct: ty::Const<'tcx>) -> Result<(), PrintError> {
607 Err(fmt::Error)
608 }
609
610 fn path_crate(&mut self, cnum: CrateNum) -> Result<(), PrintError> {
611 self.segments = vec![self.tcx.crate_name(cnum).to_string()];
612 Ok(())
613 }
614 fn path_qualified(
615 &mut self,
616 _self_ty: Ty<'tcx>,
617 _trait_ref: Option<ty::TraitRef<'tcx>>,
618 ) -> Result<(), PrintError> {
619 Err(fmt::Error)
620 }
621
622 fn path_append_impl(
623 &mut self,
624 _print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
625 _disambiguated_data: &DisambiguatedDefPathData,
626 _self_ty: Ty<'tcx>,
627 _trait_ref: Option<ty::TraitRef<'tcx>>,
628 ) -> Result<(), PrintError> {
629 Err(fmt::Error)
630 }
631 fn path_append(
632 &mut self,
633 print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
634 disambiguated_data: &DisambiguatedDefPathData,
635 ) -> Result<(), PrintError> {
636 print_prefix(self)?;
637 self.segments.push(disambiguated_data.to_string());
638 Ok(())
639 }
640 fn path_generic_args(
641 &mut self,
642 print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
643 _args: &[GenericArg<'tcx>],
644 ) -> Result<(), PrintError> {
645 print_prefix(self)
646 }
647 }
648
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)
657 };
658
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)?)
664 };
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() {
668 format!(
669 "the crate `{crate_name}` is compiled multiple times, possibly with different configurations"
670 )
671 } else {
672 format!(
673 "perhaps two different versions of crate `{crate_name}` are being used?"
674 )
675 };
676 err.note(msg);
677 }
678 }
679 };
680 match terr {
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())
686 {
687 report_path_match(err, exp_adt.did(), found_adt.did());
688 }
689 }
690 TypeError::Traits(ref exp_found) => {
691 report_path_match(err, exp_found.expected, exp_found.found);
692 }
693 _ => (), // FIXME(#22750) handle traits and stuff
694 }
695 }
696
697 fn note_error_origin(
698 &self,
699 err: &mut Diagnostic,
700 cause: &ObligationCause<'tcx>,
701 exp_found: Option<ty::error::ExpectedFound<Ty<'tcx>>>,
702 terr: TypeError<'tcx>,
703 ) {
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(_)))
708 {
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)
713 {
714 err.span_label(
715 span,
716 format!("this is an iterator with items of type `{}`", args.type_at(0)),
717 );
718 } else {
719 err.span_label(span, format!("this expression has type `{ty}`"));
720 }
721 }
722 if let Some(ty::error::ExpectedFound { found, .. }) = exp_found
723 && ty.is_box()
724 && ty.boxed_ty() == found
725 && let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span)
726 {
727 err.span_suggestion(
728 span,
729 "consider dereferencing the boxed value",
730 format!("*{snippet}"),
731 Applicability::MachineApplicable,
732 );
733 }
734 }
735 ObligationCauseCode::Pattern { origin_expr: false, span: Some(span), .. } => {
736 err.span_label(span, "expected due to this");
737 }
738 ObligationCauseCode::BlockTailExpression(
739 _,
740 hir::MatchSource::TryDesugar(scrut_hir_id),
741 ) => {
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");
746 self.typeck_results
747 .as_ref()
748 .and_then(|typeck_results| typeck_results.expr_ty_opt(arg_expr))
749 } else {
750 bug!("try desugaring w/out call expr as scrutinee");
751 };
752
753 match scrut_ty {
754 Some(ty) if expected == ty => {
755 let source_map = self.tcx.sess.source_map();
756 err.span_suggestion(
757 source_map.end_point(cause.span()),
758 "try removing this `?`",
759 "",
760 Applicability::MachineApplicable,
761 );
762 }
763 _ => {}
764 }
765 }
766 }
767 ObligationCauseCode::MatchExpressionArm(box MatchExpressionArmCause {
768 arm_block_id,
769 arm_span,
770 arm_ty,
771 prior_arm_block_id,
772 prior_arm_span,
773 prior_arm_ty,
774 source,
775 ref prior_arms,
776 opt_suggest_box_span,
777 scrut_span,
778 scrut_hir_id,
779 ..
780 }) => match source {
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");
786 self.typeck_results
787 .as_ref()
788 .and_then(|typeck_results| typeck_results.expr_ty_opt(arg_expr))
789 } else {
790 bug!("try desugaring w/out call expr as scrutinee");
791 };
792
793 match scrut_ty {
794 Some(ty) if expected == ty => {
795 let source_map = self.tcx.sess.source_map();
796 err.span_suggestion(
797 source_map.end_point(cause.span()),
798 "try removing this `?`",
799 "",
800 Applicability::MachineApplicable,
801 );
802 }
803 _ => {}
804 }
805 }
806 }
807 _ => {
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,
811 _ => prior_arm_ty,
812 });
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}`"));
819 }
820 } else if let Some(sp) = prior_arms.last() {
821 any_multiline_arm |= source_map.is_multiline(*sp);
822 err.span_label(
823 *sp,
824 format!("this and all prior arms are found to be of type `{t}`"),
825 );
826 }
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)
831 } else {
832 cause.span
833 };
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(
837 prior_arm_block_id,
838 prior_arm_ty,
839 prior_arm_span,
840 arm_block_id,
841 arm_ty,
842 arm_span,
843 ) {
844 err.subdiagnostic(subdiag);
845 }
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
849 {
850 err.span_suggestion_verbose(
851 stmt.span.shrink_to_hi(),
852 "consider using a semicolon here, but this will discard any values \
853 in the match arms",
854 ";",
855 Applicability::MaybeIncorrect,
856 );
857 }
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(
861 err,
862 ret_sp,
863 prior_arms.iter().chain(std::iter::once(&arm_span)).map(|s| *s),
864 );
865 }
866 }
867 },
868 ObligationCauseCode::IfExpression(box IfExpressionCause {
869 then_id,
870 else_id,
871 then_ty,
872 else_ty,
873 outer_span,
874 opt_suggest_box_span,
875 }) => {
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");
881 }
882 if let Some(subdiag) = self.suggest_remove_semi_or_return_binding(
883 Some(then_id),
884 then_ty,
885 then_span,
886 Some(else_id),
887 else_ty,
888 else_span,
889 ) {
890 err.subdiagnostic(subdiag);
891 }
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 {
895 return false;
896 };
897 if blk.expr.is_some() || !blk.stmts.is_empty() {
898 return false;
899 }
900 let Some((_, hir::Node::Expr(expr))) = self.tcx.hir().parent_iter(id).nth(1)
901 else {
902 return false;
903 };
904 matches!(expr.kind, hir::ExprKind::If(..))
905 };
906 if let Some(ret_sp) = opt_suggest_box_span
907 && !is_empty_arm(then_id)
908 && !is_empty_arm(else_id)
909 {
910 self.suggest_boxing_for_return_impl_trait(
911 err,
912 ret_sp,
913 [then_span, else_span].into_iter(),
914 );
915 }
916 }
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`");
920 }
921 _ => {
922 if let ObligationCauseCode::BindingObligation(_, span)
923 | ObligationCauseCode::ExprBindingObligation(_, span, ..) =
924 cause.code().peel_derives()
925 && let TypeError::RegionsPlaceholderMismatch = terr
926 {
927 err.span_note(*span, "the lifetime requirement is introduced here");
928 }
929 }
930 }
931 }
932
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`.
936 ///
937 /// ```text
938 /// Foo<Bar<Qux>>
939 /// ^^^^--------^ this is highlighted
940 /// | |
941 /// | this type argument is exactly the same as the other type, not highlighted
942 /// this is highlighted
943 /// Bar<Qux>
944 /// -------- this type is the same as a type argument in the other type, not highlighted
945 /// ```
946 fn highlight_outer(
947 &self,
948 value: &mut DiagnosticStyledString,
949 other_value: &mut DiagnosticStyledString,
950 name: String,
951 sub: ty::GenericArgsRef<'tcx>,
952 pos: usize,
953 other_ty: Ty<'tcx>,
954 ) {
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);
958 let len = sub.len();
959 if len > 0 {
960 value.push_highlighted("<");
961 }
962
963 // Output the lifetimes for the first type
964 let lifetimes = sub
965 .regions()
966 .map(|lifetime| {
967 let s = lifetime.to_string();
968 if s.is_empty() { "'_".to_string() } else { s }
969 })
970 .collect::<Vec<_>>()
971 .join(", ");
972 if !lifetimes.is_empty() {
973 if sub.regions().count() < len {
974 value.push_normal(lifetimes + ", ");
975 } else {
976 value.push_normal(lifetimes);
977 }
978 }
979
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() {
983 if i == pos {
984 let values = self.cmp(type_arg, other_ty);
985 value.0.extend((values.0).0);
986 other_value.0.extend((values.1).0);
987 } else {
988 value.push_highlighted(type_arg.to_string());
989 }
990
991 if len > 0 && i != len - 1 {
992 value.push_normal(", ");
993 }
994 }
995 if len > 0 {
996 value.push_highlighted(">");
997 }
998 }
999
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.
1002 ///
1003 /// For the following code:
1004 ///
1005 /// ```ignore (illustrative)
1006 /// let x: Foo<Bar<Qux>> = foo::<Bar<Qux>>();
1007 /// ```
1008 ///
1009 /// The type error output will behave in the following way:
1010 ///
1011 /// ```text
1012 /// Foo<Bar<Qux>>
1013 /// ^^^^--------^ this is highlighted
1014 /// | |
1015 /// | this type argument is exactly the same as the other type, not highlighted
1016 /// this is highlighted
1017 /// Bar<Qux>
1018 /// -------- this type is the same as a type argument in the other type, not highlighted
1019 /// ```
1020 fn cmp_type_arg(
1021 &self,
1022 mut t1_out: &mut DiagnosticStyledString,
1023 mut t2_out: &mut DiagnosticStyledString,
1024 path: String,
1025 sub: &'tcx [ty::GenericArg<'tcx>],
1026 other_path: String,
1027 other_ty: Ty<'tcx>,
1028 ) -> Option<()> {
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() {
1033 if ta == other_ty {
1034 self.highlight_outer(&mut t1_out, &mut t2_out, path, sub, i, other_ty);
1035 return Some(());
1036 }
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);
1041 return Some(());
1042 }
1043 }
1044 }
1045 None
1046 }
1047
1048 /// Adds a `,` to the type representation only if it is appropriate.
1049 fn push_comma(
1050 &self,
1051 value: &mut DiagnosticStyledString,
1052 other_value: &mut DiagnosticStyledString,
1053 len: usize,
1054 pos: usize,
1055 ) {
1056 if len > 0 && pos != len - 1 {
1057 value.push_normal(", ");
1058 other_value.push_normal(", ");
1059 }
1060 }
1061
1062 /// Given two `fn` signatures highlight only sub-parts that are different.
1063 fn cmp_fn_sig(
1064 &self,
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);
1070
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)
1075 .unwrap();
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)
1078 };
1079
1080 let (lt1, sig1) = get_lifetimes(sig1);
1081 let (lt2, sig2) = get_lifetimes(sig2);
1082
1083 // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
1084 let mut values = (
1085 DiagnosticStyledString::normal("".to_string()),
1086 DiagnosticStyledString::normal("".to_string()),
1087 );
1088
1089 // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
1090 // ^^^^^^
1091 values.0.push(sig1.unsafety.prefix_str(), sig1.unsafety != sig2.unsafety);
1092 values.1.push(sig2.unsafety.prefix_str(), sig1.unsafety != sig2.unsafety);
1093
1094 // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
1095 // ^^^^^^^^^^
1096 if sig1.abi != abi::Abi::Rust {
1097 values.0.push(format!("extern {} ", sig1.abi), sig1.abi != sig2.abi);
1098 }
1099 if sig2.abi != abi::Abi::Rust {
1100 values.1.push(format!("extern {} ", sig2.abi), sig1.abi != sig2.abi);
1101 }
1102
1103 // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
1104 // ^^^^^^^^
1105 let lifetime_diff = lt1 != lt2;
1106 values.0.push(lt1, lifetime_diff);
1107 values.1.push(lt2, lifetime_diff);
1108
1109 // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
1110 // ^^^
1111 values.0.push_normal("fn(");
1112 values.1.push_normal("fn(");
1113
1114 // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
1115 // ^^^^^
1116 let len1 = sig1.inputs().len();
1117 let len2 = sig2.inputs().len();
1118 if len1 == len2 {
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);
1124 }
1125 } else {
1126 for (i, l) in sig1.inputs().iter().enumerate() {
1127 values.0.push_highlighted(l.to_string());
1128 if i != len1 - 1 {
1129 values.0.push_highlighted(", ");
1130 }
1131 }
1132 for (i, r) in sig2.inputs().iter().enumerate() {
1133 values.1.push_highlighted(r.to_string());
1134 if i != len2 - 1 {
1135 values.1.push_highlighted(", ");
1136 }
1137 }
1138 }
1139
1140 if sig1.c_variadic {
1141 if len1 > 0 {
1142 values.0.push_normal(", ");
1143 }
1144 values.0.push("...", !sig2.c_variadic);
1145 }
1146 if sig2.c_variadic {
1147 if len2 > 0 {
1148 values.1.push_normal(", ");
1149 }
1150 values.1.push("...", !sig1.c_variadic);
1151 }
1152
1153 // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
1154 // ^
1155 values.0.push_normal(")");
1156 values.1.push_normal(")");
1157
1158 // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
1159 // ^^^^^^^^
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);
1166 }
1167 if !output2.is_unit() {
1168 values.1.push_normal(" -> ");
1169 (values.1).0.extend(x2.0);
1170 }
1171 values
1172 }
1173
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.
1176 pub fn cmp(
1177 &self,
1178 t1: Ty<'tcx>,
1179 t2: Ty<'tcx>,
1180 ) -> (DiagnosticStyledString, DiagnosticStyledString) {
1181 debug!("cmp(t1={}, t1.kind={:?}, t2={}, t2.kind={:?})", t1, t1.kind(), t2, t2.kind());
1182
1183 // helper functions
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(_)))
1188 | (
1189 &ty::Infer(ty::InferTy::IntVar(_)),
1190 &ty::Int(_) | &ty::Infer(ty::InferTy::IntVar(_)),
1191 )
1192 | (&ty::Float(_), &ty::Infer(ty::InferTy::FloatVar(_)))
1193 | (
1194 &ty::Infer(ty::InferTy::FloatVar(_)),
1195 &ty::Float(_) | &ty::Infer(ty::InferTy::FloatVar(_)),
1196 ) => true,
1197 _ => false,
1198 }
1199 }
1200
1201 fn push_ty_ref<'tcx>(
1202 region: ty::Region<'tcx>,
1203 ty: Ty<'tcx>,
1204 mutbl: hir::Mutability,
1205 s: &mut DiagnosticStyledString,
1206 ) {
1207 let mut r = region.to_string();
1208 if r == "'_" {
1209 r.clear();
1210 } else {
1211 r.push(' ');
1212 }
1213 s.push_highlighted(format!("&{}{}", r, mutbl.prefix_str()));
1214 s.push_normal(ty.to_string());
1215 }
1216
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);
1229 if did1 == 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>>();
1233 // Foo<Bar, _>
1234 // Foo<Quz, _>
1235 // --- ^ type argument elided
1236 // |
1237 // highlighted in output
1238 values.0.push_normal(path1);
1239 values.1.push_normal(path2);
1240
1241 // Avoid printing out default generic parameters that are common to both
1242 // types.
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)
1251 .count();
1252 let len = sub1.len() - common_default_params;
1253 let consts_offset = len - sub1.consts().count();
1254
1255 // Only draw `<...>` if there are lifetime/type arguments.
1256 if len > 0 {
1257 values.0.push_normal("<");
1258 values.1.push_normal("<");
1259 }
1260
1261 fn lifetime_display(lifetime: Region<'_>) -> String {
1262 let s = lifetime.to_string();
1263 if s.is_empty() { "'_".to_string() } else { s }
1264 }
1265 // At one point we'd like to elide all lifetimes here, they are irrelevant for
1266 // all diagnostics that use this output
1267 //
1268 // Foo<'x, '_, Bar>
1269 // Foo<'y, '_, Qux>
1270 // ^^ ^^ --- type arguments are not elided
1271 // | |
1272 // | elided as they were the same
1273 // not elided, they were different, but irrelevant
1274 //
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
1278 //
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);
1291 } else {
1292 values.0.push_normal("'_");
1293 values.1.push_normal("'_");
1294 }
1295 self.push_comma(&mut values.0, &mut values.1, len, i);
1296 }
1297
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
1300 // output.
1301 // Foo<_, Bar>
1302 // Foo<_, Qux>
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("_");
1312 } else {
1313 let (x1, x2) = self.cmp(ta1, ta2);
1314 (values.0).0.extend(x1.0);
1315 (values.1).0.extend(x2.0);
1316 }
1317 self.push_comma(&mut values.0, &mut values.1, len, i);
1318 }
1319
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("_");
1328 } else {
1329 values.0.push_highlighted(ca1.to_string());
1330 values.1.push_highlighted(ca2.to_string());
1331 }
1332 self.push_comma(&mut values.0, &mut values.1, len, i);
1333 }
1334
1335 // Close the type argument bracket.
1336 // Only draw `<...>` if there are lifetime/type arguments.
1337 if len > 0 {
1338 values.0.push_normal(">");
1339 values.1.push_normal(">");
1340 }
1341 values
1342 } else {
1343 // Check for case:
1344 // let x: Foo<Bar<Qux> = foo::<Bar<Qux>>();
1345 // Foo<Bar<Qux>
1346 // ------- this type argument is exactly the same as the other type
1347 // Bar<Qux>
1348 if self
1349 .cmp_type_arg(
1350 &mut values.0,
1351 &mut values.1,
1352 path1.clone(),
1353 sub_no_defaults_1,
1354 path2.clone(),
1355 t2,
1356 )
1357 .is_some()
1358 {
1359 return values;
1360 }
1361 // Check for case:
1362 // let x: Bar<Qux> = y:<Foo<Bar<Qux>>>();
1363 // Bar<Qux>
1364 // Foo<Bar<Qux>>
1365 // ------- this type argument is exactly the same as the other type
1366 if self
1367 .cmp_type_arg(
1368 &mut values.1,
1369 &mut values.0,
1370 path2,
1371 sub_no_defaults_2,
1372 path1,
1373 t1,
1374 )
1375 .is_some()
1376 {
1377 return values;
1378 }
1379
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
1385
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());
1389
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)
1396 .sum();
1397
1398 debug!(?separator_len, ?split_idx, ?min_len, "cmp");
1399
1400 if split_idx >= min_len {
1401 // paths are identical, highlight everything
1402 (
1403 DiagnosticStyledString::highlighted(t1_str),
1404 DiagnosticStyledString::highlighted(t2_str),
1405 )
1406 } else {
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");
1410
1411 values.0.push_normal(common);
1412 values.0.push_highlighted(uniq1);
1413 values.1.push_normal(common);
1414 values.1.push_highlighted(uniq2);
1415
1416 values
1417 }
1418 }
1419 }
1420
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());
1426 values
1427 }
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);
1432 values
1433 }
1434
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) =>
1438 {
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);
1442 values
1443 }
1444
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() => {
1447 let mut values =
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);
1455 }
1456 if len == 1 {
1457 // Keep the output for single element tuples as `(ty,)`.
1458 values.0.push_normal(",");
1459 values.1.push_normal(",");
1460 }
1461 values.0.push_normal(")");
1462 values.1.push_normal(")");
1463 values
1464 }
1465
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);
1475 values
1476 }
1477
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!(
1482 " {{{}}}",
1483 self.tcx.def_path_str_with_args(*did1, args1)
1484 ));
1485 values
1486 }
1487
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);
1491 values
1492 .1
1493 .push_normal(format!(" {{{}}}", self.tcx.def_path_str_with_args(*did2, args2)));
1494 values
1495 }
1496
1497 (ty::FnPtr(sig1), ty::FnPtr(sig2)) => self.cmp_fn_sig(sig1, sig2),
1498
1499 _ => {
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("_"))
1503 } else {
1504 // We couldn't find anything in common, highlight everything.
1505 (
1506 DiagnosticStyledString::highlighted(t1.to_string()),
1507 DiagnosticStyledString::highlighted(t2.to_string()),
1508 )
1509 }
1510 }
1511 }
1512 }
1513
1514 /// Extend a type error with extra labels pointing at "non-trivial" types, like closures and
1515 /// the return type of `async fn`s.
1516 ///
1517 /// `secondary_span` gives the caller the opportunity to expand `diag` with a `span_label`.
1518 ///
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`.
1523 #[instrument(
1524 level = "debug",
1525 skip(self, diag, secondary_span, swap_secondary_and_primary, prefer_label)
1526 )]
1527 pub fn note_type_err(
1528 &self,
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,
1535 prefer_label: bool,
1536 ) {
1537 let span = cause.span();
1538
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 {
1542 values = None;
1543 }
1544 struct OpaqueTypesVisitor<'tcx> {
1545 types: FxIndexMap<TyCategory, FxIndexSet<Span>>,
1546 expected: FxIndexMap<TyCategory, FxIndexSet<Span>>,
1547 found: FxIndexMap<TyCategory, FxIndexSet<Span>>,
1548 ignore_span: Span,
1549 tcx: TyCtxt<'tcx>,
1550 }
1551
1552 impl<'tcx> OpaqueTypesVisitor<'tcx> {
1553 fn visit_expected_found(
1554 tcx: TyCtxt<'tcx>,
1555 expected: impl TypeVisitable<TyCtxt<'tcx>>,
1556 found: impl TypeVisitable<TyCtxt<'tcx>>,
1557 ignore_span: Span,
1558 ) -> Self {
1559 let mut types_visitor = OpaqueTypesVisitor {
1560 types: Default::default(),
1561 expected: Default::default(),
1562 found: Default::default(),
1563 ignore_span,
1564 tcx,
1565 };
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);
1573 types_visitor
1574 }
1575
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);
1579 }
1580
1581 fn add_labels_for_types(
1582 &self,
1583 err: &mut Diagnostic,
1584 target: &str,
1585 types: &FxIndexMap<TyCategory, FxIndexSet<Span>>,
1586 ) {
1587 for (kind, values) in types.iter() {
1588 let count = values.len();
1589 for &sp in values {
1590 err.span_label(
1591 sp,
1592 format!(
1593 "{}{} {:#}{}",
1594 if count == 1 { "the " } else { "one of the " },
1595 target,
1596 kind,
1597 pluralize!(count),
1598 ),
1599 );
1600 }
1601 }
1602 }
1603 }
1604
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:
1610 //
1611 // error[E0308]: mismatched types
1612 // --> $DIR/issue-20862.rs:2:5
1613 // |
1614 // LL | |y| x + y
1615 // | ^^^^^^^^^
1616 // | |
1617 // | the found closure
1618 // | expected `()`, found closure
1619 // |
1620 // = note: expected unit type `()`
1621 // found closure `{closure@$DIR/issue-20862.rs:2:5: 2:14 x:_}`
1622 //
1623 // Also ignore opaque `Future`s that come from async fns.
1624 if !self.ignore_span.overlaps(span)
1625 && !span.is_desugaring(DesugaringKind::Async)
1626 {
1627 self.types.entry(kind).or_default().insert(span);
1628 }
1629 }
1630 t.super_visit_with(self)
1631 }
1632 }
1633
1634 debug!("note_type_err(diag={:?})", diag);
1635 enum Mismatch<'a> {
1636 Variable(ty::error::ExpectedFound<Ty<'a>>),
1637 Fixed(&'static str),
1638 }
1639 let (expected_found, exp_found, is_simple_error, values) = match values {
1640 None => (None, Mismatch::Fixed("type"), false, None),
1641 Some(values) => {
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,
1651 )
1652 .report(diag);
1653
1654 (
1655 is_simple_err,
1656 Mismatch::Variable(infer::ExpectedFound { expected, found }),
1657 )
1658 }
1659 (ty::TermKind::Const(_), ty::TermKind::Const(_)) => {
1660 (false, Mismatch::Fixed("constant"))
1661 }
1662 _ => (false, Mismatch::Fixed("type")),
1663 }
1664 }
1665 ValuePairs::PolySigs(infer::ExpectedFound { expected, found }) => {
1666 OpaqueTypesVisitor::visit_expected_found(self.tcx, expected, found, span)
1667 .report(diag);
1668 (false, Mismatch::Fixed("signature"))
1669 }
1670 ValuePairs::TraitRefs(_) | ValuePairs::PolyTraitRefs(_) => {
1671 (false, Mismatch::Fixed("trait"))
1672 }
1673 ValuePairs::Aliases(infer::ExpectedFound { expected, .. }) => {
1674 (false, Mismatch::Fixed(self.tcx.def_descr(expected.def_id)))
1675 }
1676 ValuePairs::Regions(_) => (false, Mismatch::Fixed("lifetime")),
1677 ValuePairs::ExistentialTraitRef(_) => {
1678 (false, Mismatch::Fixed("existential trait ref"))
1679 }
1680 ValuePairs::ExistentialProjection(_) => {
1681 (false, Mismatch::Fixed("existential projection"))
1682 }
1683 };
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();
1689 return;
1690 };
1691 (Some(vals), exp_found, is_simple_error, Some(values))
1692 }
1693 };
1694
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);
1698 } else {
1699 diag.span_note(span, msg);
1700 }
1701 };
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 {
1705 expected,
1706 ..
1707 })) = values
1708 {
1709 Cow::from(format!("expected this to be `{expected}`"))
1710 } else {
1711 terr.to_string(self.tcx)
1712 };
1713 label_or_note(sp, terr);
1714 label_or_note(span, msg);
1715 } else {
1716 label_or_note(span, terr.to_string(self.tcx));
1717 label_or_note(sp, msg);
1718 }
1719 } else {
1720 if let Some(values) = values
1721 && let Some((e, f)) = values.ty()
1722 && let TypeError::ArgumentSorts(..) | TypeError::Sorts(_) = terr
1723 {
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));
1730 } else {
1731 label_or_note(span, Cow::from(format!("expected {expected}, found {found}")));
1732 }
1733 } else {
1734 label_or_note(span, terr.to_string(self.tcx));
1735 }
1736 }
1737
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),
1743 Some(ef),
1744 ),
1745 Mismatch::Fixed(s) => (s.into(), s.into(), None),
1746 };
1747
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> },
1752 }
1753
1754 let similarity = |ExpectedFound { expected, found }: ExpectedFound<Ty<'tcx>>| {
1755 if let ty::Adt(expected, _) = expected.kind()
1756 && let Some(primitive) = found.primitive_symbol()
1757 {
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 });
1762 }
1763 } else if let Some(primitive) = expected.primitive_symbol()
1764 && let ty::Adt(found, _) = found.kind()
1765 {
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 });
1770 }
1771 } else if let ty::Adt(expected, _) = expected.kind()
1772 && let ty::Adt(found, _) = found.kind()
1773 {
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.
1778 return None;
1779 }
1780 let f_path = self.tcx.def_path(found.did()).data;
1781 let e_path = self.tcx.def_path(expected.did()).data;
1782
1783 if let (Some(e_last), Some(f_last)) = (e_path.last(), f_path.last())
1784 && e_last == f_last
1785 {
1786 return Some(Similar::Adts { expected: *expected, found: *found });
1787 }
1788 }
1789 None
1790 };
1791
1792 match terr {
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 =
1796 |prim: Ty<'tcx>,
1797 shadow: Ty<'tcx>,
1798 defid: DefId,
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"
1803 ));
1804 diagnostic
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")
1809 } else {
1810 let crate_name = self.tcx.crate_name(defid.krate);
1811 format!("{name} is defined in crate `{crate_name}`")
1812 };
1813 diagnostic.span_note(def_span, msg);
1814 };
1815
1816 let diagnose_adts =
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);
1822
1823 let found_defid = found_adt.did();
1824 let expected_defid = expected_adt.did();
1825
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)]
1829 {
1830 let def_span = self.tcx.def_span(defid);
1831
1832 let msg = if found_defid.is_local() && expected_defid.is_local() {
1833 let module = self
1834 .tcx
1835 .parent_module_from_def_id(defid.expect_local())
1836 .to_def_id();
1837 let module_name =
1838 self.tcx.def_path(module).to_string_no_crate_verbose();
1839 format!(
1840 "{name} is defined in module `crate{module_name}` of the current crate"
1841 )
1842 } else if defid.is_local() {
1843 format!("{name} is defined in the current crate")
1844 } else {
1845 let crate_name = self.tcx.crate_name(defid.krate);
1846 format!("{name} is defined in crate `{crate_name}`")
1847 };
1848 diagnostic.span_note(def_span, msg);
1849 }
1850 };
1851
1852 match s {
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)
1856 }
1857 Similar::PrimitiveExpected { expected: prim, found } => {
1858 diagnose_primitive(prim, values.found, found.did(), diag)
1859 }
1860 }
1861 }
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());
1869 format!(
1870 " (opaque type at <{}:{}:{}>)",
1871 sm.filename_for_diagnostics(&pos.file.name),
1872 pos.line,
1873 pos.col.to_usize() + 1,
1874 )
1875 }
1876 (true, ty::Alias(ty::Projection, proj))
1877 if self.tcx.is_impl_trait_in_trait(proj.def_id) =>
1878 {
1879 let sm = self.tcx.sess.source_map();
1880 let pos = sm.lookup_char_pos(self.tcx.def_span(proj.def_id).lo());
1881 format!(
1882 " (trait associated opaque type at <{}:{}:{}>)",
1883 sm.filename_for_diagnostics(&pos.file.name),
1884 pos.line,
1885 pos.col.to_usize() + 1,
1886 )
1887 }
1888 (true, _) => format!(" ({})", ty.sort_string(self.tcx)),
1889 (false, _) => "".to_string(),
1890 };
1891 if let Some(path) = path {
1892 s.push_str(&format!(
1893 "\nthe full type name has been written to '{}'",
1894 path.display(),
1895 ));
1896 }
1897 s
1898 };
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
1910 } else {
1911 false
1912 }
1913 }))
1914 {
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(
1924 &expected_label,
1925 expected,
1926 &found_label,
1927 found,
1928 &sort_string(values.expected, exp_p),
1929 &sort_string(values.found, found_p),
1930 );
1931 }
1932 }
1933 }
1934 }
1935 _ => {
1936 debug!(
1937 "note_type_err: exp_found={:?}, expected={:?} found={:?}",
1938 exp_found, expected, found
1939 );
1940 if !is_simple_error || terr.must_include_note() {
1941 diag.note_expected_found(&expected_label, expected, &found_label, found);
1942 }
1943 }
1944 }
1945 }
1946 let exp_found = match exp_found {
1947 Mismatch::Variable(exp_found) => Some(exp_found),
1948 Mismatch::Fixed(_) => None,
1949 };
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) =>
1954 {
1955 Some(terr)
1956 }
1957 _ => exp_found,
1958 };
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)
1966 } else {
1967 true
1968 };
1969
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(..))
1975 {
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);
1980 }
1981 }
1982
1983 self.check_and_note_conflicting_crates(diag, terr);
1984
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
1989 {
1990 self.note_and_explain_type_err(diag, exp_found, cause, span, cause.body_id.to_def_id());
1991 }
1992
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()
1997 {
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(
2001 span,
2002 self.tcx.hir().get_by_def_id(def_id),
2003 &exp_found,
2004 diag,
2005 );
2006 }
2007
2008 // It reads better to have the error origin as the final
2009 // thing.
2010 self.note_error_origin(diag, cause, exp_found, terr);
2011
2012 debug!(?diag);
2013 }
2014
2015 pub fn type_error_additional_suggestions(
2016 &self,
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))
2032 }
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)
2038 && let Some(code) =
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())
2044 {
2045 suggestions.push(TypeErrorAdditionalDiags::MeantByteLiteral {
2046 span,
2047 code: escape_literal(code),
2048 })
2049 }
2050 }
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
2058 {
2059 suggestions.push(TypeErrorAdditionalDiags::MeantCharLiteral {
2060 span,
2061 code: escape_literal(code),
2062 })
2063 }
2064 }
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) {
2069 if let Some(code) =
2070 code.strip_prefix('\'').and_then(|s| s.strip_suffix('\''))
2071 {
2072 suggestions.push(TypeErrorAdditionalDiags::MeantStrLiteral {
2073 span,
2074 code: escape_literal(code),
2075 })
2076 }
2077 }
2078 }
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));
2084 }
2085 }
2086 (ty::Array(_, _), ty::Array(_, _)) => {
2087 suggestions.extend(self.suggest_specify_actual_length(terr, trace, span))
2088 }
2089 _ => {}
2090 }
2091 }
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)
2097 {
2098 suggestions.push(TypeErrorAdditionalDiags::TryCannotConvert {
2099 found: found_ty.content(),
2100 expected: expected_ty.content(),
2101 });
2102 }
2103 suggestions
2104 }
2105
2106 fn suggest_specify_actual_length(
2107 &self,
2108 terr: TypeError<'_>,
2109 trace: &TypeTrace<'_>,
2110 span: Span,
2111 ) -> Option<TypeErrorAdditionalDiags> {
2112 let hir = self.tcx.hir();
2113 let TypeError::FixedArraySize(sz) = terr else {
2114 return None;
2115 };
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> {
2120 span: Span,
2121 result: Option<&'v hir::Ty<'v>>,
2122 }
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() {
2126 return;
2127 }
2128 // Find a local statement where the initializer has
2129 // the same span as the error and the type is specified.
2130 if let hir::Stmt {
2131 kind:
2132 hir::StmtKind::Local(hir::Local {
2133 init: Some(hir::Expr { span: init_span, .. }),
2134 ty: Some(array_ty),
2135 ..
2136 }),
2137 ..
2138 } = s
2139 && init_span == &self.span
2140 {
2141 self.result = Some(*array_ty);
2142 }
2143 }
2144 }
2145 let mut visitor = LetVisitor { span, result: None };
2146 visitor.visit_body(body);
2147 visitor.result.map(|r| &r.peel_refs().kind)
2148 }
2149 Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Const(ty, _, _), .. })) => {
2150 Some(&ty.peel_refs().kind)
2151 }
2152 _ => None,
2153 };
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)
2158 {
2159 Some(TypeErrorAdditionalDiags::ConsiderSpecifyingLength { span, length: sz.found })
2160 } else {
2161 None
2162 }
2163 }
2164
2165 pub fn report_and_explain_type_error(
2166 &self,
2167 trace: TypeTrace<'tcx>,
2168 terr: TypeError<'tcx>,
2169 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
2170 debug!("report_and_explain_type_error(trace={:?}, terr={:?})", trace, terr);
2171
2172 let span = trace.cause.span();
2173 let failure_code = trace.cause.as_failure_code_diag(
2174 terr,
2175 span,
2176 self.type_error_additional_suggestions(&trace, terr),
2177 );
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);
2180 diag
2181 }
2182
2183 fn suggest_wrap_to_build_a_tuple(
2184 &self,
2185 span: Span,
2186 found: Ty<'tcx>,
2187 expected_fields: &List<Ty<'tcx>>,
2188 ) -> Option<TypeErrorAdditionalDiags> {
2189 let [expected_tup_elem] = expected_fields[..] else { return None };
2190
2191 if !self.same_type_modulo_infer(expected_tup_elem, found) {
2192 return None;
2193 }
2194
2195 let Ok(code) = self.tcx.sess().source_map().span_to_snippet(span) else { return None };
2196
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(),
2201 }
2202 } else {
2203 TypeErrorAdditionalDiags::TupleAlsoParentheses {
2204 span_low: span.shrink_to_lo(),
2205 span_high: span.shrink_to_hi(),
2206 }
2207 };
2208 Some(sugg)
2209 }
2210
2211 fn values_str(
2212 &self,
2213 values: ValuePairs<'tcx>,
2214 ) -> Option<(DiagnosticStyledString, DiagnosticStyledString, Option<PathBuf>, Option<PathBuf>)>
2215 {
2216 match values {
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(),
2226 };
2227 match self.expected_found_str(pretty_exp_found) {
2228 Some((expected, found, _, _)) if expected == found => {
2229 self.expected_found_str(exp_found)
2230 }
2231 ret => ret,
2232 }
2233 }
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(),
2238 };
2239 match self.expected_found_str(pretty_exp_found) {
2240 Some((expected, found, _, _)) if expected == found => {
2241 self.expected_found_str(exp_found)
2242 }
2243 ret => ret,
2244 }
2245 }
2246 infer::PolySigs(exp_found) => {
2247 let exp_found = self.resolve_vars_if_possible(exp_found);
2248 if exp_found.references_error() {
2249 return None;
2250 }
2251 let (exp, fnd) = self.cmp_fn_sig(&exp_found.expected, &exp_found.found);
2252 Some((exp, fnd, None, None))
2253 }
2254 }
2255 }
2256
2257 fn expected_found_str_term(
2258 &self,
2259 exp_found: ty::error::ExpectedFound<ty::Term<'tcx>>,
2260 ) -> Option<(DiagnosticStyledString, DiagnosticStyledString, Option<PathBuf>, Option<PathBuf>)>
2261 {
2262 let exp_found = self.resolve_vars_if_possible(exp_found);
2263 if exp_found.references_error() {
2264 return None;
2265 }
2266
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);
2281 exp_p = exp_path;
2282 }
2283 if fnd_s.len() > len {
2284 let (fnd_s, fnd_path) = self.tcx.short_ty_string(found);
2285 fnd = DiagnosticStyledString::highlighted(fnd_s);
2286 fnd_p = fnd_path;
2287 }
2288 (exp, fnd, exp_p, fnd_p)
2289 }
2290 _ => (
2291 DiagnosticStyledString::highlighted(exp_found.expected.to_string()),
2292 DiagnosticStyledString::highlighted(exp_found.found.to_string()),
2293 None,
2294 None,
2295 ),
2296 })
2297 }
2298
2299 /// Returns a string of the form "expected `{}`, found `{}`".
2300 fn expected_found_str<T: fmt::Display + TypeFoldable<TyCtxt<'tcx>>>(
2301 &self,
2302 exp_found: ty::error::ExpectedFound<T>,
2303 ) -> Option<(DiagnosticStyledString, DiagnosticStyledString, Option<PathBuf>, Option<PathBuf>)>
2304 {
2305 let exp_found = self.resolve_vars_if_possible(exp_found);
2306 if exp_found.references_error() {
2307 return None;
2308 }
2309
2310 Some((
2311 DiagnosticStyledString::highlighted(exp_found.expected.to_string()),
2312 DiagnosticStyledString::highlighted(exp_found.found.to_string()),
2313 None,
2314 None,
2315 ))
2316 }
2317
2318 pub fn report_generic_bound_failure(
2319 &self,
2320 generic_param_scope: LocalDefId,
2321 span: Span,
2322 origin: Option<SubregionOrigin<'tcx>>,
2323 bound_kind: GenericKind<'tcx>,
2324 sub: Region<'tcx>,
2325 ) {
2326 self.construct_generic_bound_failure(generic_param_scope, span, origin, bound_kind, sub)
2327 .emit();
2328 }
2329
2330 pub fn construct_generic_bound_failure(
2331 &self,
2332 generic_param_scope: LocalDefId,
2333 span: Span,
2334 origin: Option<SubregionOrigin<'tcx>>,
2335 bound_kind: GenericKind<'tcx>,
2336 sub: Region<'tcx>,
2337 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
2338 if let Some(SubregionOrigin::CompareImplItemObligation {
2339 span,
2340 impl_item_def_id,
2341 trait_item_def_id,
2342 }) = origin
2343 {
2344 return self.report_extra_impl_obligation(
2345 span,
2346 impl_item_def_id,
2347 trait_item_def_id,
2348 &format!("`{bound_kind}: {sub}`"),
2349 );
2350 }
2351
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}`")
2357 }
2358 ty::AliasKind::Weak => format!("the type alias `{p}`"),
2359 ty::AliasKind::Opaque => format!("the opaque type `{p}`"),
2360 },
2361 };
2362
2363 let mut err = self.tcx.sess.struct_span_err_with_code(
2364 span,
2365 format!("{labeled_user_string} may not live long enough"),
2366 match sub.kind() {
2367 ty::ReEarlyBound(_) | ty::ReFree(_) if sub.has_name() => error_code!(E0309),
2368 ty::ReStatic => error_code!(E0310),
2369 _ => error_code!(E0311),
2370 },
2371 );
2372
2373 '_explain: {
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))
2377 }
2378 _ => (format!("lifetime `{sub}`"), Some(span)),
2379 };
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);
2384 }
2385 }
2386
2387 'suggestion: {
2388 let msg = "consider adding an explicit lifetime bound";
2389
2390 if (bound_kind, sub).has_infer_regions()
2391 || (bound_kind, sub).has_placeholders()
2392 || !bound_kind.is_suggestable(self.tcx, false)
2393 {
2394 let lt_name = sub.get_name_or_anon().to_string();
2395 err.help(format!("{msg} `{bound_kind}: {lt_name}`..."));
2396 break 'suggestion;
2397 }
2398
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);
2402 }
2403
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)),
2419 };
2420 (scope, sugg_span)
2421 }
2422 _ => (generic_param_scope, None),
2423 };
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,
2430 },
2431 };
2432 match self.tcx.is_descendant_of(type_scope.into(), lifetime_scope.into()) {
2433 true => type_scope,
2434 false => lifetime_scope,
2435 }
2436 };
2437
2438 let mut suggs = vec![];
2439 let lt_name = self.suggest_name_region(sub, &mut suggs);
2440
2441 if let Some((sp, has_lifetimes)) = type_param_sugg_span
2442 && suggestion_scope == type_scope
2443 {
2444 let suggestion =
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))
2451 } else {
2452 let consider = format!("{msg} `{bound_kind}: {sub}`...");
2453 err.help(consider);
2454 }
2455
2456 if !suggs.is_empty() {
2457 err.multipart_suggestion_verbose(
2458 format!("{msg}"),
2459 suggs,
2460 Applicability::MaybeIncorrect, // Issue #41966
2461 );
2462 }
2463 }
2464
2465 err
2466 }
2467
2468 pub fn suggest_name_region(
2469 &self,
2470 lifetime: Region<'tcx>,
2471 add_lt_suggs: &mut Vec<(Span, String)>,
2472 ) -> String {
2473 struct LifetimeReplaceVisitor<'tcx, 'a> {
2474 tcx: TyCtxt<'tcx>,
2475 needle: hir::LifetimeName,
2476 new_lt: &'a str,
2477 add_lt_suggs: &'a mut Vec<(Span, String)>,
2478 }
2479
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}, ")
2491 }
2492 hir::LifetimeSuggestionPosition::ObjectDefault => format!("+ {new_lt}"),
2493 };
2494 self.add_lt_suggs.push((span, sugg));
2495 }
2496 }
2497
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);
2501 };
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)
2505 {
2506 let prev_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);
2510 }
2511 self.needle = prev_needle;
2512 }
2513 }
2514 }
2515
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)
2519 }
2520 _ => return lifetime.get_name_or_anon().to_string(),
2521 };
2522
2523 let new_lt = {
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))
2529 .map(|p| p.name)
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| {
2534 match p {
2535 ty::BoundVariableKind::Region(lt) => lt.get_name(),
2536 _ => None,
2537 }
2538 }))
2539 }
2540 (b'a'..=b'z')
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())
2544 };
2545
2546 let mut visitor = LifetimeReplaceVisitor {
2547 tcx: self.tcx,
2548 needle: hir::LifetimeName::Param(lifetime_def_id),
2549 add_lt_suggs,
2550 new_lt: &new_lt,
2551 };
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"),
2558 }
2559
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);
2566
2567 new_lt
2568 }
2569
2570 fn report_sub_sup_conflict(
2571 &self,
2572 var_origin: RegionVariableOrigin,
2573 sub_origin: SubregionOrigin<'tcx>,
2574 sub_region: Region<'tcx>,
2575 sup_origin: SubregionOrigin<'tcx>,
2576 sup_region: Region<'tcx>,
2577 ) {
2578 let mut err = self.report_inference_failure(var_origin);
2579
2580 note_and_explain_region(
2581 self.tcx,
2582 &mut err,
2583 "first, the lifetime cannot outlive ",
2584 sup_region,
2585 "...",
2586 None,
2587 );
2588
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);
2594
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
2601 {
2602 note_and_explain_region(
2603 self.tcx,
2604 &mut err,
2605 "...but the lifetime must also be valid for ",
2606 sub_region,
2607 "...",
2608 None,
2609 );
2610 err.span_note(
2611 sup_trace.cause.span,
2612 format!("...so that the {}", sup_trace.cause.as_requirement_str()),
2613 );
2614
2615 err.note_expected_found(&"", sup_expected, &"", sup_found);
2616 if sub_region.is_error() | sup_region.is_error() {
2617 err.delay_as_bug();
2618 } else {
2619 err.emit();
2620 }
2621 return;
2622 }
2623
2624 self.note_region_origin(&mut err, &sup_origin);
2625
2626 note_and_explain_region(
2627 self.tcx,
2628 &mut err,
2629 "but, the lifetime must be valid for ",
2630 sub_region,
2631 "...",
2632 None,
2633 );
2634
2635 self.note_region_origin(&mut err, &sub_origin);
2636 if sub_region.is_error() | sup_region.is_error() {
2637 err.delay_as_bug();
2638 } else {
2639 err.emit();
2640 }
2641 }
2642
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)
2649 }
2650
2651 /// Structurally compares two types, modulo any inference variables.
2652 ///
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()
2660 }
2661 }
2662
2663 struct SameTypeModuloInfer<'a, 'tcx>(&'a InferCtxt<'tcx>);
2664
2665 impl<'tcx> TypeRelation<'tcx> for SameTypeModuloInfer<'_, 'tcx> {
2666 fn tcx(&self) -> TyCtxt<'tcx> {
2667 self.0.tcx
2668 }
2669
2670 fn param_env(&self) -> ty::ParamEnv<'tcx> {
2671 // Unused, only for consts which we treat as always equal
2672 ty::ParamEnv::empty()
2673 }
2674
2675 fn tag(&self) -> &'static str {
2676 "SameTypeModuloInfer"
2677 }
2678
2679 fn a_is_expected(&self) -> bool {
2680 true
2681 }
2682
2683 fn relate_with_variance<T: relate::Relate<'tcx>>(
2684 &mut self,
2685 _variance: ty::Variance,
2686 _info: ty::VarianceDiagInfo<'tcx>,
2687 a: T,
2688 b: T,
2689 ) -> relate::RelateResult<'tcx, T> {
2690 self.relate(a, b)
2691 }
2692
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(_)))
2696 | (
2697 ty::Infer(ty::InferTy::IntVar(_)),
2698 ty::Int(_) | ty::Uint(_) | ty::Infer(ty::InferTy::IntVar(_)),
2699 )
2700 | (ty::Float(_), ty::Infer(ty::InferTy::FloatVar(_)))
2701 | (
2702 ty::Infer(ty::InferTy::FloatVar(_)),
2703 ty::Float(_) | ty::Infer(ty::InferTy::FloatVar(_)),
2704 )
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),
2709 }
2710 }
2711
2712 fn regions(
2713 &mut self,
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())
2720 || a == b
2721 {
2722 Ok(a)
2723 } else {
2724 Err(TypeError::Mismatch)
2725 }
2726 }
2727
2728 fn binders<T>(
2729 &mut self,
2730 a: ty::Binder<'tcx, T>,
2731 b: ty::Binder<'tcx, T>,
2732 ) -> relate::RelateResult<'tcx, ty::Binder<'tcx, T>>
2733 where
2734 T: relate::Relate<'tcx>,
2735 {
2736 Ok(a.rebind(self.relate(a.skip_binder(), b.skip_binder())?))
2737 }
2738
2739 fn consts(
2740 &mut self,
2741 a: ty::Const<'tcx>,
2742 _b: ty::Const<'tcx>,
2743 ) -> relate::RelateResult<'tcx, ty::Const<'tcx>> {
2744 // FIXME(compiler-errors): This could at least do some first-order
2745 // relation
2746 Ok(a)
2747 }
2748 }
2749
2750 impl<'tcx> InferCtxt<'tcx> {
2751 fn report_inference_failure(
2752 &self,
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(),
2758 _ => String::new(),
2759 };
2760 if !s.is_empty() {
2761 s.push(' ');
2762 }
2763 s
2764 };
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))
2773 }
2774 infer::LateBoundRegion(_, br, infer::HigherRankedType) => {
2775 format!(" for lifetime parameter {}in generic type", br_string(br))
2776 }
2777 infer::LateBoundRegion(_, br, infer::AssocTypeProjection(def_id)) => format!(
2778 " for lifetime parameter {}in trait containing associated type `{}`",
2779 br_string(br),
2780 self.tcx.associated_item(def_id).name
2781 ),
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")
2786 }
2787 infer::Nll(..) => bug!("NLL variable found in lexical phase"),
2788 };
2789
2790 struct_span_err!(
2791 self.tcx.sess,
2792 var_origin.span(),
2793 E0495,
2794 "cannot infer an appropriate lifetime{} due to conflicting requirements",
2795 var_description
2796 )
2797 }
2798 }
2799
2800 pub enum FailureCode {
2801 Error0317,
2802 Error0580,
2803 Error0308,
2804 Error0644,
2805 }
2806
2807 pub trait ObligationCauseExt<'tcx> {
2808 fn as_failure_code(&self, terr: TypeError<'tcx>) -> FailureCode;
2809
2810 fn as_failure_code_diag(
2811 &self,
2812 terr: TypeError<'tcx>,
2813 span: Span,
2814 subdiags: Vec<TypeErrorAdditionalDiags>,
2815 ) -> ObligationCauseFailureCode;
2816 fn as_requirement_str(&self) -> &'static str;
2817 }
2818
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::*;
2823 match self.code() {
2824 IfExpressionWithNoElse => Error0317,
2825 MainFunctionType => Error0580,
2826 CompareImplItemObligation { .. }
2827 | MatchExpressionArm(_)
2828 | IfExpression { .. }
2829 | LetElse
2830 | StartFunctionType
2831 | LangFunctionType(_)
2832 | IntrinsicType
2833 | MethodReceiver => Error0308,
2834
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
2837 // tailor to that.
2838 _ => match terr {
2839 TypeError::CyclicTy(ty) if ty.is_closure() || ty.is_coroutine() => Error0644,
2840 TypeError::IntrinsicCast => Error0308,
2841 _ => Error0308,
2842 },
2843 }
2844 }
2845 fn as_failure_code_diag(
2846 &self,
2847 terr: TypeError<'tcx>,
2848 span: Span,
2849 subdiags: Vec<TypeErrorAdditionalDiags>,
2850 ) -> ObligationCauseFailureCode {
2851 use crate::traits::ObligationCauseCode::*;
2852 match self.code() {
2853 CompareImplItemObligation { kind: ty::AssocKind::Fn, .. } => {
2854 ObligationCauseFailureCode::MethodCompat { span, subdiags }
2855 }
2856 CompareImplItemObligation { kind: ty::AssocKind::Type, .. } => {
2857 ObligationCauseFailureCode::TypeCompat { span, subdiags }
2858 }
2859 CompareImplItemObligation { kind: ty::AssocKind::Const, .. } => {
2860 ObligationCauseFailureCode::ConstCompat { span, subdiags }
2861 }
2862 BlockTailExpression(.., hir::MatchSource::TryDesugar(_)) => {
2863 ObligationCauseFailureCode::TryCompat { span, subdiags }
2864 }
2865 MatchExpressionArm(box MatchExpressionArmCause { source, .. }) => match source {
2866 hir::MatchSource::TryDesugar(_) => {
2867 ObligationCauseFailureCode::TryCompat { span, subdiags }
2868 }
2869 _ => ObligationCauseFailureCode::MatchCompat { span, subdiags },
2870 },
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 }
2878 }
2879 IntrinsicType => ObligationCauseFailureCode::IntrinsicCorrectType { span, subdiags },
2880 MethodReceiver => ObligationCauseFailureCode::MethodCorrectType { span, subdiags },
2881
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
2884 // tailor to that.
2885 _ => match terr {
2886 TypeError::CyclicTy(ty) if ty.is_closure() || ty.is_coroutine() => {
2887 ObligationCauseFailureCode::ClosureSelfref { span }
2888 }
2889 TypeError::IntrinsicCast => {
2890 ObligationCauseFailureCode::CantCoerce { span, subdiags }
2891 }
2892 _ => ObligationCauseFailureCode::Generic { span, subdiags },
2893 },
2894 }
2895 }
2896
2897 fn as_requirement_str(&self) -> &'static str {
2898 use crate::traits::ObligationCauseCode::*;
2899 match self.code() {
2900 CompareImplItemObligation { kind: ty::AssocKind::Fn, .. } => {
2901 "method type is compatible with trait"
2902 }
2903 CompareImplItemObligation { kind: ty::AssocKind::Type, .. } => {
2904 "associated type is compatible with trait"
2905 }
2906 CompareImplItemObligation { kind: ty::AssocKind::Const, .. } => {
2907 "const is compatible with trait"
2908 }
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",
2918 }
2919 }
2920 }
2921
2922 /// Newtype to allow implementing IntoDiagnosticArg
2923 pub struct ObligationCauseAsDiagArg<'tcx>(pub ObligationCause<'tcx>);
2924
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",
2940 _ => "other",
2941 }
2942 .into();
2943 rustc_errors::DiagnosticArgValue::Str(kind)
2944 }
2945 }
2946
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 {
2951 Closure,
2952 Opaque,
2953 OpaqueFuture,
2954 Coroutine(hir::CoroutineKind),
2955 Foreign,
2956 }
2957
2958 impl fmt::Display for TyCategory {
2959 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2960 match self {
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),
2966 }
2967 }
2968 }
2969
2970 impl TyCategory {
2971 pub fn from_ty(tcx: TyCtxt<'_>, ty: Ty<'_>) -> Option<(Self, DefId)> {
2972 match *ty.kind() {
2973 ty::Closure(def_id, _) => Some((Self::Closure, def_id)),
2974 ty::Alias(ty::Opaque, ty::AliasTy { def_id, .. }) => {
2975 let kind =
2976 if tcx.ty_is_opaque_future(ty) { Self::OpaqueFuture } else { Self::Opaque };
2977 Some((kind, def_id))
2978 }
2979 ty::Coroutine(def_id, ..) => {
2980 Some((Self::Coroutine(tcx.coroutine_kind(def_id).unwrap()), def_id))
2981 }
2982 ty::Foreign(def_id) => Some((Self::Foreign, def_id)),
2983 _ => None,
2984 }
2985 }
2986 }
2987
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 {
2994 expr.span
2995 } else if let Some(stmt) = block.stmts.last() {
2996 // possibly incorrect trailing `;` in the else arm
2997 stmt.span
2998 } else {
2999 // empty block; point at its entirety
3000 block.span
3001 }
3002 }
3003
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,
3013 }
3014 }
3015 }