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