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