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