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