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