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