]> git.lizzy.rs Git - rust.git/blob - src/librustc/traits/error_reporting.rs
Auto merge of #67563 - euclio:rustdoc-buffer-lexer, r=GuillaumeGomez
[rust.git] / src / librustc / traits / error_reporting.rs
1 use super::{
2     ConstEvalFailure, EvaluationResult, FulfillmentError, FulfillmentErrorCode,
3     MismatchedProjectionTypes, ObjectSafetyViolation, Obligation, ObligationCause,
4     ObligationCauseCode, OnUnimplementedDirective, OnUnimplementedNote,
5     OutputTypeParameterMismatch, Overflow, PredicateObligation, SelectionContext, SelectionError,
6     TraitNotObjectSafe,
7 };
8
9 use crate::hir;
10 use crate::hir::def_id::DefId;
11 use crate::hir::Node;
12 use crate::infer::error_reporting::TypeAnnotationNeeded as ErrorCode;
13 use crate::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
14 use crate::infer::{self, InferCtxt};
15 use crate::session::DiagnosticMessageId;
16 use crate::ty::error::ExpectedFound;
17 use crate::ty::fast_reject;
18 use crate::ty::fold::TypeFolder;
19 use crate::ty::subst::Subst;
20 use crate::ty::GenericParamDefKind;
21 use crate::ty::SubtypePredicate;
22 use crate::ty::TypeckTables;
23 use crate::ty::{self, AdtKind, DefIdTree, ToPolyTraitRef, ToPredicate, Ty, TyCtxt, TypeFoldable};
24
25 use errors::{pluralize, Applicability, DiagnosticBuilder, Style};
26 use rustc::hir::def_id::LOCAL_CRATE;
27 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
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 = self.tcx.object_safety_violations(trait_def_id);
920                         self.tcx.report_object_safety_error(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 = self.tcx.object_safety_violations(did);
1084                 self.tcx.report_object_safety_error(span, did, violations)
1085             }
1086
1087             // already reported in the query
1088             ConstEvalFailure(err) => {
1089                 self.tcx.sess.delay_span_bug(
1090                     span,
1091                     &format!("constant in type had an ignored error: {:?}", err),
1092                 );
1093                 return;
1094             }
1095
1096             Overflow => {
1097                 bug!("overflow should be handled before the `report_selection_error` path");
1098             }
1099         };
1100
1101         self.note_obligation_cause(&mut err, obligation);
1102
1103         err.emit();
1104     }
1105
1106     /// If the `Self` type of the unsatisfied trait `trait_ref` implements a trait
1107     /// with the same path as `trait_ref`, a help message about
1108     /// a probable version mismatch is added to `err`
1109     fn note_version_mismatch(
1110         &self,
1111         err: &mut DiagnosticBuilder<'_>,
1112         trait_ref: &ty::PolyTraitRef<'tcx>,
1113     ) {
1114         let get_trait_impl = |trait_def_id| {
1115             let mut trait_impl = None;
1116             self.tcx.for_each_relevant_impl(trait_def_id, trait_ref.self_ty(), |impl_def_id| {
1117                 if trait_impl.is_none() {
1118                     trait_impl = Some(impl_def_id);
1119                 }
1120             });
1121             trait_impl
1122         };
1123         let required_trait_path = self.tcx.def_path_str(trait_ref.def_id());
1124         let all_traits = self.tcx.all_traits(LOCAL_CRATE);
1125         let traits_with_same_path: std::collections::BTreeSet<_> = all_traits
1126             .iter()
1127             .filter(|trait_def_id| **trait_def_id != trait_ref.def_id())
1128             .filter(|trait_def_id| self.tcx.def_path_str(**trait_def_id) == required_trait_path)
1129             .collect();
1130         for trait_with_same_path in traits_with_same_path {
1131             if let Some(impl_def_id) = get_trait_impl(*trait_with_same_path) {
1132                 let impl_span = self.tcx.def_span(impl_def_id);
1133                 err.span_help(impl_span, "trait impl with same name found");
1134                 let trait_crate = self.tcx.crate_name(trait_with_same_path.krate);
1135                 let crate_msg = format!(
1136                     "Perhaps two different versions of crate `{}` are being used?",
1137                     trait_crate
1138                 );
1139                 err.note(&crate_msg);
1140             }
1141         }
1142     }
1143     fn suggest_restricting_param_bound(
1144         &self,
1145         mut err: &mut DiagnosticBuilder<'_>,
1146         trait_ref: &ty::PolyTraitRef<'_>,
1147         body_id: hir::HirId,
1148     ) {
1149         let self_ty = trait_ref.self_ty();
1150         let (param_ty, projection) = match &self_ty.kind {
1151             ty::Param(_) => (true, None),
1152             ty::Projection(projection) => (false, Some(projection)),
1153             _ => return,
1154         };
1155
1156         let suggest_restriction =
1157             |generics: &hir::Generics<'_>, msg, err: &mut DiagnosticBuilder<'_>| {
1158                 let span = generics.where_clause.span_for_predicates_or_empty_place();
1159                 if !span.from_expansion() && span.desugaring_kind().is_none() {
1160                     err.span_suggestion(
1161                         generics.where_clause.span_for_predicates_or_empty_place().shrink_to_hi(),
1162                         &format!("consider further restricting {}", msg),
1163                         format!(
1164                             "{} {} ",
1165                             if !generics.where_clause.predicates.is_empty() {
1166                                 ","
1167                             } else {
1168                                 " where"
1169                             },
1170                             trait_ref.to_predicate(),
1171                         ),
1172                         Applicability::MachineApplicable,
1173                     );
1174                 }
1175             };
1176
1177         // FIXME: Add check for trait bound that is already present, particularly `?Sized` so we
1178         //        don't suggest `T: Sized + ?Sized`.
1179         let mut hir_id = body_id;
1180         while let Some(node) = self.tcx.hir().find(hir_id) {
1181             match node {
1182                 hir::Node::TraitItem(hir::TraitItem {
1183                     generics,
1184                     kind: hir::TraitItemKind::Method(..),
1185                     ..
1186                 }) if param_ty && self_ty == self.tcx.types.self_param => {
1187                     // Restricting `Self` for a single method.
1188                     suggest_restriction(&generics, "`Self`", err);
1189                     return;
1190                 }
1191
1192                 hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(_, generics, _), .. })
1193                 | hir::Node::TraitItem(hir::TraitItem {
1194                     generics,
1195                     kind: hir::TraitItemKind::Method(..),
1196                     ..
1197                 })
1198                 | hir::Node::ImplItem(hir::ImplItem {
1199                     generics,
1200                     kind: hir::ImplItemKind::Method(..),
1201                     ..
1202                 })
1203                 | hir::Node::Item(hir::Item {
1204                     kind: hir::ItemKind::Trait(_, _, generics, _, _),
1205                     ..
1206                 })
1207                 | hir::Node::Item(hir::Item {
1208                     kind: hir::ItemKind::Impl(_, _, _, generics, ..),
1209                     ..
1210                 }) if projection.is_some() => {
1211                     // Missing associated type bound.
1212                     suggest_restriction(&generics, "the associated type", err);
1213                     return;
1214                 }
1215
1216                 hir::Node::Item(hir::Item {
1217                     kind: hir::ItemKind::Struct(_, generics),
1218                     span,
1219                     ..
1220                 })
1221                 | hir::Node::Item(hir::Item {
1222                     kind: hir::ItemKind::Enum(_, generics), span, ..
1223                 })
1224                 | hir::Node::Item(hir::Item {
1225                     kind: hir::ItemKind::Union(_, generics),
1226                     span,
1227                     ..
1228                 })
1229                 | hir::Node::Item(hir::Item {
1230                     kind: hir::ItemKind::Trait(_, _, generics, ..),
1231                     span,
1232                     ..
1233                 })
1234                 | hir::Node::Item(hir::Item {
1235                     kind: hir::ItemKind::Impl(_, _, _, generics, ..),
1236                     span,
1237                     ..
1238                 })
1239                 | hir::Node::Item(hir::Item {
1240                     kind: hir::ItemKind::Fn(_, generics, _),
1241                     span,
1242                     ..
1243                 })
1244                 | hir::Node::Item(hir::Item {
1245                     kind: hir::ItemKind::TyAlias(_, generics),
1246                     span,
1247                     ..
1248                 })
1249                 | hir::Node::Item(hir::Item {
1250                     kind: hir::ItemKind::TraitAlias(generics, _),
1251                     span,
1252                     ..
1253                 })
1254                 | hir::Node::Item(hir::Item {
1255                     kind: hir::ItemKind::OpaqueTy(hir::OpaqueTy { generics, .. }),
1256                     span,
1257                     ..
1258                 })
1259                 | hir::Node::TraitItem(hir::TraitItem { generics, span, .. })
1260                 | hir::Node::ImplItem(hir::ImplItem { generics, span, .. })
1261                     if param_ty =>
1262                 {
1263                     // Missing generic type parameter bound.
1264                     let param_name = self_ty.to_string();
1265                     let constraint = trait_ref.print_only_trait_path().to_string();
1266                     if suggest_constraining_type_param(
1267                         generics,
1268                         &mut err,
1269                         &param_name,
1270                         &constraint,
1271                         self.tcx.sess.source_map(),
1272                         *span,
1273                     ) {
1274                         return;
1275                     }
1276                 }
1277
1278                 hir::Node::Crate => return,
1279
1280                 _ => {}
1281             }
1282
1283             hir_id = self.tcx.hir().get_parent_item(hir_id);
1284         }
1285     }
1286
1287     /// When encountering an assignment of an unsized trait, like `let x = ""[..];`, provide a
1288     /// suggestion to borrow the initializer in order to use have a slice instead.
1289     fn suggest_borrow_on_unsized_slice(
1290         &self,
1291         code: &ObligationCauseCode<'tcx>,
1292         err: &mut DiagnosticBuilder<'tcx>,
1293     ) {
1294         if let &ObligationCauseCode::VariableType(hir_id) = code {
1295             let parent_node = self.tcx.hir().get_parent_node(hir_id);
1296             if let Some(Node::Local(ref local)) = self.tcx.hir().find(parent_node) {
1297                 if let Some(ref expr) = local.init {
1298                     if let hir::ExprKind::Index(_, _) = expr.kind {
1299                         if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(expr.span) {
1300                             err.span_suggestion(
1301                                 expr.span,
1302                                 "consider borrowing here",
1303                                 format!("&{}", snippet),
1304                                 Applicability::MachineApplicable,
1305                             );
1306                         }
1307                     }
1308                 }
1309             }
1310         }
1311     }
1312
1313     fn mk_obligation_for_def_id(
1314         &self,
1315         def_id: DefId,
1316         output_ty: Ty<'tcx>,
1317         cause: ObligationCause<'tcx>,
1318         param_env: ty::ParamEnv<'tcx>,
1319     ) -> PredicateObligation<'tcx> {
1320         let new_trait_ref =
1321             ty::TraitRef { def_id, substs: self.tcx.mk_substs_trait(output_ty, &[]) };
1322         Obligation::new(cause, param_env, new_trait_ref.to_predicate())
1323     }
1324
1325     /// Given a closure's `DefId`, return the given name of the closure.
1326     ///
1327     /// This doesn't account for reassignments, but it's only used for suggestions.
1328     fn get_closure_name(
1329         &self,
1330         def_id: DefId,
1331         err: &mut DiagnosticBuilder<'_>,
1332         msg: &str,
1333     ) -> Option<String> {
1334         let get_name =
1335             |err: &mut DiagnosticBuilder<'_>, kind: &hir::PatKind<'_>| -> Option<String> {
1336                 // Get the local name of this closure. This can be inaccurate because
1337                 // of the possibility of reassignment, but this should be good enough.
1338                 match &kind {
1339                     hir::PatKind::Binding(hir::BindingAnnotation::Unannotated, _, name, None) => {
1340                         Some(format!("{}", name))
1341                     }
1342                     _ => {
1343                         err.note(&msg);
1344                         None
1345                     }
1346                 }
1347             };
1348
1349         let hir = self.tcx.hir();
1350         let hir_id = hir.as_local_hir_id(def_id)?;
1351         let parent_node = hir.get_parent_node(hir_id);
1352         match hir.find(parent_node) {
1353             Some(hir::Node::Stmt(hir::Stmt { kind: hir::StmtKind::Local(local), .. })) => {
1354                 get_name(err, &local.pat.kind)
1355             }
1356             // Different to previous arm because one is `&hir::Local` and the other
1357             // is `P<hir::Local>`.
1358             Some(hir::Node::Local(local)) => get_name(err, &local.pat.kind),
1359             _ => return None,
1360         }
1361     }
1362
1363     /// We tried to apply the bound to an `fn` or closure. Check whether calling it would
1364     /// evaluate to a type that *would* satisfy the trait binding. If it would, suggest calling
1365     /// it: `bar(foo)` → `bar(foo())`. This case is *very* likely to be hit if `foo` is `async`.
1366     fn suggest_fn_call(
1367         &self,
1368         obligation: &PredicateObligation<'tcx>,
1369         err: &mut DiagnosticBuilder<'_>,
1370         trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
1371         points_at_arg: bool,
1372     ) {
1373         let self_ty = trait_ref.self_ty();
1374         let (def_id, output_ty, callable) = match self_ty.kind {
1375             ty::Closure(def_id, substs) => {
1376                 (def_id, self.closure_sig(def_id, substs).output(), "closure")
1377             }
1378             ty::FnDef(def_id, _) => (def_id, self_ty.fn_sig(self.tcx).output(), "function"),
1379             _ => return,
1380         };
1381         let msg = format!("use parentheses to call the {}", callable);
1382
1383         let obligation = self.mk_obligation_for_def_id(
1384             trait_ref.def_id(),
1385             output_ty.skip_binder(),
1386             obligation.cause.clone(),
1387             obligation.param_env,
1388         );
1389
1390         match self.evaluate_obligation(&obligation) {
1391             Ok(EvaluationResult::EvaluatedToOk)
1392             | Ok(EvaluationResult::EvaluatedToOkModuloRegions)
1393             | Ok(EvaluationResult::EvaluatedToAmbig) => {}
1394             _ => return,
1395         }
1396         let hir = self.tcx.hir();
1397         // Get the name of the callable and the arguments to be used in the suggestion.
1398         let snippet = match hir.get_if_local(def_id) {
1399             Some(hir::Node::Expr(hir::Expr {
1400                 kind: hir::ExprKind::Closure(_, decl, _, span, ..),
1401                 ..
1402             })) => {
1403                 err.span_label(*span, "consider calling this closure");
1404                 let name = match self.get_closure_name(def_id, err, &msg) {
1405                     Some(name) => name,
1406                     None => return,
1407                 };
1408                 let args = decl.inputs.iter().map(|_| "_").collect::<Vec<_>>().join(", ");
1409                 format!("{}({})", name, args)
1410             }
1411             Some(hir::Node::Item(hir::Item {
1412                 ident,
1413                 kind: hir::ItemKind::Fn(.., body_id),
1414                 ..
1415             })) => {
1416                 err.span_label(ident.span, "consider calling this function");
1417                 let body = hir.body(*body_id);
1418                 let args = body
1419                     .params
1420                     .iter()
1421                     .map(|arg| match &arg.pat.kind {
1422                         hir::PatKind::Binding(_, _, ident, None)
1423                         // FIXME: provide a better suggestion when encountering `SelfLower`, it
1424                         // should suggest a method call.
1425                         if ident.name != kw::SelfLower => ident.to_string(),
1426                         _ => "_".to_string(),
1427                     })
1428                     .collect::<Vec<_>>()
1429                     .join(", ");
1430                 format!("{}({})", ident, args)
1431             }
1432             _ => return,
1433         };
1434         if points_at_arg {
1435             // When the obligation error has been ensured to have been caused by
1436             // an argument, the `obligation.cause.span` points at the expression
1437             // of the argument, so we can provide a suggestion. This is signaled
1438             // by `points_at_arg`. Otherwise, we give a more general note.
1439             err.span_suggestion(
1440                 obligation.cause.span,
1441                 &msg,
1442                 snippet,
1443                 Applicability::HasPlaceholders,
1444             );
1445         } else {
1446             err.help(&format!("{}: `{}`", msg, snippet));
1447         }
1448     }
1449
1450     fn suggest_add_reference_to_arg(
1451         &self,
1452         obligation: &PredicateObligation<'tcx>,
1453         err: &mut DiagnosticBuilder<'tcx>,
1454         trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
1455         points_at_arg: bool,
1456         has_custom_message: bool,
1457     ) -> bool {
1458         if !points_at_arg {
1459             return false;
1460         }
1461
1462         let span = obligation.cause.span;
1463         let param_env = obligation.param_env;
1464         let trait_ref = trait_ref.skip_binder();
1465
1466         if let ObligationCauseCode::ImplDerivedObligation(obligation) = &obligation.cause.code {
1467             // Try to apply the original trait binding obligation by borrowing.
1468             let self_ty = trait_ref.self_ty();
1469             let found = self_ty.to_string();
1470             let new_self_ty = self.tcx.mk_imm_ref(self.tcx.lifetimes.re_static, self_ty);
1471             let substs = self.tcx.mk_substs_trait(new_self_ty, &[]);
1472             let new_trait_ref = ty::TraitRef::new(obligation.parent_trait_ref.def_id(), substs);
1473             let new_obligation =
1474                 Obligation::new(ObligationCause::dummy(), param_env, new_trait_ref.to_predicate());
1475             if self.predicate_must_hold_modulo_regions(&new_obligation) {
1476                 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
1477                     // We have a very specific type of error, where just borrowing this argument
1478                     // might solve the problem. In cases like this, the important part is the
1479                     // original type obligation, not the last one that failed, which is arbitrary.
1480                     // Because of this, we modify the error to refer to the original obligation and
1481                     // return early in the caller.
1482                     let msg = format!(
1483                         "the trait bound `{}: {}` is not satisfied",
1484                         found,
1485                         obligation.parent_trait_ref.skip_binder().print_only_trait_path(),
1486                     );
1487                     if has_custom_message {
1488                         err.note(&msg);
1489                     } else {
1490                         err.message = vec![(msg, Style::NoStyle)];
1491                     }
1492                     if snippet.starts_with('&') {
1493                         // This is already a literal borrow and the obligation is failing
1494                         // somewhere else in the obligation chain. Do not suggest non-sense.
1495                         return false;
1496                     }
1497                     err.span_label(
1498                         span,
1499                         &format!(
1500                             "expected an implementor of trait `{}`",
1501                             obligation.parent_trait_ref.skip_binder().print_only_trait_path(),
1502                         ),
1503                     );
1504                     err.span_suggestion(
1505                         span,
1506                         "consider borrowing here",
1507                         format!("&{}", snippet),
1508                         Applicability::MaybeIncorrect,
1509                     );
1510                     return true;
1511                 }
1512             }
1513         }
1514         false
1515     }
1516
1517     /// Whenever references are used by mistake, like `for (i, e) in &vec.iter().enumerate()`,
1518     /// suggest removing these references until we reach a type that implements the trait.
1519     fn suggest_remove_reference(
1520         &self,
1521         obligation: &PredicateObligation<'tcx>,
1522         err: &mut DiagnosticBuilder<'tcx>,
1523         trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
1524     ) {
1525         let trait_ref = trait_ref.skip_binder();
1526         let span = obligation.cause.span;
1527
1528         if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
1529             let refs_number =
1530                 snippet.chars().filter(|c| !c.is_whitespace()).take_while(|c| *c == '&').count();
1531             if let Some('\'') =
1532                 snippet.chars().filter(|c| !c.is_whitespace()).skip(refs_number).next()
1533             {
1534                 // Do not suggest removal of borrow from type arguments.
1535                 return;
1536             }
1537
1538             let mut trait_type = trait_ref.self_ty();
1539
1540             for refs_remaining in 0..refs_number {
1541                 if let ty::Ref(_, t_type, _) = trait_type.kind {
1542                     trait_type = t_type;
1543
1544                     let new_obligation = self.mk_obligation_for_def_id(
1545                         trait_ref.def_id,
1546                         trait_type,
1547                         ObligationCause::dummy(),
1548                         obligation.param_env,
1549                     );
1550
1551                     if self.predicate_may_hold(&new_obligation) {
1552                         let sp = self
1553                             .tcx
1554                             .sess
1555                             .source_map()
1556                             .span_take_while(span, |c| c.is_whitespace() || *c == '&');
1557
1558                         let remove_refs = refs_remaining + 1;
1559                         let format_str =
1560                             format!("consider removing {} leading `&`-references", remove_refs);
1561
1562                         err.span_suggestion_short(
1563                             sp,
1564                             &format_str,
1565                             String::new(),
1566                             Applicability::MachineApplicable,
1567                         );
1568                         break;
1569                     }
1570                 } else {
1571                     break;
1572                 }
1573             }
1574         }
1575     }
1576
1577     /// Check if the trait bound is implemented for a different mutability and note it in the
1578     /// final error.
1579     fn suggest_change_mut(
1580         &self,
1581         obligation: &PredicateObligation<'tcx>,
1582         err: &mut DiagnosticBuilder<'tcx>,
1583         trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
1584         points_at_arg: bool,
1585     ) {
1586         let span = obligation.cause.span;
1587         if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
1588             let refs_number =
1589                 snippet.chars().filter(|c| !c.is_whitespace()).take_while(|c| *c == '&').count();
1590             if let Some('\'') =
1591                 snippet.chars().filter(|c| !c.is_whitespace()).skip(refs_number).next()
1592             {
1593                 // Do not suggest removal of borrow from type arguments.
1594                 return;
1595             }
1596             let trait_ref = self.resolve_vars_if_possible(trait_ref);
1597             if trait_ref.has_infer_types() {
1598                 // Do not ICE while trying to find if a reborrow would succeed on a trait with
1599                 // unresolved bindings.
1600                 return;
1601             }
1602
1603             if let ty::Ref(region, t_type, mutability) = trait_ref.skip_binder().self_ty().kind {
1604                 let trait_type = match mutability {
1605                     hir::Mutability::Mut => self.tcx.mk_imm_ref(region, t_type),
1606                     hir::Mutability::Not => self.tcx.mk_mut_ref(region, t_type),
1607                 };
1608
1609                 let new_obligation = self.mk_obligation_for_def_id(
1610                     trait_ref.skip_binder().def_id,
1611                     trait_type,
1612                     ObligationCause::dummy(),
1613                     obligation.param_env,
1614                 );
1615
1616                 if self.evaluate_obligation_no_overflow(&new_obligation).must_apply_modulo_regions()
1617                 {
1618                     let sp = self
1619                         .tcx
1620                         .sess
1621                         .source_map()
1622                         .span_take_while(span, |c| c.is_whitespace() || *c == '&');
1623                     if points_at_arg && mutability == hir::Mutability::Not && refs_number > 0 {
1624                         err.span_suggestion(
1625                             sp,
1626                             "consider changing this borrow's mutability",
1627                             "&mut ".to_string(),
1628                             Applicability::MachineApplicable,
1629                         );
1630                     } else {
1631                         err.note(&format!(
1632                             "`{}` is implemented for `{:?}`, but not for `{:?}`",
1633                             trait_ref.print_only_trait_path(),
1634                             trait_type,
1635                             trait_ref.skip_binder().self_ty(),
1636                         ));
1637                     }
1638                 }
1639             }
1640         }
1641     }
1642
1643     fn suggest_semicolon_removal(
1644         &self,
1645         obligation: &PredicateObligation<'tcx>,
1646         err: &mut DiagnosticBuilder<'tcx>,
1647         span: Span,
1648         trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
1649     ) {
1650         let hir = self.tcx.hir();
1651         let parent_node = hir.get_parent_node(obligation.cause.body_id);
1652         let node = hir.find(parent_node);
1653         if let Some(hir::Node::Item(hir::Item {
1654             kind: hir::ItemKind::Fn(sig, _, body_id), ..
1655         })) = node
1656         {
1657             let body = hir.body(*body_id);
1658             if let hir::ExprKind::Block(blk, _) = &body.value.kind {
1659                 if sig.decl.output.span().overlaps(span)
1660                     && blk.expr.is_none()
1661                     && "()" == &trait_ref.self_ty().to_string()
1662                 {
1663                     // FIXME(estebank): When encountering a method with a trait
1664                     // bound not satisfied in the return type with a body that has
1665                     // no return, suggest removal of semicolon on last statement.
1666                     // Once that is added, close #54771.
1667                     if let Some(ref stmt) = blk.stmts.last() {
1668                         let sp = self.tcx.sess.source_map().end_point(stmt.span);
1669                         err.span_label(sp, "consider removing this semicolon");
1670                     }
1671                 }
1672             }
1673         }
1674     }
1675
1676     /// Given some node representing a fn-like thing in the HIR map,
1677     /// returns a span and `ArgKind` information that describes the
1678     /// arguments it expects. This can be supplied to
1679     /// `report_arg_count_mismatch`.
1680     pub fn get_fn_like_arguments(&self, node: Node<'_>) -> (Span, Vec<ArgKind>) {
1681         match node {
1682             Node::Expr(&hir::Expr {
1683                 kind: hir::ExprKind::Closure(_, ref _decl, id, span, _),
1684                 ..
1685             }) => (
1686                 self.tcx.sess.source_map().def_span(span),
1687                 self.tcx
1688                     .hir()
1689                     .body(id)
1690                     .params
1691                     .iter()
1692                     .map(|arg| {
1693                         if let hir::Pat { kind: hir::PatKind::Tuple(ref args, _), span, .. } =
1694                             *arg.pat
1695                         {
1696                             ArgKind::Tuple(
1697                                 Some(span),
1698                                 args.iter()
1699                                     .map(|pat| {
1700                                         let snippet = self
1701                                             .tcx
1702                                             .sess
1703                                             .source_map()
1704                                             .span_to_snippet(pat.span)
1705                                             .unwrap();
1706                                         (snippet, "_".to_owned())
1707                                     })
1708                                     .collect::<Vec<_>>(),
1709                             )
1710                         } else {
1711                             let name =
1712                                 self.tcx.sess.source_map().span_to_snippet(arg.pat.span).unwrap();
1713                             ArgKind::Arg(name, "_".to_owned())
1714                         }
1715                     })
1716                     .collect::<Vec<ArgKind>>(),
1717             ),
1718             Node::Item(&hir::Item { span, kind: hir::ItemKind::Fn(ref sig, ..), .. })
1719             | Node::ImplItem(&hir::ImplItem {
1720                 span,
1721                 kind: hir::ImplItemKind::Method(ref sig, _),
1722                 ..
1723             })
1724             | Node::TraitItem(&hir::TraitItem {
1725                 span,
1726                 kind: hir::TraitItemKind::Method(ref sig, _),
1727                 ..
1728             }) => (
1729                 self.tcx.sess.source_map().def_span(span),
1730                 sig.decl
1731                     .inputs
1732                     .iter()
1733                     .map(|arg| match arg.clone().kind {
1734                         hir::TyKind::Tup(ref tys) => ArgKind::Tuple(
1735                             Some(arg.span),
1736                             vec![("_".to_owned(), "_".to_owned()); tys.len()],
1737                         ),
1738                         _ => ArgKind::empty(),
1739                     })
1740                     .collect::<Vec<ArgKind>>(),
1741             ),
1742             Node::Ctor(ref variant_data) => {
1743                 let span = variant_data
1744                     .ctor_hir_id()
1745                     .map(|hir_id| self.tcx.hir().span(hir_id))
1746                     .unwrap_or(DUMMY_SP);
1747                 let span = self.tcx.sess.source_map().def_span(span);
1748
1749                 (span, vec![ArgKind::empty(); variant_data.fields().len()])
1750             }
1751             _ => panic!("non-FnLike node found: {:?}", node),
1752         }
1753     }
1754
1755     /// Reports an error when the number of arguments needed by a
1756     /// trait match doesn't match the number that the expression
1757     /// provides.
1758     pub fn report_arg_count_mismatch(
1759         &self,
1760         span: Span,
1761         found_span: Option<Span>,
1762         expected_args: Vec<ArgKind>,
1763         found_args: Vec<ArgKind>,
1764         is_closure: bool,
1765     ) -> DiagnosticBuilder<'tcx> {
1766         let kind = if is_closure { "closure" } else { "function" };
1767
1768         let args_str = |arguments: &[ArgKind], other: &[ArgKind]| {
1769             let arg_length = arguments.len();
1770             let distinct = match &other[..] {
1771                 &[ArgKind::Tuple(..)] => true,
1772                 _ => false,
1773             };
1774             match (arg_length, arguments.get(0)) {
1775                 (1, Some(&ArgKind::Tuple(_, ref fields))) => {
1776                     format!("a single {}-tuple as argument", fields.len())
1777                 }
1778                 _ => format!(
1779                     "{} {}argument{}",
1780                     arg_length,
1781                     if distinct && arg_length > 1 { "distinct " } else { "" },
1782                     pluralize!(arg_length)
1783                 ),
1784             }
1785         };
1786
1787         let expected_str = args_str(&expected_args, &found_args);
1788         let found_str = args_str(&found_args, &expected_args);
1789
1790         let mut err = struct_span_err!(
1791             self.tcx.sess,
1792             span,
1793             E0593,
1794             "{} is expected to take {}, but it takes {}",
1795             kind,
1796             expected_str,
1797             found_str,
1798         );
1799
1800         err.span_label(span, format!("expected {} that takes {}", kind, expected_str));
1801
1802         if let Some(found_span) = found_span {
1803             err.span_label(found_span, format!("takes {}", found_str));
1804
1805             // move |_| { ... }
1806             // ^^^^^^^^-- def_span
1807             //
1808             // move |_| { ... }
1809             // ^^^^^-- prefix
1810             let prefix_span = self.tcx.sess.source_map().span_until_non_whitespace(found_span);
1811             // move |_| { ... }
1812             //      ^^^-- pipe_span
1813             let pipe_span =
1814                 if let Some(span) = found_span.trim_start(prefix_span) { span } else { found_span };
1815
1816             // Suggest to take and ignore the arguments with expected_args_length `_`s if
1817             // found arguments is empty (assume the user just wants to ignore args in this case).
1818             // For example, if `expected_args_length` is 2, suggest `|_, _|`.
1819             if found_args.is_empty() && is_closure {
1820                 let underscores = vec!["_"; expected_args.len()].join(", ");
1821                 err.span_suggestion(
1822                     pipe_span,
1823                     &format!(
1824                         "consider changing the closure to take and ignore the expected argument{}",
1825                         if expected_args.len() < 2 { "" } else { "s" }
1826                     ),
1827                     format!("|{}|", underscores),
1828                     Applicability::MachineApplicable,
1829                 );
1830             }
1831
1832             if let &[ArgKind::Tuple(_, ref fields)] = &found_args[..] {
1833                 if fields.len() == expected_args.len() {
1834                     let sugg = fields
1835                         .iter()
1836                         .map(|(name, _)| name.to_owned())
1837                         .collect::<Vec<String>>()
1838                         .join(", ");
1839                     err.span_suggestion(
1840                         found_span,
1841                         "change the closure to take multiple arguments instead of a single tuple",
1842                         format!("|{}|", sugg),
1843                         Applicability::MachineApplicable,
1844                     );
1845                 }
1846             }
1847             if let &[ArgKind::Tuple(_, ref fields)] = &expected_args[..] {
1848                 if fields.len() == found_args.len() && is_closure {
1849                     let sugg = format!(
1850                         "|({}){}|",
1851                         found_args
1852                             .iter()
1853                             .map(|arg| match arg {
1854                                 ArgKind::Arg(name, _) => name.to_owned(),
1855                                 _ => "_".to_owned(),
1856                             })
1857                             .collect::<Vec<String>>()
1858                             .join(", "),
1859                         // add type annotations if available
1860                         if found_args.iter().any(|arg| match arg {
1861                             ArgKind::Arg(_, ty) => ty != "_",
1862                             _ => false,
1863                         }) {
1864                             format!(
1865                                 ": ({})",
1866                                 fields
1867                                     .iter()
1868                                     .map(|(_, ty)| ty.to_owned())
1869                                     .collect::<Vec<String>>()
1870                                     .join(", ")
1871                             )
1872                         } else {
1873                             String::new()
1874                         },
1875                     );
1876                     err.span_suggestion(
1877                         found_span,
1878                         "change the closure to accept a tuple instead of individual arguments",
1879                         sugg,
1880                         Applicability::MachineApplicable,
1881                     );
1882                 }
1883             }
1884         }
1885
1886         err
1887     }
1888
1889     fn report_closure_arg_mismatch(
1890         &self,
1891         span: Span,
1892         found_span: Option<Span>,
1893         expected_ref: ty::PolyTraitRef<'tcx>,
1894         found: ty::PolyTraitRef<'tcx>,
1895     ) -> DiagnosticBuilder<'tcx> {
1896         fn build_fn_sig_string<'tcx>(tcx: TyCtxt<'tcx>, trait_ref: &ty::TraitRef<'tcx>) -> String {
1897             let inputs = trait_ref.substs.type_at(1);
1898             let sig = if let ty::Tuple(inputs) = inputs.kind {
1899                 tcx.mk_fn_sig(
1900                     inputs.iter().map(|k| k.expect_ty()),
1901                     tcx.mk_ty_infer(ty::TyVar(ty::TyVid { index: 0 })),
1902                     false,
1903                     hir::Unsafety::Normal,
1904                     ::rustc_target::spec::abi::Abi::Rust,
1905                 )
1906             } else {
1907                 tcx.mk_fn_sig(
1908                     ::std::iter::once(inputs),
1909                     tcx.mk_ty_infer(ty::TyVar(ty::TyVid { index: 0 })),
1910                     false,
1911                     hir::Unsafety::Normal,
1912                     ::rustc_target::spec::abi::Abi::Rust,
1913                 )
1914             };
1915             ty::Binder::bind(sig).to_string()
1916         }
1917
1918         let argument_is_closure = expected_ref.skip_binder().substs.type_at(0).is_closure();
1919         let mut err = struct_span_err!(
1920             self.tcx.sess,
1921             span,
1922             E0631,
1923             "type mismatch in {} arguments",
1924             if argument_is_closure { "closure" } else { "function" }
1925         );
1926
1927         let found_str = format!(
1928             "expected signature of `{}`",
1929             build_fn_sig_string(self.tcx, found.skip_binder())
1930         );
1931         err.span_label(span, found_str);
1932
1933         let found_span = found_span.unwrap_or(span);
1934         let expected_str = format!(
1935             "found signature of `{}`",
1936             build_fn_sig_string(self.tcx, expected_ref.skip_binder())
1937         );
1938         err.span_label(found_span, expected_str);
1939
1940         err
1941     }
1942 }
1943
1944 impl<'tcx> TyCtxt<'tcx> {
1945     pub fn recursive_type_with_infinite_size_error(
1946         self,
1947         type_def_id: DefId,
1948     ) -> DiagnosticBuilder<'tcx> {
1949         assert!(type_def_id.is_local());
1950         let span = self.hir().span_if_local(type_def_id).unwrap();
1951         let span = self.sess.source_map().def_span(span);
1952         let mut err = struct_span_err!(
1953             self.sess,
1954             span,
1955             E0072,
1956             "recursive type `{}` has infinite size",
1957             self.def_path_str(type_def_id)
1958         );
1959         err.span_label(span, "recursive type has infinite size");
1960         err.help(&format!(
1961             "insert indirection (e.g., a `Box`, `Rc`, or `&`) \
1962                            at some point to make `{}` representable",
1963             self.def_path_str(type_def_id)
1964         ));
1965         err
1966     }
1967
1968     pub fn report_object_safety_error(
1969         self,
1970         span: Span,
1971         trait_def_id: DefId,
1972         violations: Vec<ObjectSafetyViolation>,
1973     ) -> DiagnosticBuilder<'tcx> {
1974         let trait_str = self.def_path_str(trait_def_id);
1975         let span = self.sess.source_map().def_span(span);
1976         let mut err = struct_span_err!(
1977             self.sess,
1978             span,
1979             E0038,
1980             "the trait `{}` cannot be made into an object",
1981             trait_str
1982         );
1983         err.span_label(span, format!("the trait `{}` cannot be made into an object", trait_str));
1984
1985         let mut reported_violations = FxHashSet::default();
1986         for violation in violations {
1987             if reported_violations.insert(violation.clone()) {
1988                 match violation.span() {
1989                     Some(span) => err.span_label(span, violation.error_msg()),
1990                     None => err.note(&violation.error_msg()),
1991                 };
1992             }
1993         }
1994
1995         if self.sess.trait_methods_not_found.borrow().contains(&span) {
1996             // Avoid emitting error caused by non-existing method (#58734)
1997             err.cancel();
1998         }
1999
2000         err
2001     }
2002 }
2003
2004 impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
2005     fn maybe_report_ambiguity(
2006         &self,
2007         obligation: &PredicateObligation<'tcx>,
2008         body_id: Option<hir::BodyId>,
2009     ) {
2010         // Unable to successfully determine, probably means
2011         // insufficient type information, but could mean
2012         // ambiguous impls. The latter *ought* to be a
2013         // coherence violation, so we don't report it here.
2014
2015         let predicate = self.resolve_vars_if_possible(&obligation.predicate);
2016         let span = obligation.cause.span;
2017
2018         debug!(
2019             "maybe_report_ambiguity(predicate={:?}, obligation={:?} body_id={:?}, code={:?})",
2020             predicate, obligation, body_id, obligation.cause.code,
2021         );
2022
2023         // Ambiguity errors are often caused as fallout from earlier
2024         // errors. So just ignore them if this infcx is tainted.
2025         if self.is_tainted_by_errors() {
2026             return;
2027         }
2028
2029         let mut err = match predicate {
2030             ty::Predicate::Trait(ref data) => {
2031                 let trait_ref = data.to_poly_trait_ref();
2032                 let self_ty = trait_ref.self_ty();
2033                 debug!("self_ty {:?} {:?} trait_ref {:?}", self_ty, self_ty.kind, trait_ref);
2034
2035                 if predicate.references_error() {
2036                     return;
2037                 }
2038                 // Typically, this ambiguity should only happen if
2039                 // there are unresolved type inference variables
2040                 // (otherwise it would suggest a coherence
2041                 // failure). But given #21974 that is not necessarily
2042                 // the case -- we can have multiple where clauses that
2043                 // are only distinguished by a region, which results
2044                 // in an ambiguity even when all types are fully
2045                 // known, since we don't dispatch based on region
2046                 // relationships.
2047
2048                 // This is kind of a hack: it frequently happens that some earlier
2049                 // error prevents types from being fully inferred, and then we get
2050                 // a bunch of uninteresting errors saying something like "<generic
2051                 // #0> doesn't implement Sized".  It may even be true that we
2052                 // could just skip over all checks where the self-ty is an
2053                 // inference variable, but I was afraid that there might be an
2054                 // inference variable created, registered as an obligation, and
2055                 // then never forced by writeback, and hence by skipping here we'd
2056                 // be ignoring the fact that we don't KNOW the type works
2057                 // out. Though even that would probably be harmless, given that
2058                 // we're only talking about builtin traits, which are known to be
2059                 // inhabited. We used to check for `self.tcx.sess.has_errors()` to
2060                 // avoid inundating the user with unnecessary errors, but we now
2061                 // check upstream for type errors and dont add the obligations to
2062                 // begin with in those cases.
2063                 if self
2064                     .tcx
2065                     .lang_items()
2066                     .sized_trait()
2067                     .map_or(false, |sized_id| sized_id == trait_ref.def_id())
2068                 {
2069                     self.need_type_info_err(body_id, span, self_ty, ErrorCode::E0282).emit();
2070                     return;
2071                 }
2072                 let mut err = self.need_type_info_err(body_id, span, self_ty, ErrorCode::E0283);
2073                 err.note(&format!("cannot resolve `{}`", predicate));
2074                 if let (Ok(ref snippet), ObligationCauseCode::BindingObligation(ref def_id, _)) =
2075                     (self.tcx.sess.source_map().span_to_snippet(span), &obligation.cause.code)
2076                 {
2077                     let generics = self.tcx.generics_of(*def_id);
2078                     if !generics.params.is_empty() && !snippet.ends_with('>') {
2079                         // FIXME: To avoid spurious suggestions in functions where type arguments
2080                         // where already supplied, we check the snippet to make sure it doesn't
2081                         // end with a turbofish. Ideally we would have access to a `PathSegment`
2082                         // instead. Otherwise we would produce the following output:
2083                         //
2084                         // error[E0283]: type annotations needed
2085                         //   --> $DIR/issue-54954.rs:3:24
2086                         //    |
2087                         // LL | const ARR_LEN: usize = Tt::const_val::<[i8; 123]>();
2088                         //    |                        ^^^^^^^^^^^^^^^^^^^^^^^^^^
2089                         //    |                        |
2090                         //    |                        cannot infer type
2091                         //    |                        help: consider specifying the type argument
2092                         //    |                        in the function call:
2093                         //    |                        `Tt::const_val::<[i8; 123]>::<T>`
2094                         // ...
2095                         // LL |     const fn const_val<T: Sized>() -> usize {
2096                         //    |              --------- - required by this bound in `Tt::const_val`
2097                         //    |
2098                         //    = note: cannot resolve `_: Tt`
2099
2100                         err.span_suggestion(
2101                             span,
2102                             &format!(
2103                                 "consider specifying the type argument{} in the function call",
2104                                 if generics.params.len() > 1 { "s" } else { "" },
2105                             ),
2106                             format!(
2107                                 "{}::<{}>",
2108                                 snippet,
2109                                 generics
2110                                     .params
2111                                     .iter()
2112                                     .map(|p| p.name.to_string())
2113                                     .collect::<Vec<String>>()
2114                                     .join(", ")
2115                             ),
2116                             Applicability::HasPlaceholders,
2117                         );
2118                     }
2119                 }
2120                 err
2121             }
2122
2123             ty::Predicate::WellFormed(ty) => {
2124                 // Same hacky approach as above to avoid deluging user
2125                 // with error messages.
2126                 if ty.references_error() || self.tcx.sess.has_errors() {
2127                     return;
2128                 }
2129                 self.need_type_info_err(body_id, span, ty, ErrorCode::E0282)
2130             }
2131
2132             ty::Predicate::Subtype(ref data) => {
2133                 if data.references_error() || self.tcx.sess.has_errors() {
2134                     // no need to overload user in such cases
2135                     return;
2136                 }
2137                 let &SubtypePredicate { a_is_expected: _, a, b } = data.skip_binder();
2138                 // both must be type variables, or the other would've been instantiated
2139                 assert!(a.is_ty_var() && b.is_ty_var());
2140                 self.need_type_info_err(body_id, span, a, ErrorCode::E0282)
2141             }
2142             ty::Predicate::Projection(ref data) => {
2143                 let trait_ref = data.to_poly_trait_ref(self.tcx);
2144                 let self_ty = trait_ref.self_ty();
2145                 if predicate.references_error() {
2146                     return;
2147                 }
2148                 let mut err = self.need_type_info_err(body_id, span, self_ty, ErrorCode::E0284);
2149                 err.note(&format!("cannot resolve `{}`", predicate));
2150                 err
2151             }
2152
2153             _ => {
2154                 if self.tcx.sess.has_errors() {
2155                     return;
2156                 }
2157                 let mut err = struct_span_err!(
2158                     self.tcx.sess,
2159                     span,
2160                     E0284,
2161                     "type annotations needed: cannot resolve `{}`",
2162                     predicate,
2163                 );
2164                 err.span_label(span, &format!("cannot resolve `{}`", predicate));
2165                 err
2166             }
2167         };
2168         self.note_obligation_cause(&mut err, obligation);
2169         err.emit();
2170     }
2171
2172     /// Returns `true` if the trait predicate may apply for *some* assignment
2173     /// to the type parameters.
2174     fn predicate_can_apply(
2175         &self,
2176         param_env: ty::ParamEnv<'tcx>,
2177         pred: ty::PolyTraitRef<'tcx>,
2178     ) -> bool {
2179         struct ParamToVarFolder<'a, 'tcx> {
2180             infcx: &'a InferCtxt<'a, 'tcx>,
2181             var_map: FxHashMap<Ty<'tcx>, Ty<'tcx>>,
2182         }
2183
2184         impl<'a, 'tcx> TypeFolder<'tcx> for ParamToVarFolder<'a, 'tcx> {
2185             fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
2186                 self.infcx.tcx
2187             }
2188
2189             fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
2190                 if let ty::Param(ty::ParamTy { name, .. }) = ty.kind {
2191                     let infcx = self.infcx;
2192                     self.var_map.entry(ty).or_insert_with(|| {
2193                         infcx.next_ty_var(TypeVariableOrigin {
2194                             kind: TypeVariableOriginKind::TypeParameterDefinition(name, None),
2195                             span: DUMMY_SP,
2196                         })
2197                     })
2198                 } else {
2199                     ty.super_fold_with(self)
2200                 }
2201             }
2202         }
2203
2204         self.probe(|_| {
2205             let mut selcx = SelectionContext::new(self);
2206
2207             let cleaned_pred =
2208                 pred.fold_with(&mut ParamToVarFolder { infcx: self, var_map: Default::default() });
2209
2210             let cleaned_pred = super::project::normalize(
2211                 &mut selcx,
2212                 param_env,
2213                 ObligationCause::dummy(),
2214                 &cleaned_pred,
2215             )
2216             .value;
2217
2218             let obligation =
2219                 Obligation::new(ObligationCause::dummy(), param_env, cleaned_pred.to_predicate());
2220
2221             self.predicate_may_hold(&obligation)
2222         })
2223     }
2224
2225     fn note_obligation_cause(
2226         &self,
2227         err: &mut DiagnosticBuilder<'_>,
2228         obligation: &PredicateObligation<'tcx>,
2229     ) {
2230         // First, attempt to add note to this error with an async-await-specific
2231         // message, and fall back to regular note otherwise.
2232         if !self.maybe_note_obligation_cause_for_async_await(err, obligation) {
2233             self.note_obligation_cause_code(
2234                 err,
2235                 &obligation.predicate,
2236                 &obligation.cause.code,
2237                 &mut vec![],
2238             );
2239         }
2240     }
2241
2242     /// Adds an async-await specific note to the diagnostic when the future does not implement
2243     /// an auto trait because of a captured type.
2244     ///
2245     /// ```ignore (diagnostic)
2246     /// note: future does not implement `Qux` as this value is used across an await
2247     ///   --> $DIR/issue-64130-3-other.rs:17:5
2248     ///    |
2249     /// LL |     let x = Foo;
2250     ///    |         - has type `Foo`
2251     /// LL |     baz().await;
2252     ///    |     ^^^^^^^^^^^ await occurs here, with `x` maybe used later
2253     /// LL | }
2254     ///    | - `x` is later dropped here
2255     /// ```
2256     ///
2257     /// When the diagnostic does not implement `Send` or `Sync` specifically, then the diagnostic
2258     /// is "replaced" with a different message and a more specific error.
2259     ///
2260     /// ```ignore (diagnostic)
2261     /// error: future cannot be sent between threads safely
2262     ///   --> $DIR/issue-64130-2-send.rs:21:5
2263     ///    |
2264     /// LL | fn is_send<T: Send>(t: T) { }
2265     ///    |    -------    ---- required by this bound in `is_send`
2266     /// ...
2267     /// LL |     is_send(bar());
2268     ///    |     ^^^^^^^ future returned by `bar` is not send
2269     ///    |
2270     ///    = help: within `impl std::future::Future`, the trait `std::marker::Send` is not
2271     ///            implemented for `Foo`
2272     /// note: future is not send as this value is used across an await
2273     ///   --> $DIR/issue-64130-2-send.rs:15:5
2274     ///    |
2275     /// LL |     let x = Foo;
2276     ///    |         - has type `Foo`
2277     /// LL |     baz().await;
2278     ///    |     ^^^^^^^^^^^ await occurs here, with `x` maybe used later
2279     /// LL | }
2280     ///    | - `x` is later dropped here
2281     /// ```
2282     ///
2283     /// Returns `true` if an async-await specific note was added to the diagnostic.
2284     fn maybe_note_obligation_cause_for_async_await(
2285         &self,
2286         err: &mut DiagnosticBuilder<'_>,
2287         obligation: &PredicateObligation<'tcx>,
2288     ) -> bool {
2289         debug!(
2290             "maybe_note_obligation_cause_for_async_await: obligation.predicate={:?} \
2291                 obligation.cause.span={:?}",
2292             obligation.predicate, obligation.cause.span
2293         );
2294         let source_map = self.tcx.sess.source_map();
2295
2296         // Attempt to detect an async-await error by looking at the obligation causes, looking
2297         // for a generator to be present.
2298         //
2299         // When a future does not implement a trait because of a captured type in one of the
2300         // generators somewhere in the call stack, then the result is a chain of obligations.
2301         //
2302         // Given a `async fn` A that calls a `async fn` B which captures a non-send type and that
2303         // future is passed as an argument to a function C which requires a `Send` type, then the
2304         // chain looks something like this:
2305         //
2306         // - `BuiltinDerivedObligation` with a generator witness (B)
2307         // - `BuiltinDerivedObligation` with a generator (B)
2308         // - `BuiltinDerivedObligation` with `std::future::GenFuture` (B)
2309         // - `BuiltinDerivedObligation` with `impl std::future::Future` (B)
2310         // - `BuiltinDerivedObligation` with `impl std::future::Future` (B)
2311         // - `BuiltinDerivedObligation` with a generator witness (A)
2312         // - `BuiltinDerivedObligation` with a generator (A)
2313         // - `BuiltinDerivedObligation` with `std::future::GenFuture` (A)
2314         // - `BuiltinDerivedObligation` with `impl std::future::Future` (A)
2315         // - `BuiltinDerivedObligation` with `impl std::future::Future` (A)
2316         // - `BindingObligation` with `impl_send (Send requirement)
2317         //
2318         // The first obligation in the chain is the most useful and has the generator that captured
2319         // the type. The last generator has information about where the bound was introduced. At
2320         // least one generator should be present for this diagnostic to be modified.
2321         let (mut trait_ref, mut target_ty) = match obligation.predicate {
2322             ty::Predicate::Trait(p) => {
2323                 (Some(p.skip_binder().trait_ref), Some(p.skip_binder().self_ty()))
2324             }
2325             _ => (None, None),
2326         };
2327         let mut generator = None;
2328         let mut last_generator = None;
2329         let mut next_code = Some(&obligation.cause.code);
2330         while let Some(code) = next_code {
2331             debug!("maybe_note_obligation_cause_for_async_await: code={:?}", code);
2332             match code {
2333                 ObligationCauseCode::BuiltinDerivedObligation(derived_obligation)
2334                 | ObligationCauseCode::ImplDerivedObligation(derived_obligation) => {
2335                     let ty = derived_obligation.parent_trait_ref.self_ty();
2336                     debug!(
2337                         "maybe_note_obligation_cause_for_async_await: \
2338                             parent_trait_ref={:?} self_ty.kind={:?}",
2339                         derived_obligation.parent_trait_ref, ty.kind
2340                     );
2341
2342                     match ty.kind {
2343                         ty::Generator(did, ..) => {
2344                             generator = generator.or(Some(did));
2345                             last_generator = Some(did);
2346                         }
2347                         ty::GeneratorWitness(..) => {}
2348                         _ if generator.is_none() => {
2349                             trait_ref = Some(*derived_obligation.parent_trait_ref.skip_binder());
2350                             target_ty = Some(ty);
2351                         }
2352                         _ => {}
2353                     }
2354
2355                     next_code = Some(derived_obligation.parent_code.as_ref());
2356                 }
2357                 _ => break,
2358             }
2359         }
2360
2361         // Only continue if a generator was found.
2362         debug!(
2363             "maybe_note_obligation_cause_for_async_await: generator={:?} trait_ref={:?} \
2364                 target_ty={:?}",
2365             generator, trait_ref, target_ty
2366         );
2367         let (generator_did, trait_ref, target_ty) = match (generator, trait_ref, target_ty) {
2368             (Some(generator_did), Some(trait_ref), Some(target_ty)) => {
2369                 (generator_did, trait_ref, target_ty)
2370             }
2371             _ => return false,
2372         };
2373
2374         let span = self.tcx.def_span(generator_did);
2375
2376         // Do not ICE on closure typeck (#66868).
2377         if self.tcx.hir().as_local_hir_id(generator_did).is_none() {
2378             return false;
2379         }
2380
2381         // Get the tables from the infcx if the generator is the function we are
2382         // currently type-checking; otherwise, get them by performing a query.
2383         // This is needed to avoid cycles.
2384         let in_progress_tables = self.in_progress_tables.map(|t| t.borrow());
2385         let generator_did_root = self.tcx.closure_base_def_id(generator_did);
2386         debug!(
2387             "maybe_note_obligation_cause_for_async_await: generator_did={:?} \
2388              generator_did_root={:?} in_progress_tables.local_id_root={:?} span={:?}",
2389             generator_did,
2390             generator_did_root,
2391             in_progress_tables.as_ref().map(|t| t.local_id_root),
2392             span
2393         );
2394         let query_tables;
2395         let tables: &TypeckTables<'tcx> = match &in_progress_tables {
2396             Some(t) if t.local_id_root == Some(generator_did_root) => t,
2397             _ => {
2398                 query_tables = self.tcx.typeck_tables_of(generator_did);
2399                 &query_tables
2400             }
2401         };
2402
2403         // Look for a type inside the generator interior that matches the target type to get
2404         // a span.
2405         let target_ty_erased = self.tcx.erase_regions(&target_ty);
2406         let target_span = tables
2407             .generator_interior_types
2408             .iter()
2409             .find(|ty::GeneratorInteriorTypeCause { ty, .. }| {
2410                 // Careful: the regions for types that appear in the
2411                 // generator interior are not generally known, so we
2412                 // want to erase them when comparing (and anyway,
2413                 // `Send` and other bounds are generally unaffected by
2414                 // the choice of region).  When erasing regions, we
2415                 // also have to erase late-bound regions. This is
2416                 // because the types that appear in the generator
2417                 // interior generally contain "bound regions" to
2418                 // represent regions that are part of the suspended
2419                 // generator frame. Bound regions are preserved by
2420                 // `erase_regions` and so we must also call
2421                 // `erase_late_bound_regions`.
2422                 let ty_erased = self.tcx.erase_late_bound_regions(&ty::Binder::bind(*ty));
2423                 let ty_erased = self.tcx.erase_regions(&ty_erased);
2424                 let eq = ty::TyS::same_type(ty_erased, target_ty_erased);
2425                 debug!(
2426                     "maybe_note_obligation_cause_for_async_await: ty_erased={:?} \
2427                         target_ty_erased={:?} eq={:?}",
2428                     ty_erased, target_ty_erased, eq
2429                 );
2430                 eq
2431             })
2432             .map(|ty::GeneratorInteriorTypeCause { span, scope_span, .. }| {
2433                 (span, source_map.span_to_snippet(*span), scope_span)
2434             });
2435         debug!(
2436             "maybe_note_obligation_cause_for_async_await: target_ty={:?} \
2437                 generator_interior_types={:?} target_span={:?}",
2438             target_ty, tables.generator_interior_types, target_span
2439         );
2440         if let Some((target_span, Ok(snippet), scope_span)) = target_span {
2441             self.note_obligation_cause_for_async_await(
2442                 err,
2443                 *target_span,
2444                 scope_span,
2445                 snippet,
2446                 generator_did,
2447                 last_generator,
2448                 trait_ref,
2449                 target_ty,
2450                 tables,
2451                 obligation,
2452                 next_code,
2453             );
2454             true
2455         } else {
2456             false
2457         }
2458     }
2459
2460     /// Unconditionally adds the diagnostic note described in
2461     /// `maybe_note_obligation_cause_for_async_await`'s documentation comment.
2462     fn note_obligation_cause_for_async_await(
2463         &self,
2464         err: &mut DiagnosticBuilder<'_>,
2465         target_span: Span,
2466         scope_span: &Option<Span>,
2467         snippet: String,
2468         first_generator: DefId,
2469         last_generator: Option<DefId>,
2470         trait_ref: ty::TraitRef<'_>,
2471         target_ty: Ty<'tcx>,
2472         tables: &ty::TypeckTables<'_>,
2473         obligation: &PredicateObligation<'tcx>,
2474         next_code: Option<&ObligationCauseCode<'tcx>>,
2475     ) {
2476         let source_map = self.tcx.sess.source_map();
2477
2478         let is_async_fn = self
2479             .tcx
2480             .parent(first_generator)
2481             .map(|parent_did| self.tcx.asyncness(parent_did))
2482             .map(|parent_asyncness| parent_asyncness == hir::IsAsync::Async)
2483             .unwrap_or(false);
2484         let is_async_move = self
2485             .tcx
2486             .hir()
2487             .as_local_hir_id(first_generator)
2488             .and_then(|hir_id| self.tcx.hir().maybe_body_owned_by(hir_id))
2489             .map(|body_id| self.tcx.hir().body(body_id))
2490             .and_then(|body| body.generator_kind())
2491             .map(|generator_kind| match generator_kind {
2492                 hir::GeneratorKind::Async(..) => true,
2493                 _ => false,
2494             })
2495             .unwrap_or(false);
2496         let await_or_yield = if is_async_fn || is_async_move { "await" } else { "yield" };
2497
2498         // Special case the primary error message when send or sync is the trait that was
2499         // not implemented.
2500         let is_send = self.tcx.is_diagnostic_item(sym::send_trait, trait_ref.def_id);
2501         let is_sync = self.tcx.is_diagnostic_item(sym::sync_trait, trait_ref.def_id);
2502         let trait_explanation = if is_send || is_sync {
2503             let (trait_name, trait_verb) =
2504                 if is_send { ("`Send`", "sent") } else { ("`Sync`", "shared") };
2505
2506             err.clear_code();
2507             err.set_primary_message(format!(
2508                 "future cannot be {} between threads safely",
2509                 trait_verb
2510             ));
2511
2512             let original_span = err.span.primary_span().unwrap();
2513             let mut span = MultiSpan::from_span(original_span);
2514
2515             let message = if let Some(name) = last_generator
2516                 .and_then(|generator_did| self.tcx.parent(generator_did))
2517                 .and_then(|parent_did| self.tcx.hir().as_local_hir_id(parent_did))
2518                 .and_then(|parent_hir_id| self.tcx.hir().opt_name(parent_hir_id))
2519             {
2520                 format!("future returned by `{}` is not {}", name, trait_name)
2521             } else {
2522                 format!("future is not {}", trait_name)
2523             };
2524
2525             span.push_span_label(original_span, message);
2526             err.set_span(span);
2527
2528             format!("is not {}", trait_name)
2529         } else {
2530             format!("does not implement `{}`", trait_ref.print_only_trait_path())
2531         };
2532
2533         // Look at the last interior type to get a span for the `.await`.
2534         let await_span = tables.generator_interior_types.iter().map(|i| i.span).last().unwrap();
2535         let mut span = MultiSpan::from_span(await_span);
2536         span.push_span_label(
2537             await_span,
2538             format!("{} occurs here, with `{}` maybe used later", await_or_yield, snippet),
2539         );
2540
2541         span.push_span_label(target_span, format!("has type `{}`", target_ty));
2542
2543         // If available, use the scope span to annotate the drop location.
2544         if let Some(scope_span) = scope_span {
2545             span.push_span_label(
2546                 source_map.end_point(*scope_span),
2547                 format!("`{}` is later dropped here", snippet),
2548             );
2549         }
2550
2551         err.span_note(
2552             span,
2553             &format!(
2554                 "future {} as this value is used across an {}",
2555                 trait_explanation, await_or_yield,
2556             ),
2557         );
2558
2559         // Add a note for the item obligation that remains - normally a note pointing to the
2560         // bound that introduced the obligation (e.g. `T: Send`).
2561         debug!("note_obligation_cause_for_async_await: next_code={:?}", next_code);
2562         self.note_obligation_cause_code(
2563             err,
2564             &obligation.predicate,
2565             next_code.unwrap(),
2566             &mut Vec::new(),
2567         );
2568     }
2569
2570     fn note_obligation_cause_code<T>(
2571         &self,
2572         err: &mut DiagnosticBuilder<'_>,
2573         predicate: &T,
2574         cause_code: &ObligationCauseCode<'tcx>,
2575         obligated_types: &mut Vec<&ty::TyS<'tcx>>,
2576     ) where
2577         T: fmt::Display,
2578     {
2579         let tcx = self.tcx;
2580         match *cause_code {
2581             ObligationCauseCode::ExprAssignable
2582             | ObligationCauseCode::MatchExpressionArm { .. }
2583             | ObligationCauseCode::Pattern { .. }
2584             | ObligationCauseCode::IfExpression { .. }
2585             | ObligationCauseCode::IfExpressionWithNoElse
2586             | ObligationCauseCode::MainFunctionType
2587             | ObligationCauseCode::StartFunctionType
2588             | ObligationCauseCode::IntrinsicType
2589             | ObligationCauseCode::MethodReceiver
2590             | ObligationCauseCode::ReturnNoExpression
2591             | ObligationCauseCode::MiscObligation => {}
2592             ObligationCauseCode::SliceOrArrayElem => {
2593                 err.note("slice and array elements must have `Sized` type");
2594             }
2595             ObligationCauseCode::TupleElem => {
2596                 err.note("only the last element of a tuple may have a dynamically sized type");
2597             }
2598             ObligationCauseCode::ProjectionWf(data) => {
2599                 err.note(&format!("required so that the projection `{}` is well-formed", data,));
2600             }
2601             ObligationCauseCode::ReferenceOutlivesReferent(ref_ty) => {
2602                 err.note(&format!(
2603                     "required so that reference `{}` does not outlive its referent",
2604                     ref_ty,
2605                 ));
2606             }
2607             ObligationCauseCode::ObjectTypeBound(object_ty, region) => {
2608                 err.note(&format!(
2609                     "required so that the lifetime bound of `{}` for `{}` is satisfied",
2610                     region, object_ty,
2611                 ));
2612             }
2613             ObligationCauseCode::ItemObligation(item_def_id) => {
2614                 let item_name = tcx.def_path_str(item_def_id);
2615                 let msg = format!("required by `{}`", item_name);
2616
2617                 if let Some(sp) = tcx.hir().span_if_local(item_def_id) {
2618                     let sp = tcx.sess.source_map().def_span(sp);
2619                     err.span_label(sp, &msg);
2620                 } else {
2621                     err.note(&msg);
2622                 }
2623             }
2624             ObligationCauseCode::BindingObligation(item_def_id, span) => {
2625                 let item_name = tcx.def_path_str(item_def_id);
2626                 let msg = format!("required by this bound in `{}`", item_name);
2627                 if let Some(ident) = tcx.opt_item_name(item_def_id) {
2628                     err.span_label(ident.span, "");
2629                 }
2630                 if span != DUMMY_SP {
2631                     err.span_label(span, &msg);
2632                 } else {
2633                     err.note(&msg);
2634                 }
2635             }
2636             ObligationCauseCode::ObjectCastObligation(object_ty) => {
2637                 err.note(&format!(
2638                     "required for the cast to the object type `{}`",
2639                     self.ty_to_string(object_ty)
2640                 ));
2641             }
2642             ObligationCauseCode::Coercion { source: _, target } => {
2643                 err.note(&format!("required by cast to type `{}`", self.ty_to_string(target)));
2644             }
2645             ObligationCauseCode::RepeatVec(suggest_const_in_array_repeat_expressions) => {
2646                 err.note(
2647                     "the `Copy` trait is required because the \
2648                           repeated element will be copied",
2649                 );
2650                 if suggest_const_in_array_repeat_expressions {
2651                     err.note(
2652                         "this array initializer can be evaluated at compile-time, for more \
2653                               information, see issue \
2654                               https://github.com/rust-lang/rust/issues/49147",
2655                     );
2656                     if tcx.sess.opts.unstable_features.is_nightly_build() {
2657                         err.help(
2658                             "add `#![feature(const_in_array_repeat_expressions)]` to the \
2659                                   crate attributes to enable",
2660                         );
2661                     }
2662                 }
2663             }
2664             ObligationCauseCode::VariableType(_) => {
2665                 err.note("all local variables must have a statically known size");
2666                 if !self.tcx.features().unsized_locals {
2667                     err.help("unsized locals are gated as an unstable feature");
2668                 }
2669             }
2670             ObligationCauseCode::SizedArgumentType => {
2671                 err.note("all function arguments must have a statically known size");
2672                 if !self.tcx.features().unsized_locals {
2673                     err.help("unsized locals are gated as an unstable feature");
2674                 }
2675             }
2676             ObligationCauseCode::SizedReturnType => {
2677                 err.note(
2678                     "the return type of a function must have a \
2679                           statically known size",
2680                 );
2681             }
2682             ObligationCauseCode::SizedYieldType => {
2683                 err.note(
2684                     "the yield type of a generator must have a \
2685                           statically known size",
2686                 );
2687             }
2688             ObligationCauseCode::AssignmentLhsSized => {
2689                 err.note("the left-hand-side of an assignment must have a statically known size");
2690             }
2691             ObligationCauseCode::TupleInitializerSized => {
2692                 err.note("tuples must have a statically known size to be initialized");
2693             }
2694             ObligationCauseCode::StructInitializerSized => {
2695                 err.note("structs must have a statically known size to be initialized");
2696             }
2697             ObligationCauseCode::FieldSized { adt_kind: ref item, last } => match *item {
2698                 AdtKind::Struct => {
2699                     if last {
2700                         err.note(
2701                             "the last field of a packed struct may only have a \
2702                                       dynamically sized type if it does not need drop to be run",
2703                         );
2704                     } else {
2705                         err.note(
2706                             "only the last field of a struct may have a dynamically \
2707                                       sized type",
2708                         );
2709                     }
2710                 }
2711                 AdtKind::Union => {
2712                     err.note("no field of a union may have a dynamically sized type");
2713                 }
2714                 AdtKind::Enum => {
2715                     err.note("no field of an enum variant may have a dynamically sized type");
2716                 }
2717             },
2718             ObligationCauseCode::ConstSized => {
2719                 err.note("constant expressions must have a statically known size");
2720             }
2721             ObligationCauseCode::ConstPatternStructural => {
2722                 err.note("constants used for pattern-matching must derive `PartialEq` and `Eq`");
2723             }
2724             ObligationCauseCode::SharedStatic => {
2725                 err.note("shared static variables must have a type that implements `Sync`");
2726             }
2727             ObligationCauseCode::BuiltinDerivedObligation(ref data) => {
2728                 let parent_trait_ref = self.resolve_vars_if_possible(&data.parent_trait_ref);
2729                 let ty = parent_trait_ref.skip_binder().self_ty();
2730                 err.note(&format!("required because it appears within the type `{}`", ty));
2731                 obligated_types.push(ty);
2732
2733                 let parent_predicate = parent_trait_ref.to_predicate();
2734                 if !self.is_recursive_obligation(obligated_types, &data.parent_code) {
2735                     self.note_obligation_cause_code(
2736                         err,
2737                         &parent_predicate,
2738                         &data.parent_code,
2739                         obligated_types,
2740                     );
2741                 }
2742             }
2743             ObligationCauseCode::ImplDerivedObligation(ref data) => {
2744                 let parent_trait_ref = self.resolve_vars_if_possible(&data.parent_trait_ref);
2745                 err.note(&format!(
2746                     "required because of the requirements on the impl of `{}` for `{}`",
2747                     parent_trait_ref.print_only_trait_path(),
2748                     parent_trait_ref.skip_binder().self_ty()
2749                 ));
2750                 let parent_predicate = parent_trait_ref.to_predicate();
2751                 self.note_obligation_cause_code(
2752                     err,
2753                     &parent_predicate,
2754                     &data.parent_code,
2755                     obligated_types,
2756                 );
2757             }
2758             ObligationCauseCode::CompareImplMethodObligation { .. } => {
2759                 err.note(&format!(
2760                     "the requirement `{}` appears on the impl method \
2761                               but not on the corresponding trait method",
2762                     predicate
2763                 ));
2764             }
2765             ObligationCauseCode::CompareImplTypeObligation { .. } => {
2766                 err.note(&format!(
2767                     "the requirement `{}` appears on the associated impl type\
2768                      but not on the corresponding associated trait type",
2769                     predicate
2770                 ));
2771             }
2772             ObligationCauseCode::ReturnType
2773             | ObligationCauseCode::ReturnValue(_)
2774             | ObligationCauseCode::BlockTailExpression(_) => (),
2775             ObligationCauseCode::TrivialBound => {
2776                 err.help("see issue #48214");
2777                 if tcx.sess.opts.unstable_features.is_nightly_build() {
2778                     err.help(
2779                         "add `#![feature(trivial_bounds)]` to the \
2780                               crate attributes to enable",
2781                     );
2782                 }
2783             }
2784             ObligationCauseCode::AssocTypeBound(ref data) => {
2785                 err.span_label(data.original, "associated type defined here");
2786                 if let Some(sp) = data.impl_span {
2787                     err.span_label(sp, "in this `impl` item");
2788                 }
2789                 for sp in &data.bounds {
2790                     err.span_label(*sp, "restricted in this bound");
2791                 }
2792             }
2793         }
2794     }
2795
2796     fn suggest_new_overflow_limit(&self, err: &mut DiagnosticBuilder<'_>) {
2797         let current_limit = self.tcx.sess.recursion_limit.get();
2798         let suggested_limit = current_limit * 2;
2799         err.help(&format!(
2800             "consider adding a `#![recursion_limit=\"{}\"]` attribute to your crate",
2801             suggested_limit
2802         ));
2803     }
2804
2805     fn is_recursive_obligation(
2806         &self,
2807         obligated_types: &mut Vec<&ty::TyS<'tcx>>,
2808         cause_code: &ObligationCauseCode<'tcx>,
2809     ) -> bool {
2810         if let ObligationCauseCode::BuiltinDerivedObligation(ref data) = cause_code {
2811             let parent_trait_ref = self.resolve_vars_if_possible(&data.parent_trait_ref);
2812
2813             if obligated_types.iter().any(|ot| ot == &parent_trait_ref.skip_binder().self_ty()) {
2814                 return true;
2815             }
2816         }
2817         false
2818     }
2819 }
2820
2821 /// Summarizes information
2822 #[derive(Clone)]
2823 pub enum ArgKind {
2824     /// An argument of non-tuple type. Parameters are (name, ty)
2825     Arg(String, String),
2826
2827     /// An argument of tuple type. For a "found" argument, the span is
2828     /// the locationo in the source of the pattern. For a "expected"
2829     /// argument, it will be None. The vector is a list of (name, ty)
2830     /// strings for the components of the tuple.
2831     Tuple(Option<Span>, Vec<(String, String)>),
2832 }
2833
2834 impl ArgKind {
2835     fn empty() -> ArgKind {
2836         ArgKind::Arg("_".to_owned(), "_".to_owned())
2837     }
2838
2839     /// Creates an `ArgKind` from the expected type of an
2840     /// argument. It has no name (`_`) and an optional source span.
2841     pub fn from_expected_ty(t: Ty<'_>, span: Option<Span>) -> ArgKind {
2842         match t.kind {
2843             ty::Tuple(ref tys) => ArgKind::Tuple(
2844                 span,
2845                 tys.iter().map(|ty| ("_".to_owned(), ty.to_string())).collect::<Vec<_>>(),
2846             ),
2847             _ => ArgKind::Arg("_".to_owned(), t.to_string()),
2848         }
2849     }
2850 }
2851
2852 /// Suggest restricting a type param with a new bound.
2853 pub fn suggest_constraining_type_param(
2854     generics: &hir::Generics<'_>,
2855     err: &mut DiagnosticBuilder<'_>,
2856     param_name: &str,
2857     constraint: &str,
2858     source_map: &SourceMap,
2859     span: Span,
2860 ) -> bool {
2861     let restrict_msg = "consider further restricting this bound";
2862     if let Some(param) =
2863         generics.params.iter().filter(|p| p.name.ident().as_str() == param_name).next()
2864     {
2865         if param_name.starts_with("impl ") {
2866             // `impl Trait` in argument:
2867             // `fn foo(x: impl Trait) {}` → `fn foo(t: impl Trait + Trait2) {}`
2868             err.span_suggestion(
2869                 param.span,
2870                 restrict_msg,
2871                 // `impl CurrentTrait + MissingTrait`
2872                 format!("{} + {}", param_name, constraint),
2873                 Applicability::MachineApplicable,
2874             );
2875         } else if generics.where_clause.predicates.is_empty() && param.bounds.is_empty() {
2876             // If there are no bounds whatsoever, suggest adding a constraint
2877             // to the type parameter:
2878             // `fn foo<T>(t: T) {}` → `fn foo<T: Trait>(t: T) {}`
2879             err.span_suggestion(
2880                 param.span,
2881                 "consider restricting this bound",
2882                 format!("{}: {}", param_name, constraint),
2883                 Applicability::MachineApplicable,
2884             );
2885         } else if !generics.where_clause.predicates.is_empty() {
2886             // There is a `where` clause, so suggest expanding it:
2887             // `fn foo<T>(t: T) where T: Debug {}` →
2888             // `fn foo<T>(t: T) where T: Debug, T: Trait {}`
2889             err.span_suggestion(
2890                 generics.where_clause.span().unwrap().shrink_to_hi(),
2891                 &format!("consider further restricting type parameter `{}`", param_name),
2892                 format!(", {}: {}", param_name, constraint),
2893                 Applicability::MachineApplicable,
2894             );
2895         } else {
2896             // If there is no `where` clause lean towards constraining to the
2897             // type parameter:
2898             // `fn foo<X: Bar, T>(t: T, x: X) {}` → `fn foo<T: Trait>(t: T) {}`
2899             // `fn foo<T: Bar>(t: T) {}` → `fn foo<T: Bar + Trait>(t: T) {}`
2900             let sp = param.span.with_hi(span.hi());
2901             let span = source_map.span_through_char(sp, ':');
2902             if sp != param.span && sp != span {
2903                 // Only suggest if we have high certainty that the span
2904                 // covers the colon in `foo<T: Trait>`.
2905                 err.span_suggestion(
2906                     span,
2907                     restrict_msg,
2908                     format!("{}: {} + ", param_name, constraint),
2909                     Applicability::MachineApplicable,
2910                 );
2911             } else {
2912                 err.span_label(
2913                     param.span,
2914                     &format!("consider adding a `where {}: {}` bound", param_name, constraint),
2915                 );
2916             }
2917         }
2918         return true;
2919     }
2920     false
2921 }