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