]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_infer/src/infer/error_reporting/mod.rs
fix most compiler/ doctests
[rust.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::infer;
53 use crate::infer::error_reporting::nice_region_error::find_anon_type::find_anon_type;
54 use crate::traits::error_reporting::report_object_safety_error;
55 use crate::traits::{
56     IfExpressionCause, MatchExpressionArmCause, ObligationCause, ObligationCauseCode,
57     StatementAsExpression,
58 };
59
60 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
61 use rustc_errors::{pluralize, struct_span_err, Diagnostic, ErrorGuaranteed};
62 use rustc_errors::{Applicability, DiagnosticBuilder, DiagnosticStyledString, MultiSpan};
63 use rustc_hir as hir;
64 use rustc_hir::def_id::{DefId, LocalDefId};
65 use rustc_hir::lang_items::LangItem;
66 use rustc_hir::{Item, ItemKind, Node};
67 use rustc_middle::dep_graph::DepContext;
68 use rustc_middle::ty::print::with_no_trimmed_paths;
69 use rustc_middle::ty::{
70     self,
71     error::TypeError,
72     subst::{GenericArgKind, Subst, SubstsRef},
73     Binder, List, Region, Ty, TyCtxt, TypeFoldable,
74 };
75 use rustc_span::{sym, BytePos, DesugaringKind, Pos, Span};
76 use rustc_target::spec::abi;
77 use std::ops::ControlFlow;
78 use std::{cmp, fmt, iter};
79
80 mod note;
81
82 mod need_type_info;
83 pub use need_type_info::TypeAnnotationNeeded;
84
85 pub mod nice_region_error;
86
87 pub(super) fn note_and_explain_region<'tcx>(
88     tcx: TyCtxt<'tcx>,
89     err: &mut Diagnostic,
90     prefix: &str,
91     region: ty::Region<'tcx>,
92     suffix: &str,
93     alt_span: Option<Span>,
94 ) {
95     let (description, span) = match *region {
96         ty::ReEarlyBound(_) | ty::ReFree(_) | ty::ReStatic => {
97             msg_span_from_free_region(tcx, region, alt_span)
98         }
99
100         ty::ReEmpty(ty::UniverseIndex::ROOT) => ("the empty lifetime".to_owned(), alt_span),
101
102         // uh oh, hope no user ever sees THIS
103         ty::ReEmpty(ui) => (format!("the empty lifetime in universe {:?}", ui), alt_span),
104
105         ty::RePlaceholder(_) => return,
106
107         // FIXME(#13998) RePlaceholder should probably print like
108         // ReFree rather than dumping Debug output on the user.
109         //
110         // We shouldn't really be having unification failures with ReVar
111         // and ReLateBound though.
112         ty::ReVar(_) | ty::ReLateBound(..) | ty::ReErased => {
113             (format!("lifetime {:?}", region), alt_span)
114         }
115     };
116
117     emit_msg_span(err, prefix, description, span, suffix);
118 }
119
120 fn explain_free_region<'tcx>(
121     tcx: TyCtxt<'tcx>,
122     err: &mut Diagnostic,
123     prefix: &str,
124     region: ty::Region<'tcx>,
125     suffix: &str,
126 ) {
127     let (description, span) = msg_span_from_free_region(tcx, region, None);
128
129     label_msg_span(err, prefix, description, span, suffix);
130 }
131
132 fn msg_span_from_free_region<'tcx>(
133     tcx: TyCtxt<'tcx>,
134     region: ty::Region<'tcx>,
135     alt_span: Option<Span>,
136 ) -> (String, Option<Span>) {
137     match *region {
138         ty::ReEarlyBound(_) | ty::ReFree(_) => {
139             let (msg, span) = msg_span_from_early_bound_and_free_regions(tcx, region);
140             (msg, Some(span))
141         }
142         ty::ReStatic => ("the static lifetime".to_owned(), alt_span),
143         ty::ReEmpty(ty::UniverseIndex::ROOT) => ("an empty lifetime".to_owned(), alt_span),
144         ty::ReEmpty(ui) => (format!("an empty lifetime in universe {:?}", ui), alt_span),
145         _ => bug!("{:?}", region),
146     }
147 }
148
149 fn msg_span_from_early_bound_and_free_regions<'tcx>(
150     tcx: TyCtxt<'tcx>,
151     region: ty::Region<'tcx>,
152 ) -> (String, Span) {
153     let sm = tcx.sess.source_map();
154
155     let scope = region.free_region_binding_scope(tcx).expect_local();
156     match *region {
157         ty::ReEarlyBound(ref br) => {
158             let mut sp = sm.guess_head_span(tcx.def_span(scope));
159             if let Some(param) =
160                 tcx.hir().get_generics(scope).and_then(|generics| generics.get_named(br.name))
161             {
162                 sp = param.span;
163             }
164             (format!("the lifetime `{}` as defined here", br.name), sp)
165         }
166         ty::ReFree(ty::FreeRegion {
167             bound_region: ty::BoundRegionKind::BrNamed(_, name), ..
168         }) => {
169             let mut sp = sm.guess_head_span(tcx.def_span(scope));
170             if let Some(param) =
171                 tcx.hir().get_generics(scope).and_then(|generics| generics.get_named(name))
172             {
173                 sp = param.span;
174             }
175             (format!("the lifetime `{}` as defined here", name), sp)
176         }
177         ty::ReFree(ref fr) => match fr.bound_region {
178             ty::BrAnon(idx) => {
179                 if let Some((ty, _)) = find_anon_type(tcx, region, &fr.bound_region) {
180                     ("the anonymous lifetime defined here".to_string(), ty.span)
181                 } else {
182                     (
183                         format!("the anonymous lifetime #{} defined here", idx + 1),
184                         tcx.def_span(scope),
185                     )
186                 }
187             }
188             _ => (
189                 format!("the lifetime `{}` as defined here", region),
190                 sm.guess_head_span(tcx.def_span(scope)),
191             ),
192         },
193         _ => bug!(),
194     }
195 }
196
197 fn emit_msg_span(
198     err: &mut Diagnostic,
199     prefix: &str,
200     description: String,
201     span: Option<Span>,
202     suffix: &str,
203 ) {
204     let message = format!("{}{}{}", prefix, description, suffix);
205
206     if let Some(span) = span {
207         err.span_note(span, &message);
208     } else {
209         err.note(&message);
210     }
211 }
212
213 fn label_msg_span(
214     err: &mut Diagnostic,
215     prefix: &str,
216     description: String,
217     span: Option<Span>,
218     suffix: &str,
219 ) {
220     let message = format!("{}{}{}", prefix, description, suffix);
221
222     if let Some(span) = span {
223         err.span_label(span, &message);
224     } else {
225         err.note(&message);
226     }
227 }
228
229 pub fn unexpected_hidden_region_diagnostic<'tcx>(
230     tcx: TyCtxt<'tcx>,
231     span: Span,
232     hidden_ty: Ty<'tcx>,
233     hidden_region: ty::Region<'tcx>,
234 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
235     let mut err = struct_span_err!(
236         tcx.sess,
237         span,
238         E0700,
239         "hidden type for `impl Trait` captures lifetime that does not appear in bounds",
240     );
241
242     // Explain the region we are capturing.
243     match *hidden_region {
244         ty::ReEmpty(ty::UniverseIndex::ROOT) => {
245             // All lifetimes shorter than the function body are `empty` in
246             // lexical region resolution. The default explanation of "an empty
247             // lifetime" isn't really accurate here.
248             let message = format!(
249                 "hidden type `{}` captures lifetime smaller than the function body",
250                 hidden_ty
251             );
252             err.span_note(span, &message);
253         }
254         ty::ReEarlyBound(_) | ty::ReFree(_) | ty::ReStatic | ty::ReEmpty(_) => {
255             // Assuming regionck succeeded (*), we ought to always be
256             // capturing *some* region from the fn header, and hence it
257             // ought to be free. So under normal circumstances, we will go
258             // down this path which gives a decent human readable
259             // explanation.
260             //
261             // (*) if not, the `tainted_by_errors` field would be set to
262             // `Some(ErrorGuaranteed)` in any case, so we wouldn't be here at all.
263             explain_free_region(
264                 tcx,
265                 &mut err,
266                 &format!("hidden type `{}` captures ", hidden_ty),
267                 hidden_region,
268                 "",
269             );
270             if let Some(reg_info) = tcx.is_suitable_region(hidden_region) {
271                 let fn_returns = tcx.return_type_impl_or_dyn_traits(reg_info.def_id);
272                 nice_region_error::suggest_new_region_bound(
273                     tcx,
274                     &mut err,
275                     fn_returns,
276                     hidden_region.to_string(),
277                     None,
278                     format!("captures `{}`", hidden_region),
279                     None,
280                 )
281             }
282         }
283         _ => {
284             // Ugh. This is a painful case: the hidden region is not one
285             // that we can easily summarize or explain. This can happen
286             // in a case like
287             // `src/test/ui/multiple-lifetimes/ordinary-bounds-unsuited.rs`:
288             //
289             // ```
290             // fn upper_bounds<'a, 'b>(a: Ordinary<'a>, b: Ordinary<'b>) -> impl Trait<'a, 'b> {
291             //   if condition() { a } else { b }
292             // }
293             // ```
294             //
295             // Here the captured lifetime is the intersection of `'a` and
296             // `'b`, which we can't quite express.
297
298             // We can at least report a really cryptic error for now.
299             note_and_explain_region(
300                 tcx,
301                 &mut err,
302                 &format!("hidden type `{}` captures ", hidden_ty),
303                 hidden_region,
304                 "",
305                 None,
306             );
307         }
308     }
309
310     err
311 }
312
313 /// Structurally compares two types, modulo any inference variables.
314 ///
315 /// Returns `true` if two types are equal, or if one type is an inference variable compatible
316 /// with the other type. A TyVar inference type is compatible with any type, and an IntVar or
317 /// FloatVar inference type are compatible with themselves or their concrete types (Int and
318 /// Float types, respectively). When comparing two ADTs, these rules apply recursively.
319 pub fn same_type_modulo_infer<'tcx>(a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
320     match (&a.kind(), &b.kind()) {
321         (&ty::Adt(did_a, substs_a), &ty::Adt(did_b, substs_b)) => {
322             if did_a != did_b {
323                 return false;
324             }
325
326             substs_a.types().zip(substs_b.types()).all(|(a, b)| same_type_modulo_infer(a, b))
327         }
328         (&ty::Int(_), &ty::Infer(ty::InferTy::IntVar(_)))
329         | (&ty::Infer(ty::InferTy::IntVar(_)), &ty::Int(_) | &ty::Infer(ty::InferTy::IntVar(_)))
330         | (&ty::Float(_), &ty::Infer(ty::InferTy::FloatVar(_)))
331         | (
332             &ty::Infer(ty::InferTy::FloatVar(_)),
333             &ty::Float(_) | &ty::Infer(ty::InferTy::FloatVar(_)),
334         )
335         | (&ty::Infer(ty::InferTy::TyVar(_)), _)
336         | (_, &ty::Infer(ty::InferTy::TyVar(_))) => true,
337         (&ty::Ref(reg_a, ty_a, mut_a), &ty::Ref(reg_b, ty_b, mut_b)) => {
338             reg_a == reg_b && mut_a == mut_b && same_type_modulo_infer(*ty_a, *ty_b)
339         }
340         _ => a == b,
341     }
342 }
343
344 impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
345     pub fn report_region_errors(&self, errors: &Vec<RegionResolutionError<'tcx>>) {
346         debug!("report_region_errors(): {} errors to start", errors.len());
347
348         // try to pre-process the errors, which will group some of them
349         // together into a `ProcessedErrors` group:
350         let errors = self.process_errors(errors);
351
352         debug!("report_region_errors: {} errors after preprocessing", errors.len());
353
354         for error in errors {
355             debug!("report_region_errors: error = {:?}", error);
356
357             if !self.try_report_nice_region_error(&error) {
358                 match error.clone() {
359                     // These errors could indicate all manner of different
360                     // problems with many different solutions. Rather
361                     // than generate a "one size fits all" error, what we
362                     // attempt to do is go through a number of specific
363                     // scenarios and try to find the best way to present
364                     // the error. If all of these fails, we fall back to a rather
365                     // general bit of code that displays the error information
366                     RegionResolutionError::ConcreteFailure(origin, sub, sup) => {
367                         if sub.is_placeholder() || sup.is_placeholder() {
368                             self.report_placeholder_failure(origin, sub, sup).emit();
369                         } else {
370                             self.report_concrete_failure(origin, sub, sup).emit();
371                         }
372                     }
373
374                     RegionResolutionError::GenericBoundFailure(origin, param_ty, sub) => {
375                         self.report_generic_bound_failure(
376                             origin.span(),
377                             Some(origin),
378                             param_ty,
379                             sub,
380                         );
381                     }
382
383                     RegionResolutionError::SubSupConflict(
384                         _,
385                         var_origin,
386                         sub_origin,
387                         sub_r,
388                         sup_origin,
389                         sup_r,
390                         _,
391                     ) => {
392                         if sub_r.is_placeholder() {
393                             self.report_placeholder_failure(sub_origin, sub_r, sup_r).emit();
394                         } else if sup_r.is_placeholder() {
395                             self.report_placeholder_failure(sup_origin, sub_r, sup_r).emit();
396                         } else {
397                             self.report_sub_sup_conflict(
398                                 var_origin, sub_origin, sub_r, sup_origin, sup_r,
399                             );
400                         }
401                     }
402
403                     RegionResolutionError::UpperBoundUniverseConflict(
404                         _,
405                         _,
406                         var_universe,
407                         sup_origin,
408                         sup_r,
409                     ) => {
410                         assert!(sup_r.is_placeholder());
411
412                         // Make a dummy value for the "sub region" --
413                         // this is the initial value of the
414                         // placeholder. In practice, we expect more
415                         // tailored errors that don't really use this
416                         // value.
417                         let sub_r = self.tcx.mk_region(ty::ReEmpty(var_universe));
418
419                         self.report_placeholder_failure(sup_origin, sub_r, sup_r).emit();
420                     }
421                 }
422             }
423         }
424     }
425
426     // This method goes through all the errors and try to group certain types
427     // of error together, for the purpose of suggesting explicit lifetime
428     // parameters to the user. This is done so that we can have a more
429     // complete view of what lifetimes should be the same.
430     // If the return value is an empty vector, it means that processing
431     // failed (so the return value of this method should not be used).
432     //
433     // The method also attempts to weed out messages that seem like
434     // duplicates that will be unhelpful to the end-user. But
435     // obviously it never weeds out ALL errors.
436     fn process_errors(
437         &self,
438         errors: &[RegionResolutionError<'tcx>],
439     ) -> Vec<RegionResolutionError<'tcx>> {
440         debug!("process_errors()");
441
442         // We want to avoid reporting generic-bound failures if we can
443         // avoid it: these have a very high rate of being unhelpful in
444         // practice. This is because they are basically secondary
445         // checks that test the state of the region graph after the
446         // rest of inference is done, and the other kinds of errors
447         // indicate that the region constraint graph is internally
448         // inconsistent, so these test results are likely to be
449         // meaningless.
450         //
451         // Therefore, we filter them out of the list unless they are
452         // the only thing in the list.
453
454         let is_bound_failure = |e: &RegionResolutionError<'tcx>| match *e {
455             RegionResolutionError::GenericBoundFailure(..) => true,
456             RegionResolutionError::ConcreteFailure(..)
457             | RegionResolutionError::SubSupConflict(..)
458             | RegionResolutionError::UpperBoundUniverseConflict(..) => false,
459         };
460
461         let mut errors = if errors.iter().all(|e| is_bound_failure(e)) {
462             errors.to_owned()
463         } else {
464             errors.iter().filter(|&e| !is_bound_failure(e)).cloned().collect()
465         };
466
467         // sort the errors by span, for better error message stability.
468         errors.sort_by_key(|u| match *u {
469             RegionResolutionError::ConcreteFailure(ref sro, _, _) => sro.span(),
470             RegionResolutionError::GenericBoundFailure(ref sro, _, _) => sro.span(),
471             RegionResolutionError::SubSupConflict(_, ref rvo, _, _, _, _, _) => rvo.span(),
472             RegionResolutionError::UpperBoundUniverseConflict(_, ref rvo, _, _, _) => rvo.span(),
473         });
474         errors
475     }
476
477     /// Adds a note if the types come from similarly named crates
478     fn check_and_note_conflicting_crates(&self, err: &mut Diagnostic, terr: &TypeError<'tcx>) {
479         use hir::def_id::CrateNum;
480         use rustc_hir::definitions::DisambiguatedDefPathData;
481         use ty::print::Printer;
482         use ty::subst::GenericArg;
483
484         struct AbsolutePathPrinter<'tcx> {
485             tcx: TyCtxt<'tcx>,
486         }
487
488         struct NonTrivialPath;
489
490         impl<'tcx> Printer<'tcx> for AbsolutePathPrinter<'tcx> {
491             type Error = NonTrivialPath;
492
493             type Path = Vec<String>;
494             type Region = !;
495             type Type = !;
496             type DynExistential = !;
497             type Const = !;
498
499             fn tcx<'a>(&'a self) -> TyCtxt<'tcx> {
500                 self.tcx
501             }
502
503             fn print_region(self, _region: ty::Region<'_>) -> Result<Self::Region, Self::Error> {
504                 Err(NonTrivialPath)
505             }
506
507             fn print_type(self, _ty: Ty<'tcx>) -> Result<Self::Type, Self::Error> {
508                 Err(NonTrivialPath)
509             }
510
511             fn print_dyn_existential(
512                 self,
513                 _predicates: &'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>,
514             ) -> Result<Self::DynExistential, Self::Error> {
515                 Err(NonTrivialPath)
516             }
517
518             fn print_const(self, _ct: ty::Const<'tcx>) -> Result<Self::Const, Self::Error> {
519                 Err(NonTrivialPath)
520             }
521
522             fn path_crate(self, cnum: CrateNum) -> Result<Self::Path, Self::Error> {
523                 Ok(vec![self.tcx.crate_name(cnum).to_string()])
524             }
525             fn path_qualified(
526                 self,
527                 _self_ty: Ty<'tcx>,
528                 _trait_ref: Option<ty::TraitRef<'tcx>>,
529             ) -> Result<Self::Path, Self::Error> {
530                 Err(NonTrivialPath)
531             }
532
533             fn path_append_impl(
534                 self,
535                 _print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
536                 _disambiguated_data: &DisambiguatedDefPathData,
537                 _self_ty: Ty<'tcx>,
538                 _trait_ref: Option<ty::TraitRef<'tcx>>,
539             ) -> Result<Self::Path, Self::Error> {
540                 Err(NonTrivialPath)
541             }
542             fn path_append(
543                 self,
544                 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
545                 disambiguated_data: &DisambiguatedDefPathData,
546             ) -> Result<Self::Path, Self::Error> {
547                 let mut path = print_prefix(self)?;
548                 path.push(disambiguated_data.to_string());
549                 Ok(path)
550             }
551             fn path_generic_args(
552                 self,
553                 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
554                 _args: &[GenericArg<'tcx>],
555             ) -> Result<Self::Path, Self::Error> {
556                 print_prefix(self)
557             }
558         }
559
560         let report_path_match = |err: &mut Diagnostic, did1: DefId, did2: DefId| {
561             // Only external crates, if either is from a local
562             // module we could have false positives
563             if !(did1.is_local() || did2.is_local()) && did1.krate != did2.krate {
564                 let abs_path =
565                     |def_id| AbsolutePathPrinter { tcx: self.tcx }.print_def_path(def_id, &[]);
566
567                 // We compare strings because DefPath can be different
568                 // for imported and non-imported crates
569                 let same_path = || -> Result<_, NonTrivialPath> {
570                     Ok(self.tcx.def_path_str(did1) == self.tcx.def_path_str(did2)
571                         || abs_path(did1)? == abs_path(did2)?)
572                 };
573                 if same_path().unwrap_or(false) {
574                     let crate_name = self.tcx.crate_name(did1.krate);
575                     err.note(&format!(
576                         "perhaps two different versions of crate `{}` are being used?",
577                         crate_name
578                     ));
579                 }
580             }
581         };
582         match *terr {
583             TypeError::Sorts(ref exp_found) => {
584                 // if they are both "path types", there's a chance of ambiguity
585                 // due to different versions of the same crate
586                 if let (&ty::Adt(exp_adt, _), &ty::Adt(found_adt, _)) =
587                     (exp_found.expected.kind(), exp_found.found.kind())
588                 {
589                     report_path_match(err, exp_adt.did(), found_adt.did());
590                 }
591             }
592             TypeError::Traits(ref exp_found) => {
593                 report_path_match(err, exp_found.expected, exp_found.found);
594             }
595             _ => (), // FIXME(#22750) handle traits and stuff
596         }
597     }
598
599     fn note_error_origin(
600         &self,
601         err: &mut Diagnostic,
602         cause: &ObligationCause<'tcx>,
603         exp_found: Option<ty::error::ExpectedFound<Ty<'tcx>>>,
604         terr: &TypeError<'tcx>,
605     ) {
606         match *cause.code() {
607             ObligationCauseCode::Pattern { origin_expr: true, span: Some(span), root_ty } => {
608                 let ty = self.resolve_vars_if_possible(root_ty);
609                 if !matches!(ty.kind(), ty::Infer(ty::InferTy::TyVar(_) | ty::InferTy::FreshTy(_)))
610                 {
611                     // don't show type `_`
612                     err.span_label(span, format!("this expression has type `{}`", ty));
613                 }
614                 if let Some(ty::error::ExpectedFound { found, .. }) = exp_found
615                     && ty.is_box() && ty.boxed_ty() == found
616                     && let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span)
617                 {
618                     err.span_suggestion(
619                         span,
620                         "consider dereferencing the boxed value",
621                         format!("*{}", snippet),
622                         Applicability::MachineApplicable,
623                     );
624                 }
625             }
626             ObligationCauseCode::Pattern { origin_expr: false, span: Some(span), .. } => {
627                 err.span_label(span, "expected due to this");
628             }
629             ObligationCauseCode::MatchExpressionArm(box MatchExpressionArmCause {
630                 semi_span,
631                 source,
632                 ref prior_arms,
633                 last_ty,
634                 scrut_hir_id,
635                 opt_suggest_box_span,
636                 arm_span,
637                 scrut_span,
638                 ..
639             }) => match source {
640                 hir::MatchSource::TryDesugar => {
641                     if let Some(ty::error::ExpectedFound { expected, .. }) = exp_found {
642                         let scrut_expr = self.tcx.hir().expect_expr(scrut_hir_id);
643                         let scrut_ty = if let hir::ExprKind::Call(_, args) = &scrut_expr.kind {
644                             let arg_expr = args.first().expect("try desugaring call w/out arg");
645                             self.in_progress_typeck_results.and_then(|typeck_results| {
646                                 typeck_results.borrow().expr_ty_opt(arg_expr)
647                             })
648                         } else {
649                             bug!("try desugaring w/out call expr as scrutinee");
650                         };
651
652                         match scrut_ty {
653                             Some(ty) if expected == ty => {
654                                 let source_map = self.tcx.sess.source_map();
655                                 err.span_suggestion(
656                                     source_map.end_point(cause.span),
657                                     "try removing this `?`",
658                                     "".to_string(),
659                                     Applicability::MachineApplicable,
660                                 );
661                             }
662                             _ => {}
663                         }
664                     }
665                 }
666                 _ => {
667                     // `last_ty` can be `!`, `expected` will have better info when present.
668                     let t = self.resolve_vars_if_possible(match exp_found {
669                         Some(ty::error::ExpectedFound { expected, .. }) => expected,
670                         _ => last_ty,
671                     });
672                     let source_map = self.tcx.sess.source_map();
673                     let mut any_multiline_arm = source_map.is_multiline(arm_span);
674                     if prior_arms.len() <= 4 {
675                         for sp in prior_arms {
676                             any_multiline_arm |= source_map.is_multiline(*sp);
677                             err.span_label(*sp, format!("this is found to be of type `{}`", t));
678                         }
679                     } else if let Some(sp) = prior_arms.last() {
680                         any_multiline_arm |= source_map.is_multiline(*sp);
681                         err.span_label(
682                             *sp,
683                             format!("this and all prior arms are found to be of type `{}`", t),
684                         );
685                     }
686                     let outer_error_span = if any_multiline_arm {
687                         // Cover just `match` and the scrutinee expression, not
688                         // the entire match body, to reduce diagram noise.
689                         cause.span.shrink_to_lo().to(scrut_span)
690                     } else {
691                         cause.span
692                     };
693                     let msg = "`match` arms have incompatible types";
694                     err.span_label(outer_error_span, msg);
695                     if let Some((sp, boxed)) = semi_span {
696                         if let (StatementAsExpression::NeedsBoxing, [.., prior_arm]) =
697                             (boxed, &prior_arms[..])
698                         {
699                             err.multipart_suggestion(
700                                 "consider removing this semicolon and boxing the expressions",
701                                 vec![
702                                     (prior_arm.shrink_to_lo(), "Box::new(".to_string()),
703                                     (prior_arm.shrink_to_hi(), ")".to_string()),
704                                     (arm_span.shrink_to_lo(), "Box::new(".to_string()),
705                                     (arm_span.shrink_to_hi(), ")".to_string()),
706                                     (sp, String::new()),
707                                 ],
708                                 Applicability::HasPlaceholders,
709                             );
710                         } else if matches!(boxed, StatementAsExpression::NeedsBoxing) {
711                             err.span_suggestion_short(
712                                 sp,
713                                 "consider removing this semicolon and boxing the expressions",
714                                 String::new(),
715                                 Applicability::MachineApplicable,
716                             );
717                         } else {
718                             err.span_suggestion_short(
719                                 sp,
720                                 "consider removing this semicolon",
721                                 String::new(),
722                                 Applicability::MachineApplicable,
723                             );
724                         }
725                     }
726                     if let Some(ret_sp) = opt_suggest_box_span {
727                         // Get return type span and point to it.
728                         self.suggest_boxing_for_return_impl_trait(
729                             err,
730                             ret_sp,
731                             prior_arms.iter().chain(std::iter::once(&arm_span)).map(|s| *s),
732                         );
733                     }
734                 }
735             },
736             ObligationCauseCode::IfExpression(box IfExpressionCause {
737                 then,
738                 else_sp,
739                 outer,
740                 semicolon,
741                 opt_suggest_box_span,
742             }) => {
743                 err.span_label(then, "expected because of this");
744                 if let Some(sp) = outer {
745                     err.span_label(sp, "`if` and `else` have incompatible types");
746                 }
747                 if let Some((sp, boxed)) = semicolon {
748                     if matches!(boxed, StatementAsExpression::NeedsBoxing) {
749                         err.multipart_suggestion(
750                             "consider removing this semicolon and boxing the expression",
751                             vec![
752                                 (then.shrink_to_lo(), "Box::new(".to_string()),
753                                 (then.shrink_to_hi(), ")".to_string()),
754                                 (else_sp.shrink_to_lo(), "Box::new(".to_string()),
755                                 (else_sp.shrink_to_hi(), ")".to_string()),
756                                 (sp, String::new()),
757                             ],
758                             Applicability::MachineApplicable,
759                         );
760                     } else {
761                         err.span_suggestion_short(
762                             sp,
763                             "consider removing this semicolon",
764                             String::new(),
765                             Applicability::MachineApplicable,
766                         );
767                     }
768                 }
769                 if let Some(ret_sp) = opt_suggest_box_span {
770                     self.suggest_boxing_for_return_impl_trait(
771                         err,
772                         ret_sp,
773                         [then, else_sp].into_iter(),
774                     );
775                 }
776             }
777             ObligationCauseCode::LetElse => {
778                 err.help("try adding a diverging expression, such as `return` or `panic!(..)`");
779                 err.help("...or use `match` instead of `let...else`");
780             }
781             _ => {
782                 if let ObligationCauseCode::BindingObligation(_, binding_span) =
783                     cause.code().peel_derives()
784                 {
785                     if matches!(terr, TypeError::RegionsPlaceholderMismatch) {
786                         err.span_note(*binding_span, "the lifetime requirement is introduced here");
787                     }
788                 }
789             }
790         }
791     }
792
793     fn suggest_boxing_for_return_impl_trait(
794         &self,
795         err: &mut Diagnostic,
796         return_sp: Span,
797         arm_spans: impl Iterator<Item = Span>,
798     ) {
799         err.multipart_suggestion(
800             "you could change the return type to be a boxed trait object",
801             vec![
802                 (return_sp.with_hi(return_sp.lo() + BytePos(4)), "Box<dyn".to_string()),
803                 (return_sp.shrink_to_hi(), ">".to_string()),
804             ],
805             Applicability::MaybeIncorrect,
806         );
807         let sugg = arm_spans
808             .flat_map(|sp| {
809                 [(sp.shrink_to_lo(), "Box::new(".to_string()), (sp.shrink_to_hi(), ")".to_string())]
810                     .into_iter()
811             })
812             .collect::<Vec<_>>();
813         err.multipart_suggestion(
814             "if you change the return type to expect trait objects, box the returned expressions",
815             sugg,
816             Applicability::MaybeIncorrect,
817         );
818     }
819
820     /// Given that `other_ty` is the same as a type argument for `name` in `sub`, populate `value`
821     /// highlighting `name` and every type argument that isn't at `pos` (which is `other_ty`), and
822     /// populate `other_value` with `other_ty`.
823     ///
824     /// ```text
825     /// Foo<Bar<Qux>>
826     /// ^^^^--------^ this is highlighted
827     /// |   |
828     /// |   this type argument is exactly the same as the other type, not highlighted
829     /// this is highlighted
830     /// Bar<Qux>
831     /// -------- this type is the same as a type argument in the other type, not highlighted
832     /// ```
833     fn highlight_outer(
834         &self,
835         value: &mut DiagnosticStyledString,
836         other_value: &mut DiagnosticStyledString,
837         name: String,
838         sub: ty::subst::SubstsRef<'tcx>,
839         pos: usize,
840         other_ty: Ty<'tcx>,
841     ) {
842         // `value` and `other_value` hold two incomplete type representation for display.
843         // `name` is the path of both types being compared. `sub`
844         value.push_highlighted(name);
845         let len = sub.len();
846         if len > 0 {
847             value.push_highlighted("<");
848         }
849
850         // Output the lifetimes for the first type
851         let lifetimes = sub
852             .regions()
853             .map(|lifetime| {
854                 let s = lifetime.to_string();
855                 if s.is_empty() { "'_".to_string() } else { s }
856             })
857             .collect::<Vec<_>>()
858             .join(", ");
859         if !lifetimes.is_empty() {
860             if sub.regions().count() < len {
861                 value.push_normal(lifetimes + ", ");
862             } else {
863                 value.push_normal(lifetimes);
864             }
865         }
866
867         // Highlight all the type arguments that aren't at `pos` and compare the type argument at
868         // `pos` and `other_ty`.
869         for (i, type_arg) in sub.types().enumerate() {
870             if i == pos {
871                 let values = self.cmp(type_arg, other_ty);
872                 value.0.extend((values.0).0);
873                 other_value.0.extend((values.1).0);
874             } else {
875                 value.push_highlighted(type_arg.to_string());
876             }
877
878             if len > 0 && i != len - 1 {
879                 value.push_normal(", ");
880             }
881         }
882         if len > 0 {
883             value.push_highlighted(">");
884         }
885     }
886
887     /// If `other_ty` is the same as a type argument present in `sub`, highlight `path` in `t1_out`,
888     /// as that is the difference to the other type.
889     ///
890     /// For the following code:
891     ///
892     /// ```ignore (illustrative)
893     /// let x: Foo<Bar<Qux>> = foo::<Bar<Qux>>();
894     /// ```
895     ///
896     /// The type error output will behave in the following way:
897     ///
898     /// ```text
899     /// Foo<Bar<Qux>>
900     /// ^^^^--------^ this is highlighted
901     /// |   |
902     /// |   this type argument is exactly the same as the other type, not highlighted
903     /// this is highlighted
904     /// Bar<Qux>
905     /// -------- this type is the same as a type argument in the other type, not highlighted
906     /// ```
907     fn cmp_type_arg(
908         &self,
909         mut t1_out: &mut DiagnosticStyledString,
910         mut t2_out: &mut DiagnosticStyledString,
911         path: String,
912         sub: ty::subst::SubstsRef<'tcx>,
913         other_path: String,
914         other_ty: Ty<'tcx>,
915     ) -> Option<()> {
916         for (i, ta) in sub.types().enumerate() {
917             if ta == other_ty {
918                 self.highlight_outer(&mut t1_out, &mut t2_out, path, sub, i, other_ty);
919                 return Some(());
920             }
921             if let ty::Adt(def, _) = ta.kind() {
922                 let path_ = self.tcx.def_path_str(def.did());
923                 if path_ == other_path {
924                     self.highlight_outer(&mut t1_out, &mut t2_out, path, sub, i, other_ty);
925                     return Some(());
926                 }
927             }
928         }
929         None
930     }
931
932     /// Adds a `,` to the type representation only if it is appropriate.
933     fn push_comma(
934         &self,
935         value: &mut DiagnosticStyledString,
936         other_value: &mut DiagnosticStyledString,
937         len: usize,
938         pos: usize,
939     ) {
940         if len > 0 && pos != len - 1 {
941             value.push_normal(", ");
942             other_value.push_normal(", ");
943         }
944     }
945
946     /// For generic types with parameters with defaults, remove the parameters corresponding to
947     /// the defaults. This repeats a lot of the logic found in `ty::print::pretty`.
948     fn strip_generic_default_params(
949         &self,
950         def_id: DefId,
951         substs: ty::subst::SubstsRef<'tcx>,
952     ) -> SubstsRef<'tcx> {
953         let generics = self.tcx.generics_of(def_id);
954         let mut num_supplied_defaults = 0;
955
956         let default_params = generics.params.iter().rev().filter_map(|param| match param.kind {
957             ty::GenericParamDefKind::Type { has_default: true, .. } => Some(param.def_id),
958             ty::GenericParamDefKind::Const { has_default: true } => Some(param.def_id),
959             _ => None,
960         });
961         for (def_id, actual) in iter::zip(default_params, substs.iter().rev()) {
962             match actual.unpack() {
963                 GenericArgKind::Const(c) => {
964                     if self.tcx.const_param_default(def_id).subst(self.tcx, substs) != c {
965                         break;
966                     }
967                 }
968                 GenericArgKind::Type(ty) => {
969                     if self.tcx.type_of(def_id).subst(self.tcx, substs) != ty {
970                         break;
971                     }
972                 }
973                 _ => break,
974             }
975             num_supplied_defaults += 1;
976         }
977         let len = generics.params.len();
978         let mut generics = generics.clone();
979         generics.params.truncate(len - num_supplied_defaults);
980         substs.truncate_to(self.tcx, &generics)
981     }
982
983     /// Given two `fn` signatures highlight only sub-parts that are different.
984     fn cmp_fn_sig(
985         &self,
986         sig1: &ty::PolyFnSig<'tcx>,
987         sig2: &ty::PolyFnSig<'tcx>,
988     ) -> (DiagnosticStyledString, DiagnosticStyledString) {
989         let get_lifetimes = |sig| {
990             use rustc_hir::def::Namespace;
991             let (_, sig, reg) = ty::print::FmtPrinter::new(self.tcx, Namespace::TypeNS)
992                 .name_all_regions(sig)
993                 .unwrap();
994             let lts: Vec<String> = reg.into_iter().map(|(_, kind)| kind.to_string()).collect();
995             (if lts.is_empty() { String::new() } else { format!("for<{}> ", lts.join(", ")) }, sig)
996         };
997
998         let (lt1, sig1) = get_lifetimes(sig1);
999         let (lt2, sig2) = get_lifetimes(sig2);
1000
1001         // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
1002         let mut values = (
1003             DiagnosticStyledString::normal("".to_string()),
1004             DiagnosticStyledString::normal("".to_string()),
1005         );
1006
1007         // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
1008         // ^^^^^^
1009         values.0.push(sig1.unsafety.prefix_str(), sig1.unsafety != sig2.unsafety);
1010         values.1.push(sig2.unsafety.prefix_str(), sig1.unsafety != sig2.unsafety);
1011
1012         // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
1013         //        ^^^^^^^^^^
1014         if sig1.abi != abi::Abi::Rust {
1015             values.0.push(format!("extern {} ", sig1.abi), sig1.abi != sig2.abi);
1016         }
1017         if sig2.abi != abi::Abi::Rust {
1018             values.1.push(format!("extern {} ", sig2.abi), sig1.abi != sig2.abi);
1019         }
1020
1021         // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
1022         //                   ^^^^^^^^
1023         let lifetime_diff = lt1 != lt2;
1024         values.0.push(lt1, lifetime_diff);
1025         values.1.push(lt2, lifetime_diff);
1026
1027         // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
1028         //                           ^^^
1029         values.0.push_normal("fn(");
1030         values.1.push_normal("fn(");
1031
1032         // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
1033         //                              ^^^^^
1034         let len1 = sig1.inputs().len();
1035         let len2 = sig2.inputs().len();
1036         if len1 == len2 {
1037             for (i, (l, r)) in iter::zip(sig1.inputs(), sig2.inputs()).enumerate() {
1038                 let (x1, x2) = self.cmp(*l, *r);
1039                 (values.0).0.extend(x1.0);
1040                 (values.1).0.extend(x2.0);
1041                 self.push_comma(&mut values.0, &mut values.1, len1, i);
1042             }
1043         } else {
1044             for (i, l) in sig1.inputs().iter().enumerate() {
1045                 values.0.push_highlighted(l.to_string());
1046                 if i != len1 - 1 {
1047                     values.0.push_highlighted(", ");
1048                 }
1049             }
1050             for (i, r) in sig2.inputs().iter().enumerate() {
1051                 values.1.push_highlighted(r.to_string());
1052                 if i != len2 - 1 {
1053                     values.1.push_highlighted(", ");
1054                 }
1055             }
1056         }
1057
1058         if sig1.c_variadic {
1059             if len1 > 0 {
1060                 values.0.push_normal(", ");
1061             }
1062             values.0.push("...", !sig2.c_variadic);
1063         }
1064         if sig2.c_variadic {
1065             if len2 > 0 {
1066                 values.1.push_normal(", ");
1067             }
1068             values.1.push("...", !sig1.c_variadic);
1069         }
1070
1071         // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
1072         //                                   ^
1073         values.0.push_normal(")");
1074         values.1.push_normal(")");
1075
1076         // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
1077         //                                     ^^^^^^^^
1078         let output1 = sig1.output();
1079         let output2 = sig2.output();
1080         let (x1, x2) = self.cmp(output1, output2);
1081         if !output1.is_unit() {
1082             values.0.push_normal(" -> ");
1083             (values.0).0.extend(x1.0);
1084         }
1085         if !output2.is_unit() {
1086             values.1.push_normal(" -> ");
1087             (values.1).0.extend(x2.0);
1088         }
1089         values
1090     }
1091
1092     /// Compares two given types, eliding parts that are the same between them and highlighting
1093     /// relevant differences, and return two representation of those types for highlighted printing.
1094     pub fn cmp(
1095         &self,
1096         t1: Ty<'tcx>,
1097         t2: Ty<'tcx>,
1098     ) -> (DiagnosticStyledString, DiagnosticStyledString) {
1099         debug!("cmp(t1={}, t1.kind={:?}, t2={}, t2.kind={:?})", t1, t1.kind(), t2, t2.kind());
1100
1101         // helper functions
1102         fn equals<'tcx>(a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
1103             match (a.kind(), b.kind()) {
1104                 (a, b) if *a == *b => true,
1105                 (&ty::Int(_), &ty::Infer(ty::InferTy::IntVar(_)))
1106                 | (
1107                     &ty::Infer(ty::InferTy::IntVar(_)),
1108                     &ty::Int(_) | &ty::Infer(ty::InferTy::IntVar(_)),
1109                 )
1110                 | (&ty::Float(_), &ty::Infer(ty::InferTy::FloatVar(_)))
1111                 | (
1112                     &ty::Infer(ty::InferTy::FloatVar(_)),
1113                     &ty::Float(_) | &ty::Infer(ty::InferTy::FloatVar(_)),
1114                 ) => true,
1115                 _ => false,
1116             }
1117         }
1118
1119         fn push_ty_ref<'tcx>(
1120             region: ty::Region<'tcx>,
1121             ty: Ty<'tcx>,
1122             mutbl: hir::Mutability,
1123             s: &mut DiagnosticStyledString,
1124         ) {
1125             let mut r = region.to_string();
1126             if r == "'_" {
1127                 r.clear();
1128             } else {
1129                 r.push(' ');
1130             }
1131             s.push_highlighted(format!("&{}{}", r, mutbl.prefix_str()));
1132             s.push_normal(ty.to_string());
1133         }
1134
1135         // process starts here
1136         match (t1.kind(), t2.kind()) {
1137             (&ty::Adt(def1, sub1), &ty::Adt(def2, sub2)) => {
1138                 let did1 = def1.did();
1139                 let did2 = def2.did();
1140                 let sub_no_defaults_1 = self.strip_generic_default_params(did1, sub1);
1141                 let sub_no_defaults_2 = self.strip_generic_default_params(did2, sub2);
1142                 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
1143                 let path1 = self.tcx.def_path_str(did1);
1144                 let path2 = self.tcx.def_path_str(did2);
1145                 if did1 == did2 {
1146                     // Easy case. Replace same types with `_` to shorten the output and highlight
1147                     // the differing ones.
1148                     //     let x: Foo<Bar, Qux> = y::<Foo<Quz, Qux>>();
1149                     //     Foo<Bar, _>
1150                     //     Foo<Quz, _>
1151                     //         ---  ^ type argument elided
1152                     //         |
1153                     //         highlighted in output
1154                     values.0.push_normal(path1);
1155                     values.1.push_normal(path2);
1156
1157                     // Avoid printing out default generic parameters that are common to both
1158                     // types.
1159                     let len1 = sub_no_defaults_1.len();
1160                     let len2 = sub_no_defaults_2.len();
1161                     let common_len = cmp::min(len1, len2);
1162                     let remainder1: Vec<_> = sub1.types().skip(common_len).collect();
1163                     let remainder2: Vec<_> = sub2.types().skip(common_len).collect();
1164                     let common_default_params =
1165                         iter::zip(remainder1.iter().rev(), remainder2.iter().rev())
1166                             .filter(|(a, b)| a == b)
1167                             .count();
1168                     let len = sub1.len() - common_default_params;
1169                     let consts_offset = len - sub1.consts().count();
1170
1171                     // Only draw `<...>` if there are lifetime/type arguments.
1172                     if len > 0 {
1173                         values.0.push_normal("<");
1174                         values.1.push_normal("<");
1175                     }
1176
1177                     fn lifetime_display(lifetime: Region<'_>) -> String {
1178                         let s = lifetime.to_string();
1179                         if s.is_empty() { "'_".to_string() } else { s }
1180                     }
1181                     // At one point we'd like to elide all lifetimes here, they are irrelevant for
1182                     // all diagnostics that use this output
1183                     //
1184                     //     Foo<'x, '_, Bar>
1185                     //     Foo<'y, '_, Qux>
1186                     //         ^^  ^^  --- type arguments are not elided
1187                     //         |   |
1188                     //         |   elided as they were the same
1189                     //         not elided, they were different, but irrelevant
1190                     //
1191                     // For bound lifetimes, keep the names of the lifetimes,
1192                     // even if they are the same so that it's clear what's happening
1193                     // if we have something like
1194                     //
1195                     // for<'r, 's> fn(Inv<'r>, Inv<'s>)
1196                     // for<'r> fn(Inv<'r>, Inv<'r>)
1197                     let lifetimes = sub1.regions().zip(sub2.regions());
1198                     for (i, lifetimes) in lifetimes.enumerate() {
1199                         let l1 = lifetime_display(lifetimes.0);
1200                         let l2 = lifetime_display(lifetimes.1);
1201                         if lifetimes.0 != lifetimes.1 {
1202                             values.0.push_highlighted(l1);
1203                             values.1.push_highlighted(l2);
1204                         } else if lifetimes.0.is_late_bound() {
1205                             values.0.push_normal(l1);
1206                             values.1.push_normal(l2);
1207                         } else {
1208                             values.0.push_normal("'_");
1209                             values.1.push_normal("'_");
1210                         }
1211                         self.push_comma(&mut values.0, &mut values.1, len, i);
1212                     }
1213
1214                     // We're comparing two types with the same path, so we compare the type
1215                     // arguments for both. If they are the same, do not highlight and elide from the
1216                     // output.
1217                     //     Foo<_, Bar>
1218                     //     Foo<_, Qux>
1219                     //         ^ elided type as this type argument was the same in both sides
1220                     let type_arguments = sub1.types().zip(sub2.types());
1221                     let regions_len = sub1.regions().count();
1222                     let num_display_types = consts_offset - regions_len;
1223                     for (i, (ta1, ta2)) in type_arguments.take(num_display_types).enumerate() {
1224                         let i = i + regions_len;
1225                         if ta1 == ta2 {
1226                             values.0.push_normal("_");
1227                             values.1.push_normal("_");
1228                         } else {
1229                             let (x1, x2) = self.cmp(ta1, ta2);
1230                             (values.0).0.extend(x1.0);
1231                             (values.1).0.extend(x2.0);
1232                         }
1233                         self.push_comma(&mut values.0, &mut values.1, len, i);
1234                     }
1235
1236                     // Do the same for const arguments, if they are equal, do not highlight and
1237                     // elide them from the output.
1238                     let const_arguments = sub1.consts().zip(sub2.consts());
1239                     for (i, (ca1, ca2)) in const_arguments.enumerate() {
1240                         let i = i + consts_offset;
1241                         if ca1 == ca2 {
1242                             values.0.push_normal("_");
1243                             values.1.push_normal("_");
1244                         } else {
1245                             values.0.push_highlighted(ca1.to_string());
1246                             values.1.push_highlighted(ca2.to_string());
1247                         }
1248                         self.push_comma(&mut values.0, &mut values.1, len, i);
1249                     }
1250
1251                     // Close the type argument bracket.
1252                     // Only draw `<...>` if there are lifetime/type arguments.
1253                     if len > 0 {
1254                         values.0.push_normal(">");
1255                         values.1.push_normal(">");
1256                     }
1257                     values
1258                 } else {
1259                     // Check for case:
1260                     //     let x: Foo<Bar<Qux> = foo::<Bar<Qux>>();
1261                     //     Foo<Bar<Qux>
1262                     //         ------- this type argument is exactly the same as the other type
1263                     //     Bar<Qux>
1264                     if self
1265                         .cmp_type_arg(
1266                             &mut values.0,
1267                             &mut values.1,
1268                             path1.clone(),
1269                             sub_no_defaults_1,
1270                             path2.clone(),
1271                             t2,
1272                         )
1273                         .is_some()
1274                     {
1275                         return values;
1276                     }
1277                     // Check for case:
1278                     //     let x: Bar<Qux> = y:<Foo<Bar<Qux>>>();
1279                     //     Bar<Qux>
1280                     //     Foo<Bar<Qux>>
1281                     //         ------- this type argument is exactly the same as the other type
1282                     if self
1283                         .cmp_type_arg(
1284                             &mut values.1,
1285                             &mut values.0,
1286                             path2,
1287                             sub_no_defaults_2,
1288                             path1,
1289                             t1,
1290                         )
1291                         .is_some()
1292                     {
1293                         return values;
1294                     }
1295
1296                     // We can't find anything in common, highlight relevant part of type path.
1297                     //     let x: foo::bar::Baz<Qux> = y:<foo::bar::Bar<Zar>>();
1298                     //     foo::bar::Baz<Qux>
1299                     //     foo::bar::Bar<Zar>
1300                     //               -------- this part of the path is different
1301
1302                     let t1_str = t1.to_string();
1303                     let t2_str = t2.to_string();
1304                     let min_len = t1_str.len().min(t2_str.len());
1305
1306                     const SEPARATOR: &str = "::";
1307                     let separator_len = SEPARATOR.len();
1308                     let split_idx: usize =
1309                         iter::zip(t1_str.split(SEPARATOR), t2_str.split(SEPARATOR))
1310                             .take_while(|(mod1_str, mod2_str)| mod1_str == mod2_str)
1311                             .map(|(mod_str, _)| mod_str.len() + separator_len)
1312                             .sum();
1313
1314                     debug!(
1315                         "cmp: separator_len={}, split_idx={}, min_len={}",
1316                         separator_len, split_idx, min_len
1317                     );
1318
1319                     if split_idx >= min_len {
1320                         // paths are identical, highlight everything
1321                         (
1322                             DiagnosticStyledString::highlighted(t1_str),
1323                             DiagnosticStyledString::highlighted(t2_str),
1324                         )
1325                     } else {
1326                         let (common, uniq1) = t1_str.split_at(split_idx);
1327                         let (_, uniq2) = t2_str.split_at(split_idx);
1328                         debug!("cmp: common={}, uniq1={}, uniq2={}", common, uniq1, uniq2);
1329
1330                         values.0.push_normal(common);
1331                         values.0.push_highlighted(uniq1);
1332                         values.1.push_normal(common);
1333                         values.1.push_highlighted(uniq2);
1334
1335                         values
1336                     }
1337                 }
1338             }
1339
1340             // When finding T != &T, highlight only the borrow
1341             (&ty::Ref(r1, ref_ty1, mutbl1), _) if equals(ref_ty1, t2) => {
1342                 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
1343                 push_ty_ref(r1, ref_ty1, mutbl1, &mut values.0);
1344                 values.1.push_normal(t2.to_string());
1345                 values
1346             }
1347             (_, &ty::Ref(r2, ref_ty2, mutbl2)) if equals(t1, ref_ty2) => {
1348                 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
1349                 values.0.push_normal(t1.to_string());
1350                 push_ty_ref(r2, ref_ty2, mutbl2, &mut values.1);
1351                 values
1352             }
1353
1354             // When encountering &T != &mut T, highlight only the borrow
1355             (&ty::Ref(r1, ref_ty1, mutbl1), &ty::Ref(r2, ref_ty2, mutbl2))
1356                 if equals(ref_ty1, ref_ty2) =>
1357             {
1358                 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
1359                 push_ty_ref(r1, ref_ty1, mutbl1, &mut values.0);
1360                 push_ty_ref(r2, ref_ty2, mutbl2, &mut values.1);
1361                 values
1362             }
1363
1364             // When encountering tuples of the same size, highlight only the differing types
1365             (&ty::Tuple(substs1), &ty::Tuple(substs2)) if substs1.len() == substs2.len() => {
1366                 let mut values =
1367                     (DiagnosticStyledString::normal("("), DiagnosticStyledString::normal("("));
1368                 let len = substs1.len();
1369                 for (i, (left, right)) in substs1.iter().zip(substs2).enumerate() {
1370                     let (x1, x2) = self.cmp(left, right);
1371                     (values.0).0.extend(x1.0);
1372                     (values.1).0.extend(x2.0);
1373                     self.push_comma(&mut values.0, &mut values.1, len, i);
1374                 }
1375                 if len == 1 {
1376                     // Keep the output for single element tuples as `(ty,)`.
1377                     values.0.push_normal(",");
1378                     values.1.push_normal(",");
1379                 }
1380                 values.0.push_normal(")");
1381                 values.1.push_normal(")");
1382                 values
1383             }
1384
1385             (ty::FnDef(did1, substs1), ty::FnDef(did2, substs2)) => {
1386                 let sig1 = self.tcx.fn_sig(*did1).subst(self.tcx, substs1);
1387                 let sig2 = self.tcx.fn_sig(*did2).subst(self.tcx, substs2);
1388                 let mut values = self.cmp_fn_sig(&sig1, &sig2);
1389                 let path1 = format!(" {{{}}}", self.tcx.def_path_str_with_substs(*did1, substs1));
1390                 let path2 = format!(" {{{}}}", self.tcx.def_path_str_with_substs(*did2, substs2));
1391                 let same_path = path1 == path2;
1392                 values.0.push(path1, !same_path);
1393                 values.1.push(path2, !same_path);
1394                 values
1395             }
1396
1397             (ty::FnDef(did1, substs1), ty::FnPtr(sig2)) => {
1398                 let sig1 = self.tcx.fn_sig(*did1).subst(self.tcx, substs1);
1399                 let mut values = self.cmp_fn_sig(&sig1, sig2);
1400                 values.0.push_highlighted(format!(
1401                     " {{{}}}",
1402                     self.tcx.def_path_str_with_substs(*did1, substs1)
1403                 ));
1404                 values
1405             }
1406
1407             (ty::FnPtr(sig1), ty::FnDef(did2, substs2)) => {
1408                 let sig2 = self.tcx.fn_sig(*did2).subst(self.tcx, substs2);
1409                 let mut values = self.cmp_fn_sig(sig1, &sig2);
1410                 values.1.push_normal(format!(
1411                     " {{{}}}",
1412                     self.tcx.def_path_str_with_substs(*did2, substs2)
1413                 ));
1414                 values
1415             }
1416
1417             (ty::FnPtr(sig1), ty::FnPtr(sig2)) => self.cmp_fn_sig(sig1, sig2),
1418
1419             _ => {
1420                 if t1 == t2 {
1421                     // The two types are the same, elide and don't highlight.
1422                     (DiagnosticStyledString::normal("_"), DiagnosticStyledString::normal("_"))
1423                 } else {
1424                     // We couldn't find anything in common, highlight everything.
1425                     (
1426                         DiagnosticStyledString::highlighted(t1.to_string()),
1427                         DiagnosticStyledString::highlighted(t2.to_string()),
1428                     )
1429                 }
1430             }
1431         }
1432     }
1433
1434     /// Extend a type error with extra labels pointing at "non-trivial" types, like closures and
1435     /// the return type of `async fn`s.
1436     ///
1437     /// `secondary_span` gives the caller the opportunity to expand `diag` with a `span_label`.
1438     ///
1439     /// `swap_secondary_and_primary` is used to make projection errors in particular nicer by using
1440     /// the message in `secondary_span` as the primary label, and apply the message that would
1441     /// otherwise be used for the primary label on the `secondary_span` `Span`. This applies on
1442     /// E0271, like `src/test/ui/issues/issue-39970.stderr`.
1443     pub fn note_type_err(
1444         &self,
1445         diag: &mut Diagnostic,
1446         cause: &ObligationCause<'tcx>,
1447         secondary_span: Option<(Span, String)>,
1448         mut values: Option<ValuePairs<'tcx>>,
1449         terr: &TypeError<'tcx>,
1450         swap_secondary_and_primary: bool,
1451         force_label: bool,
1452     ) {
1453         let span = cause.span(self.tcx);
1454         debug!("note_type_err cause={:?} values={:?}, terr={:?}", cause, values, terr);
1455
1456         // For some types of errors, expected-found does not make
1457         // sense, so just ignore the values we were given.
1458         if let TypeError::CyclicTy(_) = terr {
1459             values = None;
1460         }
1461         struct OpaqueTypesVisitor<'tcx> {
1462             types: FxHashMap<TyCategory, FxHashSet<Span>>,
1463             expected: FxHashMap<TyCategory, FxHashSet<Span>>,
1464             found: FxHashMap<TyCategory, FxHashSet<Span>>,
1465             ignore_span: Span,
1466             tcx: TyCtxt<'tcx>,
1467         }
1468
1469         impl<'tcx> OpaqueTypesVisitor<'tcx> {
1470             fn visit_expected_found(
1471                 tcx: TyCtxt<'tcx>,
1472                 expected: Ty<'tcx>,
1473                 found: Ty<'tcx>,
1474                 ignore_span: Span,
1475             ) -> Self {
1476                 let mut types_visitor = OpaqueTypesVisitor {
1477                     types: Default::default(),
1478                     expected: Default::default(),
1479                     found: Default::default(),
1480                     ignore_span,
1481                     tcx,
1482                 };
1483                 // The visitor puts all the relevant encountered types in `self.types`, but in
1484                 // here we want to visit two separate types with no relation to each other, so we
1485                 // move the results from `types` to `expected` or `found` as appropriate.
1486                 expected.visit_with(&mut types_visitor);
1487                 std::mem::swap(&mut types_visitor.expected, &mut types_visitor.types);
1488                 found.visit_with(&mut types_visitor);
1489                 std::mem::swap(&mut types_visitor.found, &mut types_visitor.types);
1490                 types_visitor
1491             }
1492
1493             fn report(&self, err: &mut Diagnostic) {
1494                 self.add_labels_for_types(err, "expected", &self.expected);
1495                 self.add_labels_for_types(err, "found", &self.found);
1496             }
1497
1498             fn add_labels_for_types(
1499                 &self,
1500                 err: &mut Diagnostic,
1501                 target: &str,
1502                 types: &FxHashMap<TyCategory, FxHashSet<Span>>,
1503             ) {
1504                 for (key, values) in types.iter() {
1505                     let count = values.len();
1506                     let kind = key.descr();
1507                     let mut returned_async_output_error = false;
1508                     for &sp in values {
1509                         if sp.is_desugaring(DesugaringKind::Async) && !returned_async_output_error {
1510                             if [sp] != err.span.primary_spans() {
1511                                 let mut span: MultiSpan = sp.into();
1512                                 span.push_span_label(
1513                                     sp,
1514                                     format!(
1515                                         "checked the `Output` of this `async fn`, {}{} {}{}",
1516                                         if count > 1 { "one of the " } else { "" },
1517                                         target,
1518                                         kind,
1519                                         pluralize!(count),
1520                                     ),
1521                                 );
1522                                 err.span_note(
1523                                     span,
1524                                     "while checking the return type of the `async fn`",
1525                                 );
1526                             } else {
1527                                 err.span_label(
1528                                     sp,
1529                                     format!(
1530                                         "checked the `Output` of this `async fn`, {}{} {}{}",
1531                                         if count > 1 { "one of the " } else { "" },
1532                                         target,
1533                                         kind,
1534                                         pluralize!(count),
1535                                     ),
1536                                 );
1537                                 err.note("while checking the return type of the `async fn`");
1538                             }
1539                             returned_async_output_error = true;
1540                         } else {
1541                             err.span_label(
1542                                 sp,
1543                                 format!(
1544                                     "{}{} {}{}",
1545                                     if count == 1 { "the " } else { "one of the " },
1546                                     target,
1547                                     kind,
1548                                     pluralize!(count),
1549                                 ),
1550                             );
1551                         }
1552                     }
1553                 }
1554             }
1555         }
1556
1557         impl<'tcx> ty::fold::TypeVisitor<'tcx> for OpaqueTypesVisitor<'tcx> {
1558             fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
1559                 if let Some((kind, def_id)) = TyCategory::from_ty(self.tcx, t) {
1560                     let span = self.tcx.def_span(def_id);
1561                     // Avoid cluttering the output when the "found" and error span overlap:
1562                     //
1563                     // error[E0308]: mismatched types
1564                     //   --> $DIR/issue-20862.rs:2:5
1565                     //    |
1566                     // LL |     |y| x + y
1567                     //    |     ^^^^^^^^^
1568                     //    |     |
1569                     //    |     the found closure
1570                     //    |     expected `()`, found closure
1571                     //    |
1572                     //    = note: expected unit type `()`
1573                     //                 found closure `[closure@$DIR/issue-20862.rs:2:5: 2:14 x:_]`
1574                     if !self.ignore_span.overlaps(span) {
1575                         self.types.entry(kind).or_default().insert(span);
1576                     }
1577                 }
1578                 t.super_visit_with(self)
1579             }
1580         }
1581
1582         debug!("note_type_err(diag={:?})", diag);
1583         enum Mismatch<'a> {
1584             Variable(ty::error::ExpectedFound<Ty<'a>>),
1585             Fixed(&'static str),
1586         }
1587         let (expected_found, exp_found, is_simple_error) = match values {
1588             None => (None, Mismatch::Fixed("type"), false),
1589             Some(values) => {
1590                 let (is_simple_error, exp_found) = match values {
1591                     ValuePairs::Terms(infer::ExpectedFound {
1592                         expected: ty::Term::Ty(expected),
1593                         found: ty::Term::Ty(found),
1594                     }) => {
1595                         let is_simple_err = expected.is_simple_text() && found.is_simple_text();
1596                         OpaqueTypesVisitor::visit_expected_found(self.tcx, expected, found, span)
1597                             .report(diag);
1598
1599                         (
1600                             is_simple_err,
1601                             Mismatch::Variable(infer::ExpectedFound { expected, found }),
1602                         )
1603                     }
1604                     ValuePairs::TraitRefs(_) => (false, Mismatch::Fixed("trait")),
1605                     _ => (false, Mismatch::Fixed("type")),
1606                 };
1607                 let vals = match self.values_str(values) {
1608                     Some((expected, found)) => Some((expected, found)),
1609                     None => {
1610                         // Derived error. Cancel the emitter.
1611                         // NOTE(eddyb) this was `.cancel()`, but `diag`
1612                         // is borrowed, so we can't fully defuse it.
1613                         diag.downgrade_to_delayed_bug();
1614                         return;
1615                     }
1616                 };
1617                 (vals, exp_found, is_simple_error)
1618             }
1619         };
1620
1621         // Ignore msg for object safe coercion
1622         // since E0038 message will be printed
1623         match terr {
1624             TypeError::ObjectUnsafeCoercion(_) => {}
1625             _ => {
1626                 let mut label_or_note = |span: Span, msg: &str| {
1627                     if force_label || &[span] == diag.span.primary_spans() {
1628                         diag.span_label(span, msg);
1629                     } else {
1630                         diag.span_note(span, msg);
1631                     }
1632                 };
1633                 if let Some((sp, msg)) = secondary_span {
1634                     if swap_secondary_and_primary {
1635                         let terr = if let Some(infer::ValuePairs::Terms(infer::ExpectedFound {
1636                             expected,
1637                             ..
1638                         })) = values
1639                         {
1640                             format!("expected this to be `{}`", expected)
1641                         } else {
1642                             terr.to_string()
1643                         };
1644                         label_or_note(sp, &terr);
1645                         label_or_note(span, &msg);
1646                     } else {
1647                         label_or_note(span, &terr.to_string());
1648                         label_or_note(sp, &msg);
1649                     }
1650                 } else {
1651                     label_or_note(span, &terr.to_string());
1652                 }
1653             }
1654         };
1655         if let Some((expected, found)) = expected_found {
1656             let (expected_label, found_label, exp_found) = match exp_found {
1657                 Mismatch::Variable(ef) => (
1658                     ef.expected.prefix_string(self.tcx),
1659                     ef.found.prefix_string(self.tcx),
1660                     Some(ef),
1661                 ),
1662                 Mismatch::Fixed(s) => (s.into(), s.into(), None),
1663             };
1664             match (&terr, expected == found) {
1665                 (TypeError::Sorts(values), extra) => {
1666                     let sort_string = |ty: Ty<'tcx>| match (extra, ty.kind()) {
1667                         (true, ty::Opaque(def_id, _)) => {
1668                             let sm = self.tcx.sess.source_map();
1669                             let pos = sm.lookup_char_pos(self.tcx.def_span(*def_id).lo());
1670                             format!(
1671                                 " (opaque type at <{}:{}:{}>)",
1672                                 sm.filename_for_diagnostics(&pos.file.name),
1673                                 pos.line,
1674                                 pos.col.to_usize() + 1,
1675                             )
1676                         }
1677                         (true, _) => format!(" ({})", ty.sort_string(self.tcx)),
1678                         (false, _) => "".to_string(),
1679                     };
1680                     if !(values.expected.is_simple_text() && values.found.is_simple_text())
1681                         || (exp_found.map_or(false, |ef| {
1682                             // This happens when the type error is a subset of the expectation,
1683                             // like when you have two references but one is `usize` and the other
1684                             // is `f32`. In those cases we still want to show the `note`. If the
1685                             // value from `ef` is `Infer(_)`, then we ignore it.
1686                             if !ef.expected.is_ty_infer() {
1687                                 ef.expected != values.expected
1688                             } else if !ef.found.is_ty_infer() {
1689                                 ef.found != values.found
1690                             } else {
1691                                 false
1692                             }
1693                         }))
1694                     {
1695                         diag.note_expected_found_extra(
1696                             &expected_label,
1697                             expected,
1698                             &found_label,
1699                             found,
1700                             &sort_string(values.expected),
1701                             &sort_string(values.found),
1702                         );
1703                     }
1704                 }
1705                 (TypeError::ObjectUnsafeCoercion(_), _) => {
1706                     diag.note_unsuccessful_coercion(found, expected);
1707                 }
1708                 (_, _) => {
1709                     debug!(
1710                         "note_type_err: exp_found={:?}, expected={:?} found={:?}",
1711                         exp_found, expected, found
1712                     );
1713                     if !is_simple_error || terr.must_include_note() {
1714                         diag.note_expected_found(&expected_label, expected, &found_label, found);
1715                     }
1716                 }
1717             }
1718         }
1719         let exp_found = match exp_found {
1720             Mismatch::Variable(exp_found) => Some(exp_found),
1721             Mismatch::Fixed(_) => None,
1722         };
1723         let exp_found = match terr {
1724             // `terr` has more accurate type information than `exp_found` in match expressions.
1725             ty::error::TypeError::Sorts(terr)
1726                 if exp_found.map_or(false, |ef| terr.found == ef.found) =>
1727             {
1728                 Some(*terr)
1729             }
1730             _ => exp_found,
1731         };
1732         debug!("exp_found {:?} terr {:?} cause.code {:?}", exp_found, terr, cause.code());
1733         if let Some(exp_found) = exp_found {
1734             let should_suggest_fixes = if let ObligationCauseCode::Pattern { root_ty, .. } =
1735                 cause.code()
1736             {
1737                 // Skip if the root_ty of the pattern is not the same as the expected_ty.
1738                 // If these types aren't equal then we've probably peeled off a layer of arrays.
1739                 same_type_modulo_infer(self.resolve_vars_if_possible(*root_ty), exp_found.expected)
1740             } else {
1741                 true
1742             };
1743
1744             if should_suggest_fixes {
1745                 self.suggest_tuple_pattern(cause, &exp_found, diag);
1746                 self.suggest_as_ref_where_appropriate(span, &exp_found, diag);
1747                 self.suggest_accessing_field_where_appropriate(cause, &exp_found, diag);
1748                 self.suggest_await_on_expect_found(cause, span, &exp_found, diag);
1749             }
1750         }
1751
1752         // In some (most?) cases cause.body_id points to actual body, but in some cases
1753         // it's an actual definition. According to the comments (e.g. in
1754         // librustc_typeck/check/compare_method.rs:compare_predicate_entailment) the latter
1755         // is relied upon by some other code. This might (or might not) need cleanup.
1756         let body_owner_def_id =
1757             self.tcx.hir().opt_local_def_id(cause.body_id).unwrap_or_else(|| {
1758                 self.tcx.hir().body_owner_def_id(hir::BodyId { hir_id: cause.body_id })
1759             });
1760         self.check_and_note_conflicting_crates(diag, terr);
1761         self.tcx.note_and_explain_type_err(diag, terr, cause, span, body_owner_def_id.to_def_id());
1762
1763         if let Some(ValuePairs::PolyTraitRefs(exp_found)) = values
1764             && let ty::Closure(def_id, _) = exp_found.expected.skip_binder().self_ty().kind()
1765             && let Some(def_id) = def_id.as_local()
1766         {
1767             let span = self.tcx.def_span(def_id);
1768             diag.span_note(span, "this closure does not fulfill the lifetime requirements");
1769         }
1770
1771         // It reads better to have the error origin as the final
1772         // thing.
1773         self.note_error_origin(diag, cause, exp_found, terr);
1774     }
1775
1776     fn suggest_tuple_pattern(
1777         &self,
1778         cause: &ObligationCause<'tcx>,
1779         exp_found: &ty::error::ExpectedFound<Ty<'tcx>>,
1780         diag: &mut Diagnostic,
1781     ) {
1782         // Heavily inspired by `FnCtxt::suggest_compatible_variants`, with
1783         // some modifications due to that being in typeck and this being in infer.
1784         if let ObligationCauseCode::Pattern { .. } = cause.code() {
1785             if let ty::Adt(expected_adt, substs) = exp_found.expected.kind() {
1786                 let compatible_variants: Vec<_> = expected_adt
1787                     .variants()
1788                     .iter()
1789                     .filter(|variant| {
1790                         variant.fields.len() == 1 && variant.ctor_kind == hir::def::CtorKind::Fn
1791                     })
1792                     .filter_map(|variant| {
1793                         let sole_field = &variant.fields[0];
1794                         let sole_field_ty = sole_field.ty(self.tcx, substs);
1795                         if same_type_modulo_infer(sole_field_ty, exp_found.found) {
1796                             let variant_path =
1797                                 with_no_trimmed_paths!(self.tcx.def_path_str(variant.def_id));
1798                             // FIXME #56861: DRYer prelude filtering
1799                             if let Some(path) = variant_path.strip_prefix("std::prelude::") {
1800                                 if let Some((_, path)) = path.split_once("::") {
1801                                     return Some(path.to_string());
1802                                 }
1803                             }
1804                             Some(variant_path)
1805                         } else {
1806                             None
1807                         }
1808                     })
1809                     .collect();
1810                 match &compatible_variants[..] {
1811                     [] => {}
1812                     [variant] => {
1813                         diag.multipart_suggestion_verbose(
1814                             &format!("try wrapping the pattern in `{}`", variant),
1815                             vec![
1816                                 (cause.span.shrink_to_lo(), format!("{}(", variant)),
1817                                 (cause.span.shrink_to_hi(), ")".to_string()),
1818                             ],
1819                             Applicability::MaybeIncorrect,
1820                         );
1821                     }
1822                     _ => {
1823                         // More than one matching variant.
1824                         diag.multipart_suggestions(
1825                             &format!(
1826                                 "try wrapping the pattern in a variant of `{}`",
1827                                 self.tcx.def_path_str(expected_adt.did())
1828                             ),
1829                             compatible_variants.into_iter().map(|variant| {
1830                                 vec![
1831                                     (cause.span.shrink_to_lo(), format!("{}(", variant)),
1832                                     (cause.span.shrink_to_hi(), ")".to_string()),
1833                                 ]
1834                             }),
1835                             Applicability::MaybeIncorrect,
1836                         );
1837                     }
1838                 }
1839             }
1840         }
1841     }
1842
1843     pub fn get_impl_future_output_ty(&self, ty: Ty<'tcx>) -> Option<Binder<'tcx, Ty<'tcx>>> {
1844         if let ty::Opaque(def_id, substs) = ty.kind() {
1845             let future_trait = self.tcx.require_lang_item(LangItem::Future, None);
1846             // Future::Output
1847             let item_def_id = self.tcx.associated_item_def_ids(future_trait)[0];
1848
1849             let bounds = self.tcx.explicit_item_bounds(*def_id);
1850
1851             for (predicate, _) in bounds {
1852                 let predicate = predicate.subst(self.tcx, substs);
1853                 let output = predicate
1854                     .kind()
1855                     .map_bound(|kind| match kind {
1856                         ty::PredicateKind::Projection(projection_predicate)
1857                             if projection_predicate.projection_ty.item_def_id == item_def_id =>
1858                         {
1859                             projection_predicate.term.ty()
1860                         }
1861                         _ => None,
1862                     })
1863                     .transpose();
1864                 if output.is_some() {
1865                     // We don't account for multiple `Future::Output = Ty` constraints.
1866                     return output;
1867                 }
1868             }
1869         }
1870         None
1871     }
1872
1873     /// A possible error is to forget to add `.await` when using futures:
1874     ///
1875     /// ```compile_fail,E0308
1876     /// async fn make_u32() -> u32 {
1877     ///     22
1878     /// }
1879     ///
1880     /// fn take_u32(x: u32) {}
1881     ///
1882     /// async fn foo() {
1883     ///     let x = make_u32();
1884     ///     take_u32(x);
1885     /// }
1886     /// ```
1887     ///
1888     /// This routine checks if the found type `T` implements `Future<Output=U>` where `U` is the
1889     /// expected type. If this is the case, and we are inside of an async body, it suggests adding
1890     /// `.await` to the tail of the expression.
1891     fn suggest_await_on_expect_found(
1892         &self,
1893         cause: &ObligationCause<'tcx>,
1894         exp_span: Span,
1895         exp_found: &ty::error::ExpectedFound<Ty<'tcx>>,
1896         diag: &mut Diagnostic,
1897     ) {
1898         debug!(
1899             "suggest_await_on_expect_found: exp_span={:?}, expected_ty={:?}, found_ty={:?}",
1900             exp_span, exp_found.expected, exp_found.found,
1901         );
1902
1903         if let ObligationCauseCode::CompareImplMethodObligation { .. } = cause.code() {
1904             return;
1905         }
1906
1907         match (
1908             self.get_impl_future_output_ty(exp_found.expected).map(Binder::skip_binder),
1909             self.get_impl_future_output_ty(exp_found.found).map(Binder::skip_binder),
1910         ) {
1911             (Some(exp), Some(found)) if same_type_modulo_infer(exp, found) => match cause.code() {
1912                 ObligationCauseCode::IfExpression(box IfExpressionCause { then, .. }) => {
1913                     diag.multipart_suggestion(
1914                         "consider `await`ing on both `Future`s",
1915                         vec![
1916                             (then.shrink_to_hi(), ".await".to_string()),
1917                             (exp_span.shrink_to_hi(), ".await".to_string()),
1918                         ],
1919                         Applicability::MaybeIncorrect,
1920                     );
1921                 }
1922                 ObligationCauseCode::MatchExpressionArm(box MatchExpressionArmCause {
1923                     prior_arms,
1924                     ..
1925                 }) => {
1926                     if let [.., arm_span] = &prior_arms[..] {
1927                         diag.multipart_suggestion(
1928                             "consider `await`ing on both `Future`s",
1929                             vec![
1930                                 (arm_span.shrink_to_hi(), ".await".to_string()),
1931                                 (exp_span.shrink_to_hi(), ".await".to_string()),
1932                             ],
1933                             Applicability::MaybeIncorrect,
1934                         );
1935                     } else {
1936                         diag.help("consider `await`ing on both `Future`s");
1937                     }
1938                 }
1939                 _ => {
1940                     diag.help("consider `await`ing on both `Future`s");
1941                 }
1942             },
1943             (_, Some(ty)) if same_type_modulo_infer(exp_found.expected, ty) => {
1944                 diag.span_suggestion_verbose(
1945                     exp_span.shrink_to_hi(),
1946                     "consider `await`ing on the `Future`",
1947                     ".await".to_string(),
1948                     Applicability::MaybeIncorrect,
1949                 );
1950             }
1951             (Some(ty), _) if same_type_modulo_infer(ty, exp_found.found) => match cause.code() {
1952                 ObligationCauseCode::Pattern { span: Some(span), .. }
1953                 | ObligationCauseCode::IfExpression(box IfExpressionCause { then: span, .. }) => {
1954                     diag.span_suggestion_verbose(
1955                         span.shrink_to_hi(),
1956                         "consider `await`ing on the `Future`",
1957                         ".await".to_string(),
1958                         Applicability::MaybeIncorrect,
1959                     );
1960                 }
1961                 ObligationCauseCode::MatchExpressionArm(box MatchExpressionArmCause {
1962                     ref prior_arms,
1963                     ..
1964                 }) => {
1965                     diag.multipart_suggestion_verbose(
1966                         "consider `await`ing on the `Future`",
1967                         prior_arms
1968                             .iter()
1969                             .map(|arm| (arm.shrink_to_hi(), ".await".to_string()))
1970                             .collect(),
1971                         Applicability::MaybeIncorrect,
1972                     );
1973                 }
1974                 _ => {}
1975             },
1976             _ => {}
1977         }
1978     }
1979
1980     fn suggest_accessing_field_where_appropriate(
1981         &self,
1982         cause: &ObligationCause<'tcx>,
1983         exp_found: &ty::error::ExpectedFound<Ty<'tcx>>,
1984         diag: &mut Diagnostic,
1985     ) {
1986         debug!(
1987             "suggest_accessing_field_where_appropriate(cause={:?}, exp_found={:?})",
1988             cause, exp_found
1989         );
1990         if let ty::Adt(expected_def, expected_substs) = exp_found.expected.kind() {
1991             if expected_def.is_enum() {
1992                 return;
1993             }
1994
1995             if let Some((name, ty)) = expected_def
1996                 .non_enum_variant()
1997                 .fields
1998                 .iter()
1999                 .filter(|field| field.vis.is_accessible_from(field.did, self.tcx))
2000                 .map(|field| (field.name, field.ty(self.tcx, expected_substs)))
2001                 .find(|(_, ty)| same_type_modulo_infer(*ty, exp_found.found))
2002             {
2003                 if let ObligationCauseCode::Pattern { span: Some(span), .. } = *cause.code() {
2004                     if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
2005                         let suggestion = if expected_def.is_struct() {
2006                             format!("{}.{}", snippet, name)
2007                         } else if expected_def.is_union() {
2008                             format!("unsafe {{ {}.{} }}", snippet, name)
2009                         } else {
2010                             return;
2011                         };
2012                         diag.span_suggestion(
2013                             span,
2014                             &format!(
2015                                 "you might have meant to use field `{}` whose type is `{}`",
2016                                 name, ty
2017                             ),
2018                             suggestion,
2019                             Applicability::MaybeIncorrect,
2020                         );
2021                     }
2022                 }
2023             }
2024         }
2025     }
2026
2027     /// When encountering a case where `.as_ref()` on a `Result` or `Option` would be appropriate,
2028     /// suggests it.
2029     fn suggest_as_ref_where_appropriate(
2030         &self,
2031         span: Span,
2032         exp_found: &ty::error::ExpectedFound<Ty<'tcx>>,
2033         diag: &mut Diagnostic,
2034     ) {
2035         if let (ty::Adt(exp_def, exp_substs), ty::Ref(_, found_ty, _)) =
2036             (exp_found.expected.kind(), exp_found.found.kind())
2037         {
2038             if let ty::Adt(found_def, found_substs) = *found_ty.kind() {
2039                 let path_str = format!("{:?}", exp_def);
2040                 if exp_def == &found_def {
2041                     let opt_msg = "you can convert from `&Option<T>` to `Option<&T>` using \
2042                                        `.as_ref()`";
2043                     let result_msg = "you can convert from `&Result<T, E>` to \
2044                                           `Result<&T, &E>` using `.as_ref()`";
2045                     let have_as_ref = &[
2046                         ("std::option::Option", opt_msg),
2047                         ("core::option::Option", opt_msg),
2048                         ("std::result::Result", result_msg),
2049                         ("core::result::Result", result_msg),
2050                     ];
2051                     if let Some(msg) = have_as_ref
2052                         .iter()
2053                         .find_map(|(path, msg)| (&path_str == path).then_some(msg))
2054                     {
2055                         let mut show_suggestion = true;
2056                         for (exp_ty, found_ty) in
2057                             iter::zip(exp_substs.types(), found_substs.types())
2058                         {
2059                             match *exp_ty.kind() {
2060                                 ty::Ref(_, exp_ty, _) => {
2061                                     match (exp_ty.kind(), found_ty.kind()) {
2062                                         (_, ty::Param(_))
2063                                         | (_, ty::Infer(_))
2064                                         | (ty::Param(_), _)
2065                                         | (ty::Infer(_), _) => {}
2066                                         _ if same_type_modulo_infer(exp_ty, found_ty) => {}
2067                                         _ => show_suggestion = false,
2068                                     };
2069                                 }
2070                                 ty::Param(_) | ty::Infer(_) => {}
2071                                 _ => show_suggestion = false,
2072                             }
2073                         }
2074                         if let (Ok(snippet), true) =
2075                             (self.tcx.sess.source_map().span_to_snippet(span), show_suggestion)
2076                         {
2077                             diag.span_suggestion(
2078                                 span,
2079                                 *msg,
2080                                 format!("{}.as_ref()", snippet),
2081                                 Applicability::MachineApplicable,
2082                             );
2083                         }
2084                     }
2085                 }
2086             }
2087         }
2088     }
2089
2090     pub fn report_and_explain_type_error(
2091         &self,
2092         trace: TypeTrace<'tcx>,
2093         terr: &TypeError<'tcx>,
2094     ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
2095         use crate::traits::ObligationCauseCode::MatchExpressionArm;
2096
2097         debug!("report_and_explain_type_error(trace={:?}, terr={:?})", trace, terr);
2098
2099         let span = trace.cause.span(self.tcx);
2100         let failure_code = trace.cause.as_failure_code(terr);
2101         let mut diag = match failure_code {
2102             FailureCode::Error0038(did) => {
2103                 let violations = self.tcx.object_safety_violations(did);
2104                 report_object_safety_error(self.tcx, span, did, violations)
2105             }
2106             FailureCode::Error0317(failure_str) => {
2107                 struct_span_err!(self.tcx.sess, span, E0317, "{}", failure_str)
2108             }
2109             FailureCode::Error0580(failure_str) => {
2110                 struct_span_err!(self.tcx.sess, span, E0580, "{}", failure_str)
2111             }
2112             FailureCode::Error0308(failure_str) => {
2113                 let mut err = struct_span_err!(self.tcx.sess, span, E0308, "{}", failure_str);
2114                 if let Some((expected, found)) = trace.values.ty() {
2115                     match (expected.kind(), found.kind()) {
2116                         (ty::Tuple(_), ty::Tuple(_)) => {}
2117                         // If a tuple of length one was expected and the found expression has
2118                         // parentheses around it, perhaps the user meant to write `(expr,)` to
2119                         // build a tuple (issue #86100)
2120                         (ty::Tuple(fields), _) => {
2121                             self.emit_tuple_wrap_err(&mut err, span, found, fields)
2122                         }
2123                         // If a character was expected and the found expression is a string literal
2124                         // containing a single character, perhaps the user meant to write `'c'` to
2125                         // specify a character literal (issue #92479)
2126                         (ty::Char, ty::Ref(_, r, _)) if r.is_str() => {
2127                             if let Ok(code) = self.tcx.sess().source_map().span_to_snippet(span)
2128                                 && let Some(code) = code.strip_prefix('"').and_then(|s| s.strip_suffix('"'))
2129                                 && code.chars().count() == 1
2130                             {
2131                                 err.span_suggestion(
2132                                     span,
2133                                     "if you meant to write a `char` literal, use single quotes",
2134                                     format!("'{}'", code),
2135                                     Applicability::MachineApplicable,
2136                                 );
2137                             }
2138                         }
2139                         // If a string was expected and the found expression is a character literal,
2140                         // perhaps the user meant to write `"s"` to specify a string literal.
2141                         (ty::Ref(_, r, _), ty::Char) if r.is_str() => {
2142                             if let Ok(code) = self.tcx.sess().source_map().span_to_snippet(span) {
2143                                 if let Some(code) =
2144                                     code.strip_prefix('\'').and_then(|s| s.strip_suffix('\''))
2145                                 {
2146                                     err.span_suggestion(
2147                                         span,
2148                                         "if you meant to write a `str` literal, use double quotes",
2149                                         format!("\"{}\"", code),
2150                                         Applicability::MachineApplicable,
2151                                     );
2152                                 }
2153                             }
2154                         }
2155                         _ => {}
2156                     }
2157                 }
2158                 let code = trace.cause.code();
2159                 if let &MatchExpressionArm(box MatchExpressionArmCause { source, .. }) = code
2160                     && let hir::MatchSource::TryDesugar = source
2161                     && let Some((expected_ty, found_ty)) = self.values_str(trace.values)
2162                 {
2163                     err.note(&format!(
2164                         "`?` operator cannot convert from `{}` to `{}`",
2165                         found_ty.content(),
2166                         expected_ty.content(),
2167                     ));
2168                 }
2169                 err
2170             }
2171             FailureCode::Error0644(failure_str) => {
2172                 struct_span_err!(self.tcx.sess, span, E0644, "{}", failure_str)
2173             }
2174         };
2175         self.note_type_err(&mut diag, &trace.cause, None, Some(trace.values), terr, false, false);
2176         diag
2177     }
2178
2179     fn emit_tuple_wrap_err(
2180         &self,
2181         err: &mut Diagnostic,
2182         span: Span,
2183         found: Ty<'tcx>,
2184         expected_fields: &List<Ty<'tcx>>,
2185     ) {
2186         let [expected_tup_elem] = expected_fields[..] else { return };
2187
2188         if !same_type_modulo_infer(expected_tup_elem, found) {
2189             return;
2190         }
2191
2192         let Ok(code) = self.tcx.sess().source_map().span_to_snippet(span)
2193             else { return };
2194
2195         let msg = "use a trailing comma to create a tuple with one element";
2196         if code.starts_with('(') && code.ends_with(')') {
2197             let before_close = span.hi() - BytePos::from_u32(1);
2198             err.span_suggestion(
2199                 span.with_hi(before_close).shrink_to_hi(),
2200                 msg,
2201                 ",",
2202                 Applicability::MachineApplicable,
2203             );
2204         } else {
2205             err.multipart_suggestion(
2206                 msg,
2207                 vec![(span.shrink_to_lo(), "(".into()), (span.shrink_to_hi(), ",)".into())],
2208                 Applicability::MachineApplicable,
2209             );
2210         }
2211     }
2212
2213     fn values_str(
2214         &self,
2215         values: ValuePairs<'tcx>,
2216     ) -> Option<(DiagnosticStyledString, DiagnosticStyledString)> {
2217         match values {
2218             infer::Regions(exp_found) => self.expected_found_str(exp_found),
2219             infer::Terms(exp_found) => self.expected_found_str_term(exp_found),
2220             infer::TraitRefs(exp_found) => {
2221                 let pretty_exp_found = ty::error::ExpectedFound {
2222                     expected: exp_found.expected.print_only_trait_path(),
2223                     found: exp_found.found.print_only_trait_path(),
2224                 };
2225                 match self.expected_found_str(pretty_exp_found) {
2226                     Some((expected, found)) if expected == found => {
2227                         self.expected_found_str(exp_found)
2228                     }
2229                     ret => ret,
2230                 }
2231             }
2232             infer::PolyTraitRefs(exp_found) => {
2233                 let pretty_exp_found = ty::error::ExpectedFound {
2234                     expected: exp_found.expected.print_only_trait_path(),
2235                     found: exp_found.found.print_only_trait_path(),
2236                 };
2237                 match self.expected_found_str(pretty_exp_found) {
2238                     Some((expected, found)) if expected == found => {
2239                         self.expected_found_str(exp_found)
2240                     }
2241                     ret => ret,
2242                 }
2243             }
2244         }
2245     }
2246
2247     fn expected_found_str_term(
2248         &self,
2249         exp_found: ty::error::ExpectedFound<ty::Term<'tcx>>,
2250     ) -> Option<(DiagnosticStyledString, DiagnosticStyledString)> {
2251         let exp_found = self.resolve_vars_if_possible(exp_found);
2252         if exp_found.references_error() {
2253             return None;
2254         }
2255
2256         Some(match (exp_found.expected, exp_found.found) {
2257             (ty::Term::Ty(expected), ty::Term::Ty(found)) => self.cmp(expected, found),
2258             (expected, found) => (
2259                 DiagnosticStyledString::highlighted(expected.to_string()),
2260                 DiagnosticStyledString::highlighted(found.to_string()),
2261             ),
2262         })
2263     }
2264
2265     /// Returns a string of the form "expected `{}`, found `{}`".
2266     fn expected_found_str<T: fmt::Display + TypeFoldable<'tcx>>(
2267         &self,
2268         exp_found: ty::error::ExpectedFound<T>,
2269     ) -> Option<(DiagnosticStyledString, DiagnosticStyledString)> {
2270         let exp_found = self.resolve_vars_if_possible(exp_found);
2271         if exp_found.references_error() {
2272             return None;
2273         }
2274
2275         Some((
2276             DiagnosticStyledString::highlighted(exp_found.expected.to_string()),
2277             DiagnosticStyledString::highlighted(exp_found.found.to_string()),
2278         ))
2279     }
2280
2281     pub fn report_generic_bound_failure(
2282         &self,
2283         span: Span,
2284         origin: Option<SubregionOrigin<'tcx>>,
2285         bound_kind: GenericKind<'tcx>,
2286         sub: Region<'tcx>,
2287     ) {
2288         let owner =
2289             self.in_progress_typeck_results.map(|typeck_results| typeck_results.borrow().hir_owner);
2290         self.construct_generic_bound_failure(span, origin, bound_kind, sub, owner).emit();
2291     }
2292
2293     pub fn construct_generic_bound_failure(
2294         &self,
2295         span: Span,
2296         origin: Option<SubregionOrigin<'tcx>>,
2297         bound_kind: GenericKind<'tcx>,
2298         sub: Region<'tcx>,
2299         owner: Option<LocalDefId>,
2300     ) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
2301         let hir = self.tcx.hir();
2302         // Attempt to obtain the span of the parameter so we can
2303         // suggest adding an explicit lifetime bound to it.
2304         let generics = owner.map(|owner| {
2305             let hir_id = hir.local_def_id_to_hir_id(owner);
2306             let parent_id = hir.get_parent_item(hir_id);
2307             (
2308                 // Parent item could be a `mod`, so we check the HIR before calling:
2309                 if let Some(Node::Item(Item {
2310                     kind: ItemKind::Trait(..) | ItemKind::Impl { .. },
2311                     ..
2312                 })) = hir.find_by_def_id(parent_id)
2313                 {
2314                     Some(self.tcx.generics_of(parent_id))
2315                 } else {
2316                     None
2317                 },
2318                 self.tcx.generics_of(owner.to_def_id()),
2319                 hir.span(hir_id),
2320             )
2321         });
2322
2323         let span = match generics {
2324             // This is to get around the trait identity obligation, that has a `DUMMY_SP` as signal
2325             // for other diagnostics, so we need to recover it here.
2326             Some((_, _, node)) if span.is_dummy() => node,
2327             _ => span,
2328         };
2329
2330         // type_param_span is (span, has_bounds)
2331         let type_param_span = match (generics, bound_kind) {
2332             (Some((_, ref generics, _)), GenericKind::Param(ref param)) => {
2333                 // Account for the case where `param` corresponds to `Self`,
2334                 // which doesn't have the expected type argument.
2335                 if !(generics.has_self && param.index == 0) {
2336                     let type_param = generics.type_param(param, self.tcx);
2337                     type_param.def_id.as_local().map(|def_id| {
2338                         // Get the `hir::Param` to verify whether it already has any bounds.
2339                         // We do this to avoid suggesting code that ends up as `T: 'a'b`,
2340                         // instead we suggest `T: 'a + 'b` in that case.
2341                         let hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id);
2342                         let ast_generics = self.tcx.hir().get_generics(hir_id.owner);
2343                         let bounds =
2344                             ast_generics.and_then(|g| g.bounds_span_for_suggestions(def_id));
2345                         // `sp` only covers `T`, change it so that it covers
2346                         // `T:` when appropriate
2347                         if let Some(span) = bounds {
2348                             (span, true)
2349                         } else {
2350                             let sp = self.tcx.def_span(def_id);
2351                             (sp.shrink_to_hi(), false)
2352                         }
2353                     })
2354                 } else {
2355                     None
2356                 }
2357             }
2358             _ => None,
2359         };
2360         let new_lt = generics
2361             .as_ref()
2362             .and_then(|(parent_g, g, _)| {
2363                 let mut possible = (b'a'..=b'z').map(|c| format!("'{}", c as char));
2364                 let mut lts_names = g
2365                     .params
2366                     .iter()
2367                     .filter(|p| matches!(p.kind, ty::GenericParamDefKind::Lifetime))
2368                     .map(|p| p.name.as_str())
2369                     .collect::<Vec<_>>();
2370                 if let Some(g) = parent_g {
2371                     lts_names.extend(
2372                         g.params
2373                             .iter()
2374                             .filter(|p| matches!(p.kind, ty::GenericParamDefKind::Lifetime))
2375                             .map(|p| p.name.as_str()),
2376                     );
2377                 }
2378                 possible.find(|candidate| !lts_names.contains(&&candidate[..]))
2379             })
2380             .unwrap_or("'lt".to_string());
2381         let add_lt_sugg = generics
2382             .as_ref()
2383             .and_then(|(_, g, _)| g.params.first())
2384             .and_then(|param| param.def_id.as_local())
2385             .map(|def_id| (self.tcx.def_span(def_id).shrink_to_lo(), format!("{}, ", new_lt)));
2386
2387         let labeled_user_string = match bound_kind {
2388             GenericKind::Param(ref p) => format!("the parameter type `{}`", p),
2389             GenericKind::Projection(ref p) => format!("the associated type `{}`", p),
2390         };
2391
2392         if let Some(SubregionOrigin::CompareImplMethodObligation {
2393             span,
2394             impl_item_def_id,
2395             trait_item_def_id,
2396         }) = origin
2397         {
2398             return self.report_extra_impl_obligation(
2399                 span,
2400                 impl_item_def_id,
2401                 trait_item_def_id,
2402                 &format!("`{}: {}`", bound_kind, sub),
2403             );
2404         }
2405
2406         fn binding_suggestion<'tcx, S: fmt::Display>(
2407             err: &mut Diagnostic,
2408             type_param_span: Option<(Span, bool)>,
2409             bound_kind: GenericKind<'tcx>,
2410             sub: S,
2411         ) {
2412             let msg = "consider adding an explicit lifetime bound";
2413             if let Some((sp, has_lifetimes)) = type_param_span {
2414                 let suggestion =
2415                     if has_lifetimes { format!(" + {}", sub) } else { format!(": {}", sub) };
2416                 err.span_suggestion_verbose(
2417                     sp,
2418                     &format!("{}...", msg),
2419                     suggestion,
2420                     Applicability::MaybeIncorrect, // Issue #41966
2421                 );
2422             } else {
2423                 let consider = format!("{} `{}: {}`...", msg, bound_kind, sub,);
2424                 err.help(&consider);
2425             }
2426         }
2427
2428         let new_binding_suggestion =
2429             |err: &mut Diagnostic, type_param_span: Option<(Span, bool)>| {
2430                 let msg = "consider introducing an explicit lifetime bound";
2431                 if let Some((sp, has_lifetimes)) = type_param_span {
2432                     let suggestion = if has_lifetimes {
2433                         format!(" + {}", new_lt)
2434                     } else {
2435                         format!(": {}", new_lt)
2436                     };
2437                     let mut sugg =
2438                         vec![(sp, suggestion), (span.shrink_to_hi(), format!(" + {}", new_lt))];
2439                     if let Some(lt) = add_lt_sugg {
2440                         sugg.push(lt);
2441                         sugg.rotate_right(1);
2442                     }
2443                     // `MaybeIncorrect` due to issue #41966.
2444                     err.multipart_suggestion(msg, sugg, Applicability::MaybeIncorrect);
2445                 }
2446             };
2447
2448         #[derive(Debug)]
2449         enum SubOrigin<'hir> {
2450             GAT(&'hir hir::Generics<'hir>),
2451             Impl(&'hir hir::Generics<'hir>),
2452             Trait(&'hir hir::Generics<'hir>),
2453             Fn(&'hir hir::Generics<'hir>),
2454             Unknown,
2455         }
2456         let sub_origin = 'origin: {
2457             match *sub {
2458                 ty::ReEarlyBound(ty::EarlyBoundRegion { def_id, .. }) => {
2459                     let node = self.tcx.hir().get_if_local(def_id).unwrap();
2460                     match node {
2461                         Node::GenericParam(param) => {
2462                             for h in self.tcx.hir().parent_iter(param.hir_id) {
2463                                 break 'origin match h.1 {
2464                                     Node::ImplItem(hir::ImplItem {
2465                                         kind: hir::ImplItemKind::TyAlias(..),
2466                                         generics,
2467                                         ..
2468                                     }) => SubOrigin::GAT(generics),
2469                                     Node::ImplItem(hir::ImplItem {
2470                                         kind: hir::ImplItemKind::Fn(..),
2471                                         generics,
2472                                         ..
2473                                     }) => SubOrigin::Fn(generics),
2474                                     Node::TraitItem(hir::TraitItem {
2475                                         kind: hir::TraitItemKind::Type(..),
2476                                         generics,
2477                                         ..
2478                                     }) => SubOrigin::GAT(generics),
2479                                     Node::TraitItem(hir::TraitItem {
2480                                         kind: hir::TraitItemKind::Fn(..),
2481                                         generics,
2482                                         ..
2483                                     }) => SubOrigin::Fn(generics),
2484                                     Node::Item(hir::Item {
2485                                         kind: hir::ItemKind::Trait(_, _, generics, _, _),
2486                                         ..
2487                                     }) => SubOrigin::Trait(generics),
2488                                     Node::Item(hir::Item {
2489                                         kind: hir::ItemKind::Impl(hir::Impl { generics, .. }),
2490                                         ..
2491                                     }) => SubOrigin::Impl(generics),
2492                                     Node::Item(hir::Item {
2493                                         kind: hir::ItemKind::Fn(_, generics, _),
2494                                         ..
2495                                     }) => SubOrigin::Fn(generics),
2496                                     _ => continue,
2497                                 };
2498                             }
2499                         }
2500                         _ => {}
2501                     }
2502                 }
2503                 _ => {}
2504             }
2505             SubOrigin::Unknown
2506         };
2507         debug!(?sub_origin);
2508
2509         let mut err = match (*sub, sub_origin) {
2510             // In the case of GATs, we have to be careful. If we a type parameter `T` on an impl,
2511             // but a lifetime `'a` on an associated type, then we might need to suggest adding
2512             // `where T: 'a`. Importantly, this is on the GAT span, not on the `T` declaration.
2513             (ty::ReEarlyBound(ty::EarlyBoundRegion { name: _, .. }), SubOrigin::GAT(generics)) => {
2514                 // Does the required lifetime have a nice name we can print?
2515                 let mut err = struct_span_err!(
2516                     self.tcx.sess,
2517                     span,
2518                     E0309,
2519                     "{} may not live long enough",
2520                     labeled_user_string
2521                 );
2522                 let pred = format!("{}: {}", bound_kind, sub);
2523                 let suggestion = format!(
2524                     "{} {}",
2525                     if !generics.predicates.is_empty() { "," } else { " where" },
2526                     pred,
2527                 );
2528                 err.span_suggestion(
2529                     generics.tail_span_for_predicate_suggestion(),
2530                     "consider adding a where clause",
2531                     suggestion,
2532                     Applicability::MaybeIncorrect,
2533                 );
2534                 err
2535             }
2536             (
2537                 ty::ReEarlyBound(ty::EarlyBoundRegion { name, .. })
2538                 | ty::ReFree(ty::FreeRegion { bound_region: ty::BrNamed(_, name), .. }),
2539                 _,
2540             ) => {
2541                 // Does the required lifetime have a nice name we can print?
2542                 let mut err = struct_span_err!(
2543                     self.tcx.sess,
2544                     span,
2545                     E0309,
2546                     "{} may not live long enough",
2547                     labeled_user_string
2548                 );
2549                 // Explicitly use the name instead of `sub`'s `Display` impl. The `Display` impl
2550                 // for the bound is not suitable for suggestions when `-Zverbose` is set because it
2551                 // uses `Debug` output, so we handle it specially here so that suggestions are
2552                 // always correct.
2553                 binding_suggestion(&mut err, type_param_span, bound_kind, name);
2554                 err
2555             }
2556
2557             (ty::ReStatic, _) => {
2558                 // Does the required lifetime have a nice name we can print?
2559                 let mut err = struct_span_err!(
2560                     self.tcx.sess,
2561                     span,
2562                     E0310,
2563                     "{} may not live long enough",
2564                     labeled_user_string
2565                 );
2566                 binding_suggestion(&mut err, type_param_span, bound_kind, "'static");
2567                 err
2568             }
2569
2570             _ => {
2571                 // If not, be less specific.
2572                 let mut err = struct_span_err!(
2573                     self.tcx.sess,
2574                     span,
2575                     E0311,
2576                     "{} may not live long enough",
2577                     labeled_user_string
2578                 );
2579                 note_and_explain_region(
2580                     self.tcx,
2581                     &mut err,
2582                     &format!("{} must be valid for ", labeled_user_string),
2583                     sub,
2584                     "...",
2585                     None,
2586                 );
2587                 if let Some(infer::RelateParamBound(_, t, _)) = origin {
2588                     let return_impl_trait =
2589                         owner.and_then(|owner| self.tcx.return_type_impl_trait(owner)).is_some();
2590                     let t = self.resolve_vars_if_possible(t);
2591                     match t.kind() {
2592                         // We've got:
2593                         // fn get_later<G, T>(g: G, dest: &mut T) -> impl FnOnce() + '_
2594                         // suggest:
2595                         // fn get_later<'a, G: 'a, T>(g: G, dest: &mut T) -> impl FnOnce() + '_ + 'a
2596                         ty::Closure(_, _substs) | ty::Opaque(_, _substs) if return_impl_trait => {
2597                             new_binding_suggestion(&mut err, type_param_span);
2598                         }
2599                         _ => {
2600                             binding_suggestion(&mut err, type_param_span, bound_kind, new_lt);
2601                         }
2602                     }
2603                 }
2604                 err
2605             }
2606         };
2607
2608         if let Some(origin) = origin {
2609             self.note_region_origin(&mut err, &origin);
2610         }
2611         err
2612     }
2613
2614     fn report_sub_sup_conflict(
2615         &self,
2616         var_origin: RegionVariableOrigin,
2617         sub_origin: SubregionOrigin<'tcx>,
2618         sub_region: Region<'tcx>,
2619         sup_origin: SubregionOrigin<'tcx>,
2620         sup_region: Region<'tcx>,
2621     ) {
2622         let mut err = self.report_inference_failure(var_origin);
2623
2624         note_and_explain_region(
2625             self.tcx,
2626             &mut err,
2627             "first, the lifetime cannot outlive ",
2628             sup_region,
2629             "...",
2630             None,
2631         );
2632
2633         debug!("report_sub_sup_conflict: var_origin={:?}", var_origin);
2634         debug!("report_sub_sup_conflict: sub_region={:?}", sub_region);
2635         debug!("report_sub_sup_conflict: sub_origin={:?}", sub_origin);
2636         debug!("report_sub_sup_conflict: sup_region={:?}", sup_region);
2637         debug!("report_sub_sup_conflict: sup_origin={:?}", sup_origin);
2638
2639         if let (&infer::Subtype(ref sup_trace), &infer::Subtype(ref sub_trace)) =
2640             (&sup_origin, &sub_origin)
2641         {
2642             debug!("report_sub_sup_conflict: sup_trace={:?}", sup_trace);
2643             debug!("report_sub_sup_conflict: sub_trace={:?}", sub_trace);
2644             debug!("report_sub_sup_conflict: sup_trace.values={:?}", sup_trace.values);
2645             debug!("report_sub_sup_conflict: sub_trace.values={:?}", sub_trace.values);
2646
2647             if let (Some((sup_expected, sup_found)), Some((sub_expected, sub_found))) =
2648                 (self.values_str(sup_trace.values), self.values_str(sub_trace.values))
2649             {
2650                 if sub_expected == sup_expected && sub_found == sup_found {
2651                     note_and_explain_region(
2652                         self.tcx,
2653                         &mut err,
2654                         "...but the lifetime must also be valid for ",
2655                         sub_region,
2656                         "...",
2657                         None,
2658                     );
2659                     err.span_note(
2660                         sup_trace.cause.span,
2661                         &format!("...so that the {}", sup_trace.cause.as_requirement_str()),
2662                     );
2663
2664                     err.note_expected_found(&"", sup_expected, &"", sup_found);
2665                     err.emit();
2666                     return;
2667                 }
2668             }
2669         }
2670
2671         self.note_region_origin(&mut err, &sup_origin);
2672
2673         note_and_explain_region(
2674             self.tcx,
2675             &mut err,
2676             "but, the lifetime must be valid for ",
2677             sub_region,
2678             "...",
2679             None,
2680         );
2681
2682         self.note_region_origin(&mut err, &sub_origin);
2683         err.emit();
2684     }
2685
2686     /// Determine whether an error associated with the given span and definition
2687     /// should be treated as being caused by the implicit `From` conversion
2688     /// within `?` desugaring.
2689     pub fn is_try_conversion(&self, span: Span, trait_def_id: DefId) -> bool {
2690         span.is_desugaring(DesugaringKind::QuestionMark)
2691             && self.tcx.is_diagnostic_item(sym::From, trait_def_id)
2692     }
2693 }
2694
2695 impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
2696     fn report_inference_failure(
2697         &self,
2698         var_origin: RegionVariableOrigin,
2699     ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
2700         let br_string = |br: ty::BoundRegionKind| {
2701             let mut s = match br {
2702                 ty::BrNamed(_, name) => name.to_string(),
2703                 _ => String::new(),
2704             };
2705             if !s.is_empty() {
2706                 s.push(' ');
2707             }
2708             s
2709         };
2710         let var_description = match var_origin {
2711             infer::MiscVariable(_) => String::new(),
2712             infer::PatternRegion(_) => " for pattern".to_string(),
2713             infer::AddrOfRegion(_) => " for borrow expression".to_string(),
2714             infer::Autoref(_) => " for autoref".to_string(),
2715             infer::Coercion(_) => " for automatic coercion".to_string(),
2716             infer::LateBoundRegion(_, br, infer::FnCall) => {
2717                 format!(" for lifetime parameter {}in function call", br_string(br))
2718             }
2719             infer::LateBoundRegion(_, br, infer::HigherRankedType) => {
2720                 format!(" for lifetime parameter {}in generic type", br_string(br))
2721             }
2722             infer::LateBoundRegion(_, br, infer::AssocTypeProjection(def_id)) => format!(
2723                 " for lifetime parameter {}in trait containing associated type `{}`",
2724                 br_string(br),
2725                 self.tcx.associated_item(def_id).name
2726             ),
2727             infer::EarlyBoundRegion(_, name) => format!(" for lifetime parameter `{}`", name),
2728             infer::UpvarRegion(ref upvar_id, _) => {
2729                 let var_name = self.tcx.hir().name(upvar_id.var_path.hir_id);
2730                 format!(" for capture of `{}` by closure", var_name)
2731             }
2732             infer::Nll(..) => bug!("NLL variable found in lexical phase"),
2733         };
2734
2735         struct_span_err!(
2736             self.tcx.sess,
2737             var_origin.span(),
2738             E0495,
2739             "cannot infer an appropriate lifetime{} due to conflicting requirements",
2740             var_description
2741         )
2742     }
2743 }
2744
2745 pub enum FailureCode {
2746     Error0038(DefId),
2747     Error0317(&'static str),
2748     Error0580(&'static str),
2749     Error0308(&'static str),
2750     Error0644(&'static str),
2751 }
2752
2753 pub trait ObligationCauseExt<'tcx> {
2754     fn as_failure_code(&self, terr: &TypeError<'tcx>) -> FailureCode;
2755     fn as_requirement_str(&self) -> &'static str;
2756 }
2757
2758 impl<'tcx> ObligationCauseExt<'tcx> for ObligationCause<'tcx> {
2759     fn as_failure_code(&self, terr: &TypeError<'tcx>) -> FailureCode {
2760         use self::FailureCode::*;
2761         use crate::traits::ObligationCauseCode::*;
2762         match self.code() {
2763             CompareImplMethodObligation { .. } => Error0308("method not compatible with trait"),
2764             CompareImplTypeObligation { .. } => Error0308("type not compatible with trait"),
2765             MatchExpressionArm(box MatchExpressionArmCause { source, .. }) => {
2766                 Error0308(match source {
2767                     hir::MatchSource::TryDesugar => "`?` operator has incompatible types",
2768                     _ => "`match` arms have incompatible types",
2769                 })
2770             }
2771             IfExpression { .. } => Error0308("`if` and `else` have incompatible types"),
2772             IfExpressionWithNoElse => Error0317("`if` may be missing an `else` clause"),
2773             LetElse => Error0308("`else` clause of `let...else` does not diverge"),
2774             MainFunctionType => Error0580("`main` function has wrong type"),
2775             StartFunctionType => Error0308("`#[start]` function has wrong type"),
2776             IntrinsicType => Error0308("intrinsic has wrong type"),
2777             MethodReceiver => Error0308("mismatched `self` parameter type"),
2778
2779             // In the case where we have no more specific thing to
2780             // say, also take a look at the error code, maybe we can
2781             // tailor to that.
2782             _ => match terr {
2783                 TypeError::CyclicTy(ty) if ty.is_closure() || ty.is_generator() => {
2784                     Error0644("closure/generator type that references itself")
2785                 }
2786                 TypeError::IntrinsicCast => {
2787                     Error0308("cannot coerce intrinsics to function pointers")
2788                 }
2789                 TypeError::ObjectUnsafeCoercion(did) => Error0038(*did),
2790                 _ => Error0308("mismatched types"),
2791             },
2792         }
2793     }
2794
2795     fn as_requirement_str(&self) -> &'static str {
2796         use crate::traits::ObligationCauseCode::*;
2797         match self.code() {
2798             CompareImplMethodObligation { .. } => "method type is compatible with trait",
2799             CompareImplTypeObligation { .. } => "associated type is compatible with trait",
2800             ExprAssignable => "expression is assignable",
2801             IfExpression { .. } => "`if` and `else` have incompatible types",
2802             IfExpressionWithNoElse => "`if` missing an `else` returns `()`",
2803             MainFunctionType => "`main` function has the correct type",
2804             StartFunctionType => "`#[start]` function has the correct type",
2805             IntrinsicType => "intrinsic has the correct type",
2806             MethodReceiver => "method receiver has the correct type",
2807             _ => "types are compatible",
2808         }
2809     }
2810 }
2811
2812 /// This is a bare signal of what kind of type we're dealing with. `ty::TyKind` tracks
2813 /// extra information about each type, but we only care about the category.
2814 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
2815 pub enum TyCategory {
2816     Closure,
2817     Opaque,
2818     Generator(hir::GeneratorKind),
2819     Foreign,
2820 }
2821
2822 impl TyCategory {
2823     fn descr(&self) -> &'static str {
2824         match self {
2825             Self::Closure => "closure",
2826             Self::Opaque => "opaque type",
2827             Self::Generator(gk) => gk.descr(),
2828             Self::Foreign => "foreign type",
2829         }
2830     }
2831
2832     pub fn from_ty(tcx: TyCtxt<'_>, ty: Ty<'_>) -> Option<(Self, DefId)> {
2833         match *ty.kind() {
2834             ty::Closure(def_id, _) => Some((Self::Closure, def_id)),
2835             ty::Opaque(def_id, _) => Some((Self::Opaque, def_id)),
2836             ty::Generator(def_id, ..) => {
2837                 Some((Self::Generator(tcx.generator_kind(def_id).unwrap()), def_id))
2838             }
2839             ty::Foreign(def_id) => Some((Self::Foreign, def_id)),
2840             _ => None,
2841         }
2842     }
2843 }