]> git.lizzy.rs Git - rust.git/blob - src/librustc_infer/traits/error_reporting/mod.rs
use find(x) instead of filter(x).next()
[rust.git] / src / librustc_infer / traits / error_reporting / mod.rs
1 pub mod on_unimplemented;
2 pub mod suggestions;
3
4 use super::{
5     ConstEvalFailure, EvaluationResult, FulfillmentError, FulfillmentErrorCode,
6     MismatchedProjectionTypes, ObjectSafetyViolation, Obligation, ObligationCause,
7     ObligationCauseCode, OnUnimplementedDirective, OnUnimplementedNote,
8     OutputTypeParameterMismatch, Overflow, PredicateObligation, SelectionContext, SelectionError,
9     TraitNotObjectSafe,
10 };
11
12 use crate::infer::error_reporting::{TyCategory, TypeAnnotationNeeded as ErrorCode};
13 use crate::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
14 use crate::infer::{self, InferCtxt, TyCtxtInferExt};
15 use rustc::mir::interpret::ErrorHandled;
16 use rustc::session::DiagnosticMessageId;
17 use rustc::ty::error::ExpectedFound;
18 use rustc::ty::fast_reject;
19 use rustc::ty::fold::TypeFolder;
20 use rustc::ty::SubtypePredicate;
21 use rustc::ty::{
22     self, AdtKind, ToPolyTraitRef, ToPredicate, Ty, TyCtxt, TypeFoldable, WithConstness,
23 };
24 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
25 use rustc_errors::{struct_span_err, Applicability, DiagnosticBuilder};
26 use rustc_hir as hir;
27 use rustc_hir::def_id::{DefId, LOCAL_CRATE};
28 use rustc_hir::{QPath, TyKind, WhereBoundPredicate, WherePredicate};
29 use rustc_span::source_map::SourceMap;
30 use rustc_span::{ExpnKind, Span, DUMMY_SP};
31 use std::fmt;
32 use syntax::ast;
33
34 impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
35     pub fn report_fulfillment_errors(
36         &self,
37         errors: &[FulfillmentError<'tcx>],
38         body_id: Option<hir::BodyId>,
39         fallback_has_occurred: bool,
40     ) {
41         #[derive(Debug)]
42         struct ErrorDescriptor<'tcx> {
43             predicate: ty::Predicate<'tcx>,
44             index: Option<usize>, // None if this is an old error
45         }
46
47         let mut error_map: FxHashMap<_, Vec<_>> = self
48             .reported_trait_errors
49             .borrow()
50             .iter()
51             .map(|(&span, predicates)| {
52                 (
53                     span,
54                     predicates
55                         .iter()
56                         .map(|&predicate| ErrorDescriptor { predicate, index: None })
57                         .collect(),
58                 )
59             })
60             .collect();
61
62         for (index, error) in errors.iter().enumerate() {
63             // We want to ignore desugarings here: spans are equivalent even
64             // if one is the result of a desugaring and the other is not.
65             let mut span = error.obligation.cause.span;
66             let expn_data = span.ctxt().outer_expn_data();
67             if let ExpnKind::Desugaring(_) = expn_data.kind {
68                 span = expn_data.call_site;
69             }
70
71             error_map.entry(span).or_default().push(ErrorDescriptor {
72                 predicate: error.obligation.predicate,
73                 index: Some(index),
74             });
75
76             self.reported_trait_errors
77                 .borrow_mut()
78                 .entry(span)
79                 .or_default()
80                 .push(error.obligation.predicate.clone());
81         }
82
83         // We do this in 2 passes because we want to display errors in order, though
84         // maybe it *is* better to sort errors by span or something.
85         let mut is_suppressed = vec![false; errors.len()];
86         for (_, error_set) in error_map.iter() {
87             // We want to suppress "duplicate" errors with the same span.
88             for error in error_set {
89                 if let Some(index) = error.index {
90                     // Suppress errors that are either:
91                     // 1) strictly implied by another error.
92                     // 2) implied by an error with a smaller index.
93                     for error2 in error_set {
94                         if error2.index.map_or(false, |index2| is_suppressed[index2]) {
95                             // Avoid errors being suppressed by already-suppressed
96                             // errors, to prevent all errors from being suppressed
97                             // at once.
98                             continue;
99                         }
100
101                         if self.error_implies(&error2.predicate, &error.predicate)
102                             && !(error2.index >= error.index
103                                 && self.error_implies(&error.predicate, &error2.predicate))
104                         {
105                             info!("skipping {:?} (implied by {:?})", error, error2);
106                             is_suppressed[index] = true;
107                             break;
108                         }
109                     }
110                 }
111             }
112         }
113
114         for (error, suppressed) in errors.iter().zip(is_suppressed) {
115             if !suppressed {
116                 self.report_fulfillment_error(error, body_id, fallback_has_occurred);
117             }
118         }
119     }
120
121     // returns if `cond` not occurring implies that `error` does not occur - i.e., that
122     // `error` occurring implies that `cond` occurs.
123     fn error_implies(&self, cond: &ty::Predicate<'tcx>, error: &ty::Predicate<'tcx>) -> bool {
124         if cond == error {
125             return true;
126         }
127
128         let (cond, error) = match (cond, error) {
129             (&ty::Predicate::Trait(..), &ty::Predicate::Trait(ref error, _)) => (cond, error),
130             _ => {
131                 // FIXME: make this work in other cases too.
132                 return false;
133             }
134         };
135
136         for implication in super::elaborate_predicates(self.tcx, vec![*cond]) {
137             if let ty::Predicate::Trait(implication, _) = implication {
138                 let error = error.to_poly_trait_ref();
139                 let implication = implication.to_poly_trait_ref();
140                 // FIXME: I'm just not taking associated types at all here.
141                 // Eventually I'll need to implement param-env-aware
142                 // `Γ₁ ⊦ φ₁ => Γ₂ ⊦ φ₂` logic.
143                 let param_env = ty::ParamEnv::empty();
144                 if self.can_sub(param_env, error, implication).is_ok() {
145                     debug!("error_implies: {:?} -> {:?} -> {:?}", cond, error, implication);
146                     return true;
147                 }
148             }
149         }
150
151         false
152     }
153
154     fn report_fulfillment_error(
155         &self,
156         error: &FulfillmentError<'tcx>,
157         body_id: Option<hir::BodyId>,
158         fallback_has_occurred: bool,
159     ) {
160         debug!("report_fulfillment_error({:?})", error);
161         match error.code {
162             FulfillmentErrorCode::CodeSelectionError(ref selection_error) => {
163                 self.report_selection_error(
164                     &error.obligation,
165                     selection_error,
166                     fallback_has_occurred,
167                     error.points_at_arg_span,
168                 );
169             }
170             FulfillmentErrorCode::CodeProjectionError(ref e) => {
171                 self.report_projection_error(&error.obligation, e);
172             }
173             FulfillmentErrorCode::CodeAmbiguity => {
174                 self.maybe_report_ambiguity(&error.obligation, body_id);
175             }
176             FulfillmentErrorCode::CodeSubtypeError(ref expected_found, ref err) => {
177                 self.report_mismatched_types(
178                     &error.obligation.cause,
179                     expected_found.expected,
180                     expected_found.found,
181                     err.clone(),
182                 )
183                 .emit();
184             }
185         }
186     }
187
188     fn report_projection_error(
189         &self,
190         obligation: &PredicateObligation<'tcx>,
191         error: &MismatchedProjectionTypes<'tcx>,
192     ) {
193         let predicate = self.resolve_vars_if_possible(&obligation.predicate);
194
195         if predicate.references_error() {
196             return;
197         }
198
199         self.probe(|_| {
200             let err_buf;
201             let mut err = &error.err;
202             let mut values = None;
203
204             // try to find the mismatched types to report the error with.
205             //
206             // this can fail if the problem was higher-ranked, in which
207             // cause I have no idea for a good error message.
208             if let ty::Predicate::Projection(ref data) = predicate {
209                 let mut selcx = SelectionContext::new(self);
210                 let (data, _) = self.replace_bound_vars_with_fresh_vars(
211                     obligation.cause.span,
212                     infer::LateBoundRegionConversionTime::HigherRankedType,
213                     data,
214                 );
215                 let mut obligations = vec![];
216                 let normalized_ty = super::normalize_projection_type(
217                     &mut selcx,
218                     obligation.param_env,
219                     data.projection_ty,
220                     obligation.cause.clone(),
221                     0,
222                     &mut obligations,
223                 );
224
225                 debug!(
226                     "report_projection_error obligation.cause={:?} obligation.param_env={:?}",
227                     obligation.cause, obligation.param_env
228                 );
229
230                 debug!(
231                     "report_projection_error normalized_ty={:?} data.ty={:?}",
232                     normalized_ty, data.ty
233                 );
234
235                 let is_normalized_ty_expected = match &obligation.cause.code {
236                     ObligationCauseCode::ItemObligation(_)
237                     | ObligationCauseCode::BindingObligation(_, _)
238                     | ObligationCauseCode::ObjectCastObligation(_) => false,
239                     _ => true,
240                 };
241
242                 if let Err(error) = self.at(&obligation.cause, obligation.param_env).eq_exp(
243                     is_normalized_ty_expected,
244                     normalized_ty,
245                     data.ty,
246                 ) {
247                     values = Some(infer::ValuePairs::Types(ExpectedFound::new(
248                         is_normalized_ty_expected,
249                         normalized_ty,
250                         data.ty,
251                     )));
252
253                     err_buf = error;
254                     err = &err_buf;
255                 }
256             }
257
258             let msg = format!("type mismatch resolving `{}`", predicate);
259             let error_id = (DiagnosticMessageId::ErrorId(271), Some(obligation.cause.span), msg);
260             let fresh = self.tcx.sess.one_time_diagnostics.borrow_mut().insert(error_id);
261             if fresh {
262                 let mut diag = struct_span_err!(
263                     self.tcx.sess,
264                     obligation.cause.span,
265                     E0271,
266                     "type mismatch resolving `{}`",
267                     predicate
268                 );
269                 self.note_type_err(&mut diag, &obligation.cause, None, values, err);
270                 self.note_obligation_cause(&mut diag, obligation);
271                 diag.emit();
272             }
273         });
274     }
275
276     fn fuzzy_match_tys(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
277         /// returns the fuzzy category of a given type, or None
278         /// if the type can be equated to any type.
279         fn type_category(t: Ty<'_>) -> Option<u32> {
280             match t.kind {
281                 ty::Bool => Some(0),
282                 ty::Char => Some(1),
283                 ty::Str => Some(2),
284                 ty::Int(..) | ty::Uint(..) | ty::Infer(ty::IntVar(..)) => Some(3),
285                 ty::Float(..) | ty::Infer(ty::FloatVar(..)) => Some(4),
286                 ty::Ref(..) | ty::RawPtr(..) => Some(5),
287                 ty::Array(..) | ty::Slice(..) => Some(6),
288                 ty::FnDef(..) | ty::FnPtr(..) => Some(7),
289                 ty::Dynamic(..) => Some(8),
290                 ty::Closure(..) => Some(9),
291                 ty::Tuple(..) => Some(10),
292                 ty::Projection(..) => Some(11),
293                 ty::Param(..) => Some(12),
294                 ty::Opaque(..) => Some(13),
295                 ty::Never => Some(14),
296                 ty::Adt(adt, ..) => match adt.adt_kind() {
297                     AdtKind::Struct => Some(15),
298                     AdtKind::Union => Some(16),
299                     AdtKind::Enum => Some(17),
300                 },
301                 ty::Generator(..) => Some(18),
302                 ty::Foreign(..) => Some(19),
303                 ty::GeneratorWitness(..) => Some(20),
304                 ty::Placeholder(..) | ty::Bound(..) | ty::Infer(..) | ty::Error => None,
305                 ty::UnnormalizedProjection(..) => bug!("only used with chalk-engine"),
306             }
307         }
308
309         match (type_category(a), type_category(b)) {
310             (Some(cat_a), Some(cat_b)) => match (&a.kind, &b.kind) {
311                 (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) => def_a == def_b,
312                 _ => cat_a == cat_b,
313             },
314             // infer and error can be equated to all types
315             _ => true,
316         }
317     }
318
319     fn describe_generator(&self, body_id: hir::BodyId) -> Option<&'static str> {
320         self.tcx.hir().body(body_id).generator_kind.map(|gen_kind| match gen_kind {
321             hir::GeneratorKind::Gen => "a generator",
322             hir::GeneratorKind::Async(hir::AsyncGeneratorKind::Block) => "an async block",
323             hir::GeneratorKind::Async(hir::AsyncGeneratorKind::Fn) => "an async function",
324             hir::GeneratorKind::Async(hir::AsyncGeneratorKind::Closure) => "an async closure",
325         })
326     }
327
328     fn find_similar_impl_candidates(
329         &self,
330         trait_ref: ty::PolyTraitRef<'tcx>,
331     ) -> Vec<ty::TraitRef<'tcx>> {
332         let simp = fast_reject::simplify_type(self.tcx, trait_ref.skip_binder().self_ty(), true);
333         let all_impls = self.tcx.all_impls(trait_ref.def_id());
334
335         match simp {
336             Some(simp) => all_impls
337                 .iter()
338                 .filter_map(|&def_id| {
339                     let imp = self.tcx.impl_trait_ref(def_id).unwrap();
340                     let imp_simp = fast_reject::simplify_type(self.tcx, imp.self_ty(), true);
341                     if let Some(imp_simp) = imp_simp {
342                         if simp != imp_simp {
343                             return None;
344                         }
345                     }
346
347                     Some(imp)
348                 })
349                 .collect(),
350             None => {
351                 all_impls.iter().map(|&def_id| self.tcx.impl_trait_ref(def_id).unwrap()).collect()
352             }
353         }
354     }
355
356     fn report_similar_impl_candidates(
357         &self,
358         impl_candidates: Vec<ty::TraitRef<'tcx>>,
359         err: &mut DiagnosticBuilder<'_>,
360     ) {
361         if impl_candidates.is_empty() {
362             return;
363         }
364
365         let len = impl_candidates.len();
366         let end = if impl_candidates.len() <= 5 { impl_candidates.len() } else { 4 };
367
368         let normalize = |candidate| {
369             self.tcx.infer_ctxt().enter(|ref infcx| {
370                 let normalized = infcx
371                     .at(&ObligationCause::dummy(), ty::ParamEnv::empty())
372                     .normalize(candidate)
373                     .ok();
374                 match normalized {
375                     Some(normalized) => format!("\n  {:?}", normalized.value),
376                     None => format!("\n  {:?}", candidate),
377                 }
378             })
379         };
380
381         // Sort impl candidates so that ordering is consistent for UI tests.
382         let mut normalized_impl_candidates =
383             impl_candidates.iter().map(normalize).collect::<Vec<String>>();
384
385         // Sort before taking the `..end` range,
386         // because the ordering of `impl_candidates` may not be deterministic:
387         // https://github.com/rust-lang/rust/pull/57475#issuecomment-455519507
388         normalized_impl_candidates.sort();
389
390         err.help(&format!(
391             "the following implementations were found:{}{}",
392             normalized_impl_candidates[..end].join(""),
393             if len > 5 { format!("\nand {} others", len - 4) } else { String::new() }
394         ));
395     }
396
397     /// Reports that an overflow has occurred and halts compilation. We
398     /// halt compilation unconditionally because it is important that
399     /// overflows never be masked -- they basically represent computations
400     /// whose result could not be truly determined and thus we can't say
401     /// if the program type checks or not -- and they are unusual
402     /// occurrences in any case.
403     pub fn report_overflow_error<T>(
404         &self,
405         obligation: &Obligation<'tcx, T>,
406         suggest_increasing_limit: bool,
407     ) -> !
408     where
409         T: fmt::Display + TypeFoldable<'tcx>,
410     {
411         let predicate = self.resolve_vars_if_possible(&obligation.predicate);
412         let mut err = struct_span_err!(
413             self.tcx.sess,
414             obligation.cause.span,
415             E0275,
416             "overflow evaluating the requirement `{}`",
417             predicate
418         );
419
420         if suggest_increasing_limit {
421             self.suggest_new_overflow_limit(&mut err);
422         }
423
424         self.note_obligation_cause_code(
425             &mut err,
426             &obligation.predicate,
427             &obligation.cause.code,
428             &mut vec![],
429         );
430
431         err.emit();
432         self.tcx.sess.abort_if_errors();
433         bug!();
434     }
435
436     /// Reports that a cycle was detected which led to overflow and halts
437     /// compilation. This is equivalent to `report_overflow_error` except
438     /// that we can give a more helpful error message (and, in particular,
439     /// we do not suggest increasing the overflow limit, which is not
440     /// going to help).
441     pub fn report_overflow_error_cycle(&self, cycle: &[PredicateObligation<'tcx>]) -> ! {
442         let cycle = self.resolve_vars_if_possible(&cycle.to_owned());
443         assert!(cycle.len() > 0);
444
445         debug!("report_overflow_error_cycle: cycle={:?}", cycle);
446
447         self.report_overflow_error(&cycle[0], false);
448     }
449
450     pub fn report_extra_impl_obligation(
451         &self,
452         error_span: Span,
453         item_name: ast::Name,
454         _impl_item_def_id: DefId,
455         trait_item_def_id: DefId,
456         requirement: &dyn fmt::Display,
457     ) -> DiagnosticBuilder<'tcx> {
458         let msg = "impl has stricter requirements than trait";
459         let sp = self.tcx.sess.source_map().def_span(error_span);
460
461         let mut err = struct_span_err!(self.tcx.sess, sp, E0276, "{}", msg);
462
463         if let Some(trait_item_span) = self.tcx.hir().span_if_local(trait_item_def_id) {
464             let span = self.tcx.sess.source_map().def_span(trait_item_span);
465             err.span_label(span, format!("definition of `{}` from trait", item_name));
466         }
467
468         err.span_label(sp, format!("impl has extra requirement {}", requirement));
469
470         err
471     }
472
473     /// Gets the parent trait chain start
474     fn get_parent_trait_ref(
475         &self,
476         code: &ObligationCauseCode<'tcx>,
477     ) -> Option<(String, Option<Span>)> {
478         match code {
479             &ObligationCauseCode::BuiltinDerivedObligation(ref data) => {
480                 let parent_trait_ref = self.resolve_vars_if_possible(&data.parent_trait_ref);
481                 match self.get_parent_trait_ref(&data.parent_code) {
482                     Some(t) => Some(t),
483                     None => {
484                         let ty = parent_trait_ref.skip_binder().self_ty();
485                         let span =
486                             TyCategory::from_ty(ty).map(|(_, def_id)| self.tcx.def_span(def_id));
487                         Some((ty.to_string(), span))
488                     }
489                 }
490             }
491             _ => None,
492         }
493     }
494
495     pub fn report_selection_error(
496         &self,
497         obligation: &PredicateObligation<'tcx>,
498         error: &SelectionError<'tcx>,
499         fallback_has_occurred: bool,
500         points_at_arg: bool,
501     ) {
502         let tcx = self.tcx;
503         let span = obligation.cause.span;
504
505         let mut err = match *error {
506             SelectionError::Unimplemented => {
507                 if let ObligationCauseCode::CompareImplMethodObligation {
508                     item_name,
509                     impl_item_def_id,
510                     trait_item_def_id,
511                 }
512                 | ObligationCauseCode::CompareImplTypeObligation {
513                     item_name,
514                     impl_item_def_id,
515                     trait_item_def_id,
516                 } = obligation.cause.code
517                 {
518                     self.report_extra_impl_obligation(
519                         span,
520                         item_name,
521                         impl_item_def_id,
522                         trait_item_def_id,
523                         &format!("`{}`", obligation.predicate),
524                     )
525                     .emit();
526                     return;
527                 }
528                 match obligation.predicate {
529                     ty::Predicate::Trait(ref trait_predicate, _) => {
530                         let trait_predicate = self.resolve_vars_if_possible(trait_predicate);
531
532                         if self.tcx.sess.has_errors() && trait_predicate.references_error() {
533                             return;
534                         }
535                         let trait_ref = trait_predicate.to_poly_trait_ref();
536                         let (post_message, pre_message, type_def) = self
537                             .get_parent_trait_ref(&obligation.cause.code)
538                             .map(|(t, s)| {
539                                 (
540                                     format!(" in `{}`", t),
541                                     format!("within `{}`, ", t),
542                                     s.map(|s| (format!("within this `{}`", t), s)),
543                                 )
544                             })
545                             .unwrap_or_default();
546
547                         let OnUnimplementedNote { message, label, note, enclosing_scope } =
548                             self.on_unimplemented_note(trait_ref, obligation);
549                         let have_alt_message = message.is_some() || label.is_some();
550                         let is_try = self
551                             .tcx
552                             .sess
553                             .source_map()
554                             .span_to_snippet(span)
555                             .map(|s| &s == "?")
556                             .unwrap_or(false);
557                         let is_from = format!("{}", trait_ref.print_only_trait_path())
558                             .starts_with("std::convert::From<");
559                         let (message, note) = if is_try && is_from {
560                             (
561                                 Some(format!(
562                                     "`?` couldn't convert the error to `{}`",
563                                     trait_ref.self_ty(),
564                                 )),
565                                 Some(
566                                     "the question mark operation (`?`) implicitly performs a \
567                                      conversion on the error value using the `From` trait"
568                                         .to_owned(),
569                                 ),
570                             )
571                         } else {
572                             (message, note)
573                         };
574
575                         let mut err = struct_span_err!(
576                             self.tcx.sess,
577                             span,
578                             E0277,
579                             "{}",
580                             message.unwrap_or_else(|| format!(
581                                 "the trait bound `{}` is not satisfied{}",
582                                 trait_ref.without_const().to_predicate(),
583                                 post_message,
584                             ))
585                         );
586
587                         let explanation =
588                             if obligation.cause.code == ObligationCauseCode::MainFunctionType {
589                                 "consider using `()`, or a `Result`".to_owned()
590                             } else {
591                                 format!(
592                                     "{}the trait `{}` is not implemented for `{}`",
593                                     pre_message,
594                                     trait_ref.print_only_trait_path(),
595                                     trait_ref.self_ty(),
596                                 )
597                             };
598
599                         if self.suggest_add_reference_to_arg(
600                             &obligation,
601                             &mut err,
602                             &trait_ref,
603                             points_at_arg,
604                             have_alt_message,
605                         ) {
606                             self.note_obligation_cause(&mut err, obligation);
607                             err.emit();
608                             return;
609                         }
610                         if let Some(ref s) = label {
611                             // If it has a custom `#[rustc_on_unimplemented]`
612                             // error message, let's display it as the label!
613                             err.span_label(span, s.as_str());
614                             err.help(&explanation);
615                         } else {
616                             err.span_label(span, explanation);
617                         }
618                         if let Some((msg, span)) = type_def {
619                             err.span_label(span, &msg);
620                         }
621                         if let Some(ref s) = note {
622                             // If it has a custom `#[rustc_on_unimplemented]` note, let's display it
623                             err.note(s.as_str());
624                         }
625                         if let Some(ref s) = enclosing_scope {
626                             let enclosing_scope_span = tcx.def_span(
627                                 tcx.hir()
628                                     .opt_local_def_id(obligation.cause.body_id)
629                                     .unwrap_or_else(|| {
630                                         tcx.hir().body_owner_def_id(hir::BodyId {
631                                             hir_id: obligation.cause.body_id,
632                                         })
633                                     }),
634                             );
635
636                             err.span_label(enclosing_scope_span, s.as_str());
637                         }
638
639                         self.suggest_borrow_on_unsized_slice(&obligation.cause.code, &mut err);
640                         self.suggest_fn_call(&obligation, &mut err, &trait_ref, points_at_arg);
641                         self.suggest_remove_reference(&obligation, &mut err, &trait_ref);
642                         self.suggest_semicolon_removal(&obligation, &mut err, span, &trait_ref);
643                         self.note_version_mismatch(&mut err, &trait_ref);
644                         if self.suggest_impl_trait(&mut err, span, &obligation, &trait_ref) {
645                             err.emit();
646                             return;
647                         }
648
649                         // Try to report a help message
650                         if !trait_ref.has_infer_types()
651                             && self.predicate_can_apply(obligation.param_env, trait_ref)
652                         {
653                             // If a where-clause may be useful, remind the
654                             // user that they can add it.
655                             //
656                             // don't display an on-unimplemented note, as
657                             // these notes will often be of the form
658                             //     "the type `T` can't be frobnicated"
659                             // which is somewhat confusing.
660                             self.suggest_restricting_param_bound(
661                                 &mut err,
662                                 &trait_ref,
663                                 obligation.cause.body_id,
664                             );
665                         } else {
666                             if !have_alt_message {
667                                 // Can't show anything else useful, try to find similar impls.
668                                 let impl_candidates = self.find_similar_impl_candidates(trait_ref);
669                                 self.report_similar_impl_candidates(impl_candidates, &mut err);
670                             }
671                             self.suggest_change_mut(
672                                 &obligation,
673                                 &mut err,
674                                 &trait_ref,
675                                 points_at_arg,
676                             );
677                         }
678
679                         // If this error is due to `!: Trait` not implemented but `(): Trait` is
680                         // implemented, and fallback has occurred, then it could be due to a
681                         // variable that used to fallback to `()` now falling back to `!`. Issue a
682                         // note informing about the change in behaviour.
683                         if trait_predicate.skip_binder().self_ty().is_never()
684                             && fallback_has_occurred
685                         {
686                             let predicate = trait_predicate.map_bound(|mut trait_pred| {
687                                 trait_pred.trait_ref.substs = self.tcx.mk_substs_trait(
688                                     self.tcx.mk_unit(),
689                                     &trait_pred.trait_ref.substs[1..],
690                                 );
691                                 trait_pred
692                             });
693                             let unit_obligation = Obligation {
694                                 predicate: ty::Predicate::Trait(
695                                     predicate,
696                                     hir::Constness::NotConst,
697                                 ),
698                                 ..obligation.clone()
699                             };
700                             if self.predicate_may_hold(&unit_obligation) {
701                                 err.note(
702                                     "the trait is implemented for `()`. \
703                                      Possibly this error has been caused by changes to \
704                                      Rust's type-inference algorithm (see issue #48950 \
705                                      <https://github.com/rust-lang/rust/issues/48950> \
706                                      for more information). Consider whether you meant to use \
707                                      the type `()` here instead.",
708                                 );
709                             }
710                         }
711
712                         err
713                     }
714
715                     ty::Predicate::Subtype(ref predicate) => {
716                         // Errors for Subtype predicates show up as
717                         // `FulfillmentErrorCode::CodeSubtypeError`,
718                         // not selection error.
719                         span_bug!(span, "subtype requirement gave wrong error: `{:?}`", predicate)
720                     }
721
722                     ty::Predicate::RegionOutlives(ref predicate) => {
723                         let predicate = self.resolve_vars_if_possible(predicate);
724                         let err = self
725                             .region_outlives_predicate(&obligation.cause, &predicate)
726                             .err()
727                             .unwrap();
728                         struct_span_err!(
729                             self.tcx.sess,
730                             span,
731                             E0279,
732                             "the requirement `{}` is not satisfied (`{}`)",
733                             predicate,
734                             err,
735                         )
736                     }
737
738                     ty::Predicate::Projection(..) | ty::Predicate::TypeOutlives(..) => {
739                         let predicate = self.resolve_vars_if_possible(&obligation.predicate);
740                         struct_span_err!(
741                             self.tcx.sess,
742                             span,
743                             E0280,
744                             "the requirement `{}` is not satisfied",
745                             predicate
746                         )
747                     }
748
749                     ty::Predicate::ObjectSafe(trait_def_id) => {
750                         let violations = self.tcx.object_safety_violations(trait_def_id);
751                         report_object_safety_error(self.tcx, span, trait_def_id, violations)
752                     }
753
754                     ty::Predicate::ClosureKind(closure_def_id, closure_substs, kind) => {
755                         let found_kind = self.closure_kind(closure_def_id, closure_substs).unwrap();
756                         let closure_span = self
757                             .tcx
758                             .sess
759                             .source_map()
760                             .def_span(self.tcx.hir().span_if_local(closure_def_id).unwrap());
761                         let hir_id = self.tcx.hir().as_local_hir_id(closure_def_id).unwrap();
762                         let mut err = struct_span_err!(
763                             self.tcx.sess,
764                             closure_span,
765                             E0525,
766                             "expected a closure that implements the `{}` trait, \
767                              but this closure only implements `{}`",
768                             kind,
769                             found_kind
770                         );
771
772                         err.span_label(
773                             closure_span,
774                             format!("this closure implements `{}`, not `{}`", found_kind, kind),
775                         );
776                         err.span_label(
777                             obligation.cause.span,
778                             format!("the requirement to implement `{}` derives from here", kind),
779                         );
780
781                         // Additional context information explaining why the closure only implements
782                         // a particular trait.
783                         if let Some(tables) = self.in_progress_tables {
784                             let tables = tables.borrow();
785                             match (found_kind, tables.closure_kind_origins().get(hir_id)) {
786                                 (ty::ClosureKind::FnOnce, Some((span, name))) => {
787                                     err.span_label(
788                                         *span,
789                                         format!(
790                                             "closure is `FnOnce` because it moves the \
791                                          variable `{}` out of its environment",
792                                             name
793                                         ),
794                                     );
795                                 }
796                                 (ty::ClosureKind::FnMut, Some((span, name))) => {
797                                     err.span_label(
798                                         *span,
799                                         format!(
800                                             "closure is `FnMut` because it mutates the \
801                                          variable `{}` here",
802                                             name
803                                         ),
804                                     );
805                                 }
806                                 _ => {}
807                             }
808                         }
809
810                         err.emit();
811                         return;
812                     }
813
814                     ty::Predicate::WellFormed(ty) => {
815                         if !self.tcx.sess.opts.debugging_opts.chalk {
816                             // WF predicates cannot themselves make
817                             // errors. They can only block due to
818                             // ambiguity; otherwise, they always
819                             // degenerate into other obligations
820                             // (which may fail).
821                             span_bug!(span, "WF predicate not satisfied for {:?}", ty);
822                         } else {
823                             // FIXME: we'll need a better message which takes into account
824                             // which bounds actually failed to hold.
825                             self.tcx.sess.struct_span_err(
826                                 span,
827                                 &format!("the type `{}` is not well-formed (chalk)", ty),
828                             )
829                         }
830                     }
831
832                     ty::Predicate::ConstEvaluatable(..) => {
833                         // Errors for `ConstEvaluatable` predicates show up as
834                         // `SelectionError::ConstEvalFailure`,
835                         // not `Unimplemented`.
836                         span_bug!(
837                             span,
838                             "const-evaluatable requirement gave wrong error: `{:?}`",
839                             obligation
840                         )
841                     }
842                 }
843             }
844
845             OutputTypeParameterMismatch(ref found_trait_ref, ref expected_trait_ref, _) => {
846                 let found_trait_ref = self.resolve_vars_if_possible(&*found_trait_ref);
847                 let expected_trait_ref = self.resolve_vars_if_possible(&*expected_trait_ref);
848
849                 if expected_trait_ref.self_ty().references_error() {
850                     return;
851                 }
852
853                 let found_trait_ty = found_trait_ref.self_ty();
854
855                 let found_did = match found_trait_ty.kind {
856                     ty::Closure(did, _) | ty::Foreign(did) | ty::FnDef(did, _) => Some(did),
857                     ty::Adt(def, _) => Some(def.did),
858                     _ => None,
859                 };
860
861                 let found_span = found_did
862                     .and_then(|did| self.tcx.hir().span_if_local(did))
863                     .map(|sp| self.tcx.sess.source_map().def_span(sp)); // the sp could be an fn def
864
865                 if self.reported_closure_mismatch.borrow().contains(&(span, found_span)) {
866                     // We check closures twice, with obligations flowing in different directions,
867                     // but we want to complain about them only once.
868                     return;
869                 }
870
871                 self.reported_closure_mismatch.borrow_mut().insert((span, found_span));
872
873                 let found = match found_trait_ref.skip_binder().substs.type_at(1).kind {
874                     ty::Tuple(ref tys) => vec![ArgKind::empty(); tys.len()],
875                     _ => vec![ArgKind::empty()],
876                 };
877
878                 let expected_ty = expected_trait_ref.skip_binder().substs.type_at(1);
879                 let expected = match expected_ty.kind {
880                     ty::Tuple(ref tys) => tys
881                         .iter()
882                         .map(|t| ArgKind::from_expected_ty(t.expect_ty(), Some(span)))
883                         .collect(),
884                     _ => vec![ArgKind::Arg("_".to_owned(), expected_ty.to_string())],
885                 };
886
887                 if found.len() == expected.len() {
888                     self.report_closure_arg_mismatch(
889                         span,
890                         found_span,
891                         found_trait_ref,
892                         expected_trait_ref,
893                     )
894                 } else {
895                     let (closure_span, found) = found_did
896                         .and_then(|did| self.tcx.hir().get_if_local(did))
897                         .map(|node| {
898                             let (found_span, found) = self.get_fn_like_arguments(node);
899                             (Some(found_span), found)
900                         })
901                         .unwrap_or((found_span, found));
902
903                     self.report_arg_count_mismatch(
904                         span,
905                         closure_span,
906                         expected,
907                         found,
908                         found_trait_ty.is_closure(),
909                     )
910                 }
911             }
912
913             TraitNotObjectSafe(did) => {
914                 let violations = self.tcx.object_safety_violations(did);
915                 report_object_safety_error(self.tcx, span, did, violations)
916             }
917
918             ConstEvalFailure(ErrorHandled::TooGeneric) => {
919                 // In this instance, we have a const expression containing an unevaluated
920                 // generic parameter. We have no idea whether this expression is valid or
921                 // not (e.g. it might result in an error), but we don't want to just assume
922                 // that it's okay, because that might result in post-monomorphisation time
923                 // errors. The onus is really on the caller to provide values that it can
924                 // prove are well-formed.
925                 let mut err = self
926                     .tcx
927                     .sess
928                     .struct_span_err(span, "constant expression depends on a generic parameter");
929                 // FIXME(const_generics): we should suggest to the user how they can resolve this
930                 // issue. However, this is currently not actually possible
931                 // (see https://github.com/rust-lang/rust/issues/66962#issuecomment-575907083).
932                 err.note("this may fail depending on what value the parameter takes");
933                 err
934             }
935
936             // Already reported in the query.
937             ConstEvalFailure(ErrorHandled::Reported) => {
938                 self.tcx
939                     .sess
940                     .delay_span_bug(span, &format!("constant in type had an ignored error"));
941                 return;
942             }
943
944             Overflow => {
945                 bug!("overflow should be handled before the `report_selection_error` path");
946             }
947         };
948
949         self.note_obligation_cause(&mut err, obligation);
950         self.point_at_returns_when_relevant(&mut err, &obligation);
951
952         err.emit();
953     }
954
955     /// If the `Self` type of the unsatisfied trait `trait_ref` implements a trait
956     /// with the same path as `trait_ref`, a help message about
957     /// a probable version mismatch is added to `err`
958     fn note_version_mismatch(
959         &self,
960         err: &mut DiagnosticBuilder<'_>,
961         trait_ref: &ty::PolyTraitRef<'tcx>,
962     ) {
963         let get_trait_impl = |trait_def_id| {
964             let mut trait_impl = None;
965             self.tcx.for_each_relevant_impl(trait_def_id, trait_ref.self_ty(), |impl_def_id| {
966                 if trait_impl.is_none() {
967                     trait_impl = Some(impl_def_id);
968                 }
969             });
970             trait_impl
971         };
972         let required_trait_path = self.tcx.def_path_str(trait_ref.def_id());
973         let all_traits = self.tcx.all_traits(LOCAL_CRATE);
974         let traits_with_same_path: std::collections::BTreeSet<_> = all_traits
975             .iter()
976             .filter(|trait_def_id| **trait_def_id != trait_ref.def_id())
977             .filter(|trait_def_id| self.tcx.def_path_str(**trait_def_id) == required_trait_path)
978             .collect();
979         for trait_with_same_path in traits_with_same_path {
980             if let Some(impl_def_id) = get_trait_impl(*trait_with_same_path) {
981                 let impl_span = self.tcx.def_span(impl_def_id);
982                 err.span_help(impl_span, "trait impl with same name found");
983                 let trait_crate = self.tcx.crate_name(trait_with_same_path.krate);
984                 let crate_msg = format!(
985                     "perhaps two different versions of crate `{}` are being used?",
986                     trait_crate
987                 );
988                 err.note(&crate_msg);
989             }
990         }
991     }
992
993     fn mk_obligation_for_def_id(
994         &self,
995         def_id: DefId,
996         output_ty: Ty<'tcx>,
997         cause: ObligationCause<'tcx>,
998         param_env: ty::ParamEnv<'tcx>,
999     ) -> PredicateObligation<'tcx> {
1000         let new_trait_ref =
1001             ty::TraitRef { def_id, substs: self.tcx.mk_substs_trait(output_ty, &[]) };
1002         Obligation::new(cause, param_env, new_trait_ref.without_const().to_predicate())
1003     }
1004 }
1005
1006 pub fn recursive_type_with_infinite_size_error(
1007     tcx: TyCtxt<'tcx>,
1008     type_def_id: DefId,
1009 ) -> DiagnosticBuilder<'tcx> {
1010     assert!(type_def_id.is_local());
1011     let span = tcx.hir().span_if_local(type_def_id).unwrap();
1012     let span = tcx.sess.source_map().def_span(span);
1013     let mut err = struct_span_err!(
1014         tcx.sess,
1015         span,
1016         E0072,
1017         "recursive type `{}` has infinite size",
1018         tcx.def_path_str(type_def_id)
1019     );
1020     err.span_label(span, "recursive type has infinite size");
1021     err.help(&format!(
1022         "insert indirection (e.g., a `Box`, `Rc`, or `&`) \
1023                            at some point to make `{}` representable",
1024         tcx.def_path_str(type_def_id)
1025     ));
1026     err
1027 }
1028
1029 pub fn report_object_safety_error(
1030     tcx: TyCtxt<'tcx>,
1031     span: Span,
1032     trait_def_id: DefId,
1033     violations: Vec<ObjectSafetyViolation>,
1034 ) -> DiagnosticBuilder<'tcx> {
1035     let trait_str = tcx.def_path_str(trait_def_id);
1036     let trait_span = tcx.hir().get_if_local(trait_def_id).and_then(|node| match node {
1037         hir::Node::Item(item) => Some(item.ident.span),
1038         _ => None,
1039     });
1040     let span = tcx.sess.source_map().def_span(span);
1041     let mut err = struct_span_err!(
1042         tcx.sess,
1043         span,
1044         E0038,
1045         "the trait `{}` cannot be made into an object",
1046         trait_str
1047     );
1048     err.span_label(span, format!("the trait `{}` cannot be made into an object", trait_str));
1049
1050     let mut reported_violations = FxHashSet::default();
1051     let mut had_span_label = false;
1052     for violation in violations {
1053         if let ObjectSafetyViolation::SizedSelf(sp) = &violation {
1054             if !sp.is_empty() {
1055                 // Do not report `SizedSelf` without spans pointing at `SizedSelf` obligations
1056                 // with a `Span`.
1057                 reported_violations.insert(ObjectSafetyViolation::SizedSelf(vec![].into()));
1058             }
1059         }
1060         if reported_violations.insert(violation.clone()) {
1061             let spans = violation.spans();
1062             let msg = if trait_span.is_none() || spans.is_empty() {
1063                 format!("the trait cannot be made into an object because {}", violation.error_msg())
1064             } else {
1065                 had_span_label = true;
1066                 format!("...because {}", violation.error_msg())
1067             };
1068             if spans.is_empty() {
1069                 err.note(&msg);
1070             } else {
1071                 for span in spans {
1072                     err.span_label(span, &msg);
1073                 }
1074             }
1075             match (trait_span, violation.solution()) {
1076                 (Some(_), Some((note, None))) => {
1077                     err.help(&note);
1078                 }
1079                 (Some(_), Some((note, Some((sugg, span))))) => {
1080                     err.span_suggestion(span, &note, sugg, Applicability::MachineApplicable);
1081                 }
1082                 // Only provide the help if its a local trait, otherwise it's not actionable.
1083                 _ => {}
1084             }
1085         }
1086     }
1087     if let (Some(trait_span), true) = (trait_span, had_span_label) {
1088         err.span_label(trait_span, "this trait cannot be made into an object...");
1089     }
1090
1091     if tcx.sess.trait_methods_not_found.borrow().contains(&span) {
1092         // Avoid emitting error caused by non-existing method (#58734)
1093         err.cancel();
1094     }
1095
1096     err
1097 }
1098
1099 impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
1100     fn maybe_report_ambiguity(
1101         &self,
1102         obligation: &PredicateObligation<'tcx>,
1103         body_id: Option<hir::BodyId>,
1104     ) {
1105         // Unable to successfully determine, probably means
1106         // insufficient type information, but could mean
1107         // ambiguous impls. The latter *ought* to be a
1108         // coherence violation, so we don't report it here.
1109
1110         let predicate = self.resolve_vars_if_possible(&obligation.predicate);
1111         let span = obligation.cause.span;
1112
1113         debug!(
1114             "maybe_report_ambiguity(predicate={:?}, obligation={:?} body_id={:?}, code={:?})",
1115             predicate, obligation, body_id, obligation.cause.code,
1116         );
1117
1118         // Ambiguity errors are often caused as fallout from earlier
1119         // errors. So just ignore them if this infcx is tainted.
1120         if self.is_tainted_by_errors() {
1121             return;
1122         }
1123
1124         let mut err = match predicate {
1125             ty::Predicate::Trait(ref data, _) => {
1126                 let trait_ref = data.to_poly_trait_ref();
1127                 let self_ty = trait_ref.self_ty();
1128                 debug!("self_ty {:?} {:?} trait_ref {:?}", self_ty, self_ty.kind, trait_ref);
1129
1130                 if predicate.references_error() {
1131                     return;
1132                 }
1133                 // Typically, this ambiguity should only happen if
1134                 // there are unresolved type inference variables
1135                 // (otherwise it would suggest a coherence
1136                 // failure). But given #21974 that is not necessarily
1137                 // the case -- we can have multiple where clauses that
1138                 // are only distinguished by a region, which results
1139                 // in an ambiguity even when all types are fully
1140                 // known, since we don't dispatch based on region
1141                 // relationships.
1142
1143                 // This is kind of a hack: it frequently happens that some earlier
1144                 // error prevents types from being fully inferred, and then we get
1145                 // a bunch of uninteresting errors saying something like "<generic
1146                 // #0> doesn't implement Sized".  It may even be true that we
1147                 // could just skip over all checks where the self-ty is an
1148                 // inference variable, but I was afraid that there might be an
1149                 // inference variable created, registered as an obligation, and
1150                 // then never forced by writeback, and hence by skipping here we'd
1151                 // be ignoring the fact that we don't KNOW the type works
1152                 // out. Though even that would probably be harmless, given that
1153                 // we're only talking about builtin traits, which are known to be
1154                 // inhabited. We used to check for `self.tcx.sess.has_errors()` to
1155                 // avoid inundating the user with unnecessary errors, but we now
1156                 // check upstream for type errors and dont add the obligations to
1157                 // begin with in those cases.
1158                 if self
1159                     .tcx
1160                     .lang_items()
1161                     .sized_trait()
1162                     .map_or(false, |sized_id| sized_id == trait_ref.def_id())
1163                 {
1164                     self.need_type_info_err(body_id, span, self_ty, ErrorCode::E0282).emit();
1165                     return;
1166                 }
1167                 let mut err = self.need_type_info_err(body_id, span, self_ty, ErrorCode::E0283);
1168                 err.note(&format!("cannot resolve `{}`", predicate));
1169                 if let ObligationCauseCode::ItemObligation(def_id) = obligation.cause.code {
1170                     self.suggest_fully_qualified_path(&mut err, def_id, span, trait_ref.def_id());
1171                 } else if let (
1172                     Ok(ref snippet),
1173                     ObligationCauseCode::BindingObligation(ref def_id, _),
1174                 ) =
1175                     (self.tcx.sess.source_map().span_to_snippet(span), &obligation.cause.code)
1176                 {
1177                     let generics = self.tcx.generics_of(*def_id);
1178                     if !generics.params.is_empty() && !snippet.ends_with('>') {
1179                         // FIXME: To avoid spurious suggestions in functions where type arguments
1180                         // where already supplied, we check the snippet to make sure it doesn't
1181                         // end with a turbofish. Ideally we would have access to a `PathSegment`
1182                         // instead. Otherwise we would produce the following output:
1183                         //
1184                         // error[E0283]: type annotations needed
1185                         //   --> $DIR/issue-54954.rs:3:24
1186                         //    |
1187                         // LL | const ARR_LEN: usize = Tt::const_val::<[i8; 123]>();
1188                         //    |                        ^^^^^^^^^^^^^^^^^^^^^^^^^^
1189                         //    |                        |
1190                         //    |                        cannot infer type
1191                         //    |                        help: consider specifying the type argument
1192                         //    |                        in the function call:
1193                         //    |                        `Tt::const_val::<[i8; 123]>::<T>`
1194                         // ...
1195                         // LL |     const fn const_val<T: Sized>() -> usize {
1196                         //    |              --------- - required by this bound in `Tt::const_val`
1197                         //    |
1198                         //    = note: cannot resolve `_: Tt`
1199
1200                         err.span_suggestion(
1201                             span,
1202                             &format!(
1203                                 "consider specifying the type argument{} in the function call",
1204                                 if generics.params.len() > 1 { "s" } else { "" },
1205                             ),
1206                             format!(
1207                                 "{}::<{}>",
1208                                 snippet,
1209                                 generics
1210                                     .params
1211                                     .iter()
1212                                     .map(|p| p.name.to_string())
1213                                     .collect::<Vec<String>>()
1214                                     .join(", ")
1215                             ),
1216                             Applicability::HasPlaceholders,
1217                         );
1218                     }
1219                 }
1220                 err
1221             }
1222
1223             ty::Predicate::WellFormed(ty) => {
1224                 // Same hacky approach as above to avoid deluging user
1225                 // with error messages.
1226                 if ty.references_error() || self.tcx.sess.has_errors() {
1227                     return;
1228                 }
1229                 self.need_type_info_err(body_id, span, ty, ErrorCode::E0282)
1230             }
1231
1232             ty::Predicate::Subtype(ref data) => {
1233                 if data.references_error() || self.tcx.sess.has_errors() {
1234                     // no need to overload user in such cases
1235                     return;
1236                 }
1237                 let &SubtypePredicate { a_is_expected: _, a, b } = data.skip_binder();
1238                 // both must be type variables, or the other would've been instantiated
1239                 assert!(a.is_ty_var() && b.is_ty_var());
1240                 self.need_type_info_err(body_id, span, a, ErrorCode::E0282)
1241             }
1242             ty::Predicate::Projection(ref data) => {
1243                 let trait_ref = data.to_poly_trait_ref(self.tcx);
1244                 let self_ty = trait_ref.self_ty();
1245                 if predicate.references_error() {
1246                     return;
1247                 }
1248                 let mut err = self.need_type_info_err(body_id, span, self_ty, ErrorCode::E0284);
1249                 err.note(&format!("cannot resolve `{}`", predicate));
1250                 err
1251             }
1252
1253             _ => {
1254                 if self.tcx.sess.has_errors() {
1255                     return;
1256                 }
1257                 let mut err = struct_span_err!(
1258                     self.tcx.sess,
1259                     span,
1260                     E0284,
1261                     "type annotations needed: cannot resolve `{}`",
1262                     predicate,
1263                 );
1264                 err.span_label(span, &format!("cannot resolve `{}`", predicate));
1265                 err
1266             }
1267         };
1268         self.note_obligation_cause(&mut err, obligation);
1269         err.emit();
1270     }
1271
1272     /// Returns `true` if the trait predicate may apply for *some* assignment
1273     /// to the type parameters.
1274     fn predicate_can_apply(
1275         &self,
1276         param_env: ty::ParamEnv<'tcx>,
1277         pred: ty::PolyTraitRef<'tcx>,
1278     ) -> bool {
1279         struct ParamToVarFolder<'a, 'tcx> {
1280             infcx: &'a InferCtxt<'a, 'tcx>,
1281             var_map: FxHashMap<Ty<'tcx>, Ty<'tcx>>,
1282         }
1283
1284         impl<'a, 'tcx> TypeFolder<'tcx> for ParamToVarFolder<'a, 'tcx> {
1285             fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
1286                 self.infcx.tcx
1287             }
1288
1289             fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1290                 if let ty::Param(ty::ParamTy { name, .. }) = ty.kind {
1291                     let infcx = self.infcx;
1292                     self.var_map.entry(ty).or_insert_with(|| {
1293                         infcx.next_ty_var(TypeVariableOrigin {
1294                             kind: TypeVariableOriginKind::TypeParameterDefinition(name, None),
1295                             span: DUMMY_SP,
1296                         })
1297                     })
1298                 } else {
1299                     ty.super_fold_with(self)
1300                 }
1301             }
1302         }
1303
1304         self.probe(|_| {
1305             let mut selcx = SelectionContext::new(self);
1306
1307             let cleaned_pred =
1308                 pred.fold_with(&mut ParamToVarFolder { infcx: self, var_map: Default::default() });
1309
1310             let cleaned_pred = super::project::normalize(
1311                 &mut selcx,
1312                 param_env,
1313                 ObligationCause::dummy(),
1314                 &cleaned_pred,
1315             )
1316             .value;
1317
1318             let obligation = Obligation::new(
1319                 ObligationCause::dummy(),
1320                 param_env,
1321                 cleaned_pred.without_const().to_predicate(),
1322             );
1323
1324             self.predicate_may_hold(&obligation)
1325         })
1326     }
1327
1328     fn note_obligation_cause(
1329         &self,
1330         err: &mut DiagnosticBuilder<'_>,
1331         obligation: &PredicateObligation<'tcx>,
1332     ) {
1333         // First, attempt to add note to this error with an async-await-specific
1334         // message, and fall back to regular note otherwise.
1335         if !self.maybe_note_obligation_cause_for_async_await(err, obligation) {
1336             self.note_obligation_cause_code(
1337                 err,
1338                 &obligation.predicate,
1339                 &obligation.cause.code,
1340                 &mut vec![],
1341             );
1342             self.suggest_unsized_bound_if_applicable(err, obligation);
1343         }
1344     }
1345
1346     fn suggest_unsized_bound_if_applicable(
1347         &self,
1348         err: &mut DiagnosticBuilder<'_>,
1349         obligation: &PredicateObligation<'tcx>,
1350     ) {
1351         if let (
1352             ty::Predicate::Trait(pred, _),
1353             ObligationCauseCode::BindingObligation(item_def_id, span),
1354         ) = (&obligation.predicate, &obligation.cause.code)
1355         {
1356             if let (Some(generics), true) = (
1357                 self.tcx.hir().get_if_local(*item_def_id).as_ref().and_then(|n| n.generics()),
1358                 Some(pred.def_id()) == self.tcx.lang_items().sized_trait(),
1359             ) {
1360                 for param in generics.params {
1361                     if param.span == *span
1362                         && !param.bounds.iter().any(|bound| {
1363                             bound.trait_def_id() == self.tcx.lang_items().sized_trait()
1364                         })
1365                     {
1366                         let (span, separator) = match param.bounds {
1367                             [] => (span.shrink_to_hi(), ":"),
1368                             [.., bound] => (bound.span().shrink_to_hi(), " + "),
1369                         };
1370                         err.span_suggestion(
1371                             span,
1372                             "consider relaxing the implicit `Sized` restriction",
1373                             format!("{} ?Sized", separator),
1374                             Applicability::MachineApplicable,
1375                         );
1376                         return;
1377                     }
1378                 }
1379             }
1380         }
1381     }
1382
1383     fn is_recursive_obligation(
1384         &self,
1385         obligated_types: &mut Vec<&ty::TyS<'tcx>>,
1386         cause_code: &ObligationCauseCode<'tcx>,
1387     ) -> bool {
1388         if let ObligationCauseCode::BuiltinDerivedObligation(ref data) = cause_code {
1389             let parent_trait_ref = self.resolve_vars_if_possible(&data.parent_trait_ref);
1390
1391             if obligated_types.iter().any(|ot| ot == &parent_trait_ref.skip_binder().self_ty()) {
1392                 return true;
1393             }
1394         }
1395         false
1396     }
1397 }
1398
1399 /// Summarizes information
1400 #[derive(Clone)]
1401 pub enum ArgKind {
1402     /// An argument of non-tuple type. Parameters are (name, ty)
1403     Arg(String, String),
1404
1405     /// An argument of tuple type. For a "found" argument, the span is
1406     /// the locationo in the source of the pattern. For a "expected"
1407     /// argument, it will be None. The vector is a list of (name, ty)
1408     /// strings for the components of the tuple.
1409     Tuple(Option<Span>, Vec<(String, String)>),
1410 }
1411
1412 impl ArgKind {
1413     fn empty() -> ArgKind {
1414         ArgKind::Arg("_".to_owned(), "_".to_owned())
1415     }
1416
1417     /// Creates an `ArgKind` from the expected type of an
1418     /// argument. It has no name (`_`) and an optional source span.
1419     pub fn from_expected_ty(t: Ty<'_>, span: Option<Span>) -> ArgKind {
1420         match t.kind {
1421             ty::Tuple(ref tys) => ArgKind::Tuple(
1422                 span,
1423                 tys.iter().map(|ty| ("_".to_owned(), ty.to_string())).collect::<Vec<_>>(),
1424             ),
1425             _ => ArgKind::Arg("_".to_owned(), t.to_string()),
1426         }
1427     }
1428 }
1429
1430 /// Suggest restricting a type param with a new bound.
1431 pub fn suggest_constraining_type_param(
1432     tcx: TyCtxt<'_>,
1433     generics: &hir::Generics<'_>,
1434     err: &mut DiagnosticBuilder<'_>,
1435     param_name: &str,
1436     constraint: &str,
1437     source_map: &SourceMap,
1438     span: Span,
1439     def_id: Option<DefId>,
1440 ) -> bool {
1441     const MSG_RESTRICT_BOUND_FURTHER: &str = "consider further restricting this bound with";
1442     const MSG_RESTRICT_TYPE: &str = "consider restricting this type parameter with";
1443     const MSG_RESTRICT_TYPE_FURTHER: &str = "consider further restricting this type parameter with";
1444
1445     let param = generics.params.iter().find(|p| p.name.ident().as_str() == param_name);
1446
1447     let param = if let Some(param) = param {
1448         param
1449     } else {
1450         return false;
1451     };
1452
1453     if def_id == tcx.lang_items().sized_trait() {
1454         // Type parameters are already `Sized` by default.
1455         err.span_label(param.span, &format!("this type parameter needs to be `{}`", constraint));
1456         return true;
1457     }
1458
1459     if param_name.starts_with("impl ") {
1460         // If there's an `impl Trait` used in argument position, suggest
1461         // restricting it:
1462         //
1463         //   fn foo(t: impl Foo) { ... }
1464         //             --------
1465         //             |
1466         //             help: consider further restricting this bound with `+ Bar`
1467         //
1468         // Suggestion for tools in this case is:
1469         //
1470         //   fn foo(t: impl Foo) { ... }
1471         //             --------
1472         //             |
1473         //             replace with: `impl Foo + Bar`
1474
1475         err.span_help(param.span, &format!("{} `+ {}`", MSG_RESTRICT_BOUND_FURTHER, constraint));
1476
1477         err.tool_only_span_suggestion(
1478             param.span,
1479             MSG_RESTRICT_BOUND_FURTHER,
1480             format!("{} + {}", param_name, constraint),
1481             Applicability::MachineApplicable,
1482         );
1483
1484         return true;
1485     }
1486
1487     if generics.where_clause.predicates.is_empty() {
1488         if let Some(bounds_span) = param.bounds_span() {
1489             // If user has provided some bounds, suggest restricting them:
1490             //
1491             //   fn foo<T: Foo>(t: T) { ... }
1492             //             ---
1493             //             |
1494             //             help: consider further restricting this bound with `+ Bar`
1495             //
1496             // Suggestion for tools in this case is:
1497             //
1498             //   fn foo<T: Foo>(t: T) { ... }
1499             //          --
1500             //          |
1501             //          replace with: `T: Bar +`
1502
1503             err.span_help(
1504                 bounds_span,
1505                 &format!("{} `+ {}`", MSG_RESTRICT_BOUND_FURTHER, constraint),
1506             );
1507
1508             let span_hi = param.span.with_hi(span.hi());
1509             let span_with_colon = source_map.span_through_char(span_hi, ':');
1510
1511             if span_hi != param.span && span_with_colon != span_hi {
1512                 err.tool_only_span_suggestion(
1513                     span_with_colon,
1514                     MSG_RESTRICT_BOUND_FURTHER,
1515                     format!("{}: {} + ", param_name, constraint),
1516                     Applicability::MachineApplicable,
1517                 );
1518             }
1519         } else {
1520             // If user hasn't provided any bounds, suggest adding a new one:
1521             //
1522             //   fn foo<T>(t: T) { ... }
1523             //          - help: consider restricting this type parameter with `T: Foo`
1524
1525             err.span_help(
1526                 param.span,
1527                 &format!("{} `{}: {}`", MSG_RESTRICT_TYPE, param_name, constraint),
1528             );
1529
1530             err.tool_only_span_suggestion(
1531                 param.span,
1532                 MSG_RESTRICT_TYPE,
1533                 format!("{}: {}", param_name, constraint),
1534                 Applicability::MachineApplicable,
1535             );
1536         }
1537
1538         true
1539     } else {
1540         // This part is a bit tricky, because using the `where` clause user can
1541         // provide zero, one or many bounds for the same type parameter, so we
1542         // have following cases to consider:
1543         //
1544         // 1) When the type parameter has been provided zero bounds
1545         //
1546         //    Message:
1547         //      fn foo<X, Y>(x: X, y: Y) where Y: Foo { ... }
1548         //             - help: consider restricting this type parameter with `where X: Bar`
1549         //
1550         //    Suggestion:
1551         //      fn foo<X, Y>(x: X, y: Y) where Y: Foo { ... }
1552         //                                           - insert: `, X: Bar`
1553         //
1554         //
1555         // 2) When the type parameter has been provided one bound
1556         //
1557         //    Message:
1558         //      fn foo<T>(t: T) where T: Foo { ... }
1559         //                            ^^^^^^
1560         //                            |
1561         //                            help: consider further restricting this bound with `+ Bar`
1562         //
1563         //    Suggestion:
1564         //      fn foo<T>(t: T) where T: Foo { ... }
1565         //                            ^^
1566         //                            |
1567         //                            replace with: `T: Bar +`
1568         //
1569         //
1570         // 3) When the type parameter has been provided many bounds
1571         //
1572         //    Message:
1573         //      fn foo<T>(t: T) where T: Foo, T: Bar {... }
1574         //             - help: consider further restricting this type parameter with `where T: Zar`
1575         //
1576         //    Suggestion:
1577         //      fn foo<T>(t: T) where T: Foo, T: Bar {... }
1578         //                                          - insert: `, T: Zar`
1579
1580         let mut param_spans = Vec::new();
1581
1582         for predicate in generics.where_clause.predicates {
1583             if let WherePredicate::BoundPredicate(WhereBoundPredicate {
1584                 span, bounded_ty, ..
1585             }) = predicate
1586             {
1587                 if let TyKind::Path(QPath::Resolved(_, path)) = &bounded_ty.kind {
1588                     if let Some(segment) = path.segments.first() {
1589                         if segment.ident.to_string() == param_name {
1590                             param_spans.push(span);
1591                         }
1592                     }
1593                 }
1594             }
1595         }
1596
1597         let where_clause_span =
1598             generics.where_clause.span_for_predicates_or_empty_place().shrink_to_hi();
1599
1600         match &param_spans[..] {
1601             &[] => {
1602                 err.span_help(
1603                     param.span,
1604                     &format!("{} `where {}: {}`", MSG_RESTRICT_TYPE, param_name, constraint),
1605                 );
1606
1607                 err.tool_only_span_suggestion(
1608                     where_clause_span,
1609                     MSG_RESTRICT_TYPE,
1610                     format!(", {}: {}", param_name, constraint),
1611                     Applicability::MachineApplicable,
1612                 );
1613             }
1614
1615             &[&param_span] => {
1616                 err.span_help(
1617                     param_span,
1618                     &format!("{} `+ {}`", MSG_RESTRICT_BOUND_FURTHER, constraint),
1619                 );
1620
1621                 let span_hi = param_span.with_hi(span.hi());
1622                 let span_with_colon = source_map.span_through_char(span_hi, ':');
1623
1624                 if span_hi != param_span && span_with_colon != span_hi {
1625                     err.tool_only_span_suggestion(
1626                         span_with_colon,
1627                         MSG_RESTRICT_BOUND_FURTHER,
1628                         format!("{}: {} +", param_name, constraint),
1629                         Applicability::MachineApplicable,
1630                     );
1631                 }
1632             }
1633
1634             _ => {
1635                 err.span_help(
1636                     param.span,
1637                     &format!(
1638                         "{} `where {}: {}`",
1639                         MSG_RESTRICT_TYPE_FURTHER, param_name, constraint,
1640                     ),
1641                 );
1642
1643                 err.tool_only_span_suggestion(
1644                     where_clause_span,
1645                     MSG_RESTRICT_BOUND_FURTHER,
1646                     format!(", {}: {}", param_name, constraint),
1647                     Applicability::MachineApplicable,
1648                 );
1649             }
1650         }
1651
1652         true
1653     }
1654 }