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