]> git.lizzy.rs Git - rust.git/blob - src/librustc/traits/error_reporting.rs
Rollup merge of #67906 - varkor:silence-toogeneric, r=nagisa
[rust.git] / src / librustc / traits / error_reporting.rs
1 use super::{
2     ConstEvalFailure, EvaluationResult, FulfillmentError, FulfillmentErrorCode,
3     MismatchedProjectionTypes, ObjectSafetyViolation, Obligation, ObligationCause,
4     ObligationCauseCode, OnUnimplementedDirective, OnUnimplementedNote,
5     OutputTypeParameterMismatch, Overflow, PredicateObligation, SelectionContext, SelectionError,
6     TraitNotObjectSafe,
7 };
8
9 use crate::hir;
10 use crate::hir::def_id::DefId;
11 use crate::hir::Node;
12 use crate::infer::error_reporting::TypeAnnotationNeeded as ErrorCode;
13 use crate::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
14 use crate::infer::{self, InferCtxt};
15 use crate::mir::interpret::ErrorHandled;
16 use crate::session::DiagnosticMessageId;
17 use crate::ty::error::ExpectedFound;
18 use crate::ty::fast_reject;
19 use crate::ty::fold::TypeFolder;
20 use crate::ty::subst::Subst;
21 use crate::ty::GenericParamDefKind;
22 use crate::ty::SubtypePredicate;
23 use crate::ty::TypeckTables;
24 use crate::ty::{self, AdtKind, DefIdTree, ToPolyTraitRef, ToPredicate, Ty, TyCtxt, TypeFoldable};
25
26 use errors::{pluralize, Applicability, DiagnosticBuilder, Style};
27 use rustc::hir::def_id::LOCAL_CRATE;
28 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
29 use rustc_span::source_map::SourceMap;
30 use rustc_span::symbol::{kw, sym};
31 use rustc_span::{ExpnKind, MultiSpan, Span, DUMMY_SP};
32 use std::fmt;
33 use syntax::ast;
34
35 use rustc_error_codes::*;
36
37 impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
38     pub fn report_fulfillment_errors(
39         &self,
40         errors: &[FulfillmentError<'tcx>],
41         body_id: Option<hir::BodyId>,
42         fallback_has_occurred: bool,
43     ) {
44         #[derive(Debug)]
45         struct ErrorDescriptor<'tcx> {
46             predicate: ty::Predicate<'tcx>,
47             index: Option<usize>, // None if this is an old error
48         }
49
50         let mut error_map: FxHashMap<_, Vec<_>> = self
51             .reported_trait_errors
52             .borrow()
53             .iter()
54             .map(|(&span, predicates)| {
55                 (
56                     span,
57                     predicates
58                         .iter()
59                         .map(|predicate| ErrorDescriptor {
60                             predicate: predicate.clone(),
61                             index: None,
62                         })
63                         .collect(),
64                 )
65             })
66             .collect();
67
68         for (index, error) in errors.iter().enumerate() {
69             // We want to ignore desugarings here: spans are equivalent even
70             // if one is the result of a desugaring and the other is not.
71             let mut span = error.obligation.cause.span;
72             let expn_data = span.ctxt().outer_expn_data();
73             if let ExpnKind::Desugaring(_) = expn_data.kind {
74                 span = expn_data.call_site;
75             }
76
77             error_map.entry(span).or_default().push(ErrorDescriptor {
78                 predicate: error.obligation.predicate.clone(),
79                 index: Some(index),
80             });
81
82             self.reported_trait_errors
83                 .borrow_mut()
84                 .entry(span)
85                 .or_default()
86                 .push(error.obligation.predicate.clone());
87         }
88
89         // We do this in 2 passes because we want to display errors in order, though
90         // maybe it *is* better to sort errors by span or something.
91         let mut is_suppressed = vec![false; errors.len()];
92         for (_, error_set) in error_map.iter() {
93             // We want to suppress "duplicate" errors with the same span.
94             for error in error_set {
95                 if let Some(index) = error.index {
96                     // Suppress errors that are either:
97                     // 1) strictly implied by another error.
98                     // 2) implied by an error with a smaller index.
99                     for error2 in error_set {
100                         if error2.index.map_or(false, |index2| is_suppressed[index2]) {
101                             // Avoid errors being suppressed by already-suppressed
102                             // errors, to prevent all errors from being suppressed
103                             // at once.
104                             continue;
105                         }
106
107                         if self.error_implies(&error2.predicate, &error.predicate)
108                             && !(error2.index >= error.index
109                                 && self.error_implies(&error.predicate, &error2.predicate))
110                         {
111                             info!("skipping {:?} (implied by {:?})", error, error2);
112                             is_suppressed[index] = true;
113                             break;
114                         }
115                     }
116                 }
117             }
118         }
119
120         for (error, suppressed) in errors.iter().zip(is_suppressed) {
121             if !suppressed {
122                 self.report_fulfillment_error(error, body_id, fallback_has_occurred);
123             }
124         }
125     }
126
127     // returns if `cond` not occurring implies that `error` does not occur - i.e., that
128     // `error` occurring implies that `cond` occurs.
129     fn error_implies(&self, cond: &ty::Predicate<'tcx>, error: &ty::Predicate<'tcx>) -> bool {
130         if cond == error {
131             return true;
132         }
133
134         let (cond, error) = match (cond, error) {
135             (&ty::Predicate::Trait(..), &ty::Predicate::Trait(ref error)) => (cond, error),
136             _ => {
137                 // FIXME: make this work in other cases too.
138                 return false;
139             }
140         };
141
142         for implication in super::elaborate_predicates(self.tcx, vec![cond.clone()]) {
143             if let ty::Predicate::Trait(implication) = implication {
144                 let error = error.to_poly_trait_ref();
145                 let implication = implication.to_poly_trait_ref();
146                 // FIXME: I'm just not taking associated types at all here.
147                 // Eventually I'll need to implement param-env-aware
148                 // `Γ₁ ⊦ φ₁ => Γ₂ ⊦ φ₂` logic.
149                 let param_env = ty::ParamEnv::empty();
150                 if self.can_sub(param_env, error, implication).is_ok() {
151                     debug!("error_implies: {:?} -> {:?} -> {:?}", cond, error, implication);
152                     return true;
153                 }
154             }
155         }
156
157         false
158     }
159
160     fn report_fulfillment_error(
161         &self,
162         error: &FulfillmentError<'tcx>,
163         body_id: Option<hir::BodyId>,
164         fallback_has_occurred: bool,
165     ) {
166         debug!("report_fulfillment_error({:?})", error);
167         match error.code {
168             FulfillmentErrorCode::CodeSelectionError(ref selection_error) => {
169                 self.report_selection_error(
170                     &error.obligation,
171                     selection_error,
172                     fallback_has_occurred,
173                     error.points_at_arg_span,
174                 );
175             }
176             FulfillmentErrorCode::CodeProjectionError(ref e) => {
177                 self.report_projection_error(&error.obligation, e);
178             }
179             FulfillmentErrorCode::CodeAmbiguity => {
180                 self.maybe_report_ambiguity(&error.obligation, body_id);
181             }
182             FulfillmentErrorCode::CodeSubtypeError(ref expected_found, ref err) => {
183                 self.report_mismatched_types(
184                     &error.obligation.cause,
185                     expected_found.expected,
186                     expected_found.found,
187                     err.clone(),
188                 )
189                 .emit();
190             }
191         }
192     }
193
194     fn report_projection_error(
195         &self,
196         obligation: &PredicateObligation<'tcx>,
197         error: &MismatchedProjectionTypes<'tcx>,
198     ) {
199         let predicate = self.resolve_vars_if_possible(&obligation.predicate);
200
201         if predicate.references_error() {
202             return;
203         }
204
205         self.probe(|_| {
206             let err_buf;
207             let mut err = &error.err;
208             let mut values = None;
209
210             // try to find the mismatched types to report the error with.
211             //
212             // this can fail if the problem was higher-ranked, in which
213             // cause I have no idea for a good error message.
214             if let ty::Predicate::Projection(ref data) = predicate {
215                 let mut selcx = SelectionContext::new(self);
216                 let (data, _) = self.replace_bound_vars_with_fresh_vars(
217                     obligation.cause.span,
218                     infer::LateBoundRegionConversionTime::HigherRankedType,
219                     data,
220                 );
221                 let mut obligations = vec![];
222                 let normalized_ty = super::normalize_projection_type(
223                     &mut selcx,
224                     obligation.param_env,
225                     data.projection_ty,
226                     obligation.cause.clone(),
227                     0,
228                     &mut obligations,
229                 );
230
231                 debug!(
232                     "report_projection_error obligation.cause={:?} obligation.param_env={:?}",
233                     obligation.cause, obligation.param_env
234                 );
235
236                 debug!(
237                     "report_projection_error normalized_ty={:?} data.ty={:?}",
238                     normalized_ty, data.ty
239                 );
240
241                 let is_normalized_ty_expected = match &obligation.cause.code {
242                     ObligationCauseCode::ItemObligation(_)
243                     | ObligationCauseCode::BindingObligation(_, _)
244                     | ObligationCauseCode::ObjectCastObligation(_) => false,
245                     _ => true,
246                 };
247
248                 if let Err(error) = self.at(&obligation.cause, obligation.param_env).eq_exp(
249                     is_normalized_ty_expected,
250                     normalized_ty,
251                     data.ty,
252                 ) {
253                     values = Some(infer::ValuePairs::Types(ExpectedFound::new(
254                         is_normalized_ty_expected,
255                         normalized_ty,
256                         data.ty,
257                     )));
258
259                     err_buf = error;
260                     err = &err_buf;
261                 }
262             }
263
264             let msg = format!("type mismatch resolving `{}`", predicate);
265             let error_id = (DiagnosticMessageId::ErrorId(271), Some(obligation.cause.span), msg);
266             let fresh = self.tcx.sess.one_time_diagnostics.borrow_mut().insert(error_id);
267             if fresh {
268                 let mut diag = struct_span_err!(
269                     self.tcx.sess,
270                     obligation.cause.span,
271                     E0271,
272                     "type mismatch resolving `{}`",
273                     predicate
274                 );
275                 self.note_type_err(&mut diag, &obligation.cause, None, values, err);
276                 self.note_obligation_cause(&mut diag, obligation);
277                 diag.emit();
278             }
279         });
280     }
281
282     fn fuzzy_match_tys(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
283         /// returns the fuzzy category of a given type, or None
284         /// if the type can be equated to any type.
285         fn type_category(t: Ty<'_>) -> Option<u32> {
286             match t.kind {
287                 ty::Bool => Some(0),
288                 ty::Char => Some(1),
289                 ty::Str => Some(2),
290                 ty::Int(..) | ty::Uint(..) | ty::Infer(ty::IntVar(..)) => Some(3),
291                 ty::Float(..) | ty::Infer(ty::FloatVar(..)) => Some(4),
292                 ty::Ref(..) | ty::RawPtr(..) => Some(5),
293                 ty::Array(..) | ty::Slice(..) => Some(6),
294                 ty::FnDef(..) | ty::FnPtr(..) => Some(7),
295                 ty::Dynamic(..) => Some(8),
296                 ty::Closure(..) => Some(9),
297                 ty::Tuple(..) => Some(10),
298                 ty::Projection(..) => Some(11),
299                 ty::Param(..) => Some(12),
300                 ty::Opaque(..) => Some(13),
301                 ty::Never => Some(14),
302                 ty::Adt(adt, ..) => match adt.adt_kind() {
303                     AdtKind::Struct => Some(15),
304                     AdtKind::Union => Some(16),
305                     AdtKind::Enum => Some(17),
306                 },
307                 ty::Generator(..) => Some(18),
308                 ty::Foreign(..) => Some(19),
309                 ty::GeneratorWitness(..) => Some(20),
310                 ty::Placeholder(..) | ty::Bound(..) | ty::Infer(..) | ty::Error => None,
311                 ty::UnnormalizedProjection(..) => bug!("only used with chalk-engine"),
312             }
313         }
314
315         match (type_category(a), type_category(b)) {
316             (Some(cat_a), Some(cat_b)) => match (&a.kind, &b.kind) {
317                 (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) => def_a == def_b,
318                 _ => cat_a == cat_b,
319             },
320             // infer and error can be equated to all types
321             _ => true,
322         }
323     }
324
325     fn impl_similar_to(
326         &self,
327         trait_ref: ty::PolyTraitRef<'tcx>,
328         obligation: &PredicateObligation<'tcx>,
329     ) -> Option<DefId> {
330         let tcx = self.tcx;
331         let param_env = obligation.param_env;
332         let trait_ref = tcx.erase_late_bound_regions(&trait_ref);
333         let trait_self_ty = trait_ref.self_ty();
334
335         let mut self_match_impls = vec![];
336         let mut fuzzy_match_impls = vec![];
337
338         self.tcx.for_each_relevant_impl(trait_ref.def_id, trait_self_ty, |def_id| {
339             let impl_substs = self.fresh_substs_for_item(obligation.cause.span, def_id);
340             let impl_trait_ref = tcx.impl_trait_ref(def_id).unwrap().subst(tcx, impl_substs);
341
342             let impl_self_ty = impl_trait_ref.self_ty();
343
344             if let Ok(..) = self.can_eq(param_env, trait_self_ty, impl_self_ty) {
345                 self_match_impls.push(def_id);
346
347                 if trait_ref
348                     .substs
349                     .types()
350                     .skip(1)
351                     .zip(impl_trait_ref.substs.types().skip(1))
352                     .all(|(u, v)| self.fuzzy_match_tys(u, v))
353                 {
354                     fuzzy_match_impls.push(def_id);
355                 }
356             }
357         });
358
359         let impl_def_id = if self_match_impls.len() == 1 {
360             self_match_impls[0]
361         } else if fuzzy_match_impls.len() == 1 {
362             fuzzy_match_impls[0]
363         } else {
364             return None;
365         };
366
367         tcx.has_attr(impl_def_id, sym::rustc_on_unimplemented).then_some(impl_def_id)
368     }
369
370     fn describe_generator(&self, body_id: hir::BodyId) -> Option<&'static str> {
371         self.tcx.hir().body(body_id).generator_kind.map(|gen_kind| match gen_kind {
372             hir::GeneratorKind::Gen => "a generator",
373             hir::GeneratorKind::Async(hir::AsyncGeneratorKind::Block) => "an async block",
374             hir::GeneratorKind::Async(hir::AsyncGeneratorKind::Fn) => "an async function",
375             hir::GeneratorKind::Async(hir::AsyncGeneratorKind::Closure) => "an async closure",
376         })
377     }
378
379     /// Used to set on_unimplemented's `ItemContext`
380     /// to be the enclosing (async) block/function/closure
381     fn describe_enclosure(&self, hir_id: hir::HirId) -> Option<&'static str> {
382         let hir = &self.tcx.hir();
383         let node = hir.find(hir_id)?;
384         if let hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(sig, _, body_id), .. }) = &node {
385             self.describe_generator(*body_id).or_else(|| {
386                 Some(if let hir::FnHeader { asyncness: hir::IsAsync::Async, .. } = sig.header {
387                     "an async function"
388                 } else {
389                     "a function"
390                 })
391             })
392         } else if let hir::Node::Expr(hir::Expr {
393             kind: hir::ExprKind::Closure(_is_move, _, body_id, _, gen_movability),
394             ..
395         }) = &node
396         {
397             self.describe_generator(*body_id).or_else(|| {
398                 Some(if gen_movability.is_some() { "an async closure" } else { "a closure" })
399             })
400         } else if let hir::Node::Expr(hir::Expr { .. }) = &node {
401             let parent_hid = hir.get_parent_node(hir_id);
402             if parent_hid != hir_id {
403                 return self.describe_enclosure(parent_hid);
404             } else {
405                 None
406             }
407         } else {
408             None
409         }
410     }
411
412     fn on_unimplemented_note(
413         &self,
414         trait_ref: ty::PolyTraitRef<'tcx>,
415         obligation: &PredicateObligation<'tcx>,
416     ) -> OnUnimplementedNote {
417         let def_id =
418             self.impl_similar_to(trait_ref, obligation).unwrap_or_else(|| trait_ref.def_id());
419         let trait_ref = *trait_ref.skip_binder();
420
421         let mut flags = vec![];
422         flags.push((
423             sym::item_context,
424             self.describe_enclosure(obligation.cause.body_id).map(|s| s.to_owned()),
425         ));
426
427         match obligation.cause.code {
428             ObligationCauseCode::BuiltinDerivedObligation(..)
429             | ObligationCauseCode::ImplDerivedObligation(..) => {}
430             _ => {
431                 // this is a "direct", user-specified, rather than derived,
432                 // obligation.
433                 flags.push((sym::direct, None));
434             }
435         }
436
437         if let ObligationCauseCode::ItemObligation(item) = obligation.cause.code {
438             // FIXME: maybe also have some way of handling methods
439             // from other traits? That would require name resolution,
440             // which we might want to be some sort of hygienic.
441             //
442             // Currently I'm leaving it for what I need for `try`.
443             if self.tcx.trait_of_item(item) == Some(trait_ref.def_id) {
444                 let method = self.tcx.item_name(item);
445                 flags.push((sym::from_method, None));
446                 flags.push((sym::from_method, Some(method.to_string())));
447             }
448         }
449         if let Some(t) = self.get_parent_trait_ref(&obligation.cause.code) {
450             flags.push((sym::parent_trait, Some(t)));
451         }
452
453         if let Some(k) = obligation.cause.span.desugaring_kind() {
454             flags.push((sym::from_desugaring, None));
455             flags.push((sym::from_desugaring, Some(format!("{:?}", k))));
456         }
457         let generics = self.tcx.generics_of(def_id);
458         let self_ty = trait_ref.self_ty();
459         // This is also included through the generics list as `Self`,
460         // but the parser won't allow you to use it
461         flags.push((sym::_Self, Some(self_ty.to_string())));
462         if let Some(def) = self_ty.ty_adt_def() {
463             // We also want to be able to select self's original
464             // signature with no type arguments resolved
465             flags.push((sym::_Self, Some(self.tcx.type_of(def.did).to_string())));
466         }
467
468         for param in generics.params.iter() {
469             let value = match param.kind {
470                 GenericParamDefKind::Type { .. } | GenericParamDefKind::Const => {
471                     trait_ref.substs[param.index as usize].to_string()
472                 }
473                 GenericParamDefKind::Lifetime => continue,
474             };
475             let name = param.name;
476             flags.push((name, Some(value)));
477         }
478
479         if let Some(true) = self_ty.ty_adt_def().map(|def| def.did.is_local()) {
480             flags.push((sym::crate_local, None));
481         }
482
483         // Allow targeting all integers using `{integral}`, even if the exact type was resolved
484         if self_ty.is_integral() {
485             flags.push((sym::_Self, Some("{integral}".to_owned())));
486         }
487
488         if let ty::Array(aty, len) = self_ty.kind {
489             flags.push((sym::_Self, Some("[]".to_owned())));
490             flags.push((sym::_Self, Some(format!("[{}]", aty))));
491             if let Some(def) = aty.ty_adt_def() {
492                 // We also want to be able to select the array's type's original
493                 // signature with no type arguments resolved
494                 flags.push((
495                     sym::_Self,
496                     Some(format!("[{}]", self.tcx.type_of(def.did).to_string())),
497                 ));
498                 let tcx = self.tcx;
499                 if let Some(len) = len.try_eval_usize(tcx, ty::ParamEnv::empty()) {
500                     flags.push((
501                         sym::_Self,
502                         Some(format!("[{}; {}]", self.tcx.type_of(def.did).to_string(), len)),
503                     ));
504                 } else {
505                     flags.push((
506                         sym::_Self,
507                         Some(format!("[{}; _]", self.tcx.type_of(def.did).to_string())),
508                     ));
509                 }
510             }
511         }
512
513         if let Ok(Some(command)) =
514             OnUnimplementedDirective::of_item(self.tcx, trait_ref.def_id, def_id)
515         {
516             command.evaluate(self.tcx, trait_ref, &flags[..])
517         } else {
518             OnUnimplementedNote::default()
519         }
520     }
521
522     fn find_similar_impl_candidates(
523         &self,
524         trait_ref: ty::PolyTraitRef<'tcx>,
525     ) -> Vec<ty::TraitRef<'tcx>> {
526         let simp = fast_reject::simplify_type(self.tcx, trait_ref.skip_binder().self_ty(), true);
527         let all_impls = self.tcx.all_impls(trait_ref.def_id());
528
529         match simp {
530             Some(simp) => all_impls
531                 .iter()
532                 .filter_map(|&def_id| {
533                     let imp = self.tcx.impl_trait_ref(def_id).unwrap();
534                     let imp_simp = fast_reject::simplify_type(self.tcx, imp.self_ty(), true);
535                     if let Some(imp_simp) = imp_simp {
536                         if simp != imp_simp {
537                             return None;
538                         }
539                     }
540
541                     Some(imp)
542                 })
543                 .collect(),
544             None => {
545                 all_impls.iter().map(|&def_id| self.tcx.impl_trait_ref(def_id).unwrap()).collect()
546             }
547         }
548     }
549
550     fn report_similar_impl_candidates(
551         &self,
552         impl_candidates: Vec<ty::TraitRef<'tcx>>,
553         err: &mut DiagnosticBuilder<'_>,
554     ) {
555         if impl_candidates.is_empty() {
556             return;
557         }
558
559         let len = impl_candidates.len();
560         let end = if impl_candidates.len() <= 5 { impl_candidates.len() } else { 4 };
561
562         let normalize = |candidate| {
563             self.tcx.infer_ctxt().enter(|ref infcx| {
564                 let normalized = infcx
565                     .at(&ObligationCause::dummy(), ty::ParamEnv::empty())
566                     .normalize(candidate)
567                     .ok();
568                 match normalized {
569                     Some(normalized) => format!("\n  {:?}", normalized.value),
570                     None => format!("\n  {:?}", candidate),
571                 }
572             })
573         };
574
575         // Sort impl candidates so that ordering is consistent for UI tests.
576         let mut normalized_impl_candidates =
577             impl_candidates.iter().map(normalize).collect::<Vec<String>>();
578
579         // Sort before taking the `..end` range,
580         // because the ordering of `impl_candidates` may not be deterministic:
581         // https://github.com/rust-lang/rust/pull/57475#issuecomment-455519507
582         normalized_impl_candidates.sort();
583
584         err.help(&format!(
585             "the following implementations were found:{}{}",
586             normalized_impl_candidates[..end].join(""),
587             if len > 5 { format!("\nand {} others", len - 4) } else { String::new() }
588         ));
589     }
590
591     /// Reports that an overflow has occurred and halts compilation. We
592     /// halt compilation unconditionally because it is important that
593     /// overflows never be masked -- they basically represent computations
594     /// whose result could not be truly determined and thus we can't say
595     /// if the program type checks or not -- and they are unusual
596     /// occurrences in any case.
597     pub fn report_overflow_error<T>(
598         &self,
599         obligation: &Obligation<'tcx, T>,
600         suggest_increasing_limit: bool,
601     ) -> !
602     where
603         T: fmt::Display + TypeFoldable<'tcx>,
604     {
605         let predicate = self.resolve_vars_if_possible(&obligation.predicate);
606         let mut err = struct_span_err!(
607             self.tcx.sess,
608             obligation.cause.span,
609             E0275,
610             "overflow evaluating the requirement `{}`",
611             predicate
612         );
613
614         if suggest_increasing_limit {
615             self.suggest_new_overflow_limit(&mut err);
616         }
617
618         self.note_obligation_cause_code(
619             &mut err,
620             &obligation.predicate,
621             &obligation.cause.code,
622             &mut vec![],
623         );
624
625         err.emit();
626         self.tcx.sess.abort_if_errors();
627         bug!();
628     }
629
630     /// Reports that a cycle was detected which led to overflow and halts
631     /// compilation. This is equivalent to `report_overflow_error` except
632     /// that we can give a more helpful error message (and, in particular,
633     /// we do not suggest increasing the overflow limit, which is not
634     /// going to help).
635     pub fn report_overflow_error_cycle(&self, cycle: &[PredicateObligation<'tcx>]) -> ! {
636         let cycle = self.resolve_vars_if_possible(&cycle.to_owned());
637         assert!(cycle.len() > 0);
638
639         debug!("report_overflow_error_cycle: cycle={:?}", cycle);
640
641         self.report_overflow_error(&cycle[0], false);
642     }
643
644     pub fn report_extra_impl_obligation(
645         &self,
646         error_span: Span,
647         item_name: ast::Name,
648         _impl_item_def_id: DefId,
649         trait_item_def_id: DefId,
650         requirement: &dyn fmt::Display,
651     ) -> DiagnosticBuilder<'tcx> {
652         let msg = "impl has stricter requirements than trait";
653         let sp = self.tcx.sess.source_map().def_span(error_span);
654
655         let mut err = struct_span_err!(self.tcx.sess, sp, E0276, "{}", msg);
656
657         if let Some(trait_item_span) = self.tcx.hir().span_if_local(trait_item_def_id) {
658             let span = self.tcx.sess.source_map().def_span(trait_item_span);
659             err.span_label(span, format!("definition of `{}` from trait", item_name));
660         }
661
662         err.span_label(sp, format!("impl has extra requirement {}", requirement));
663
664         err
665     }
666
667     /// Gets the parent trait chain start
668     fn get_parent_trait_ref(&self, code: &ObligationCauseCode<'tcx>) -> Option<String> {
669         match code {
670             &ObligationCauseCode::BuiltinDerivedObligation(ref data) => {
671                 let parent_trait_ref = self.resolve_vars_if_possible(&data.parent_trait_ref);
672                 match self.get_parent_trait_ref(&data.parent_code) {
673                     Some(t) => Some(t),
674                     None => Some(parent_trait_ref.skip_binder().self_ty().to_string()),
675                 }
676             }
677             _ => None,
678         }
679     }
680
681     pub fn report_selection_error(
682         &self,
683         obligation: &PredicateObligation<'tcx>,
684         error: &SelectionError<'tcx>,
685         fallback_has_occurred: bool,
686         points_at_arg: bool,
687     ) {
688         let tcx = self.tcx;
689         let span = obligation.cause.span;
690
691         let mut err = match *error {
692             SelectionError::Unimplemented => {
693                 if let ObligationCauseCode::CompareImplMethodObligation {
694                     item_name,
695                     impl_item_def_id,
696                     trait_item_def_id,
697                 }
698                 | ObligationCauseCode::CompareImplTypeObligation {
699                     item_name,
700                     impl_item_def_id,
701                     trait_item_def_id,
702                 } = obligation.cause.code
703                 {
704                     self.report_extra_impl_obligation(
705                         span,
706                         item_name,
707                         impl_item_def_id,
708                         trait_item_def_id,
709                         &format!("`{}`", obligation.predicate),
710                     )
711                     .emit();
712                     return;
713                 }
714                 match obligation.predicate {
715                     ty::Predicate::Trait(ref trait_predicate) => {
716                         let trait_predicate = self.resolve_vars_if_possible(trait_predicate);
717
718                         if self.tcx.sess.has_errors() && trait_predicate.references_error() {
719                             return;
720                         }
721                         let trait_ref = trait_predicate.to_poly_trait_ref();
722                         let (post_message, pre_message) = self
723                             .get_parent_trait_ref(&obligation.cause.code)
724                             .map(|t| (format!(" in `{}`", t), format!("within `{}`, ", t)))
725                             .unwrap_or_default();
726
727                         let OnUnimplementedNote { message, label, note, enclosing_scope } =
728                             self.on_unimplemented_note(trait_ref, obligation);
729                         let have_alt_message = message.is_some() || label.is_some();
730                         let is_try = self
731                             .tcx
732                             .sess
733                             .source_map()
734                             .span_to_snippet(span)
735                             .map(|s| &s == "?")
736                             .unwrap_or(false);
737                         let is_from = format!("{}", trait_ref.print_only_trait_path())
738                             .starts_with("std::convert::From<");
739                         let (message, note) = if is_try && is_from {
740                             (
741                                 Some(format!(
742                                     "`?` couldn't convert the error to `{}`",
743                                     trait_ref.self_ty(),
744                                 )),
745                                 Some(
746                                     "the question mark operation (`?`) implicitly performs a \
747                                  conversion on the error value using the `From` trait"
748                                         .to_owned(),
749                                 ),
750                             )
751                         } else {
752                             (message, note)
753                         };
754
755                         let mut err = struct_span_err!(
756                             self.tcx.sess,
757                             span,
758                             E0277,
759                             "{}",
760                             message.unwrap_or_else(|| format!(
761                                 "the trait bound `{}` is not satisfied{}",
762                                 trait_ref.to_predicate(),
763                                 post_message,
764                             ))
765                         );
766
767                         let explanation =
768                             if obligation.cause.code == ObligationCauseCode::MainFunctionType {
769                                 "consider using `()`, or a `Result`".to_owned()
770                             } else {
771                                 format!(
772                                     "{}the trait `{}` is not implemented for `{}`",
773                                     pre_message,
774                                     trait_ref.print_only_trait_path(),
775                                     trait_ref.self_ty(),
776                                 )
777                             };
778
779                         if self.suggest_add_reference_to_arg(
780                             &obligation,
781                             &mut err,
782                             &trait_ref,
783                             points_at_arg,
784                             have_alt_message,
785                         ) {
786                             self.note_obligation_cause(&mut err, obligation);
787                             err.emit();
788                             return;
789                         }
790                         if let Some(ref s) = label {
791                             // If it has a custom `#[rustc_on_unimplemented]`
792                             // error message, let's display it as the label!
793                             err.span_label(span, s.as_str());
794                             err.help(&explanation);
795                         } else {
796                             err.span_label(span, explanation);
797                         }
798                         if let Some(ref s) = note {
799                             // If it has a custom `#[rustc_on_unimplemented]` note, let's display it
800                             err.note(s.as_str());
801                         }
802                         if let Some(ref s) = enclosing_scope {
803                             let enclosing_scope_span = tcx.def_span(
804                                 tcx.hir()
805                                     .opt_local_def_id(obligation.cause.body_id)
806                                     .unwrap_or_else(|| {
807                                         tcx.hir().body_owner_def_id(hir::BodyId {
808                                             hir_id: obligation.cause.body_id,
809                                         })
810                                     }),
811                             );
812
813                             err.span_label(enclosing_scope_span, s.as_str());
814                         }
815
816                         self.suggest_borrow_on_unsized_slice(&obligation.cause.code, &mut err);
817                         self.suggest_fn_call(&obligation, &mut err, &trait_ref, points_at_arg);
818                         self.suggest_remove_reference(&obligation, &mut err, &trait_ref);
819                         self.suggest_semicolon_removal(&obligation, &mut err, span, &trait_ref);
820                         self.note_version_mismatch(&mut err, &trait_ref);
821
822                         // Try to report a help message
823                         if !trait_ref.has_infer_types()
824                             && self.predicate_can_apply(obligation.param_env, trait_ref)
825                         {
826                             // If a where-clause may be useful, remind the
827                             // user that they can add it.
828                             //
829                             // don't display an on-unimplemented note, as
830                             // these notes will often be of the form
831                             //     "the type `T` can't be frobnicated"
832                             // which is somewhat confusing.
833                             self.suggest_restricting_param_bound(
834                                 &mut err,
835                                 &trait_ref,
836                                 obligation.cause.body_id,
837                             );
838                         } else {
839                             if !have_alt_message {
840                                 // Can't show anything else useful, try to find similar impls.
841                                 let impl_candidates = self.find_similar_impl_candidates(trait_ref);
842                                 self.report_similar_impl_candidates(impl_candidates, &mut err);
843                             }
844                             self.suggest_change_mut(
845                                 &obligation,
846                                 &mut err,
847                                 &trait_ref,
848                                 points_at_arg,
849                             );
850                         }
851
852                         // If this error is due to `!: Trait` not implemented but `(): Trait` is
853                         // implemented, and fallback has occurred, then it could be due to a
854                         // variable that used to fallback to `()` now falling back to `!`. Issue a
855                         // note informing about the change in behaviour.
856                         if trait_predicate.skip_binder().self_ty().is_never()
857                             && fallback_has_occurred
858                         {
859                             let predicate = trait_predicate.map_bound(|mut trait_pred| {
860                                 trait_pred.trait_ref.substs = self.tcx.mk_substs_trait(
861                                     self.tcx.mk_unit(),
862                                     &trait_pred.trait_ref.substs[1..],
863                                 );
864                                 trait_pred
865                             });
866                             let unit_obligation = Obligation {
867                                 predicate: ty::Predicate::Trait(predicate),
868                                 ..obligation.clone()
869                             };
870                             if self.predicate_may_hold(&unit_obligation) {
871                                 err.note(
872                                     "the trait is implemented for `()`. \
873                                          Possibly this error has been caused by changes to \
874                                          Rust's type-inference algorithm \
875                                          (see: https://github.com/rust-lang/rust/issues/48950 \
876                                          for more info). Consider whether you meant to use the \
877                                          type `()` here instead.",
878                                 );
879                             }
880                         }
881
882                         err
883                     }
884
885                     ty::Predicate::Subtype(ref predicate) => {
886                         // Errors for Subtype predicates show up as
887                         // `FulfillmentErrorCode::CodeSubtypeError`,
888                         // not selection error.
889                         span_bug!(span, "subtype requirement gave wrong error: `{:?}`", predicate)
890                     }
891
892                     ty::Predicate::RegionOutlives(ref predicate) => {
893                         let predicate = self.resolve_vars_if_possible(predicate);
894                         let err = self
895                             .region_outlives_predicate(&obligation.cause, &predicate)
896                             .err()
897                             .unwrap();
898                         struct_span_err!(
899                             self.tcx.sess,
900                             span,
901                             E0279,
902                             "the requirement `{}` is not satisfied (`{}`)",
903                             predicate,
904                             err,
905                         )
906                     }
907
908                     ty::Predicate::Projection(..) | ty::Predicate::TypeOutlives(..) => {
909                         let predicate = self.resolve_vars_if_possible(&obligation.predicate);
910                         struct_span_err!(
911                             self.tcx.sess,
912                             span,
913                             E0280,
914                             "the requirement `{}` is not satisfied",
915                             predicate
916                         )
917                     }
918
919                     ty::Predicate::ObjectSafe(trait_def_id) => {
920                         let violations = self.tcx.object_safety_violations(trait_def_id);
921                         self.tcx.report_object_safety_error(span, trait_def_id, violations)
922                     }
923
924                     ty::Predicate::ClosureKind(closure_def_id, closure_substs, kind) => {
925                         let found_kind = self.closure_kind(closure_def_id, closure_substs).unwrap();
926                         let closure_span = self
927                             .tcx
928                             .sess
929                             .source_map()
930                             .def_span(self.tcx.hir().span_if_local(closure_def_id).unwrap());
931                         let hir_id = self.tcx.hir().as_local_hir_id(closure_def_id).unwrap();
932                         let mut err = struct_span_err!(
933                             self.tcx.sess,
934                             closure_span,
935                             E0525,
936                             "expected a closure that implements the `{}` trait, \
937                              but this closure only implements `{}`",
938                             kind,
939                             found_kind
940                         );
941
942                         err.span_label(
943                             closure_span,
944                             format!("this closure implements `{}`, not `{}`", found_kind, kind),
945                         );
946                         err.span_label(
947                             obligation.cause.span,
948                             format!("the requirement to implement `{}` derives from here", kind),
949                         );
950
951                         // Additional context information explaining why the closure only implements
952                         // a particular trait.
953                         if let Some(tables) = self.in_progress_tables {
954                             let tables = tables.borrow();
955                             match (found_kind, tables.closure_kind_origins().get(hir_id)) {
956                                 (ty::ClosureKind::FnOnce, Some((span, name))) => {
957                                     err.span_label(
958                                         *span,
959                                         format!(
960                                             "closure is `FnOnce` because it moves the \
961                                          variable `{}` out of its environment",
962                                             name
963                                         ),
964                                     );
965                                 }
966                                 (ty::ClosureKind::FnMut, Some((span, name))) => {
967                                     err.span_label(
968                                         *span,
969                                         format!(
970                                             "closure is `FnMut` because it mutates the \
971                                          variable `{}` here",
972                                             name
973                                         ),
974                                     );
975                                 }
976                                 _ => {}
977                             }
978                         }
979
980                         err.emit();
981                         return;
982                     }
983
984                     ty::Predicate::WellFormed(ty) => {
985                         if !self.tcx.sess.opts.debugging_opts.chalk {
986                             // WF predicates cannot themselves make
987                             // errors. They can only block due to
988                             // ambiguity; otherwise, they always
989                             // degenerate into other obligations
990                             // (which may fail).
991                             span_bug!(span, "WF predicate not satisfied for {:?}", ty);
992                         } else {
993                             // FIXME: we'll need a better message which takes into account
994                             // which bounds actually failed to hold.
995                             self.tcx.sess.struct_span_err(
996                                 span,
997                                 &format!("the type `{}` is not well-formed (chalk)", ty),
998                             )
999                         }
1000                     }
1001
1002                     ty::Predicate::ConstEvaluatable(..) => {
1003                         // Errors for `ConstEvaluatable` predicates show up as
1004                         // `SelectionError::ConstEvalFailure`,
1005                         // not `Unimplemented`.
1006                         span_bug!(
1007                             span,
1008                             "const-evaluatable requirement gave wrong error: `{:?}`",
1009                             obligation
1010                         )
1011                     }
1012                 }
1013             }
1014
1015             OutputTypeParameterMismatch(ref found_trait_ref, ref expected_trait_ref, _) => {
1016                 let found_trait_ref = self.resolve_vars_if_possible(&*found_trait_ref);
1017                 let expected_trait_ref = self.resolve_vars_if_possible(&*expected_trait_ref);
1018
1019                 if expected_trait_ref.self_ty().references_error() {
1020                     return;
1021                 }
1022
1023                 let found_trait_ty = found_trait_ref.self_ty();
1024
1025                 let found_did = match found_trait_ty.kind {
1026                     ty::Closure(did, _) | ty::Foreign(did) | ty::FnDef(did, _) => Some(did),
1027                     ty::Adt(def, _) => Some(def.did),
1028                     _ => None,
1029                 };
1030
1031                 let found_span = found_did
1032                     .and_then(|did| self.tcx.hir().span_if_local(did))
1033                     .map(|sp| self.tcx.sess.source_map().def_span(sp)); // the sp could be an fn def
1034
1035                 if self.reported_closure_mismatch.borrow().contains(&(span, found_span)) {
1036                     // We check closures twice, with obligations flowing in different directions,
1037                     // but we want to complain about them only once.
1038                     return;
1039                 }
1040
1041                 self.reported_closure_mismatch.borrow_mut().insert((span, found_span));
1042
1043                 let found = match found_trait_ref.skip_binder().substs.type_at(1).kind {
1044                     ty::Tuple(ref tys) => vec![ArgKind::empty(); tys.len()],
1045                     _ => vec![ArgKind::empty()],
1046                 };
1047
1048                 let expected_ty = expected_trait_ref.skip_binder().substs.type_at(1);
1049                 let expected = match expected_ty.kind {
1050                     ty::Tuple(ref tys) => tys
1051                         .iter()
1052                         .map(|t| ArgKind::from_expected_ty(t.expect_ty(), Some(span)))
1053                         .collect(),
1054                     _ => vec![ArgKind::Arg("_".to_owned(), expected_ty.to_string())],
1055                 };
1056
1057                 if found.len() == expected.len() {
1058                     self.report_closure_arg_mismatch(
1059                         span,
1060                         found_span,
1061                         found_trait_ref,
1062                         expected_trait_ref,
1063                     )
1064                 } else {
1065                     let (closure_span, found) = found_did
1066                         .and_then(|did| self.tcx.hir().get_if_local(did))
1067                         .map(|node| {
1068                             let (found_span, found) = self.get_fn_like_arguments(node);
1069                             (Some(found_span), found)
1070                         })
1071                         .unwrap_or((found_span, found));
1072
1073                     self.report_arg_count_mismatch(
1074                         span,
1075                         closure_span,
1076                         expected,
1077                         found,
1078                         found_trait_ty.is_closure(),
1079                     )
1080                 }
1081             }
1082
1083             TraitNotObjectSafe(did) => {
1084                 let violations = self.tcx.object_safety_violations(did);
1085                 self.tcx.report_object_safety_error(span, did, violations)
1086             }
1087
1088             // already reported in the query
1089             ConstEvalFailure(err) => {
1090                 if let ErrorHandled::TooGeneric = err {
1091                     // Silence this error, as it can be produced during intermediate steps
1092                     // when a constant is not yet able to be evaluated (but will be later).
1093                     return;
1094                 }
1095                 self.tcx.sess.delay_span_bug(
1096                     span,
1097                     &format!("constant in type had an ignored error: {:?}", err),
1098                 );
1099                 return;
1100             }
1101
1102             Overflow => {
1103                 bug!("overflow should be handled before the `report_selection_error` path");
1104             }
1105         };
1106
1107         self.note_obligation_cause(&mut err, obligation);
1108
1109         err.emit();
1110     }
1111
1112     /// If the `Self` type of the unsatisfied trait `trait_ref` implements a trait
1113     /// with the same path as `trait_ref`, a help message about
1114     /// a probable version mismatch is added to `err`
1115     fn note_version_mismatch(
1116         &self,
1117         err: &mut DiagnosticBuilder<'_>,
1118         trait_ref: &ty::PolyTraitRef<'tcx>,
1119     ) {
1120         let get_trait_impl = |trait_def_id| {
1121             let mut trait_impl = None;
1122             self.tcx.for_each_relevant_impl(trait_def_id, trait_ref.self_ty(), |impl_def_id| {
1123                 if trait_impl.is_none() {
1124                     trait_impl = Some(impl_def_id);
1125                 }
1126             });
1127             trait_impl
1128         };
1129         let required_trait_path = self.tcx.def_path_str(trait_ref.def_id());
1130         let all_traits = self.tcx.all_traits(LOCAL_CRATE);
1131         let traits_with_same_path: std::collections::BTreeSet<_> = all_traits
1132             .iter()
1133             .filter(|trait_def_id| **trait_def_id != trait_ref.def_id())
1134             .filter(|trait_def_id| self.tcx.def_path_str(**trait_def_id) == required_trait_path)
1135             .collect();
1136         for trait_with_same_path in traits_with_same_path {
1137             if let Some(impl_def_id) = get_trait_impl(*trait_with_same_path) {
1138                 let impl_span = self.tcx.def_span(impl_def_id);
1139                 err.span_help(impl_span, "trait impl with same name found");
1140                 let trait_crate = self.tcx.crate_name(trait_with_same_path.krate);
1141                 let crate_msg = format!(
1142                     "Perhaps two different versions of crate `{}` are being used?",
1143                     trait_crate
1144                 );
1145                 err.note(&crate_msg);
1146             }
1147         }
1148     }
1149     fn suggest_restricting_param_bound(
1150         &self,
1151         mut err: &mut DiagnosticBuilder<'_>,
1152         trait_ref: &ty::PolyTraitRef<'_>,
1153         body_id: hir::HirId,
1154     ) {
1155         let self_ty = trait_ref.self_ty();
1156         let (param_ty, projection) = match &self_ty.kind {
1157             ty::Param(_) => (true, None),
1158             ty::Projection(projection) => (false, Some(projection)),
1159             _ => return,
1160         };
1161
1162         let suggest_restriction =
1163             |generics: &hir::Generics<'_>, msg, err: &mut DiagnosticBuilder<'_>| {
1164                 let span = generics.where_clause.span_for_predicates_or_empty_place();
1165                 if !span.from_expansion() && span.desugaring_kind().is_none() {
1166                     err.span_suggestion(
1167                         generics.where_clause.span_for_predicates_or_empty_place().shrink_to_hi(),
1168                         &format!("consider further restricting {}", msg),
1169                         format!(
1170                             "{} {} ",
1171                             if !generics.where_clause.predicates.is_empty() {
1172                                 ","
1173                             } else {
1174                                 " where"
1175                             },
1176                             trait_ref.to_predicate(),
1177                         ),
1178                         Applicability::MachineApplicable,
1179                     );
1180                 }
1181             };
1182
1183         // FIXME: Add check for trait bound that is already present, particularly `?Sized` so we
1184         //        don't suggest `T: Sized + ?Sized`.
1185         let mut hir_id = body_id;
1186         while let Some(node) = self.tcx.hir().find(hir_id) {
1187             match node {
1188                 hir::Node::TraitItem(hir::TraitItem {
1189                     generics,
1190                     kind: hir::TraitItemKind::Method(..),
1191                     ..
1192                 }) if param_ty && self_ty == self.tcx.types.self_param => {
1193                     // Restricting `Self` for a single method.
1194                     suggest_restriction(&generics, "`Self`", err);
1195                     return;
1196                 }
1197
1198                 hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(_, generics, _), .. })
1199                 | hir::Node::TraitItem(hir::TraitItem {
1200                     generics,
1201                     kind: hir::TraitItemKind::Method(..),
1202                     ..
1203                 })
1204                 | hir::Node::ImplItem(hir::ImplItem {
1205                     generics,
1206                     kind: hir::ImplItemKind::Method(..),
1207                     ..
1208                 })
1209                 | hir::Node::Item(hir::Item {
1210                     kind: hir::ItemKind::Trait(_, _, generics, _, _),
1211                     ..
1212                 })
1213                 | hir::Node::Item(hir::Item {
1214                     kind: hir::ItemKind::Impl(_, _, _, generics, ..),
1215                     ..
1216                 }) if projection.is_some() => {
1217                     // Missing associated type bound.
1218                     suggest_restriction(&generics, "the associated type", err);
1219                     return;
1220                 }
1221
1222                 hir::Node::Item(hir::Item {
1223                     kind: hir::ItemKind::Struct(_, generics),
1224                     span,
1225                     ..
1226                 })
1227                 | hir::Node::Item(hir::Item {
1228                     kind: hir::ItemKind::Enum(_, generics), span, ..
1229                 })
1230                 | hir::Node::Item(hir::Item {
1231                     kind: hir::ItemKind::Union(_, generics),
1232                     span,
1233                     ..
1234                 })
1235                 | hir::Node::Item(hir::Item {
1236                     kind: hir::ItemKind::Trait(_, _, generics, ..),
1237                     span,
1238                     ..
1239                 })
1240                 | hir::Node::Item(hir::Item {
1241                     kind: hir::ItemKind::Impl(_, _, _, generics, ..),
1242                     span,
1243                     ..
1244                 })
1245                 | hir::Node::Item(hir::Item {
1246                     kind: hir::ItemKind::Fn(_, generics, _),
1247                     span,
1248                     ..
1249                 })
1250                 | hir::Node::Item(hir::Item {
1251                     kind: hir::ItemKind::TyAlias(_, generics),
1252                     span,
1253                     ..
1254                 })
1255                 | hir::Node::Item(hir::Item {
1256                     kind: hir::ItemKind::TraitAlias(generics, _),
1257                     span,
1258                     ..
1259                 })
1260                 | hir::Node::Item(hir::Item {
1261                     kind: hir::ItemKind::OpaqueTy(hir::OpaqueTy { generics, .. }),
1262                     span,
1263                     ..
1264                 })
1265                 | hir::Node::TraitItem(hir::TraitItem { generics, span, .. })
1266                 | hir::Node::ImplItem(hir::ImplItem { generics, span, .. })
1267                     if param_ty =>
1268                 {
1269                     // Missing generic type parameter bound.
1270                     let param_name = self_ty.to_string();
1271                     let constraint = trait_ref.print_only_trait_path().to_string();
1272                     if suggest_constraining_type_param(
1273                         generics,
1274                         &mut err,
1275                         &param_name,
1276                         &constraint,
1277                         self.tcx.sess.source_map(),
1278                         *span,
1279                     ) {
1280                         return;
1281                     }
1282                 }
1283
1284                 hir::Node::Crate => return,
1285
1286                 _ => {}
1287             }
1288
1289             hir_id = self.tcx.hir().get_parent_item(hir_id);
1290         }
1291     }
1292
1293     /// When encountering an assignment of an unsized trait, like `let x = ""[..];`, provide a
1294     /// suggestion to borrow the initializer in order to use have a slice instead.
1295     fn suggest_borrow_on_unsized_slice(
1296         &self,
1297         code: &ObligationCauseCode<'tcx>,
1298         err: &mut DiagnosticBuilder<'tcx>,
1299     ) {
1300         if let &ObligationCauseCode::VariableType(hir_id) = code {
1301             let parent_node = self.tcx.hir().get_parent_node(hir_id);
1302             if let Some(Node::Local(ref local)) = self.tcx.hir().find(parent_node) {
1303                 if let Some(ref expr) = local.init {
1304                     if let hir::ExprKind::Index(_, _) = expr.kind {
1305                         if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(expr.span) {
1306                             err.span_suggestion(
1307                                 expr.span,
1308                                 "consider borrowing here",
1309                                 format!("&{}", snippet),
1310                                 Applicability::MachineApplicable,
1311                             );
1312                         }
1313                     }
1314                 }
1315             }
1316         }
1317     }
1318
1319     fn mk_obligation_for_def_id(
1320         &self,
1321         def_id: DefId,
1322         output_ty: Ty<'tcx>,
1323         cause: ObligationCause<'tcx>,
1324         param_env: ty::ParamEnv<'tcx>,
1325     ) -> PredicateObligation<'tcx> {
1326         let new_trait_ref =
1327             ty::TraitRef { def_id, substs: self.tcx.mk_substs_trait(output_ty, &[]) };
1328         Obligation::new(cause, param_env, new_trait_ref.to_predicate())
1329     }
1330
1331     /// Given a closure's `DefId`, return the given name of the closure.
1332     ///
1333     /// This doesn't account for reassignments, but it's only used for suggestions.
1334     fn get_closure_name(
1335         &self,
1336         def_id: DefId,
1337         err: &mut DiagnosticBuilder<'_>,
1338         msg: &str,
1339     ) -> Option<String> {
1340         let get_name =
1341             |err: &mut DiagnosticBuilder<'_>, kind: &hir::PatKind<'_>| -> Option<String> {
1342                 // Get the local name of this closure. This can be inaccurate because
1343                 // of the possibility of reassignment, but this should be good enough.
1344                 match &kind {
1345                     hir::PatKind::Binding(hir::BindingAnnotation::Unannotated, _, name, None) => {
1346                         Some(format!("{}", name))
1347                     }
1348                     _ => {
1349                         err.note(&msg);
1350                         None
1351                     }
1352                 }
1353             };
1354
1355         let hir = self.tcx.hir();
1356         let hir_id = hir.as_local_hir_id(def_id)?;
1357         let parent_node = hir.get_parent_node(hir_id);
1358         match hir.find(parent_node) {
1359             Some(hir::Node::Stmt(hir::Stmt { kind: hir::StmtKind::Local(local), .. })) => {
1360                 get_name(err, &local.pat.kind)
1361             }
1362             // Different to previous arm because one is `&hir::Local` and the other
1363             // is `P<hir::Local>`.
1364             Some(hir::Node::Local(local)) => get_name(err, &local.pat.kind),
1365             _ => return None,
1366         }
1367     }
1368
1369     /// We tried to apply the bound to an `fn` or closure. Check whether calling it would
1370     /// evaluate to a type that *would* satisfy the trait binding. If it would, suggest calling
1371     /// it: `bar(foo)` → `bar(foo())`. This case is *very* likely to be hit if `foo` is `async`.
1372     fn suggest_fn_call(
1373         &self,
1374         obligation: &PredicateObligation<'tcx>,
1375         err: &mut DiagnosticBuilder<'_>,
1376         trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
1377         points_at_arg: bool,
1378     ) {
1379         let self_ty = trait_ref.self_ty();
1380         let (def_id, output_ty, callable) = match self_ty.kind {
1381             ty::Closure(def_id, substs) => {
1382                 (def_id, self.closure_sig(def_id, substs).output(), "closure")
1383             }
1384             ty::FnDef(def_id, _) => (def_id, self_ty.fn_sig(self.tcx).output(), "function"),
1385             _ => return,
1386         };
1387         let msg = format!("use parentheses to call the {}", callable);
1388
1389         let obligation = self.mk_obligation_for_def_id(
1390             trait_ref.def_id(),
1391             output_ty.skip_binder(),
1392             obligation.cause.clone(),
1393             obligation.param_env,
1394         );
1395
1396         match self.evaluate_obligation(&obligation) {
1397             Ok(EvaluationResult::EvaluatedToOk)
1398             | Ok(EvaluationResult::EvaluatedToOkModuloRegions)
1399             | Ok(EvaluationResult::EvaluatedToAmbig) => {}
1400             _ => return,
1401         }
1402         let hir = self.tcx.hir();
1403         // Get the name of the callable and the arguments to be used in the suggestion.
1404         let snippet = match hir.get_if_local(def_id) {
1405             Some(hir::Node::Expr(hir::Expr {
1406                 kind: hir::ExprKind::Closure(_, decl, _, span, ..),
1407                 ..
1408             })) => {
1409                 err.span_label(*span, "consider calling this closure");
1410                 let name = match self.get_closure_name(def_id, err, &msg) {
1411                     Some(name) => name,
1412                     None => return,
1413                 };
1414                 let args = decl.inputs.iter().map(|_| "_").collect::<Vec<_>>().join(", ");
1415                 format!("{}({})", name, args)
1416             }
1417             Some(hir::Node::Item(hir::Item {
1418                 ident,
1419                 kind: hir::ItemKind::Fn(.., body_id),
1420                 ..
1421             })) => {
1422                 err.span_label(ident.span, "consider calling this function");
1423                 let body = hir.body(*body_id);
1424                 let args = body
1425                     .params
1426                     .iter()
1427                     .map(|arg| match &arg.pat.kind {
1428                         hir::PatKind::Binding(_, _, ident, None)
1429                         // FIXME: provide a better suggestion when encountering `SelfLower`, it
1430                         // should suggest a method call.
1431                         if ident.name != kw::SelfLower => ident.to_string(),
1432                         _ => "_".to_string(),
1433                     })
1434                     .collect::<Vec<_>>()
1435                     .join(", ");
1436                 format!("{}({})", ident, args)
1437             }
1438             _ => return,
1439         };
1440         if points_at_arg {
1441             // When the obligation error has been ensured to have been caused by
1442             // an argument, the `obligation.cause.span` points at the expression
1443             // of the argument, so we can provide a suggestion. This is signaled
1444             // by `points_at_arg`. Otherwise, we give a more general note.
1445             err.span_suggestion(
1446                 obligation.cause.span,
1447                 &msg,
1448                 snippet,
1449                 Applicability::HasPlaceholders,
1450             );
1451         } else {
1452             err.help(&format!("{}: `{}`", msg, snippet));
1453         }
1454     }
1455
1456     fn suggest_add_reference_to_arg(
1457         &self,
1458         obligation: &PredicateObligation<'tcx>,
1459         err: &mut DiagnosticBuilder<'tcx>,
1460         trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
1461         points_at_arg: bool,
1462         has_custom_message: bool,
1463     ) -> bool {
1464         if !points_at_arg {
1465             return false;
1466         }
1467
1468         let span = obligation.cause.span;
1469         let param_env = obligation.param_env;
1470         let trait_ref = trait_ref.skip_binder();
1471
1472         if let ObligationCauseCode::ImplDerivedObligation(obligation) = &obligation.cause.code {
1473             // Try to apply the original trait binding obligation by borrowing.
1474             let self_ty = trait_ref.self_ty();
1475             let found = self_ty.to_string();
1476             let new_self_ty = self.tcx.mk_imm_ref(self.tcx.lifetimes.re_static, self_ty);
1477             let substs = self.tcx.mk_substs_trait(new_self_ty, &[]);
1478             let new_trait_ref = ty::TraitRef::new(obligation.parent_trait_ref.def_id(), substs);
1479             let new_obligation =
1480                 Obligation::new(ObligationCause::dummy(), param_env, new_trait_ref.to_predicate());
1481             if self.predicate_must_hold_modulo_regions(&new_obligation) {
1482                 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
1483                     // We have a very specific type of error, where just borrowing this argument
1484                     // might solve the problem. In cases like this, the important part is the
1485                     // original type obligation, not the last one that failed, which is arbitrary.
1486                     // Because of this, we modify the error to refer to the original obligation and
1487                     // return early in the caller.
1488                     let msg = format!(
1489                         "the trait bound `{}: {}` is not satisfied",
1490                         found,
1491                         obligation.parent_trait_ref.skip_binder().print_only_trait_path(),
1492                     );
1493                     if has_custom_message {
1494                         err.note(&msg);
1495                     } else {
1496                         err.message = vec![(msg, Style::NoStyle)];
1497                     }
1498                     if snippet.starts_with('&') {
1499                         // This is already a literal borrow and the obligation is failing
1500                         // somewhere else in the obligation chain. Do not suggest non-sense.
1501                         return false;
1502                     }
1503                     err.span_label(
1504                         span,
1505                         &format!(
1506                             "expected an implementor of trait `{}`",
1507                             obligation.parent_trait_ref.skip_binder().print_only_trait_path(),
1508                         ),
1509                     );
1510                     err.span_suggestion(
1511                         span,
1512                         "consider borrowing here",
1513                         format!("&{}", snippet),
1514                         Applicability::MaybeIncorrect,
1515                     );
1516                     return true;
1517                 }
1518             }
1519         }
1520         false
1521     }
1522
1523     /// Whenever references are used by mistake, like `for (i, e) in &vec.iter().enumerate()`,
1524     /// suggest removing these references until we reach a type that implements the trait.
1525     fn suggest_remove_reference(
1526         &self,
1527         obligation: &PredicateObligation<'tcx>,
1528         err: &mut DiagnosticBuilder<'tcx>,
1529         trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
1530     ) {
1531         let trait_ref = trait_ref.skip_binder();
1532         let span = obligation.cause.span;
1533
1534         if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
1535             let refs_number =
1536                 snippet.chars().filter(|c| !c.is_whitespace()).take_while(|c| *c == '&').count();
1537             if let Some('\'') =
1538                 snippet.chars().filter(|c| !c.is_whitespace()).skip(refs_number).next()
1539             {
1540                 // Do not suggest removal of borrow from type arguments.
1541                 return;
1542             }
1543
1544             let mut trait_type = trait_ref.self_ty();
1545
1546             for refs_remaining in 0..refs_number {
1547                 if let ty::Ref(_, t_type, _) = trait_type.kind {
1548                     trait_type = t_type;
1549
1550                     let new_obligation = self.mk_obligation_for_def_id(
1551                         trait_ref.def_id,
1552                         trait_type,
1553                         ObligationCause::dummy(),
1554                         obligation.param_env,
1555                     );
1556
1557                     if self.predicate_may_hold(&new_obligation) {
1558                         let sp = self
1559                             .tcx
1560                             .sess
1561                             .source_map()
1562                             .span_take_while(span, |c| c.is_whitespace() || *c == '&');
1563
1564                         let remove_refs = refs_remaining + 1;
1565                         let format_str =
1566                             format!("consider removing {} leading `&`-references", remove_refs);
1567
1568                         err.span_suggestion_short(
1569                             sp,
1570                             &format_str,
1571                             String::new(),
1572                             Applicability::MachineApplicable,
1573                         );
1574                         break;
1575                     }
1576                 } else {
1577                     break;
1578                 }
1579             }
1580         }
1581     }
1582
1583     /// Check if the trait bound is implemented for a different mutability and note it in the
1584     /// final error.
1585     fn suggest_change_mut(
1586         &self,
1587         obligation: &PredicateObligation<'tcx>,
1588         err: &mut DiagnosticBuilder<'tcx>,
1589         trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
1590         points_at_arg: bool,
1591     ) {
1592         let span = obligation.cause.span;
1593         if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
1594             let refs_number =
1595                 snippet.chars().filter(|c| !c.is_whitespace()).take_while(|c| *c == '&').count();
1596             if let Some('\'') =
1597                 snippet.chars().filter(|c| !c.is_whitespace()).skip(refs_number).next()
1598             {
1599                 // Do not suggest removal of borrow from type arguments.
1600                 return;
1601             }
1602             let trait_ref = self.resolve_vars_if_possible(trait_ref);
1603             if trait_ref.has_infer_types() {
1604                 // Do not ICE while trying to find if a reborrow would succeed on a trait with
1605                 // unresolved bindings.
1606                 return;
1607             }
1608
1609             if let ty::Ref(region, t_type, mutability) = trait_ref.skip_binder().self_ty().kind {
1610                 let trait_type = match mutability {
1611                     hir::Mutability::Mut => self.tcx.mk_imm_ref(region, t_type),
1612                     hir::Mutability::Not => self.tcx.mk_mut_ref(region, t_type),
1613                 };
1614
1615                 let new_obligation = self.mk_obligation_for_def_id(
1616                     trait_ref.skip_binder().def_id,
1617                     trait_type,
1618                     ObligationCause::dummy(),
1619                     obligation.param_env,
1620                 );
1621
1622                 if self.evaluate_obligation_no_overflow(&new_obligation).must_apply_modulo_regions()
1623                 {
1624                     let sp = self
1625                         .tcx
1626                         .sess
1627                         .source_map()
1628                         .span_take_while(span, |c| c.is_whitespace() || *c == '&');
1629                     if points_at_arg && mutability == hir::Mutability::Not && refs_number > 0 {
1630                         err.span_suggestion(
1631                             sp,
1632                             "consider changing this borrow's mutability",
1633                             "&mut ".to_string(),
1634                             Applicability::MachineApplicable,
1635                         );
1636                     } else {
1637                         err.note(&format!(
1638                             "`{}` is implemented for `{:?}`, but not for `{:?}`",
1639                             trait_ref.print_only_trait_path(),
1640                             trait_type,
1641                             trait_ref.skip_binder().self_ty(),
1642                         ));
1643                     }
1644                 }
1645             }
1646         }
1647     }
1648
1649     fn suggest_semicolon_removal(
1650         &self,
1651         obligation: &PredicateObligation<'tcx>,
1652         err: &mut DiagnosticBuilder<'tcx>,
1653         span: Span,
1654         trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
1655     ) {
1656         let hir = self.tcx.hir();
1657         let parent_node = hir.get_parent_node(obligation.cause.body_id);
1658         let node = hir.find(parent_node);
1659         if let Some(hir::Node::Item(hir::Item {
1660             kind: hir::ItemKind::Fn(sig, _, body_id), ..
1661         })) = node
1662         {
1663             let body = hir.body(*body_id);
1664             if let hir::ExprKind::Block(blk, _) = &body.value.kind {
1665                 if sig.decl.output.span().overlaps(span)
1666                     && blk.expr.is_none()
1667                     && "()" == &trait_ref.self_ty().to_string()
1668                 {
1669                     // FIXME(estebank): When encountering a method with a trait
1670                     // bound not satisfied in the return type with a body that has
1671                     // no return, suggest removal of semicolon on last statement.
1672                     // Once that is added, close #54771.
1673                     if let Some(ref stmt) = blk.stmts.last() {
1674                         let sp = self.tcx.sess.source_map().end_point(stmt.span);
1675                         err.span_label(sp, "consider removing this semicolon");
1676                     }
1677                 }
1678             }
1679         }
1680     }
1681
1682     /// Given some node representing a fn-like thing in the HIR map,
1683     /// returns a span and `ArgKind` information that describes the
1684     /// arguments it expects. This can be supplied to
1685     /// `report_arg_count_mismatch`.
1686     pub fn get_fn_like_arguments(&self, node: Node<'_>) -> (Span, Vec<ArgKind>) {
1687         match node {
1688             Node::Expr(&hir::Expr {
1689                 kind: hir::ExprKind::Closure(_, ref _decl, id, span, _),
1690                 ..
1691             }) => (
1692                 self.tcx.sess.source_map().def_span(span),
1693                 self.tcx
1694                     .hir()
1695                     .body(id)
1696                     .params
1697                     .iter()
1698                     .map(|arg| {
1699                         if let hir::Pat { kind: hir::PatKind::Tuple(ref args, _), span, .. } =
1700                             *arg.pat
1701                         {
1702                             ArgKind::Tuple(
1703                                 Some(span),
1704                                 args.iter()
1705                                     .map(|pat| {
1706                                         let snippet = self
1707                                             .tcx
1708                                             .sess
1709                                             .source_map()
1710                                             .span_to_snippet(pat.span)
1711                                             .unwrap();
1712                                         (snippet, "_".to_owned())
1713                                     })
1714                                     .collect::<Vec<_>>(),
1715                             )
1716                         } else {
1717                             let name =
1718                                 self.tcx.sess.source_map().span_to_snippet(arg.pat.span).unwrap();
1719                             ArgKind::Arg(name, "_".to_owned())
1720                         }
1721                     })
1722                     .collect::<Vec<ArgKind>>(),
1723             ),
1724             Node::Item(&hir::Item { span, kind: hir::ItemKind::Fn(ref sig, ..), .. })
1725             | Node::ImplItem(&hir::ImplItem {
1726                 span,
1727                 kind: hir::ImplItemKind::Method(ref sig, _),
1728                 ..
1729             })
1730             | Node::TraitItem(&hir::TraitItem {
1731                 span,
1732                 kind: hir::TraitItemKind::Method(ref sig, _),
1733                 ..
1734             }) => (
1735                 self.tcx.sess.source_map().def_span(span),
1736                 sig.decl
1737                     .inputs
1738                     .iter()
1739                     .map(|arg| match arg.clone().kind {
1740                         hir::TyKind::Tup(ref tys) => ArgKind::Tuple(
1741                             Some(arg.span),
1742                             vec![("_".to_owned(), "_".to_owned()); tys.len()],
1743                         ),
1744                         _ => ArgKind::empty(),
1745                     })
1746                     .collect::<Vec<ArgKind>>(),
1747             ),
1748             Node::Ctor(ref variant_data) => {
1749                 let span = variant_data
1750                     .ctor_hir_id()
1751                     .map(|hir_id| self.tcx.hir().span(hir_id))
1752                     .unwrap_or(DUMMY_SP);
1753                 let span = self.tcx.sess.source_map().def_span(span);
1754
1755                 (span, vec![ArgKind::empty(); variant_data.fields().len()])
1756             }
1757             _ => panic!("non-FnLike node found: {:?}", node),
1758         }
1759     }
1760
1761     /// Reports an error when the number of arguments needed by a
1762     /// trait match doesn't match the number that the expression
1763     /// provides.
1764     pub fn report_arg_count_mismatch(
1765         &self,
1766         span: Span,
1767         found_span: Option<Span>,
1768         expected_args: Vec<ArgKind>,
1769         found_args: Vec<ArgKind>,
1770         is_closure: bool,
1771     ) -> DiagnosticBuilder<'tcx> {
1772         let kind = if is_closure { "closure" } else { "function" };
1773
1774         let args_str = |arguments: &[ArgKind], other: &[ArgKind]| {
1775             let arg_length = arguments.len();
1776             let distinct = match &other[..] {
1777                 &[ArgKind::Tuple(..)] => true,
1778                 _ => false,
1779             };
1780             match (arg_length, arguments.get(0)) {
1781                 (1, Some(&ArgKind::Tuple(_, ref fields))) => {
1782                     format!("a single {}-tuple as argument", fields.len())
1783                 }
1784                 _ => format!(
1785                     "{} {}argument{}",
1786                     arg_length,
1787                     if distinct && arg_length > 1 { "distinct " } else { "" },
1788                     pluralize!(arg_length)
1789                 ),
1790             }
1791         };
1792
1793         let expected_str = args_str(&expected_args, &found_args);
1794         let found_str = args_str(&found_args, &expected_args);
1795
1796         let mut err = struct_span_err!(
1797             self.tcx.sess,
1798             span,
1799             E0593,
1800             "{} is expected to take {}, but it takes {}",
1801             kind,
1802             expected_str,
1803             found_str,
1804         );
1805
1806         err.span_label(span, format!("expected {} that takes {}", kind, expected_str));
1807
1808         if let Some(found_span) = found_span {
1809             err.span_label(found_span, format!("takes {}", found_str));
1810
1811             // move |_| { ... }
1812             // ^^^^^^^^-- def_span
1813             //
1814             // move |_| { ... }
1815             // ^^^^^-- prefix
1816             let prefix_span = self.tcx.sess.source_map().span_until_non_whitespace(found_span);
1817             // move |_| { ... }
1818             //      ^^^-- pipe_span
1819             let pipe_span =
1820                 if let Some(span) = found_span.trim_start(prefix_span) { span } else { found_span };
1821
1822             // Suggest to take and ignore the arguments with expected_args_length `_`s if
1823             // found arguments is empty (assume the user just wants to ignore args in this case).
1824             // For example, if `expected_args_length` is 2, suggest `|_, _|`.
1825             if found_args.is_empty() && is_closure {
1826                 let underscores = vec!["_"; expected_args.len()].join(", ");
1827                 err.span_suggestion(
1828                     pipe_span,
1829                     &format!(
1830                         "consider changing the closure to take and ignore the expected argument{}",
1831                         if expected_args.len() < 2 { "" } else { "s" }
1832                     ),
1833                     format!("|{}|", underscores),
1834                     Applicability::MachineApplicable,
1835                 );
1836             }
1837
1838             if let &[ArgKind::Tuple(_, ref fields)] = &found_args[..] {
1839                 if fields.len() == expected_args.len() {
1840                     let sugg = fields
1841                         .iter()
1842                         .map(|(name, _)| name.to_owned())
1843                         .collect::<Vec<String>>()
1844                         .join(", ");
1845                     err.span_suggestion(
1846                         found_span,
1847                         "change the closure to take multiple arguments instead of a single tuple",
1848                         format!("|{}|", sugg),
1849                         Applicability::MachineApplicable,
1850                     );
1851                 }
1852             }
1853             if let &[ArgKind::Tuple(_, ref fields)] = &expected_args[..] {
1854                 if fields.len() == found_args.len() && is_closure {
1855                     let sugg = format!(
1856                         "|({}){}|",
1857                         found_args
1858                             .iter()
1859                             .map(|arg| match arg {
1860                                 ArgKind::Arg(name, _) => name.to_owned(),
1861                                 _ => "_".to_owned(),
1862                             })
1863                             .collect::<Vec<String>>()
1864                             .join(", "),
1865                         // add type annotations if available
1866                         if found_args.iter().any(|arg| match arg {
1867                             ArgKind::Arg(_, ty) => ty != "_",
1868                             _ => false,
1869                         }) {
1870                             format!(
1871                                 ": ({})",
1872                                 fields
1873                                     .iter()
1874                                     .map(|(_, ty)| ty.to_owned())
1875                                     .collect::<Vec<String>>()
1876                                     .join(", ")
1877                             )
1878                         } else {
1879                             String::new()
1880                         },
1881                     );
1882                     err.span_suggestion(
1883                         found_span,
1884                         "change the closure to accept a tuple instead of individual arguments",
1885                         sugg,
1886                         Applicability::MachineApplicable,
1887                     );
1888                 }
1889             }
1890         }
1891
1892         err
1893     }
1894
1895     fn report_closure_arg_mismatch(
1896         &self,
1897         span: Span,
1898         found_span: Option<Span>,
1899         expected_ref: ty::PolyTraitRef<'tcx>,
1900         found: ty::PolyTraitRef<'tcx>,
1901     ) -> DiagnosticBuilder<'tcx> {
1902         fn build_fn_sig_string<'tcx>(tcx: TyCtxt<'tcx>, trait_ref: &ty::TraitRef<'tcx>) -> String {
1903             let inputs = trait_ref.substs.type_at(1);
1904             let sig = if let ty::Tuple(inputs) = inputs.kind {
1905                 tcx.mk_fn_sig(
1906                     inputs.iter().map(|k| k.expect_ty()),
1907                     tcx.mk_ty_infer(ty::TyVar(ty::TyVid { index: 0 })),
1908                     false,
1909                     hir::Unsafety::Normal,
1910                     ::rustc_target::spec::abi::Abi::Rust,
1911                 )
1912             } else {
1913                 tcx.mk_fn_sig(
1914                     ::std::iter::once(inputs),
1915                     tcx.mk_ty_infer(ty::TyVar(ty::TyVid { index: 0 })),
1916                     false,
1917                     hir::Unsafety::Normal,
1918                     ::rustc_target::spec::abi::Abi::Rust,
1919                 )
1920             };
1921             ty::Binder::bind(sig).to_string()
1922         }
1923
1924         let argument_is_closure = expected_ref.skip_binder().substs.type_at(0).is_closure();
1925         let mut err = struct_span_err!(
1926             self.tcx.sess,
1927             span,
1928             E0631,
1929             "type mismatch in {} arguments",
1930             if argument_is_closure { "closure" } else { "function" }
1931         );
1932
1933         let found_str = format!(
1934             "expected signature of `{}`",
1935             build_fn_sig_string(self.tcx, found.skip_binder())
1936         );
1937         err.span_label(span, found_str);
1938
1939         let found_span = found_span.unwrap_or(span);
1940         let expected_str = format!(
1941             "found signature of `{}`",
1942             build_fn_sig_string(self.tcx, expected_ref.skip_binder())
1943         );
1944         err.span_label(found_span, expected_str);
1945
1946         err
1947     }
1948 }
1949
1950 impl<'tcx> TyCtxt<'tcx> {
1951     pub fn recursive_type_with_infinite_size_error(
1952         self,
1953         type_def_id: DefId,
1954     ) -> DiagnosticBuilder<'tcx> {
1955         assert!(type_def_id.is_local());
1956         let span = self.hir().span_if_local(type_def_id).unwrap();
1957         let span = self.sess.source_map().def_span(span);
1958         let mut err = struct_span_err!(
1959             self.sess,
1960             span,
1961             E0072,
1962             "recursive type `{}` has infinite size",
1963             self.def_path_str(type_def_id)
1964         );
1965         err.span_label(span, "recursive type has infinite size");
1966         err.help(&format!(
1967             "insert indirection (e.g., a `Box`, `Rc`, or `&`) \
1968                            at some point to make `{}` representable",
1969             self.def_path_str(type_def_id)
1970         ));
1971         err
1972     }
1973
1974     pub fn report_object_safety_error(
1975         self,
1976         span: Span,
1977         trait_def_id: DefId,
1978         violations: Vec<ObjectSafetyViolation>,
1979     ) -> DiagnosticBuilder<'tcx> {
1980         let trait_str = self.def_path_str(trait_def_id);
1981         let span = self.sess.source_map().def_span(span);
1982         let mut err = struct_span_err!(
1983             self.sess,
1984             span,
1985             E0038,
1986             "the trait `{}` cannot be made into an object",
1987             trait_str
1988         );
1989         err.span_label(span, format!("the trait `{}` cannot be made into an object", trait_str));
1990
1991         let mut reported_violations = FxHashSet::default();
1992         for violation in violations {
1993             if reported_violations.insert(violation.clone()) {
1994                 match violation.span() {
1995                     Some(span) => err.span_label(span, violation.error_msg()),
1996                     None => err.note(&violation.error_msg()),
1997                 };
1998             }
1999         }
2000
2001         if self.sess.trait_methods_not_found.borrow().contains(&span) {
2002             // Avoid emitting error caused by non-existing method (#58734)
2003             err.cancel();
2004         }
2005
2006         err
2007     }
2008 }
2009
2010 impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
2011     fn maybe_report_ambiguity(
2012         &self,
2013         obligation: &PredicateObligation<'tcx>,
2014         body_id: Option<hir::BodyId>,
2015     ) {
2016         // Unable to successfully determine, probably means
2017         // insufficient type information, but could mean
2018         // ambiguous impls. The latter *ought* to be a
2019         // coherence violation, so we don't report it here.
2020
2021         let predicate = self.resolve_vars_if_possible(&obligation.predicate);
2022         let span = obligation.cause.span;
2023
2024         debug!(
2025             "maybe_report_ambiguity(predicate={:?}, obligation={:?} body_id={:?}, code={:?})",
2026             predicate, obligation, body_id, obligation.cause.code,
2027         );
2028
2029         // Ambiguity errors are often caused as fallout from earlier
2030         // errors. So just ignore them if this infcx is tainted.
2031         if self.is_tainted_by_errors() {
2032             return;
2033         }
2034
2035         let mut err = match predicate {
2036             ty::Predicate::Trait(ref data) => {
2037                 let trait_ref = data.to_poly_trait_ref();
2038                 let self_ty = trait_ref.self_ty();
2039                 debug!("self_ty {:?} {:?} trait_ref {:?}", self_ty, self_ty.kind, trait_ref);
2040
2041                 if predicate.references_error() {
2042                     return;
2043                 }
2044                 // Typically, this ambiguity should only happen if
2045                 // there are unresolved type inference variables
2046                 // (otherwise it would suggest a coherence
2047                 // failure). But given #21974 that is not necessarily
2048                 // the case -- we can have multiple where clauses that
2049                 // are only distinguished by a region, which results
2050                 // in an ambiguity even when all types are fully
2051                 // known, since we don't dispatch based on region
2052                 // relationships.
2053
2054                 // This is kind of a hack: it frequently happens that some earlier
2055                 // error prevents types from being fully inferred, and then we get
2056                 // a bunch of uninteresting errors saying something like "<generic
2057                 // #0> doesn't implement Sized".  It may even be true that we
2058                 // could just skip over all checks where the self-ty is an
2059                 // inference variable, but I was afraid that there might be an
2060                 // inference variable created, registered as an obligation, and
2061                 // then never forced by writeback, and hence by skipping here we'd
2062                 // be ignoring the fact that we don't KNOW the type works
2063                 // out. Though even that would probably be harmless, given that
2064                 // we're only talking about builtin traits, which are known to be
2065                 // inhabited. We used to check for `self.tcx.sess.has_errors()` to
2066                 // avoid inundating the user with unnecessary errors, but we now
2067                 // check upstream for type errors and dont add the obligations to
2068                 // begin with in those cases.
2069                 if self
2070                     .tcx
2071                     .lang_items()
2072                     .sized_trait()
2073                     .map_or(false, |sized_id| sized_id == trait_ref.def_id())
2074                 {
2075                     self.need_type_info_err(body_id, span, self_ty, ErrorCode::E0282).emit();
2076                     return;
2077                 }
2078                 let mut err = self.need_type_info_err(body_id, span, self_ty, ErrorCode::E0283);
2079                 err.note(&format!("cannot resolve `{}`", predicate));
2080                 if let (Ok(ref snippet), ObligationCauseCode::BindingObligation(ref def_id, _)) =
2081                     (self.tcx.sess.source_map().span_to_snippet(span), &obligation.cause.code)
2082                 {
2083                     let generics = self.tcx.generics_of(*def_id);
2084                     if !generics.params.is_empty() && !snippet.ends_with('>') {
2085                         // FIXME: To avoid spurious suggestions in functions where type arguments
2086                         // where already supplied, we check the snippet to make sure it doesn't
2087                         // end with a turbofish. Ideally we would have access to a `PathSegment`
2088                         // instead. Otherwise we would produce the following output:
2089                         //
2090                         // error[E0283]: type annotations needed
2091                         //   --> $DIR/issue-54954.rs:3:24
2092                         //    |
2093                         // LL | const ARR_LEN: usize = Tt::const_val::<[i8; 123]>();
2094                         //    |                        ^^^^^^^^^^^^^^^^^^^^^^^^^^
2095                         //    |                        |
2096                         //    |                        cannot infer type
2097                         //    |                        help: consider specifying the type argument
2098                         //    |                        in the function call:
2099                         //    |                        `Tt::const_val::<[i8; 123]>::<T>`
2100                         // ...
2101                         // LL |     const fn const_val<T: Sized>() -> usize {
2102                         //    |              --------- - required by this bound in `Tt::const_val`
2103                         //    |
2104                         //    = note: cannot resolve `_: Tt`
2105
2106                         err.span_suggestion(
2107                             span,
2108                             &format!(
2109                                 "consider specifying the type argument{} in the function call",
2110                                 if generics.params.len() > 1 { "s" } else { "" },
2111                             ),
2112                             format!(
2113                                 "{}::<{}>",
2114                                 snippet,
2115                                 generics
2116                                     .params
2117                                     .iter()
2118                                     .map(|p| p.name.to_string())
2119                                     .collect::<Vec<String>>()
2120                                     .join(", ")
2121                             ),
2122                             Applicability::HasPlaceholders,
2123                         );
2124                     }
2125                 }
2126                 err
2127             }
2128
2129             ty::Predicate::WellFormed(ty) => {
2130                 // Same hacky approach as above to avoid deluging user
2131                 // with error messages.
2132                 if ty.references_error() || self.tcx.sess.has_errors() {
2133                     return;
2134                 }
2135                 self.need_type_info_err(body_id, span, ty, ErrorCode::E0282)
2136             }
2137
2138             ty::Predicate::Subtype(ref data) => {
2139                 if data.references_error() || self.tcx.sess.has_errors() {
2140                     // no need to overload user in such cases
2141                     return;
2142                 }
2143                 let &SubtypePredicate { a_is_expected: _, a, b } = data.skip_binder();
2144                 // both must be type variables, or the other would've been instantiated
2145                 assert!(a.is_ty_var() && b.is_ty_var());
2146                 self.need_type_info_err(body_id, span, a, ErrorCode::E0282)
2147             }
2148             ty::Predicate::Projection(ref data) => {
2149                 let trait_ref = data.to_poly_trait_ref(self.tcx);
2150                 let self_ty = trait_ref.self_ty();
2151                 if predicate.references_error() {
2152                     return;
2153                 }
2154                 let mut err = self.need_type_info_err(body_id, span, self_ty, ErrorCode::E0284);
2155                 err.note(&format!("cannot resolve `{}`", predicate));
2156                 err
2157             }
2158
2159             _ => {
2160                 if self.tcx.sess.has_errors() {
2161                     return;
2162                 }
2163                 let mut err = struct_span_err!(
2164                     self.tcx.sess,
2165                     span,
2166                     E0284,
2167                     "type annotations needed: cannot resolve `{}`",
2168                     predicate,
2169                 );
2170                 err.span_label(span, &format!("cannot resolve `{}`", predicate));
2171                 err
2172             }
2173         };
2174         self.note_obligation_cause(&mut err, obligation);
2175         err.emit();
2176     }
2177
2178     /// Returns `true` if the trait predicate may apply for *some* assignment
2179     /// to the type parameters.
2180     fn predicate_can_apply(
2181         &self,
2182         param_env: ty::ParamEnv<'tcx>,
2183         pred: ty::PolyTraitRef<'tcx>,
2184     ) -> bool {
2185         struct ParamToVarFolder<'a, 'tcx> {
2186             infcx: &'a InferCtxt<'a, 'tcx>,
2187             var_map: FxHashMap<Ty<'tcx>, Ty<'tcx>>,
2188         }
2189
2190         impl<'a, 'tcx> TypeFolder<'tcx> for ParamToVarFolder<'a, 'tcx> {
2191             fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
2192                 self.infcx.tcx
2193             }
2194
2195             fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
2196                 if let ty::Param(ty::ParamTy { name, .. }) = ty.kind {
2197                     let infcx = self.infcx;
2198                     self.var_map.entry(ty).or_insert_with(|| {
2199                         infcx.next_ty_var(TypeVariableOrigin {
2200                             kind: TypeVariableOriginKind::TypeParameterDefinition(name, None),
2201                             span: DUMMY_SP,
2202                         })
2203                     })
2204                 } else {
2205                     ty.super_fold_with(self)
2206                 }
2207             }
2208         }
2209
2210         self.probe(|_| {
2211             let mut selcx = SelectionContext::new(self);
2212
2213             let cleaned_pred =
2214                 pred.fold_with(&mut ParamToVarFolder { infcx: self, var_map: Default::default() });
2215
2216             let cleaned_pred = super::project::normalize(
2217                 &mut selcx,
2218                 param_env,
2219                 ObligationCause::dummy(),
2220                 &cleaned_pred,
2221             )
2222             .value;
2223
2224             let obligation =
2225                 Obligation::new(ObligationCause::dummy(), param_env, cleaned_pred.to_predicate());
2226
2227             self.predicate_may_hold(&obligation)
2228         })
2229     }
2230
2231     fn note_obligation_cause(
2232         &self,
2233         err: &mut DiagnosticBuilder<'_>,
2234         obligation: &PredicateObligation<'tcx>,
2235     ) {
2236         // First, attempt to add note to this error with an async-await-specific
2237         // message, and fall back to regular note otherwise.
2238         if !self.maybe_note_obligation_cause_for_async_await(err, obligation) {
2239             self.note_obligation_cause_code(
2240                 err,
2241                 &obligation.predicate,
2242                 &obligation.cause.code,
2243                 &mut vec![],
2244             );
2245         }
2246     }
2247
2248     /// Adds an async-await specific note to the diagnostic when the future does not implement
2249     /// an auto trait because of a captured type.
2250     ///
2251     /// ```ignore (diagnostic)
2252     /// note: future does not implement `Qux` as this value is used across an await
2253     ///   --> $DIR/issue-64130-3-other.rs:17:5
2254     ///    |
2255     /// LL |     let x = Foo;
2256     ///    |         - has type `Foo`
2257     /// LL |     baz().await;
2258     ///    |     ^^^^^^^^^^^ await occurs here, with `x` maybe used later
2259     /// LL | }
2260     ///    | - `x` is later dropped here
2261     /// ```
2262     ///
2263     /// When the diagnostic does not implement `Send` or `Sync` specifically, then the diagnostic
2264     /// is "replaced" with a different message and a more specific error.
2265     ///
2266     /// ```ignore (diagnostic)
2267     /// error: future cannot be sent between threads safely
2268     ///   --> $DIR/issue-64130-2-send.rs:21:5
2269     ///    |
2270     /// LL | fn is_send<T: Send>(t: T) { }
2271     ///    |    -------    ---- required by this bound in `is_send`
2272     /// ...
2273     /// LL |     is_send(bar());
2274     ///    |     ^^^^^^^ future returned by `bar` is not send
2275     ///    |
2276     ///    = help: within `impl std::future::Future`, the trait `std::marker::Send` is not
2277     ///            implemented for `Foo`
2278     /// note: future is not send as this value is used across an await
2279     ///   --> $DIR/issue-64130-2-send.rs:15:5
2280     ///    |
2281     /// LL |     let x = Foo;
2282     ///    |         - has type `Foo`
2283     /// LL |     baz().await;
2284     ///    |     ^^^^^^^^^^^ await occurs here, with `x` maybe used later
2285     /// LL | }
2286     ///    | - `x` is later dropped here
2287     /// ```
2288     ///
2289     /// Returns `true` if an async-await specific note was added to the diagnostic.
2290     fn maybe_note_obligation_cause_for_async_await(
2291         &self,
2292         err: &mut DiagnosticBuilder<'_>,
2293         obligation: &PredicateObligation<'tcx>,
2294     ) -> bool {
2295         debug!(
2296             "maybe_note_obligation_cause_for_async_await: obligation.predicate={:?} \
2297                 obligation.cause.span={:?}",
2298             obligation.predicate, obligation.cause.span
2299         );
2300         let source_map = self.tcx.sess.source_map();
2301
2302         // Attempt to detect an async-await error by looking at the obligation causes, looking
2303         // for a generator to be present.
2304         //
2305         // When a future does not implement a trait because of a captured type in one of the
2306         // generators somewhere in the call stack, then the result is a chain of obligations.
2307         //
2308         // Given a `async fn` A that calls a `async fn` B which captures a non-send type and that
2309         // future is passed as an argument to a function C which requires a `Send` type, then the
2310         // chain looks something like this:
2311         //
2312         // - `BuiltinDerivedObligation` with a generator witness (B)
2313         // - `BuiltinDerivedObligation` with a generator (B)
2314         // - `BuiltinDerivedObligation` with `std::future::GenFuture` (B)
2315         // - `BuiltinDerivedObligation` with `impl std::future::Future` (B)
2316         // - `BuiltinDerivedObligation` with `impl std::future::Future` (B)
2317         // - `BuiltinDerivedObligation` with a generator witness (A)
2318         // - `BuiltinDerivedObligation` with a generator (A)
2319         // - `BuiltinDerivedObligation` with `std::future::GenFuture` (A)
2320         // - `BuiltinDerivedObligation` with `impl std::future::Future` (A)
2321         // - `BuiltinDerivedObligation` with `impl std::future::Future` (A)
2322         // - `BindingObligation` with `impl_send (Send requirement)
2323         //
2324         // The first obligation in the chain is the most useful and has the generator that captured
2325         // the type. The last generator has information about where the bound was introduced. At
2326         // least one generator should be present for this diagnostic to be modified.
2327         let (mut trait_ref, mut target_ty) = match obligation.predicate {
2328             ty::Predicate::Trait(p) => {
2329                 (Some(p.skip_binder().trait_ref), Some(p.skip_binder().self_ty()))
2330             }
2331             _ => (None, None),
2332         };
2333         let mut generator = None;
2334         let mut last_generator = None;
2335         let mut next_code = Some(&obligation.cause.code);
2336         while let Some(code) = next_code {
2337             debug!("maybe_note_obligation_cause_for_async_await: code={:?}", code);
2338             match code {
2339                 ObligationCauseCode::BuiltinDerivedObligation(derived_obligation)
2340                 | ObligationCauseCode::ImplDerivedObligation(derived_obligation) => {
2341                     let ty = derived_obligation.parent_trait_ref.self_ty();
2342                     debug!(
2343                         "maybe_note_obligation_cause_for_async_await: \
2344                             parent_trait_ref={:?} self_ty.kind={:?}",
2345                         derived_obligation.parent_trait_ref, ty.kind
2346                     );
2347
2348                     match ty.kind {
2349                         ty::Generator(did, ..) => {
2350                             generator = generator.or(Some(did));
2351                             last_generator = Some(did);
2352                         }
2353                         ty::GeneratorWitness(..) => {}
2354                         _ if generator.is_none() => {
2355                             trait_ref = Some(*derived_obligation.parent_trait_ref.skip_binder());
2356                             target_ty = Some(ty);
2357                         }
2358                         _ => {}
2359                     }
2360
2361                     next_code = Some(derived_obligation.parent_code.as_ref());
2362                 }
2363                 _ => break,
2364             }
2365         }
2366
2367         // Only continue if a generator was found.
2368         debug!(
2369             "maybe_note_obligation_cause_for_async_await: generator={:?} trait_ref={:?} \
2370                 target_ty={:?}",
2371             generator, trait_ref, target_ty
2372         );
2373         let (generator_did, trait_ref, target_ty) = match (generator, trait_ref, target_ty) {
2374             (Some(generator_did), Some(trait_ref), Some(target_ty)) => {
2375                 (generator_did, trait_ref, target_ty)
2376             }
2377             _ => return false,
2378         };
2379
2380         let span = self.tcx.def_span(generator_did);
2381
2382         // Do not ICE on closure typeck (#66868).
2383         if self.tcx.hir().as_local_hir_id(generator_did).is_none() {
2384             return false;
2385         }
2386
2387         // Get the tables from the infcx if the generator is the function we are
2388         // currently type-checking; otherwise, get them by performing a query.
2389         // This is needed to avoid cycles.
2390         let in_progress_tables = self.in_progress_tables.map(|t| t.borrow());
2391         let generator_did_root = self.tcx.closure_base_def_id(generator_did);
2392         debug!(
2393             "maybe_note_obligation_cause_for_async_await: generator_did={:?} \
2394              generator_did_root={:?} in_progress_tables.local_id_root={:?} span={:?}",
2395             generator_did,
2396             generator_did_root,
2397             in_progress_tables.as_ref().map(|t| t.local_id_root),
2398             span
2399         );
2400         let query_tables;
2401         let tables: &TypeckTables<'tcx> = match &in_progress_tables {
2402             Some(t) if t.local_id_root == Some(generator_did_root) => t,
2403             _ => {
2404                 query_tables = self.tcx.typeck_tables_of(generator_did);
2405                 &query_tables
2406             }
2407         };
2408
2409         // Look for a type inside the generator interior that matches the target type to get
2410         // a span.
2411         let target_ty_erased = self.tcx.erase_regions(&target_ty);
2412         let target_span = tables
2413             .generator_interior_types
2414             .iter()
2415             .find(|ty::GeneratorInteriorTypeCause { ty, .. }| {
2416                 // Careful: the regions for types that appear in the
2417                 // generator interior are not generally known, so we
2418                 // want to erase them when comparing (and anyway,
2419                 // `Send` and other bounds are generally unaffected by
2420                 // the choice of region).  When erasing regions, we
2421                 // also have to erase late-bound regions. This is
2422                 // because the types that appear in the generator
2423                 // interior generally contain "bound regions" to
2424                 // represent regions that are part of the suspended
2425                 // generator frame. Bound regions are preserved by
2426                 // `erase_regions` and so we must also call
2427                 // `erase_late_bound_regions`.
2428                 let ty_erased = self.tcx.erase_late_bound_regions(&ty::Binder::bind(*ty));
2429                 let ty_erased = self.tcx.erase_regions(&ty_erased);
2430                 let eq = ty::TyS::same_type(ty_erased, target_ty_erased);
2431                 debug!(
2432                     "maybe_note_obligation_cause_for_async_await: ty_erased={:?} \
2433                         target_ty_erased={:?} eq={:?}",
2434                     ty_erased, target_ty_erased, eq
2435                 );
2436                 eq
2437             })
2438             .map(|ty::GeneratorInteriorTypeCause { span, scope_span, .. }| {
2439                 (span, source_map.span_to_snippet(*span), scope_span)
2440             });
2441         debug!(
2442             "maybe_note_obligation_cause_for_async_await: target_ty={:?} \
2443                 generator_interior_types={:?} target_span={:?}",
2444             target_ty, tables.generator_interior_types, target_span
2445         );
2446         if let Some((target_span, Ok(snippet), scope_span)) = target_span {
2447             self.note_obligation_cause_for_async_await(
2448                 err,
2449                 *target_span,
2450                 scope_span,
2451                 snippet,
2452                 generator_did,
2453                 last_generator,
2454                 trait_ref,
2455                 target_ty,
2456                 tables,
2457                 obligation,
2458                 next_code,
2459             );
2460             true
2461         } else {
2462             false
2463         }
2464     }
2465
2466     /// Unconditionally adds the diagnostic note described in
2467     /// `maybe_note_obligation_cause_for_async_await`'s documentation comment.
2468     fn note_obligation_cause_for_async_await(
2469         &self,
2470         err: &mut DiagnosticBuilder<'_>,
2471         target_span: Span,
2472         scope_span: &Option<Span>,
2473         snippet: String,
2474         first_generator: DefId,
2475         last_generator: Option<DefId>,
2476         trait_ref: ty::TraitRef<'_>,
2477         target_ty: Ty<'tcx>,
2478         tables: &ty::TypeckTables<'_>,
2479         obligation: &PredicateObligation<'tcx>,
2480         next_code: Option<&ObligationCauseCode<'tcx>>,
2481     ) {
2482         let source_map = self.tcx.sess.source_map();
2483
2484         let is_async_fn = self
2485             .tcx
2486             .parent(first_generator)
2487             .map(|parent_did| self.tcx.asyncness(parent_did))
2488             .map(|parent_asyncness| parent_asyncness == hir::IsAsync::Async)
2489             .unwrap_or(false);
2490         let is_async_move = self
2491             .tcx
2492             .hir()
2493             .as_local_hir_id(first_generator)
2494             .and_then(|hir_id| self.tcx.hir().maybe_body_owned_by(hir_id))
2495             .map(|body_id| self.tcx.hir().body(body_id))
2496             .and_then(|body| body.generator_kind())
2497             .map(|generator_kind| match generator_kind {
2498                 hir::GeneratorKind::Async(..) => true,
2499                 _ => false,
2500             })
2501             .unwrap_or(false);
2502         let await_or_yield = if is_async_fn || is_async_move { "await" } else { "yield" };
2503
2504         // Special case the primary error message when send or sync is the trait that was
2505         // not implemented.
2506         let is_send = self.tcx.is_diagnostic_item(sym::send_trait, trait_ref.def_id);
2507         let is_sync = self.tcx.is_diagnostic_item(sym::sync_trait, trait_ref.def_id);
2508         let trait_explanation = if is_send || is_sync {
2509             let (trait_name, trait_verb) =
2510                 if is_send { ("`Send`", "sent") } else { ("`Sync`", "shared") };
2511
2512             err.clear_code();
2513             err.set_primary_message(format!(
2514                 "future cannot be {} between threads safely",
2515                 trait_verb
2516             ));
2517
2518             let original_span = err.span.primary_span().unwrap();
2519             let mut span = MultiSpan::from_span(original_span);
2520
2521             let message = if let Some(name) = last_generator
2522                 .and_then(|generator_did| self.tcx.parent(generator_did))
2523                 .and_then(|parent_did| self.tcx.hir().as_local_hir_id(parent_did))
2524                 .and_then(|parent_hir_id| self.tcx.hir().opt_name(parent_hir_id))
2525             {
2526                 format!("future returned by `{}` is not {}", name, trait_name)
2527             } else {
2528                 format!("future is not {}", trait_name)
2529             };
2530
2531             span.push_span_label(original_span, message);
2532             err.set_span(span);
2533
2534             format!("is not {}", trait_name)
2535         } else {
2536             format!("does not implement `{}`", trait_ref.print_only_trait_path())
2537         };
2538
2539         // Look at the last interior type to get a span for the `.await`.
2540         let await_span = tables.generator_interior_types.iter().map(|i| i.span).last().unwrap();
2541         let mut span = MultiSpan::from_span(await_span);
2542         span.push_span_label(
2543             await_span,
2544             format!("{} occurs here, with `{}` maybe used later", await_or_yield, snippet),
2545         );
2546
2547         span.push_span_label(target_span, format!("has type `{}`", target_ty));
2548
2549         // If available, use the scope span to annotate the drop location.
2550         if let Some(scope_span) = scope_span {
2551             span.push_span_label(
2552                 source_map.end_point(*scope_span),
2553                 format!("`{}` is later dropped here", snippet),
2554             );
2555         }
2556
2557         err.span_note(
2558             span,
2559             &format!(
2560                 "future {} as this value is used across an {}",
2561                 trait_explanation, await_or_yield,
2562             ),
2563         );
2564
2565         // Add a note for the item obligation that remains - normally a note pointing to the
2566         // bound that introduced the obligation (e.g. `T: Send`).
2567         debug!("note_obligation_cause_for_async_await: next_code={:?}", next_code);
2568         self.note_obligation_cause_code(
2569             err,
2570             &obligation.predicate,
2571             next_code.unwrap(),
2572             &mut Vec::new(),
2573         );
2574     }
2575
2576     fn note_obligation_cause_code<T>(
2577         &self,
2578         err: &mut DiagnosticBuilder<'_>,
2579         predicate: &T,
2580         cause_code: &ObligationCauseCode<'tcx>,
2581         obligated_types: &mut Vec<&ty::TyS<'tcx>>,
2582     ) where
2583         T: fmt::Display,
2584     {
2585         let tcx = self.tcx;
2586         match *cause_code {
2587             ObligationCauseCode::ExprAssignable
2588             | ObligationCauseCode::MatchExpressionArm { .. }
2589             | ObligationCauseCode::Pattern { .. }
2590             | ObligationCauseCode::IfExpression { .. }
2591             | ObligationCauseCode::IfExpressionWithNoElse
2592             | ObligationCauseCode::MainFunctionType
2593             | ObligationCauseCode::StartFunctionType
2594             | ObligationCauseCode::IntrinsicType
2595             | ObligationCauseCode::MethodReceiver
2596             | ObligationCauseCode::ReturnNoExpression
2597             | ObligationCauseCode::MiscObligation => {}
2598             ObligationCauseCode::SliceOrArrayElem => {
2599                 err.note("slice and array elements must have `Sized` type");
2600             }
2601             ObligationCauseCode::TupleElem => {
2602                 err.note("only the last element of a tuple may have a dynamically sized type");
2603             }
2604             ObligationCauseCode::ProjectionWf(data) => {
2605                 err.note(&format!("required so that the projection `{}` is well-formed", data,));
2606             }
2607             ObligationCauseCode::ReferenceOutlivesReferent(ref_ty) => {
2608                 err.note(&format!(
2609                     "required so that reference `{}` does not outlive its referent",
2610                     ref_ty,
2611                 ));
2612             }
2613             ObligationCauseCode::ObjectTypeBound(object_ty, region) => {
2614                 err.note(&format!(
2615                     "required so that the lifetime bound of `{}` for `{}` is satisfied",
2616                     region, object_ty,
2617                 ));
2618             }
2619             ObligationCauseCode::ItemObligation(item_def_id) => {
2620                 let item_name = tcx.def_path_str(item_def_id);
2621                 let msg = format!("required by `{}`", item_name);
2622
2623                 if let Some(sp) = tcx.hir().span_if_local(item_def_id) {
2624                     let sp = tcx.sess.source_map().def_span(sp);
2625                     err.span_label(sp, &msg);
2626                 } else {
2627                     err.note(&msg);
2628                 }
2629             }
2630             ObligationCauseCode::BindingObligation(item_def_id, span) => {
2631                 let item_name = tcx.def_path_str(item_def_id);
2632                 let msg = format!("required by this bound in `{}`", item_name);
2633                 if let Some(ident) = tcx.opt_item_name(item_def_id) {
2634                     err.span_label(ident.span, "");
2635                 }
2636                 if span != DUMMY_SP {
2637                     err.span_label(span, &msg);
2638                 } else {
2639                     err.note(&msg);
2640                 }
2641             }
2642             ObligationCauseCode::ObjectCastObligation(object_ty) => {
2643                 err.note(&format!(
2644                     "required for the cast to the object type `{}`",
2645                     self.ty_to_string(object_ty)
2646                 ));
2647             }
2648             ObligationCauseCode::Coercion { source: _, target } => {
2649                 err.note(&format!("required by cast to type `{}`", self.ty_to_string(target)));
2650             }
2651             ObligationCauseCode::RepeatVec(suggest_const_in_array_repeat_expressions) => {
2652                 err.note(
2653                     "the `Copy` trait is required because the \
2654                           repeated element will be copied",
2655                 );
2656                 if suggest_const_in_array_repeat_expressions {
2657                     err.note(
2658                         "this array initializer can be evaluated at compile-time, for more \
2659                               information, see issue \
2660                               https://github.com/rust-lang/rust/issues/49147",
2661                     );
2662                     if tcx.sess.opts.unstable_features.is_nightly_build() {
2663                         err.help(
2664                             "add `#![feature(const_in_array_repeat_expressions)]` to the \
2665                                   crate attributes to enable",
2666                         );
2667                     }
2668                 }
2669             }
2670             ObligationCauseCode::VariableType(_) => {
2671                 err.note("all local variables must have a statically known size");
2672                 if !self.tcx.features().unsized_locals {
2673                     err.help("unsized locals are gated as an unstable feature");
2674                 }
2675             }
2676             ObligationCauseCode::SizedArgumentType => {
2677                 err.note("all function arguments must have a statically known size");
2678                 if !self.tcx.features().unsized_locals {
2679                     err.help("unsized locals are gated as an unstable feature");
2680                 }
2681             }
2682             ObligationCauseCode::SizedReturnType => {
2683                 err.note(
2684                     "the return type of a function must have a \
2685                           statically known size",
2686                 );
2687             }
2688             ObligationCauseCode::SizedYieldType => {
2689                 err.note(
2690                     "the yield type of a generator must have a \
2691                           statically known size",
2692                 );
2693             }
2694             ObligationCauseCode::AssignmentLhsSized => {
2695                 err.note("the left-hand-side of an assignment must have a statically known size");
2696             }
2697             ObligationCauseCode::TupleInitializerSized => {
2698                 err.note("tuples must have a statically known size to be initialized");
2699             }
2700             ObligationCauseCode::StructInitializerSized => {
2701                 err.note("structs must have a statically known size to be initialized");
2702             }
2703             ObligationCauseCode::FieldSized { adt_kind: ref item, last } => match *item {
2704                 AdtKind::Struct => {
2705                     if last {
2706                         err.note(
2707                             "the last field of a packed struct may only have a \
2708                                       dynamically sized type if it does not need drop to be run",
2709                         );
2710                     } else {
2711                         err.note(
2712                             "only the last field of a struct may have a dynamically \
2713                                       sized type",
2714                         );
2715                     }
2716                 }
2717                 AdtKind::Union => {
2718                     err.note("no field of a union may have a dynamically sized type");
2719                 }
2720                 AdtKind::Enum => {
2721                     err.note("no field of an enum variant may have a dynamically sized type");
2722                 }
2723             },
2724             ObligationCauseCode::ConstSized => {
2725                 err.note("constant expressions must have a statically known size");
2726             }
2727             ObligationCauseCode::ConstPatternStructural => {
2728                 err.note("constants used for pattern-matching must derive `PartialEq` and `Eq`");
2729             }
2730             ObligationCauseCode::SharedStatic => {
2731                 err.note("shared static variables must have a type that implements `Sync`");
2732             }
2733             ObligationCauseCode::BuiltinDerivedObligation(ref data) => {
2734                 let parent_trait_ref = self.resolve_vars_if_possible(&data.parent_trait_ref);
2735                 let ty = parent_trait_ref.skip_binder().self_ty();
2736                 err.note(&format!("required because it appears within the type `{}`", ty));
2737                 obligated_types.push(ty);
2738
2739                 let parent_predicate = parent_trait_ref.to_predicate();
2740                 if !self.is_recursive_obligation(obligated_types, &data.parent_code) {
2741                     self.note_obligation_cause_code(
2742                         err,
2743                         &parent_predicate,
2744                         &data.parent_code,
2745                         obligated_types,
2746                     );
2747                 }
2748             }
2749             ObligationCauseCode::ImplDerivedObligation(ref data) => {
2750                 let parent_trait_ref = self.resolve_vars_if_possible(&data.parent_trait_ref);
2751                 err.note(&format!(
2752                     "required because of the requirements on the impl of `{}` for `{}`",
2753                     parent_trait_ref.print_only_trait_path(),
2754                     parent_trait_ref.skip_binder().self_ty()
2755                 ));
2756                 let parent_predicate = parent_trait_ref.to_predicate();
2757                 self.note_obligation_cause_code(
2758                     err,
2759                     &parent_predicate,
2760                     &data.parent_code,
2761                     obligated_types,
2762                 );
2763             }
2764             ObligationCauseCode::CompareImplMethodObligation { .. } => {
2765                 err.note(&format!(
2766                     "the requirement `{}` appears on the impl method \
2767                               but not on the corresponding trait method",
2768                     predicate
2769                 ));
2770             }
2771             ObligationCauseCode::CompareImplTypeObligation { .. } => {
2772                 err.note(&format!(
2773                     "the requirement `{}` appears on the associated impl type\
2774                      but not on the corresponding associated trait type",
2775                     predicate
2776                 ));
2777             }
2778             ObligationCauseCode::ReturnType
2779             | ObligationCauseCode::ReturnValue(_)
2780             | ObligationCauseCode::BlockTailExpression(_) => (),
2781             ObligationCauseCode::TrivialBound => {
2782                 err.help("see issue #48214");
2783                 if tcx.sess.opts.unstable_features.is_nightly_build() {
2784                     err.help(
2785                         "add `#![feature(trivial_bounds)]` to the \
2786                               crate attributes to enable",
2787                     );
2788                 }
2789             }
2790             ObligationCauseCode::AssocTypeBound(ref data) => {
2791                 err.span_label(data.original, "associated type defined here");
2792                 if let Some(sp) = data.impl_span {
2793                     err.span_label(sp, "in this `impl` item");
2794                 }
2795                 for sp in &data.bounds {
2796                     err.span_label(*sp, "restricted in this bound");
2797                 }
2798             }
2799         }
2800     }
2801
2802     fn suggest_new_overflow_limit(&self, err: &mut DiagnosticBuilder<'_>) {
2803         let current_limit = self.tcx.sess.recursion_limit.get();
2804         let suggested_limit = current_limit * 2;
2805         err.help(&format!(
2806             "consider adding a `#![recursion_limit=\"{}\"]` attribute to your crate",
2807             suggested_limit
2808         ));
2809     }
2810
2811     fn is_recursive_obligation(
2812         &self,
2813         obligated_types: &mut Vec<&ty::TyS<'tcx>>,
2814         cause_code: &ObligationCauseCode<'tcx>,
2815     ) -> bool {
2816         if let ObligationCauseCode::BuiltinDerivedObligation(ref data) = cause_code {
2817             let parent_trait_ref = self.resolve_vars_if_possible(&data.parent_trait_ref);
2818
2819             if obligated_types.iter().any(|ot| ot == &parent_trait_ref.skip_binder().self_ty()) {
2820                 return true;
2821             }
2822         }
2823         false
2824     }
2825 }
2826
2827 /// Summarizes information
2828 #[derive(Clone)]
2829 pub enum ArgKind {
2830     /// An argument of non-tuple type. Parameters are (name, ty)
2831     Arg(String, String),
2832
2833     /// An argument of tuple type. For a "found" argument, the span is
2834     /// the locationo in the source of the pattern. For a "expected"
2835     /// argument, it will be None. The vector is a list of (name, ty)
2836     /// strings for the components of the tuple.
2837     Tuple(Option<Span>, Vec<(String, String)>),
2838 }
2839
2840 impl ArgKind {
2841     fn empty() -> ArgKind {
2842         ArgKind::Arg("_".to_owned(), "_".to_owned())
2843     }
2844
2845     /// Creates an `ArgKind` from the expected type of an
2846     /// argument. It has no name (`_`) and an optional source span.
2847     pub fn from_expected_ty(t: Ty<'_>, span: Option<Span>) -> ArgKind {
2848         match t.kind {
2849             ty::Tuple(ref tys) => ArgKind::Tuple(
2850                 span,
2851                 tys.iter().map(|ty| ("_".to_owned(), ty.to_string())).collect::<Vec<_>>(),
2852             ),
2853             _ => ArgKind::Arg("_".to_owned(), t.to_string()),
2854         }
2855     }
2856 }
2857
2858 /// Suggest restricting a type param with a new bound.
2859 pub fn suggest_constraining_type_param(
2860     generics: &hir::Generics<'_>,
2861     err: &mut DiagnosticBuilder<'_>,
2862     param_name: &str,
2863     constraint: &str,
2864     source_map: &SourceMap,
2865     span: Span,
2866 ) -> bool {
2867     let restrict_msg = "consider further restricting this bound";
2868     if let Some(param) =
2869         generics.params.iter().filter(|p| p.name.ident().as_str() == param_name).next()
2870     {
2871         if param_name.starts_with("impl ") {
2872             // `impl Trait` in argument:
2873             // `fn foo(x: impl Trait) {}` → `fn foo(t: impl Trait + Trait2) {}`
2874             err.span_suggestion(
2875                 param.span,
2876                 restrict_msg,
2877                 // `impl CurrentTrait + MissingTrait`
2878                 format!("{} + {}", param_name, constraint),
2879                 Applicability::MachineApplicable,
2880             );
2881         } else if generics.where_clause.predicates.is_empty() && param.bounds.is_empty() {
2882             // If there are no bounds whatsoever, suggest adding a constraint
2883             // to the type parameter:
2884             // `fn foo<T>(t: T) {}` → `fn foo<T: Trait>(t: T) {}`
2885             err.span_suggestion(
2886                 param.span,
2887                 "consider restricting this bound",
2888                 format!("{}: {}", param_name, constraint),
2889                 Applicability::MachineApplicable,
2890             );
2891         } else if !generics.where_clause.predicates.is_empty() {
2892             // There is a `where` clause, so suggest expanding it:
2893             // `fn foo<T>(t: T) where T: Debug {}` →
2894             // `fn foo<T>(t: T) where T: Debug, T: Trait {}`
2895             err.span_suggestion(
2896                 generics.where_clause.span().unwrap().shrink_to_hi(),
2897                 &format!("consider further restricting type parameter `{}`", param_name),
2898                 format!(", {}: {}", param_name, constraint),
2899                 Applicability::MachineApplicable,
2900             );
2901         } else {
2902             // If there is no `where` clause lean towards constraining to the
2903             // type parameter:
2904             // `fn foo<X: Bar, T>(t: T, x: X) {}` → `fn foo<T: Trait>(t: T) {}`
2905             // `fn foo<T: Bar>(t: T) {}` → `fn foo<T: Bar + Trait>(t: T) {}`
2906             let sp = param.span.with_hi(span.hi());
2907             let span = source_map.span_through_char(sp, ':');
2908             if sp != param.span && sp != span {
2909                 // Only suggest if we have high certainty that the span
2910                 // covers the colon in `foo<T: Trait>`.
2911                 err.span_suggestion(
2912                     span,
2913                     restrict_msg,
2914                     format!("{}: {} + ", param_name, constraint),
2915                     Applicability::MachineApplicable,
2916                 );
2917             } else {
2918                 err.span_label(
2919                     param.span,
2920                     &format!("consider adding a `where {}: {}` bound", param_name, constraint),
2921                 );
2922             }
2923         }
2924         return true;
2925     }
2926     false
2927 }