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