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