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