6 MismatchedProjectionTypes,
11 OnUnimplementedDirective,
13 OutputTypeParameterMismatch,
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};
36 use errors::{Applicability, DiagnosticBuilder, pluralize, Style};
39 use syntax::symbol::{sym, kw};
40 use syntax_pos::{DUMMY_SP, Span, ExpnKind, MultiSpan};
41 use rustc::hir::def_id::LOCAL_CRATE;
43 use rustc_error_codes::*;
45 impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
46 pub fn report_fulfillment_errors(
48 errors: &[FulfillmentError<'tcx>],
49 body_id: Option<hir::BodyId>,
50 fallback_has_occurred: bool,
53 struct ErrorDescriptor<'tcx> {
54 predicate: ty::Predicate<'tcx>,
55 index: Option<usize>, // None if this is an old error
58 let mut error_map: FxHashMap<_, Vec<_>> =
59 self.reported_trait_errors.borrow().iter().map(|(&span, predicates)| {
60 (span, predicates.iter().map(|predicate| ErrorDescriptor {
61 predicate: predicate.clone(),
66 for (index, error) in errors.iter().enumerate() {
67 // We want to ignore desugarings here: spans are equivalent even
68 // if one is the result of a desugaring and the other is not.
69 let mut span = error.obligation.cause.span;
70 let expn_data = span.ctxt().outer_expn_data();
71 if let ExpnKind::Desugaring(_) = expn_data.kind {
72 span = expn_data.call_site;
75 error_map.entry(span).or_default().push(
77 predicate: error.obligation.predicate.clone(),
82 self.reported_trait_errors.borrow_mut()
83 .entry(span).or_default()
84 .push(error.obligation.predicate.clone());
87 // We do this in 2 passes because we want to display errors in order, though
88 // maybe it *is* better to sort errors by span or something.
89 let mut is_suppressed = vec![false; errors.len()];
90 for (_, error_set) in error_map.iter() {
91 // We want to suppress "duplicate" errors with the same span.
92 for error in error_set {
93 if let Some(index) = error.index {
94 // Suppress errors that are either:
95 // 1) strictly implied by another error.
96 // 2) implied by an error with a smaller index.
97 for error2 in error_set {
98 if error2.index.map_or(false, |index2| is_suppressed[index2]) {
99 // Avoid errors being suppressed by already-suppressed
100 // errors, to prevent all errors from being suppressed
105 if self.error_implies(&error2.predicate, &error.predicate) &&
106 !(error2.index >= error.index &&
107 self.error_implies(&error.predicate, &error2.predicate))
109 info!("skipping {:?} (implied by {:?})", error, error2);
110 is_suppressed[index] = true;
118 for (error, suppressed) in errors.iter().zip(is_suppressed) {
120 self.report_fulfillment_error(error, body_id, fallback_has_occurred);
125 // returns if `cond` not occurring implies that `error` does not occur - i.e., that
126 // `error` occurring implies that `cond` occurs.
129 cond: &ty::Predicate<'tcx>,
130 error: &ty::Predicate<'tcx>,
136 let (cond, error) = match (cond, error) {
137 (&ty::Predicate::Trait(..), &ty::Predicate::Trait(ref error))
140 // FIXME: make this work in other cases too.
145 for implication in super::elaborate_predicates(self.tcx, vec![cond.clone()]) {
146 if let ty::Predicate::Trait(implication) = implication {
147 let error = error.to_poly_trait_ref();
148 let implication = implication.to_poly_trait_ref();
149 // FIXME: I'm just not taking associated types at all here.
150 // Eventually I'll need to implement param-env-aware
151 // `Γ₁ ⊦ φ₁ => Γ₂ ⊦ φ₂` logic.
152 let param_env = ty::ParamEnv::empty();
153 if self.can_sub(param_env, error, implication).is_ok() {
154 debug!("error_implies: {:?} -> {:?} -> {:?}", cond, error, implication);
163 fn report_fulfillment_error(
165 error: &FulfillmentError<'tcx>,
166 body_id: Option<hir::BodyId>,
167 fallback_has_occurred: bool,
169 debug!("report_fulfillment_errors({:?})", error);
171 FulfillmentErrorCode::CodeSelectionError(ref selection_error) => {
172 self.report_selection_error(
175 fallback_has_occurred,
176 error.points_at_arg_span,
179 FulfillmentErrorCode::CodeProjectionError(ref e) => {
180 self.report_projection_error(&error.obligation, e);
182 FulfillmentErrorCode::CodeAmbiguity => {
183 self.maybe_report_ambiguity(&error.obligation, body_id);
185 FulfillmentErrorCode::CodeSubtypeError(ref expected_found, ref err) => {
186 self.report_mismatched_types(
187 &error.obligation.cause,
188 expected_found.expected,
189 expected_found.found,
196 fn report_projection_error(
198 obligation: &PredicateObligation<'tcx>,
199 error: &MismatchedProjectionTypes<'tcx>,
201 let predicate = self.resolve_vars_if_possible(&obligation.predicate);
203 if predicate.references_error() {
209 let mut err = &error.err;
210 let mut values = None;
212 // try to find the mismatched types to report the error with.
214 // this can fail if the problem was higher-ranked, in which
215 // cause I have no idea for a good error message.
216 if let ty::Predicate::Projection(ref data) = predicate {
217 let mut selcx = SelectionContext::new(self);
218 let (data, _) = self.replace_bound_vars_with_fresh_vars(
219 obligation.cause.span,
220 infer::LateBoundRegionConversionTime::HigherRankedType,
223 let mut obligations = vec![];
224 let normalized_ty = super::normalize_projection_type(
226 obligation.param_env,
228 obligation.cause.clone(),
233 debug!("report_projection_error obligation.cause={:?} obligation.param_env={:?}",
234 obligation.cause, obligation.param_env);
236 debug!("report_projection_error normalized_ty={:?} data.ty={:?}",
237 normalized_ty, data.ty);
239 let is_normalized_ty_expected = match &obligation.cause.code {
240 ObligationCauseCode::ItemObligation(_) |
241 ObligationCauseCode::BindingObligation(_, _) |
242 ObligationCauseCode::ObjectCastObligation(_) => false,
246 if let Err(error) = self.at(&obligation.cause, obligation.param_env)
247 .eq_exp(is_normalized_ty_expected, normalized_ty, data.ty)
249 values = Some(infer::ValuePairs::Types(
250 ExpectedFound::new(is_normalized_ty_expected, normalized_ty, data.ty)));
257 let msg = format!("type mismatch resolving `{}`", predicate);
259 DiagnosticMessageId::ErrorId(271),
260 Some(obligation.cause.span),
263 let fresh = self.tcx.sess.one_time_diagnostics.borrow_mut().insert(error_id);
265 let mut diag = struct_span_err!(
267 obligation.cause.span,
269 "type mismatch resolving `{}`",
272 self.note_type_err(&mut diag, &obligation.cause, None, values, err);
273 self.note_obligation_cause(&mut diag, obligation);
279 fn fuzzy_match_tys(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
280 /// returns the fuzzy category of a given type, or None
281 /// if the type can be equated to any type.
282 fn type_category(t: Ty<'_>) -> Option<u32> {
287 ty::Int(..) | ty::Uint(..) | ty::Infer(ty::IntVar(..)) => Some(3),
288 ty::Float(..) | ty::Infer(ty::FloatVar(..)) => Some(4),
289 ty::Ref(..) | ty::RawPtr(..) => Some(5),
290 ty::Array(..) | ty::Slice(..) => Some(6),
291 ty::FnDef(..) | ty::FnPtr(..) => Some(7),
292 ty::Dynamic(..) => Some(8),
293 ty::Closure(..) => Some(9),
294 ty::Tuple(..) => Some(10),
295 ty::Projection(..) => Some(11),
296 ty::Param(..) => Some(12),
297 ty::Opaque(..) => Some(13),
298 ty::Never => Some(14),
299 ty::Adt(adt, ..) => match adt.adt_kind() {
300 AdtKind::Struct => Some(15),
301 AdtKind::Union => Some(16),
302 AdtKind::Enum => Some(17),
304 ty::Generator(..) => Some(18),
305 ty::Foreign(..) => Some(19),
306 ty::GeneratorWitness(..) => Some(20),
307 ty::Placeholder(..) | ty::Bound(..) | ty::Infer(..) | ty::Error => None,
308 ty::UnnormalizedProjection(..) => bug!("only used with chalk-engine"),
312 match (type_category(a), type_category(b)) {
313 (Some(cat_a), Some(cat_b)) => match (&a.kind, &b.kind) {
314 (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) => def_a == def_b,
317 // infer and error can be equated to all types
322 fn impl_similar_to(&self,
323 trait_ref: ty::PolyTraitRef<'tcx>,
324 obligation: &PredicateObligation<'tcx>)
328 let param_env = obligation.param_env;
329 let trait_ref = tcx.erase_late_bound_regions(&trait_ref);
330 let trait_self_ty = trait_ref.self_ty();
332 let mut self_match_impls = vec![];
333 let mut fuzzy_match_impls = vec![];
335 self.tcx.for_each_relevant_impl(
336 trait_ref.def_id, trait_self_ty, |def_id| {
337 let impl_substs = self.fresh_substs_for_item(obligation.cause.span, def_id);
338 let impl_trait_ref = tcx
339 .impl_trait_ref(def_id)
341 .subst(tcx, impl_substs);
343 let impl_self_ty = impl_trait_ref.self_ty();
345 if let Ok(..) = self.can_eq(param_env, trait_self_ty, impl_self_ty) {
346 self_match_impls.push(def_id);
348 if trait_ref.substs.types().skip(1)
349 .zip(impl_trait_ref.substs.types().skip(1))
350 .all(|(u,v)| self.fuzzy_match_tys(u, v))
352 fuzzy_match_impls.push(def_id);
357 let impl_def_id = if self_match_impls.len() == 1 {
359 } else if fuzzy_match_impls.len() == 1 {
365 if tcx.has_attr(impl_def_id, sym::rustc_on_unimplemented) {
372 fn describe_generator(&self, body_id: hir::BodyId) -> Option<&'static str> {
373 self.tcx.hir().body(body_id).generator_kind.map(|gen_kind| {
375 hir::GeneratorKind::Gen => "a generator",
376 hir::GeneratorKind::Async(hir::AsyncGeneratorKind::Block) => "an async block",
377 hir::GeneratorKind::Async(hir::AsyncGeneratorKind::Fn) => "an async function",
378 hir::GeneratorKind::Async(hir::AsyncGeneratorKind::Closure) => "an async closure",
383 /// Used to set on_unimplemented's `ItemContext`
384 /// to be the enclosing (async) block/function/closure
385 fn describe_enclosure(&self, hir_id: hir::HirId) -> Option<&'static str> {
386 let hir = &self.tcx.hir();
387 let node = hir.find(hir_id)?;
388 if let hir::Node::Item(
389 hir::Item{kind: hir::ItemKind::Fn(sig, _, body_id), .. }) = &node {
390 self.describe_generator(*body_id).or_else(||
391 Some(if let hir::FnHeader{ asyncness: hir::IsAsync::Async, .. } = sig.header {
397 } else if let hir::Node::Expr(hir::Expr {
398 kind: hir::ExprKind::Closure(_is_move, _, body_id, _, gen_movability), .. }) = &node {
399 self.describe_generator(*body_id).or_else(||
400 Some(if gen_movability.is_some() {
406 } else if let hir::Node::Expr(hir::Expr { .. }) = &node {
407 let parent_hid = hir.get_parent_node(hir_id);
408 if parent_hid != hir_id {
409 return self.describe_enclosure(parent_hid);
418 fn on_unimplemented_note(
420 trait_ref: ty::PolyTraitRef<'tcx>,
421 obligation: &PredicateObligation<'tcx>,
422 ) -> OnUnimplementedNote {
423 let def_id = self.impl_similar_to(trait_ref, obligation)
424 .unwrap_or_else(|| trait_ref.def_id());
425 let trait_ref = *trait_ref.skip_binder();
427 let mut flags = vec![];
428 flags.push((sym::item_context,
429 self.describe_enclosure(obligation.cause.body_id).map(|s|s.to_owned())));
431 match obligation.cause.code {
432 ObligationCauseCode::BuiltinDerivedObligation(..) |
433 ObligationCauseCode::ImplDerivedObligation(..) => {}
435 // this is a "direct", user-specified, rather than derived,
437 flags.push((sym::direct, None));
441 if let ObligationCauseCode::ItemObligation(item) = obligation.cause.code {
442 // FIXME: maybe also have some way of handling methods
443 // from other traits? That would require name resolution,
444 // which we might want to be some sort of hygienic.
446 // Currently I'm leaving it for what I need for `try`.
447 if self.tcx.trait_of_item(item) == Some(trait_ref.def_id) {
448 let method = self.tcx.item_name(item);
449 flags.push((sym::from_method, None));
450 flags.push((sym::from_method, Some(method.to_string())));
453 if let Some(t) = self.get_parent_trait_ref(&obligation.cause.code) {
454 flags.push((sym::parent_trait, Some(t)));
457 if let Some(k) = obligation.cause.span.desugaring_kind() {
458 flags.push((sym::from_desugaring, None));
459 flags.push((sym::from_desugaring, Some(format!("{:?}", k))));
461 let generics = self.tcx.generics_of(def_id);
462 let self_ty = trait_ref.self_ty();
463 // This is also included through the generics list as `Self`,
464 // but the parser won't allow you to use it
465 flags.push((sym::_Self, Some(self_ty.to_string())));
466 if let Some(def) = self_ty.ty_adt_def() {
467 // We also want to be able to select self's original
468 // signature with no type arguments resolved
469 flags.push((sym::_Self, Some(self.tcx.type_of(def.did).to_string())));
472 for param in generics.params.iter() {
473 let value = match param.kind {
474 GenericParamDefKind::Type { .. } |
475 GenericParamDefKind::Const => {
476 trait_ref.substs[param.index as usize].to_string()
478 GenericParamDefKind::Lifetime => continue,
480 let name = param.name;
481 flags.push((name, Some(value)));
484 if let Some(true) = self_ty.ty_adt_def().map(|def| def.did.is_local()) {
485 flags.push((sym::crate_local, None));
488 // Allow targeting all integers using `{integral}`, even if the exact type was resolved
489 if self_ty.is_integral() {
490 flags.push((sym::_Self, Some("{integral}".to_owned())));
493 if let ty::Array(aty, len) = self_ty.kind {
494 flags.push((sym::_Self, Some("[]".to_owned())));
495 flags.push((sym::_Self, Some(format!("[{}]", aty))));
496 if let Some(def) = aty.ty_adt_def() {
497 // We also want to be able to select the array's type's original
498 // signature with no type arguments resolved
501 Some(format!("[{}]", self.tcx.type_of(def.did).to_string())),
504 if let Some(len) = len.try_eval_usize(tcx, ty::ParamEnv::empty()) {
507 Some(format!("[{}; {}]", self.tcx.type_of(def.did).to_string(), len)),
512 Some(format!("[{}; _]", self.tcx.type_of(def.did).to_string())),
518 if let Ok(Some(command)) = OnUnimplementedDirective::of_item(
519 self.tcx, trait_ref.def_id, def_id
521 command.evaluate(self.tcx, trait_ref, &flags[..])
523 OnUnimplementedNote::empty()
527 fn find_similar_impl_candidates(
529 trait_ref: ty::PolyTraitRef<'tcx>,
530 ) -> Vec<ty::TraitRef<'tcx>> {
531 let simp = fast_reject::simplify_type(self.tcx, trait_ref.skip_binder().self_ty(), true);
532 let all_impls = self.tcx.all_impls(trait_ref.def_id());
535 Some(simp) => all_impls.iter().filter_map(|&def_id| {
536 let imp = self.tcx.impl_trait_ref(def_id).unwrap();
537 let imp_simp = fast_reject::simplify_type(self.tcx, imp.self_ty(), true);
538 if let Some(imp_simp) = imp_simp {
539 if simp != imp_simp {
546 None => all_impls.iter().map(|&def_id|
547 self.tcx.impl_trait_ref(def_id).unwrap()
552 fn report_similar_impl_candidates(
554 impl_candidates: Vec<ty::TraitRef<'tcx>>,
555 err: &mut DiagnosticBuilder<'_>,
557 if impl_candidates.is_empty() {
561 let len = impl_candidates.len();
562 let end = if impl_candidates.len() <= 5 {
563 impl_candidates.len()
568 let normalize = |candidate| self.tcx.infer_ctxt().enter(|ref infcx| {
569 let normalized = infcx
570 .at(&ObligationCause::dummy(), ty::ParamEnv::empty())
571 .normalize(candidate)
574 Some(normalized) => format!("\n {:?}", normalized.value),
575 None => format!("\n {:?}", candidate),
579 // Sort impl candidates so that ordering is consistent for UI tests.
580 let mut normalized_impl_candidates = impl_candidates
583 .collect::<Vec<String>>();
585 // Sort before taking the `..end` range,
586 // because the ordering of `impl_candidates` may not be deterministic:
587 // https://github.com/rust-lang/rust/pull/57475#issuecomment-455519507
588 normalized_impl_candidates.sort();
590 err.help(&format!("the following implementations were found:{}{}",
591 normalized_impl_candidates[..end].join(""),
593 format!("\nand {} others", len - 4)
600 /// Reports that an overflow has occurred and halts compilation. We
601 /// halt compilation unconditionally because it is important that
602 /// overflows never be masked -- they basically represent computations
603 /// whose result could not be truly determined and thus we can't say
604 /// if the program type checks or not -- and they are unusual
605 /// occurrences in any case.
606 pub fn report_overflow_error<T>(
608 obligation: &Obligation<'tcx, T>,
609 suggest_increasing_limit: bool,
611 where T: fmt::Display + TypeFoldable<'tcx>
614 self.resolve_vars_if_possible(&obligation.predicate);
615 let mut err = struct_span_err!(
617 obligation.cause.span,
619 "overflow evaluating the requirement `{}`",
623 if suggest_increasing_limit {
624 self.suggest_new_overflow_limit(&mut err);
627 self.note_obligation_cause_code(
629 &obligation.predicate,
630 &obligation.cause.code,
635 self.tcx.sess.abort_if_errors();
639 /// Reports that a cycle was detected which led to overflow and halts
640 /// compilation. This is equivalent to `report_overflow_error` except
641 /// that we can give a more helpful error message (and, in particular,
642 /// we do not suggest increasing the overflow limit, which is not
644 pub fn report_overflow_error_cycle(&self, cycle: &[PredicateObligation<'tcx>]) -> ! {
645 let cycle = self.resolve_vars_if_possible(&cycle.to_owned());
646 assert!(cycle.len() > 0);
648 debug!("report_overflow_error_cycle: cycle={:?}", cycle);
650 self.report_overflow_error(&cycle[0], false);
653 pub fn report_extra_impl_obligation(&self,
655 item_name: ast::Name,
656 _impl_item_def_id: DefId,
657 trait_item_def_id: DefId,
658 requirement: &dyn fmt::Display)
659 -> DiagnosticBuilder<'tcx>
661 let msg = "impl has stricter requirements than trait";
662 let sp = self.tcx.sess.source_map().def_span(error_span);
664 let mut err = struct_span_err!(self.tcx.sess, sp, E0276, "{}", msg);
666 if let Some(trait_item_span) = self.tcx.hir().span_if_local(trait_item_def_id) {
667 let span = self.tcx.sess.source_map().def_span(trait_item_span);
668 err.span_label(span, format!("definition of `{}` from trait", item_name));
671 err.span_label(sp, format!("impl has extra requirement {}", requirement));
677 /// Gets the parent trait chain start
678 fn get_parent_trait_ref(&self, code: &ObligationCauseCode<'tcx>) -> Option<String> {
680 &ObligationCauseCode::BuiltinDerivedObligation(ref data) => {
681 let parent_trait_ref = self.resolve_vars_if_possible(
682 &data.parent_trait_ref);
683 match self.get_parent_trait_ref(&data.parent_code) {
685 None => Some(parent_trait_ref.skip_binder().self_ty().to_string()),
692 pub fn report_selection_error(
694 obligation: &PredicateObligation<'tcx>,
695 error: &SelectionError<'tcx>,
696 fallback_has_occurred: bool,
699 let span = obligation.cause.span;
701 let mut err = match *error {
702 SelectionError::Unimplemented => {
703 if let ObligationCauseCode::CompareImplMethodObligation {
704 item_name, impl_item_def_id, trait_item_def_id,
705 } = obligation.cause.code {
706 self.report_extra_impl_obligation(
711 &format!("`{}`", obligation.predicate))
715 match obligation.predicate {
716 ty::Predicate::Trait(ref trait_predicate) => {
717 let trait_predicate = self.resolve_vars_if_possible(trait_predicate);
719 if self.tcx.sess.has_errors() && trait_predicate.references_error() {
722 let trait_ref = trait_predicate.to_poly_trait_ref();
726 ) = self.get_parent_trait_ref(&obligation.cause.code)
727 .map(|t| (format!(" in `{}`", t), format!("within `{}`, ", t)))
728 .unwrap_or_default();
730 let OnUnimplementedNote {
734 } = self.on_unimplemented_note(trait_ref, obligation);
735 let have_alt_message = message.is_some() || label.is_some();
736 let is_try = self.tcx.sess.source_map().span_to_snippet(span)
739 let is_from = format!("{}", trait_ref).starts_with("std::convert::From<");
740 let (message, note) = if is_try && is_from {
742 "`?` couldn't convert the error to `{}`",
745 "the question mark operation (`?`) implicitly performs a \
746 conversion on the error value using the `From` trait".to_owned()
752 let mut err = struct_span_err!(
757 message.unwrap_or_else(|| format!(
758 "the trait bound `{}` is not satisfied{}",
759 trait_ref.to_predicate(),
764 if obligation.cause.code == ObligationCauseCode::MainFunctionType {
765 "consider using `()`, or a `Result`".to_owned()
768 "{}the trait `{}` is not implemented for `{}`",
775 if self.suggest_add_reference_to_arg(
782 self.note_obligation_cause(&mut err, obligation);
786 if let Some(ref s) = label {
787 // If it has a custom `#[rustc_on_unimplemented]`
788 // error message, let's display it as the label!
789 err.span_label(span, s.as_str());
790 err.help(&explanation);
792 err.span_label(span, explanation);
794 if let Some(ref s) = note {
795 // If it has a custom `#[rustc_on_unimplemented]` note, let's display it
796 err.note(s.as_str());
799 self.suggest_borrow_on_unsized_slice(&obligation.cause.code, &mut err);
800 self.suggest_fn_call(&obligation, &mut err, &trait_ref, points_at_arg);
801 self.suggest_remove_reference(&obligation, &mut err, &trait_ref);
802 self.suggest_semicolon_removal(&obligation, &mut err, span, &trait_ref);
803 self.note_version_mismatch(&mut err, &trait_ref);
805 // Try to report a help message
806 if !trait_ref.has_infer_types() &&
807 self.predicate_can_apply(obligation.param_env, trait_ref) {
808 // If a where-clause may be useful, remind the
809 // user that they can add it.
811 // don't display an on-unimplemented note, as
812 // these notes will often be of the form
813 // "the type `T` can't be frobnicated"
814 // which is somewhat confusing.
815 self.suggest_restricting_param_bound(
818 obligation.cause.body_id,
821 if !have_alt_message {
822 // Can't show anything else useful, try to find similar impls.
823 let impl_candidates = self.find_similar_impl_candidates(trait_ref);
824 self.report_similar_impl_candidates(impl_candidates, &mut err);
826 self.suggest_change_mut(
834 // If this error is due to `!: Trait` not implemented but `(): Trait` is
835 // implemented, and fallback has occurred, then it could be due to a
836 // variable that used to fallback to `()` now falling back to `!`. Issue a
837 // note informing about the change in behaviour.
838 if trait_predicate.skip_binder().self_ty().is_never()
839 && fallback_has_occurred
841 let predicate = trait_predicate.map_bound(|mut trait_pred| {
842 trait_pred.trait_ref.substs = self.tcx.mk_substs_trait(
844 &trait_pred.trait_ref.substs[1..],
848 let unit_obligation = Obligation {
849 predicate: ty::Predicate::Trait(predicate),
850 .. obligation.clone()
852 if self.predicate_may_hold(&unit_obligation) {
853 err.note("the trait is implemented for `()`. \
854 Possibly this error has been caused by changes to \
855 Rust's type-inference algorithm \
856 (see: https://github.com/rust-lang/rust/issues/48950 \
857 for more info). Consider whether you meant to use the \
858 type `()` here instead.");
865 ty::Predicate::Subtype(ref predicate) => {
866 // Errors for Subtype predicates show up as
867 // `FulfillmentErrorCode::CodeSubtypeError`,
868 // not selection error.
869 span_bug!(span, "subtype requirement gave wrong error: `{:?}`", predicate)
872 ty::Predicate::RegionOutlives(ref predicate) => {
873 let predicate = self.resolve_vars_if_possible(predicate);
874 let err = self.region_outlives_predicate(&obligation.cause,
875 &predicate).err().unwrap();
877 self.tcx.sess, span, E0279,
878 "the requirement `{}` is not satisfied (`{}`)",
883 ty::Predicate::Projection(..) | ty::Predicate::TypeOutlives(..) => {
885 self.resolve_vars_if_possible(&obligation.predicate);
886 struct_span_err!(self.tcx.sess, span, E0280,
887 "the requirement `{}` is not satisfied",
891 ty::Predicate::ObjectSafe(trait_def_id) => {
892 let violations = self.tcx.object_safety_violations(trait_def_id);
893 self.tcx.report_object_safety_error(
900 ty::Predicate::ClosureKind(closure_def_id, closure_substs, kind) => {
901 let found_kind = self.closure_kind(closure_def_id, closure_substs).unwrap();
902 let closure_span = self.tcx.sess.source_map()
903 .def_span(self.tcx.hir().span_if_local(closure_def_id).unwrap());
904 let hir_id = self.tcx.hir().as_local_hir_id(closure_def_id).unwrap();
905 let mut err = struct_span_err!(
906 self.tcx.sess, closure_span, E0525,
907 "expected a closure that implements the `{}` trait, \
908 but this closure only implements `{}`",
914 format!("this closure implements `{}`, not `{}`", found_kind, kind));
916 obligation.cause.span,
917 format!("the requirement to implement `{}` derives from here", kind));
919 // Additional context information explaining why the closure only implements
920 // a particular trait.
921 if let Some(tables) = self.in_progress_tables {
922 let tables = tables.borrow();
923 match (found_kind, tables.closure_kind_origins().get(hir_id)) {
924 (ty::ClosureKind::FnOnce, Some((span, name))) => {
925 err.span_label(*span, format!(
926 "closure is `FnOnce` because it moves the \
927 variable `{}` out of its environment", name));
929 (ty::ClosureKind::FnMut, Some((span, name))) => {
930 err.span_label(*span, format!(
931 "closure is `FnMut` because it mutates the \
932 variable `{}` here", name));
942 ty::Predicate::WellFormed(ty) => {
943 if !self.tcx.sess.opts.debugging_opts.chalk {
944 // WF predicates cannot themselves make
945 // errors. They can only block due to
946 // ambiguity; otherwise, they always
947 // degenerate into other obligations
949 span_bug!(span, "WF predicate not satisfied for {:?}", ty);
951 // FIXME: we'll need a better message which takes into account
952 // which bounds actually failed to hold.
953 self.tcx.sess.struct_span_err(
955 &format!("the type `{}` is not well-formed (chalk)", ty)
960 ty::Predicate::ConstEvaluatable(..) => {
961 // Errors for `ConstEvaluatable` predicates show up as
962 // `SelectionError::ConstEvalFailure`,
963 // not `Unimplemented`.
965 "const-evaluatable requirement gave wrong error: `{:?}`", obligation)
970 OutputTypeParameterMismatch(ref found_trait_ref, ref expected_trait_ref, _) => {
971 let found_trait_ref = self.resolve_vars_if_possible(&*found_trait_ref);
972 let expected_trait_ref = self.resolve_vars_if_possible(&*expected_trait_ref);
974 if expected_trait_ref.self_ty().references_error() {
978 let found_trait_ty = found_trait_ref.self_ty();
980 let found_did = match found_trait_ty.kind {
981 ty::Closure(did, _) | ty::Foreign(did) | ty::FnDef(did, _) => Some(did),
982 ty::Adt(def, _) => Some(def.did),
986 let found_span = found_did.and_then(|did|
987 self.tcx.hir().span_if_local(did)
988 ).map(|sp| self.tcx.sess.source_map().def_span(sp)); // the sp could be an fn def
990 if self.reported_closure_mismatch.borrow().contains(&(span, found_span)) {
991 // We check closures twice, with obligations flowing in different directions,
992 // but we want to complain about them only once.
996 self.reported_closure_mismatch.borrow_mut().insert((span, found_span));
998 let found = match found_trait_ref.skip_binder().substs.type_at(1).kind {
999 ty::Tuple(ref tys) => vec![ArgKind::empty(); tys.len()],
1000 _ => vec![ArgKind::empty()],
1003 let expected_ty = expected_trait_ref.skip_binder().substs.type_at(1);
1004 let expected = match expected_ty.kind {
1005 ty::Tuple(ref tys) => tys.iter()
1006 .map(|t| ArgKind::from_expected_ty(t.expect_ty(), Some(span))).collect(),
1007 _ => vec![ArgKind::Arg("_".to_owned(), expected_ty.to_string())],
1010 if found.len() == expected.len() {
1011 self.report_closure_arg_mismatch(span,
1016 let (closure_span, found) = found_did
1017 .and_then(|did| self.tcx.hir().get_if_local(did))
1019 let (found_span, found) = self.get_fn_like_arguments(node);
1020 (Some(found_span), found)
1021 }).unwrap_or((found_span, found));
1023 self.report_arg_count_mismatch(span,
1027 found_trait_ty.is_closure())
1031 TraitNotObjectSafe(did) => {
1032 let violations = self.tcx.object_safety_violations(did);
1033 self.tcx.report_object_safety_error(span, did, violations)
1036 // already reported in the query
1037 ConstEvalFailure(err) => {
1038 self.tcx.sess.delay_span_bug(
1040 &format!("constant in type had an ignored error: {:?}", err),
1046 bug!("overflow should be handled before the `report_selection_error` path");
1050 self.note_obligation_cause(&mut err, obligation);
1055 /// If the `Self` type of the unsatisfied trait `trait_ref` implements a trait
1056 /// with the same path as `trait_ref`, a help message about
1057 /// a probable version mismatch is added to `err`
1058 fn note_version_mismatch(
1060 err: &mut DiagnosticBuilder<'_>,
1061 trait_ref: &ty::PolyTraitRef<'tcx>,
1063 let get_trait_impl = |trait_def_id| {
1064 let mut trait_impl = None;
1065 self.tcx.for_each_relevant_impl(trait_def_id, trait_ref.self_ty(), |impl_def_id| {
1066 if trait_impl.is_none() {
1067 trait_impl = Some(impl_def_id);
1072 let required_trait_path = self.tcx.def_path_str(trait_ref.def_id());
1073 let all_traits = self.tcx.all_traits(LOCAL_CRATE);
1074 let traits_with_same_path: std::collections::BTreeSet<_> = all_traits
1076 .filter(|trait_def_id| **trait_def_id != trait_ref.def_id())
1077 .filter(|trait_def_id| self.tcx.def_path_str(**trait_def_id) == required_trait_path)
1079 for trait_with_same_path in traits_with_same_path {
1080 if let Some(impl_def_id) = get_trait_impl(*trait_with_same_path) {
1081 let impl_span = self.tcx.def_span(impl_def_id);
1082 err.span_help(impl_span, "Trait impl with same name found");
1083 let trait_crate = self.tcx.crate_name(trait_with_same_path.krate);
1084 let crate_msg = format!(
1085 "Perhaps two different versions of crate `{}` are being used?",
1088 err.note(&crate_msg);
1092 fn suggest_restricting_param_bound(
1094 err: &mut DiagnosticBuilder<'_>,
1095 trait_ref: &ty::PolyTraitRef<'_>,
1096 body_id: hir::HirId,
1098 let self_ty = trait_ref.self_ty();
1099 let (param_ty, projection) = match &self_ty.kind {
1100 ty::Param(_) => (true, None),
1101 ty::Projection(projection) => (false, Some(projection)),
1105 let mut suggest_restriction = |generics: &hir::Generics, msg| {
1106 let span = generics.where_clause.span_for_predicates_or_empty_place();
1107 if !span.from_expansion() && span.desugaring_kind().is_none() {
1108 err.span_suggestion(
1109 generics.where_clause.span_for_predicates_or_empty_place().shrink_to_hi(),
1110 &format!("consider further restricting {}", msg),
1113 if !generics.where_clause.predicates.is_empty() {
1118 trait_ref.to_predicate(),
1120 Applicability::MachineApplicable,
1125 // FIXME: Add check for trait bound that is already present, particularly `?Sized` so we
1126 // don't suggest `T: Sized + ?Sized`.
1127 let mut hir_id = body_id;
1128 while let Some(node) = self.tcx.hir().find(hir_id) {
1130 hir::Node::TraitItem(hir::TraitItem {
1132 kind: hir::TraitItemKind::Method(..), ..
1133 }) if param_ty && self_ty == self.tcx.types.self_param => {
1134 // Restricting `Self` for a single method.
1135 suggest_restriction(&generics, "`Self`");
1139 hir::Node::Item(hir::Item {
1140 kind: hir::ItemKind::Fn(_, generics, _), ..
1142 hir::Node::TraitItem(hir::TraitItem {
1144 kind: hir::TraitItemKind::Method(..), ..
1146 hir::Node::ImplItem(hir::ImplItem {
1148 kind: hir::ImplItemKind::Method(..), ..
1150 hir::Node::Item(hir::Item {
1151 kind: hir::ItemKind::Trait(_, _, generics, _, _), ..
1153 hir::Node::Item(hir::Item {
1154 kind: hir::ItemKind::Impl(_, _, _, generics, ..), ..
1155 }) if projection.is_some() => {
1156 // Missing associated type bound.
1157 suggest_restriction(&generics, "the associated type");
1161 hir::Node::Item(hir::Item { kind: hir::ItemKind::Struct(_, generics), span, .. }) |
1162 hir::Node::Item(hir::Item { kind: hir::ItemKind::Enum(_, generics), span, .. }) |
1163 hir::Node::Item(hir::Item { kind: hir::ItemKind::Union(_, generics), span, .. }) |
1164 hir::Node::Item(hir::Item {
1165 kind: hir::ItemKind::Trait(_, _, generics, ..), span, ..
1167 hir::Node::Item(hir::Item {
1168 kind: hir::ItemKind::Impl(_, _, _, generics, ..), span, ..
1170 hir::Node::Item(hir::Item {
1171 kind: hir::ItemKind::Fn(_, generics, _), span, ..
1173 hir::Node::Item(hir::Item {
1174 kind: hir::ItemKind::TyAlias(_, generics), span, ..
1176 hir::Node::Item(hir::Item {
1177 kind: hir::ItemKind::TraitAlias(generics, _), span, ..
1179 hir::Node::Item(hir::Item {
1180 kind: hir::ItemKind::OpaqueTy(hir::OpaqueTy { generics, .. }), span, ..
1182 hir::Node::TraitItem(hir::TraitItem { generics, span, .. }) |
1183 hir::Node::ImplItem(hir::ImplItem { generics, span, .. })
1185 // Missing generic type parameter bound.
1186 let restrict_msg = "consider further restricting this bound";
1187 let param_name = self_ty.to_string();
1188 for param in generics.params.iter().filter(|p| {
1189 p.name.ident().as_str() == param_name
1191 if param_name.starts_with("impl ") {
1192 // `impl Trait` in argument:
1193 // `fn foo(x: impl Trait) {}` → `fn foo(t: impl Trait + Trait2) {}`
1194 err.span_suggestion(
1197 // `impl CurrentTrait + MissingTrait`
1198 format!("{} + {}", param.name.ident(), trait_ref),
1199 Applicability::MachineApplicable,
1201 } else if generics.where_clause.predicates.is_empty() &&
1202 param.bounds.is_empty()
1204 // If there are no bounds whatsoever, suggest adding a constraint
1205 // to the type parameter:
1206 // `fn foo<T>(t: T) {}` → `fn foo<T: Trait>(t: T) {}`
1207 err.span_suggestion(
1209 "consider restricting this bound",
1210 format!("{}", trait_ref.to_predicate()),
1211 Applicability::MachineApplicable,
1213 } else if !generics.where_clause.predicates.is_empty() {
1214 // There is a `where` clause, so suggest expanding it:
1215 // `fn foo<T>(t: T) where T: Debug {}` →
1216 // `fn foo<T>(t: T) where T: Debug, T: Trait {}`
1217 err.span_suggestion(
1218 generics.where_clause.span().unwrap().shrink_to_hi(),
1220 "consider further restricting type parameter `{}`",
1223 format!(", {}", trait_ref.to_predicate()),
1224 Applicability::MachineApplicable,
1227 // If there is no `where` clause lean towards constraining to the
1229 // `fn foo<X: Bar, T>(t: T, x: X) {}` → `fn foo<T: Trait>(t: T) {}`
1230 // `fn foo<T: Bar>(t: T) {}` → `fn foo<T: Bar + Trait>(t: T) {}`
1231 let sp = param.span.with_hi(span.hi());
1232 let span = self.tcx.sess.source_map()
1233 .span_through_char(sp, ':');
1234 if sp != param.span && sp != span {
1235 // Only suggest if we have high certainty that the span
1236 // covers the colon in `foo<T: Trait>`.
1237 err.span_suggestion(span, restrict_msg, format!(
1239 trait_ref.to_predicate(),
1240 ), Applicability::MachineApplicable);
1242 err.span_label(param.span, &format!(
1243 "consider adding a `where {}` bound",
1244 trait_ref.to_predicate(),
1252 hir::Node::Crate => return,
1257 hir_id = self.tcx.hir().get_parent_item(hir_id);
1261 /// When encountering an assignment of an unsized trait, like `let x = ""[..];`, provide a
1262 /// suggestion to borrow the initializer in order to use have a slice instead.
1263 fn suggest_borrow_on_unsized_slice(
1265 code: &ObligationCauseCode<'tcx>,
1266 err: &mut DiagnosticBuilder<'tcx>,
1268 if let &ObligationCauseCode::VariableType(hir_id) = code {
1269 let parent_node = self.tcx.hir().get_parent_node(hir_id);
1270 if let Some(Node::Local(ref local)) = self.tcx.hir().find(parent_node) {
1271 if let Some(ref expr) = local.init {
1272 if let hir::ExprKind::Index(_, _) = expr.kind {
1273 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(expr.span) {
1274 err.span_suggestion(
1276 "consider borrowing here",
1277 format!("&{}", snippet),
1278 Applicability::MachineApplicable
1287 fn mk_obligation_for_def_id(
1290 output_ty: Ty<'tcx>,
1291 cause: ObligationCause<'tcx>,
1292 param_env: ty::ParamEnv<'tcx>,
1293 ) -> PredicateObligation<'tcx> {
1294 let new_trait_ref = ty::TraitRef {
1296 substs: self.tcx.mk_substs_trait(output_ty, &[]),
1298 Obligation::new(cause, param_env, new_trait_ref.to_predicate())
1301 /// Given a closure's `DefId`, return the given name of the closure.
1303 /// This doesn't account for reassignments, but it's only used for suggestions.
1304 fn get_closure_name(
1307 err: &mut DiagnosticBuilder<'_>,
1309 ) -> Option<String> {
1310 let get_name = |err: &mut DiagnosticBuilder<'_>, kind: &hir::PatKind| -> Option<String> {
1311 // Get the local name of this closure. This can be inaccurate because
1312 // of the possibility of reassignment, but this should be good enough.
1314 hir::PatKind::Binding(hir::BindingAnnotation::Unannotated, _, name, None) => {
1315 Some(format!("{}", name))
1324 let hir = self.tcx.hir();
1325 let hir_id = hir.as_local_hir_id(def_id)?;
1326 let parent_node = hir.get_parent_node(hir_id);
1327 match hir.find(parent_node) {
1328 Some(hir::Node::Stmt(hir::Stmt {
1329 kind: hir::StmtKind::Local(local), ..
1330 })) => get_name(err, &local.pat.kind),
1331 // Different to previous arm because one is `&hir::Local` and the other
1332 // is `P<hir::Local>`.
1333 Some(hir::Node::Local(local)) => get_name(err, &local.pat.kind),
1338 /// We tried to apply the bound to an `fn` or closure. Check whether calling it would
1339 /// evaluate to a type that *would* satisfy the trait binding. If it would, suggest calling
1340 /// it: `bar(foo)` → `bar(foo())`. This case is *very* likely to be hit if `foo` is `async`.
1343 obligation: &PredicateObligation<'tcx>,
1344 err: &mut DiagnosticBuilder<'_>,
1345 trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
1346 points_at_arg: bool,
1348 let self_ty = trait_ref.self_ty();
1349 let (def_id, output_ty, callable) = match self_ty.kind {
1350 ty::Closure(def_id, substs) => {
1351 (def_id, self.closure_sig(def_id, substs).output(), "closure")
1353 ty::FnDef(def_id, _) => {
1354 (def_id, self_ty.fn_sig(self.tcx).output(), "function")
1358 let msg = format!("use parentheses to call the {}", callable);
1360 let obligation = self.mk_obligation_for_def_id(
1362 output_ty.skip_binder(),
1363 obligation.cause.clone(),
1364 obligation.param_env,
1367 match self.evaluate_obligation(&obligation) {
1368 Ok(EvaluationResult::EvaluatedToOk) |
1369 Ok(EvaluationResult::EvaluatedToOkModuloRegions) |
1370 Ok(EvaluationResult::EvaluatedToAmbig) => {}
1373 let hir = self.tcx.hir();
1374 // Get the name of the callable and the arguments to be used in the suggestion.
1375 let snippet = match hir.get_if_local(def_id) {
1376 Some(hir::Node::Expr(hir::Expr {
1377 kind: hir::ExprKind::Closure(_, decl, _, span, ..),
1380 err.span_label(*span, "consider calling this closure");
1381 let name = match self.get_closure_name(def_id, err, &msg) {
1385 let args = decl.inputs.iter()
1387 .collect::<Vec<_>>()
1389 format!("{}({})", name, args)
1391 Some(hir::Node::Item(hir::Item {
1393 kind: hir::ItemKind::Fn(.., body_id),
1396 err.span_label(ident.span, "consider calling this function");
1397 let body = hir.body(*body_id);
1398 let args = body.params.iter()
1399 .map(|arg| match &arg.pat.kind {
1400 hir::PatKind::Binding(_, _, ident, None)
1401 // FIXME: provide a better suggestion when encountering `SelfLower`, it
1402 // should suggest a method call.
1403 if ident.name != kw::SelfLower => ident.to_string(),
1404 _ => "_".to_string(),
1406 .collect::<Vec<_>>()
1408 format!("{}({})", ident, args)
1413 // When the obligation error has been ensured to have been caused by
1414 // an argument, the `obligation.cause.span` points at the expression
1415 // of the argument, so we can provide a suggestion. This is signaled
1416 // by `points_at_arg`. Otherwise, we give a more general note.
1417 err.span_suggestion(
1418 obligation.cause.span,
1421 Applicability::HasPlaceholders,
1424 err.help(&format!("{}: `{}`", msg, snippet));
1428 fn suggest_add_reference_to_arg(
1430 obligation: &PredicateObligation<'tcx>,
1431 err: &mut DiagnosticBuilder<'tcx>,
1432 trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
1433 points_at_arg: bool,
1434 has_custom_message: bool,
1440 let span = obligation.cause.span;
1441 let param_env = obligation.param_env;
1442 let trait_ref = trait_ref.skip_binder();
1444 if let ObligationCauseCode::ImplDerivedObligation(obligation) = &obligation.cause.code {
1445 // Try to apply the original trait binding obligation by borrowing.
1446 let self_ty = trait_ref.self_ty();
1447 let found = self_ty.to_string();
1448 let new_self_ty = self.tcx.mk_imm_ref(self.tcx.lifetimes.re_static, self_ty);
1449 let substs = self.tcx.mk_substs_trait(new_self_ty, &[]);
1450 let new_trait_ref = ty::TraitRef::new(obligation.parent_trait_ref.def_id(), substs);
1451 let new_obligation = Obligation::new(
1452 ObligationCause::dummy(),
1454 new_trait_ref.to_predicate(),
1456 if self.predicate_must_hold_modulo_regions(&new_obligation) {
1457 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
1458 // We have a very specific type of error, where just borrowing this argument
1459 // might solve the problem. In cases like this, the important part is the
1460 // original type obligation, not the last one that failed, which is arbitrary.
1461 // Because of this, we modify the error to refer to the original obligation and
1462 // return early in the caller.
1464 "the trait bound `{}: {}` is not satisfied",
1466 obligation.parent_trait_ref.skip_binder(),
1468 if has_custom_message {
1471 err.message = vec![(msg, Style::NoStyle)];
1473 if snippet.starts_with('&') {
1474 // This is already a literal borrow and the obligation is failing
1475 // somewhere else in the obligation chain. Do not suggest non-sense.
1478 err.span_label(span, &format!(
1479 "expected an implementor of trait `{}`",
1480 obligation.parent_trait_ref.skip_binder(),
1482 err.span_suggestion(
1484 "consider borrowing here",
1485 format!("&{}", snippet),
1486 Applicability::MaybeIncorrect,
1495 /// Whenever references are used by mistake, like `for (i, e) in &vec.iter().enumerate()`,
1496 /// suggest removing these references until we reach a type that implements the trait.
1497 fn suggest_remove_reference(
1499 obligation: &PredicateObligation<'tcx>,
1500 err: &mut DiagnosticBuilder<'tcx>,
1501 trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
1503 let trait_ref = trait_ref.skip_binder();
1504 let span = obligation.cause.span;
1506 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
1507 let refs_number = snippet.chars()
1508 .filter(|c| !c.is_whitespace())
1509 .take_while(|c| *c == '&')
1511 if let Some('\'') = snippet.chars()
1512 .filter(|c| !c.is_whitespace())
1515 { // Do not suggest removal of borrow from type arguments.
1519 let mut trait_type = trait_ref.self_ty();
1521 for refs_remaining in 0..refs_number {
1522 if let ty::Ref(_, t_type, _) = trait_type.kind {
1523 trait_type = t_type;
1525 let new_obligation = self.mk_obligation_for_def_id(
1528 ObligationCause::dummy(),
1529 obligation.param_env,
1532 if self.predicate_may_hold(&new_obligation) {
1533 let sp = self.tcx.sess.source_map()
1534 .span_take_while(span, |c| c.is_whitespace() || *c == '&');
1536 let remove_refs = refs_remaining + 1;
1537 let format_str = format!("consider removing {} leading `&`-references",
1540 err.span_suggestion_short(
1541 sp, &format_str, String::new(), Applicability::MachineApplicable
1552 /// Check if the trait bound is implemented for a different mutability and note it in the
1554 fn suggest_change_mut(
1556 obligation: &PredicateObligation<'tcx>,
1557 err: &mut DiagnosticBuilder<'tcx>,
1558 trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
1559 points_at_arg: bool,
1561 let span = obligation.cause.span;
1562 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
1563 let refs_number = snippet.chars()
1564 .filter(|c| !c.is_whitespace())
1565 .take_while(|c| *c == '&')
1567 if let Some('\'') = snippet.chars()
1568 .filter(|c| !c.is_whitespace())
1571 { // Do not suggest removal of borrow from type arguments.
1574 let trait_ref = self.resolve_vars_if_possible(trait_ref);
1575 if trait_ref.has_infer_types() {
1576 // Do not ICE while trying to find if a reborrow would succeed on a trait with
1577 // unresolved bindings.
1581 if let ty::Ref(region, t_type, mutability) = trait_ref.skip_binder().self_ty().kind {
1582 let trait_type = match mutability {
1583 hir::Mutability::Mutable => self.tcx.mk_imm_ref(region, t_type),
1584 hir::Mutability::Immutable => self.tcx.mk_mut_ref(region, t_type),
1587 let new_obligation = self.mk_obligation_for_def_id(
1588 trait_ref.skip_binder().def_id,
1590 ObligationCause::dummy(),
1591 obligation.param_env,
1594 if self.evaluate_obligation_no_overflow(
1596 ).must_apply_modulo_regions() {
1597 let sp = self.tcx.sess.source_map()
1598 .span_take_while(span, |c| c.is_whitespace() || *c == '&');
1600 mutability == hir::Mutability::Immutable &&
1603 err.span_suggestion(
1605 "consider changing this borrow's mutability",
1606 "&mut ".to_string(),
1607 Applicability::MachineApplicable,
1611 "`{}` is implemented for `{:?}`, but not for `{:?}`",
1614 trait_ref.skip_binder().self_ty(),
1622 fn suggest_semicolon_removal(
1624 obligation: &PredicateObligation<'tcx>,
1625 err: &mut DiagnosticBuilder<'tcx>,
1627 trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
1629 let hir = self.tcx.hir();
1630 let parent_node = hir.get_parent_node(obligation.cause.body_id);
1631 let node = hir.find(parent_node);
1632 if let Some(hir::Node::Item(hir::Item {
1633 kind: hir::ItemKind::Fn(sig, _, body_id),
1636 let body = hir.body(*body_id);
1637 if let hir::ExprKind::Block(blk, _) = &body.value.kind {
1638 if sig.decl.output.span().overlaps(span) && blk.expr.is_none() &&
1639 "()" == &trait_ref.self_ty().to_string()
1641 // FIXME(estebank): When encountering a method with a trait
1642 // bound not satisfied in the return type with a body that has
1643 // no return, suggest removal of semicolon on last statement.
1644 // Once that is added, close #54771.
1645 if let Some(ref stmt) = blk.stmts.last() {
1646 let sp = self.tcx.sess.source_map().end_point(stmt.span);
1647 err.span_label(sp, "consider removing this semicolon");
1654 /// Given some node representing a fn-like thing in the HIR map,
1655 /// returns a span and `ArgKind` information that describes the
1656 /// arguments it expects. This can be supplied to
1657 /// `report_arg_count_mismatch`.
1658 pub fn get_fn_like_arguments(&self, node: Node<'_>) -> (Span, Vec<ArgKind>) {
1660 Node::Expr(&hir::Expr {
1661 kind: hir::ExprKind::Closure(_, ref _decl, id, span, _),
1664 (self.tcx.sess.source_map().def_span(span),
1665 self.tcx.hir().body(id).params.iter()
1668 kind: hir::PatKind::Tuple(ref args, _),
1674 args.iter().map(|pat| {
1675 let snippet = self.tcx.sess.source_map()
1676 .span_to_snippet(pat.span).unwrap();
1677 (snippet, "_".to_owned())
1678 }).collect::<Vec<_>>(),
1681 let name = self.tcx.sess.source_map()
1682 .span_to_snippet(arg.pat.span).unwrap();
1683 ArgKind::Arg(name, "_".to_owned())
1686 .collect::<Vec<ArgKind>>())
1688 Node::Item(&hir::Item {
1690 kind: hir::ItemKind::Fn(ref sig, ..),
1693 Node::ImplItem(&hir::ImplItem {
1695 kind: hir::ImplItemKind::Method(ref sig, _),
1698 Node::TraitItem(&hir::TraitItem {
1700 kind: hir::TraitItemKind::Method(ref sig, _),
1703 (self.tcx.sess.source_map().def_span(span), sig.decl.inputs.iter()
1704 .map(|arg| match arg.clone().kind {
1705 hir::TyKind::Tup(ref tys) => ArgKind::Tuple(
1707 vec![("_".to_owned(), "_".to_owned()); tys.len()]
1709 _ => ArgKind::empty()
1710 }).collect::<Vec<ArgKind>>())
1712 Node::Ctor(ref variant_data) => {
1713 let span = variant_data.ctor_hir_id()
1714 .map(|hir_id| self.tcx.hir().span(hir_id))
1715 .unwrap_or(DUMMY_SP);
1716 let span = self.tcx.sess.source_map().def_span(span);
1718 (span, vec![ArgKind::empty(); variant_data.fields().len()])
1720 _ => panic!("non-FnLike node found: {:?}", node),
1724 /// Reports an error when the number of arguments needed by a
1725 /// trait match doesn't match the number that the expression
1727 pub fn report_arg_count_mismatch(
1730 found_span: Option<Span>,
1731 expected_args: Vec<ArgKind>,
1732 found_args: Vec<ArgKind>,
1734 ) -> DiagnosticBuilder<'tcx> {
1735 let kind = if is_closure { "closure" } else { "function" };
1737 let args_str = |arguments: &[ArgKind], other: &[ArgKind]| {
1738 let arg_length = arguments.len();
1739 let distinct = match &other[..] {
1740 &[ArgKind::Tuple(..)] => true,
1743 match (arg_length, arguments.get(0)) {
1744 (1, Some(&ArgKind::Tuple(_, ref fields))) => {
1745 format!("a single {}-tuple as argument", fields.len())
1747 _ => format!("{} {}argument{}",
1749 if distinct && arg_length > 1 { "distinct " } else { "" },
1750 pluralize!(arg_length))
1754 let expected_str = args_str(&expected_args, &found_args);
1755 let found_str = args_str(&found_args, &expected_args);
1757 let mut err = struct_span_err!(
1761 "{} is expected to take {}, but it takes {}",
1767 err.span_label(span, format!("expected {} that takes {}", kind, expected_str));
1769 if let Some(found_span) = found_span {
1770 err.span_label(found_span, format!("takes {}", found_str));
1773 // ^^^^^^^^-- def_span
1777 let prefix_span = self.tcx.sess.source_map().span_until_non_whitespace(found_span);
1780 let pipe_span = if let Some(span) = found_span.trim_start(prefix_span) {
1786 // Suggest to take and ignore the arguments with expected_args_length `_`s if
1787 // found arguments is empty (assume the user just wants to ignore args in this case).
1788 // For example, if `expected_args_length` is 2, suggest `|_, _|`.
1789 if found_args.is_empty() && is_closure {
1790 let underscores = vec!["_"; expected_args.len()].join(", ");
1791 err.span_suggestion(
1794 "consider changing the closure to take and ignore the expected argument{}",
1795 if expected_args.len() < 2 {
1801 format!("|{}|", underscores),
1802 Applicability::MachineApplicable,
1806 if let &[ArgKind::Tuple(_, ref fields)] = &found_args[..] {
1807 if fields.len() == expected_args.len() {
1808 let sugg = fields.iter()
1809 .map(|(name, _)| name.to_owned())
1810 .collect::<Vec<String>>()
1812 err.span_suggestion(
1814 "change the closure to take multiple arguments instead of a single tuple",
1815 format!("|{}|", sugg),
1816 Applicability::MachineApplicable,
1820 if let &[ArgKind::Tuple(_, ref fields)] = &expected_args[..] {
1821 if fields.len() == found_args.len() && is_closure {
1825 .map(|arg| match arg {
1826 ArgKind::Arg(name, _) => name.to_owned(),
1827 _ => "_".to_owned(),
1829 .collect::<Vec<String>>()
1831 // add type annotations if available
1832 if found_args.iter().any(|arg| match arg {
1833 ArgKind::Arg(_, ty) => ty != "_",
1838 .map(|(_, ty)| ty.to_owned())
1839 .collect::<Vec<String>>()
1845 err.span_suggestion(
1847 "change the closure to accept a tuple instead of individual arguments",
1849 Applicability::MachineApplicable,
1858 fn report_closure_arg_mismatch(
1861 found_span: Option<Span>,
1862 expected_ref: ty::PolyTraitRef<'tcx>,
1863 found: ty::PolyTraitRef<'tcx>,
1864 ) -> DiagnosticBuilder<'tcx> {
1865 fn build_fn_sig_string<'tcx>(tcx: TyCtxt<'tcx>, trait_ref: &ty::TraitRef<'tcx>) -> String {
1866 let inputs = trait_ref.substs.type_at(1);
1867 let sig = if let ty::Tuple(inputs) = inputs.kind {
1869 inputs.iter().map(|k| k.expect_ty()),
1870 tcx.mk_ty_infer(ty::TyVar(ty::TyVid { index: 0 })),
1872 hir::Unsafety::Normal,
1873 ::rustc_target::spec::abi::Abi::Rust
1877 ::std::iter::once(inputs),
1878 tcx.mk_ty_infer(ty::TyVar(ty::TyVid { index: 0 })),
1880 hir::Unsafety::Normal,
1881 ::rustc_target::spec::abi::Abi::Rust
1884 ty::Binder::bind(sig).to_string()
1887 let argument_is_closure = expected_ref.skip_binder().substs.type_at(0).is_closure();
1888 let mut err = struct_span_err!(self.tcx.sess, span, E0631,
1889 "type mismatch in {} arguments",
1890 if argument_is_closure { "closure" } else { "function" });
1892 let found_str = format!(
1893 "expected signature of `{}`",
1894 build_fn_sig_string(self.tcx, found.skip_binder())
1896 err.span_label(span, found_str);
1898 let found_span = found_span.unwrap_or(span);
1899 let expected_str = format!(
1900 "found signature of `{}`",
1901 build_fn_sig_string(self.tcx, expected_ref.skip_binder())
1903 err.span_label(found_span, expected_str);
1909 impl<'tcx> TyCtxt<'tcx> {
1910 pub fn recursive_type_with_infinite_size_error(self,
1912 -> DiagnosticBuilder<'tcx>
1914 assert!(type_def_id.is_local());
1915 let span = self.hir().span_if_local(type_def_id).unwrap();
1916 let span = self.sess.source_map().def_span(span);
1917 let mut err = struct_span_err!(self.sess, span, E0072,
1918 "recursive type `{}` has infinite size",
1919 self.def_path_str(type_def_id));
1920 err.span_label(span, "recursive type has infinite size");
1921 err.help(&format!("insert indirection (e.g., a `Box`, `Rc`, or `&`) \
1922 at some point to make `{}` representable",
1923 self.def_path_str(type_def_id)));
1927 pub fn report_object_safety_error(
1930 trait_def_id: DefId,
1931 violations: Vec<ObjectSafetyViolation>,
1932 ) -> DiagnosticBuilder<'tcx> {
1933 let trait_str = self.def_path_str(trait_def_id);
1934 let span = self.sess.source_map().def_span(span);
1935 let mut err = struct_span_err!(
1936 self.sess, span, E0038,
1937 "the trait `{}` cannot be made into an object",
1939 err.span_label(span, format!("the trait `{}` cannot be made into an object", trait_str));
1941 let mut reported_violations = FxHashSet::default();
1942 for violation in violations {
1943 if reported_violations.insert(violation.clone()) {
1944 match violation.span() {
1945 Some(span) => err.span_label(span, violation.error_msg()),
1946 None => err.note(&violation.error_msg()),
1951 if self.sess.trait_methods_not_found.borrow().contains(&span) {
1952 // Avoid emitting error caused by non-existing method (#58734)
1960 impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
1961 fn maybe_report_ambiguity(
1963 obligation: &PredicateObligation<'tcx>,
1964 body_id: Option<hir::BodyId>,
1966 // Unable to successfully determine, probably means
1967 // insufficient type information, but could mean
1968 // ambiguous impls. The latter *ought* to be a
1969 // coherence violation, so we don't report it here.
1971 let predicate = self.resolve_vars_if_possible(&obligation.predicate);
1972 let span = obligation.cause.span;
1975 "maybe_report_ambiguity(predicate={:?}, obligation={:?} body_id={:?}, code={:?})",
1979 obligation.cause.code,
1982 // Ambiguity errors are often caused as fallout from earlier
1983 // errors. So just ignore them if this infcx is tainted.
1984 if self.is_tainted_by_errors() {
1989 ty::Predicate::Trait(ref data) => {
1990 let trait_ref = data.to_poly_trait_ref();
1991 let self_ty = trait_ref.self_ty();
1992 debug!("self_ty {:?} {:?} trait_ref {:?}", self_ty, self_ty.kind, trait_ref);
1994 if predicate.references_error() {
1997 // Typically, this ambiguity should only happen if
1998 // there are unresolved type inference variables
1999 // (otherwise it would suggest a coherence
2000 // failure). But given #21974 that is not necessarily
2001 // the case -- we can have multiple where clauses that
2002 // are only distinguished by a region, which results
2003 // in an ambiguity even when all types are fully
2004 // known, since we don't dispatch based on region
2007 // This is kind of a hack: it frequently happens that some earlier
2008 // error prevents types from being fully inferred, and then we get
2009 // a bunch of uninteresting errors saying something like "<generic
2010 // #0> doesn't implement Sized". It may even be true that we
2011 // could just skip over all checks where the self-ty is an
2012 // inference variable, but I was afraid that there might be an
2013 // inference variable created, registered as an obligation, and
2014 // then never forced by writeback, and hence by skipping here we'd
2015 // be ignoring the fact that we don't KNOW the type works
2016 // out. Though even that would probably be harmless, given that
2017 // we're only talking about builtin traits, which are known to be
2018 // inhabited. We used to check for `self.tcx.sess.has_errors()` to
2019 // avoid inundating the user with unnecessary errors, but we now
2020 // check upstream for type errors and dont add the obligations to
2021 // begin with in those cases.
2023 self.tcx.lang_items().sized_trait()
2024 .map_or(false, |sized_id| sized_id == trait_ref.def_id())
2026 self.need_type_info_err(body_id, span, self_ty).emit();
2028 let mut err = struct_span_err!(
2032 "type annotations needed: cannot resolve `{}`",
2035 self.note_obligation_cause(&mut err, obligation);
2040 ty::Predicate::WellFormed(ty) => {
2041 // Same hacky approach as above to avoid deluging user
2042 // with error messages.
2043 if !ty.references_error() && !self.tcx.sess.has_errors() {
2044 self.need_type_info_err(body_id, span, ty).emit();
2048 ty::Predicate::Subtype(ref data) => {
2049 if data.references_error() || self.tcx.sess.has_errors() {
2050 // no need to overload user in such cases
2052 let &SubtypePredicate { a_is_expected: _, a, b } = data.skip_binder();
2053 // both must be type variables, or the other would've been instantiated
2054 assert!(a.is_ty_var() && b.is_ty_var());
2055 self.need_type_info_err(body_id,
2056 obligation.cause.span,
2062 if !self.tcx.sess.has_errors() {
2063 let mut err = struct_span_err!(
2065 obligation.cause.span,
2067 "type annotations needed: cannot resolve `{}`",
2070 self.note_obligation_cause(&mut err, obligation);
2077 /// Returns `true` if the trait predicate may apply for *some* assignment
2078 /// to the type parameters.
2079 fn predicate_can_apply(
2081 param_env: ty::ParamEnv<'tcx>,
2082 pred: ty::PolyTraitRef<'tcx>,
2084 struct ParamToVarFolder<'a, 'tcx> {
2085 infcx: &'a InferCtxt<'a, 'tcx>,
2086 var_map: FxHashMap<Ty<'tcx>, Ty<'tcx>>,
2089 impl<'a, 'tcx> TypeFolder<'tcx> for ParamToVarFolder<'a, 'tcx> {
2090 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> { self.infcx.tcx }
2092 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
2093 if let ty::Param(ty::ParamTy {name, .. }) = ty.kind {
2094 let infcx = self.infcx;
2095 self.var_map.entry(ty).or_insert_with(||
2097 TypeVariableOrigin {
2098 kind: TypeVariableOriginKind::TypeParameterDefinition(name),
2104 ty.super_fold_with(self)
2110 let mut selcx = SelectionContext::new(self);
2112 let cleaned_pred = pred.fold_with(&mut ParamToVarFolder {
2114 var_map: Default::default()
2117 let cleaned_pred = super::project::normalize(
2120 ObligationCause::dummy(),
2124 let obligation = Obligation::new(
2125 ObligationCause::dummy(),
2127 cleaned_pred.to_predicate()
2130 self.predicate_may_hold(&obligation)
2134 fn note_obligation_cause(
2136 err: &mut DiagnosticBuilder<'_>,
2137 obligation: &PredicateObligation<'tcx>,
2139 // First, attempt to add note to this error with an async-await-specific
2140 // message, and fall back to regular note otherwise.
2141 if !self.note_obligation_cause_for_async_await(err, obligation) {
2142 self.note_obligation_cause_code(err, &obligation.predicate, &obligation.cause.code,
2147 /// Adds an async-await specific note to the diagnostic:
2149 /// ```ignore (diagnostic)
2150 /// note: future does not implement `std::marker::Send` because this value is used across an
2152 /// --> $DIR/issue-64130-non-send-future-diags.rs:15:5
2154 /// LL | let g = x.lock().unwrap();
2155 /// | - has type `std::sync::MutexGuard<'_, u32>`
2156 /// LL | baz().await;
2157 /// | ^^^^^^^^^^^ await occurs here, with `g` maybe used later
2159 /// | - `g` is later dropped here
2162 /// Returns `true` if an async-await specific note was added to the diagnostic.
2163 fn note_obligation_cause_for_async_await(
2165 err: &mut DiagnosticBuilder<'_>,
2166 obligation: &PredicateObligation<'tcx>,
2168 debug!("note_obligation_cause_for_async_await: obligation.predicate={:?} \
2169 obligation.cause.span={:?}", obligation.predicate, obligation.cause.span);
2170 let source_map = self.tcx.sess.source_map();
2172 // Look into the obligation predicate to determine the type in the generator which meant
2173 // that the predicate was not satisifed.
2174 let (trait_ref, target_ty) = match obligation.predicate {
2175 ty::Predicate::Trait(trait_predicate) =>
2176 (trait_predicate.skip_binder().trait_ref, trait_predicate.skip_binder().self_ty()),
2179 debug!("note_obligation_cause_for_async_await: target_ty={:?}", target_ty);
2181 // Attempt to detect an async-await error by looking at the obligation causes, looking
2182 // for only generators, generator witnesses, opaque types or `std::future::GenFuture` to
2185 // When a future does not implement a trait because of a captured type in one of the
2186 // generators somewhere in the call stack, then the result is a chain of obligations.
2187 // Given a `async fn` A that calls a `async fn` B which captures a non-send type and that
2188 // future is passed as an argument to a function C which requires a `Send` type, then the
2189 // chain looks something like this:
2191 // - `BuiltinDerivedObligation` with a generator witness (B)
2192 // - `BuiltinDerivedObligation` with a generator (B)
2193 // - `BuiltinDerivedObligation` with `std::future::GenFuture` (B)
2194 // - `BuiltinDerivedObligation` with `impl std::future::Future` (B)
2195 // - `BuiltinDerivedObligation` with `impl std::future::Future` (B)
2196 // - `BuiltinDerivedObligation` with a generator witness (A)
2197 // - `BuiltinDerivedObligation` with a generator (A)
2198 // - `BuiltinDerivedObligation` with `std::future::GenFuture` (A)
2199 // - `BuiltinDerivedObligation` with `impl std::future::Future` (A)
2200 // - `BuiltinDerivedObligation` with `impl std::future::Future` (A)
2201 // - `BindingObligation` with `impl_send (Send requirement)
2203 // The first obligations in the chain can be used to get the details of the type that is
2204 // captured but the entire chain must be inspected to detect this case.
2205 let mut generator = None;
2206 let mut next_code = Some(&obligation.cause.code);
2207 while let Some(code) = next_code {
2208 debug!("note_obligation_cause_for_async_await: code={:?}", code);
2210 ObligationCauseCode::BuiltinDerivedObligation(derived_obligation) |
2211 ObligationCauseCode::ImplDerivedObligation(derived_obligation) => {
2212 debug!("note_obligation_cause_for_async_await: self_ty.kind={:?}",
2213 derived_obligation.parent_trait_ref.self_ty().kind);
2214 match derived_obligation.parent_trait_ref.self_ty().kind {
2215 ty::Adt(ty::AdtDef { did, .. }, ..) if
2216 self.tcx.is_diagnostic_item(sym::gen_future, *did) => {},
2217 ty::Generator(did, ..) => generator = generator.or(Some(did)),
2218 ty::GeneratorWitness(_) | ty::Opaque(..) => {},
2222 next_code = Some(derived_obligation.parent_code.as_ref());
2224 ObligationCauseCode::ItemObligation(_) | ObligationCauseCode::BindingObligation(..)
2225 if generator.is_some() => break,
2230 let generator_did = generator.expect("can only reach this if there was a generator");
2232 // Only continue to add a note if the generator is from an `async` function.
2233 let parent_node = self.tcx.parent(generator_did)
2234 .and_then(|parent_did| self.tcx.hir().get_if_local(parent_did));
2235 debug!("note_obligation_cause_for_async_await: parent_node={:?}", parent_node);
2236 if let Some(hir::Node::Item(hir::Item {
2237 kind: hir::ItemKind::Fn(sig, _, _),
2240 debug!("note_obligation_cause_for_async_await: header={:?}", sig.header);
2241 if sig.header.asyncness != hir::IsAsync::Async {
2246 let span = self.tcx.def_span(generator_did);
2247 let tables = self.tcx.typeck_tables_of(generator_did);
2248 debug!("note_obligation_cause_for_async_await: generator_did={:?} span={:?} ",
2249 generator_did, span);
2251 // Look for a type inside the generator interior that matches the target type to get
2253 let target_span = tables.generator_interior_types.iter()
2254 .find(|ty::GeneratorInteriorTypeCause { ty, .. }| ty::TyS::same_type(*ty, target_ty))
2255 .map(|ty::GeneratorInteriorTypeCause { span, scope_span, .. }|
2256 (span, source_map.span_to_snippet(*span), scope_span));
2257 if let Some((target_span, Ok(snippet), scope_span)) = target_span {
2258 // Look at the last interior type to get a span for the `.await`.
2259 let await_span = tables.generator_interior_types.iter().map(|i| i.span).last().unwrap();
2260 let mut span = MultiSpan::from_span(await_span);
2261 span.push_span_label(
2262 await_span, format!("await occurs here, with `{}` maybe used later", snippet));
2264 span.push_span_label(*target_span, format!("has type `{}`", target_ty));
2266 // If available, use the scope span to annotate the drop location.
2267 if let Some(scope_span) = scope_span {
2268 span.push_span_label(
2269 source_map.end_point(*scope_span),
2270 format!("`{}` is later dropped here", snippet),
2274 err.span_note(span, &format!(
2275 "future does not implement `{}` as this value is used across an await",
2279 // Add a note for the item obligation that remains - normally a note pointing to the
2280 // bound that introduced the obligation (e.g. `T: Send`).
2281 debug!("note_obligation_cause_for_async_await: next_code={:?}", next_code);
2282 self.note_obligation_cause_code(
2284 &obligation.predicate,
2295 fn note_obligation_cause_code<T>(&self,
2296 err: &mut DiagnosticBuilder<'_>,
2298 cause_code: &ObligationCauseCode<'tcx>,
2299 obligated_types: &mut Vec<&ty::TyS<'tcx>>)
2300 where T: fmt::Display
2304 ObligationCauseCode::ExprAssignable |
2305 ObligationCauseCode::MatchExpressionArm { .. } |
2306 ObligationCauseCode::MatchExpressionArmPattern { .. } |
2307 ObligationCauseCode::IfExpression { .. } |
2308 ObligationCauseCode::IfExpressionWithNoElse |
2309 ObligationCauseCode::MainFunctionType |
2310 ObligationCauseCode::StartFunctionType |
2311 ObligationCauseCode::IntrinsicType |
2312 ObligationCauseCode::MethodReceiver |
2313 ObligationCauseCode::ReturnNoExpression |
2314 ObligationCauseCode::MiscObligation => {}
2315 ObligationCauseCode::SliceOrArrayElem => {
2316 err.note("slice and array elements must have `Sized` type");
2318 ObligationCauseCode::TupleElem => {
2319 err.note("only the last element of a tuple may have a dynamically sized type");
2321 ObligationCauseCode::ProjectionWf(data) => {
2323 "required so that the projection `{}` is well-formed",
2327 ObligationCauseCode::ReferenceOutlivesReferent(ref_ty) => {
2329 "required so that reference `{}` does not outlive its referent",
2333 ObligationCauseCode::ObjectTypeBound(object_ty, region) => {
2335 "required so that the lifetime bound of `{}` for `{}` is satisfied",
2340 ObligationCauseCode::ItemObligation(item_def_id) => {
2341 let item_name = tcx.def_path_str(item_def_id);
2342 let msg = format!("required by `{}`", item_name);
2344 if let Some(sp) = tcx.hir().span_if_local(item_def_id) {
2345 let sp = tcx.sess.source_map().def_span(sp);
2346 err.span_label(sp, &msg);
2351 ObligationCauseCode::BindingObligation(item_def_id, span) => {
2352 let item_name = tcx.def_path_str(item_def_id);
2353 let msg = format!("required by this bound in `{}`", item_name);
2354 if let Some(ident) = tcx.opt_item_name(item_def_id) {
2355 err.span_label(ident.span, "");
2357 if span != DUMMY_SP {
2358 err.span_label(span, &msg);
2363 ObligationCauseCode::ObjectCastObligation(object_ty) => {
2364 err.note(&format!("required for the cast to the object type `{}`",
2365 self.ty_to_string(object_ty)));
2367 ObligationCauseCode::Coercion { source: _, target } => {
2368 err.note(&format!("required by cast to type `{}`",
2369 self.ty_to_string(target)));
2371 ObligationCauseCode::RepeatVec(suggest_const_in_array_repeat_expressions) => {
2372 err.note("the `Copy` trait is required because the \
2373 repeated element will be copied");
2374 if suggest_const_in_array_repeat_expressions {
2375 err.note("this array initializer can be evaluated at compile-time, for more \
2376 information, see issue \
2377 https://github.com/rust-lang/rust/issues/49147");
2378 if tcx.sess.opts.unstable_features.is_nightly_build() {
2379 err.help("add `#![feature(const_in_array_repeat_expressions)]` to the \
2380 crate attributes to enable");
2384 ObligationCauseCode::VariableType(_) => {
2385 err.note("all local variables must have a statically known size");
2386 if !self.tcx.features().unsized_locals {
2387 err.help("unsized locals are gated as an unstable feature");
2390 ObligationCauseCode::SizedArgumentType => {
2391 err.note("all function arguments must have a statically known size");
2392 if !self.tcx.features().unsized_locals {
2393 err.help("unsized locals are gated as an unstable feature");
2396 ObligationCauseCode::SizedReturnType => {
2397 err.note("the return type of a function must have a \
2398 statically known size");
2400 ObligationCauseCode::SizedYieldType => {
2401 err.note("the yield type of a generator must have a \
2402 statically known size");
2404 ObligationCauseCode::AssignmentLhsSized => {
2405 err.note("the left-hand-side of an assignment must have a statically known size");
2407 ObligationCauseCode::TupleInitializerSized => {
2408 err.note("tuples must have a statically known size to be initialized");
2410 ObligationCauseCode::StructInitializerSized => {
2411 err.note("structs must have a statically known size to be initialized");
2413 ObligationCauseCode::FieldSized { adt_kind: ref item, last } => {
2415 AdtKind::Struct => {
2417 err.note("the last field of a packed struct may only have a \
2418 dynamically sized type if it does not need drop to be run");
2420 err.note("only the last field of a struct may have a dynamically \
2425 err.note("no field of a union may have a dynamically sized type");
2428 err.note("no field of an enum variant may have a dynamically sized type");
2432 ObligationCauseCode::ConstSized => {
2433 err.note("constant expressions must have a statically known size");
2435 ObligationCauseCode::ConstPatternStructural => {
2436 err.note("constants used for pattern-matching must derive `PartialEq` and `Eq`");
2438 ObligationCauseCode::SharedStatic => {
2439 err.note("shared static variables must have a type that implements `Sync`");
2441 ObligationCauseCode::BuiltinDerivedObligation(ref data) => {
2442 let parent_trait_ref = self.resolve_vars_if_possible(&data.parent_trait_ref);
2443 let ty = parent_trait_ref.skip_binder().self_ty();
2444 err.note(&format!("required because it appears within the type `{}`", ty));
2445 obligated_types.push(ty);
2447 let parent_predicate = parent_trait_ref.to_predicate();
2448 if !self.is_recursive_obligation(obligated_types, &data.parent_code) {
2449 self.note_obligation_cause_code(err,
2455 ObligationCauseCode::ImplDerivedObligation(ref data) => {
2456 let parent_trait_ref = self.resolve_vars_if_possible(&data.parent_trait_ref);
2458 &format!("required because of the requirements on the impl of `{}` for `{}`",
2460 parent_trait_ref.skip_binder().self_ty()));
2461 let parent_predicate = parent_trait_ref.to_predicate();
2462 self.note_obligation_cause_code(err,
2467 ObligationCauseCode::CompareImplMethodObligation { .. } => {
2469 &format!("the requirement `{}` appears on the impl method \
2470 but not on the corresponding trait method",
2473 ObligationCauseCode::ReturnType |
2474 ObligationCauseCode::ReturnValue(_) |
2475 ObligationCauseCode::BlockTailExpression(_) => (),
2476 ObligationCauseCode::TrivialBound => {
2477 err.help("see issue #48214");
2478 if tcx.sess.opts.unstable_features.is_nightly_build() {
2479 err.help("add `#![feature(trivial_bounds)]` to the \
2480 crate attributes to enable",
2484 ObligationCauseCode::AssocTypeBound(ref data) => {
2485 err.span_label(data.original, "associated type defined here");
2486 if let Some(sp) = data.impl_span {
2487 err.span_label(sp, "in this `impl` item");
2489 for sp in &data.bounds {
2490 err.span_label(*sp, "restricted in this bound");
2496 fn suggest_new_overflow_limit(&self, err: &mut DiagnosticBuilder<'_>) {
2497 let current_limit = self.tcx.sess.recursion_limit.get();
2498 let suggested_limit = current_limit * 2;
2499 err.help(&format!("consider adding a `#![recursion_limit=\"{}\"]` attribute to your crate",
2503 fn is_recursive_obligation(&self,
2504 obligated_types: &mut Vec<&ty::TyS<'tcx>>,
2505 cause_code: &ObligationCauseCode<'tcx>) -> bool {
2506 if let ObligationCauseCode::BuiltinDerivedObligation(ref data) = cause_code {
2507 let parent_trait_ref = self.resolve_vars_if_possible(&data.parent_trait_ref);
2509 if obligated_types.iter().any(|ot| ot == &parent_trait_ref.skip_binder().self_ty()) {
2517 /// Summarizes information
2520 /// An argument of non-tuple type. Parameters are (name, ty)
2521 Arg(String, String),
2523 /// An argument of tuple type. For a "found" argument, the span is
2524 /// the locationo in the source of the pattern. For a "expected"
2525 /// argument, it will be None. The vector is a list of (name, ty)
2526 /// strings for the components of the tuple.
2527 Tuple(Option<Span>, Vec<(String, String)>),
2531 fn empty() -> ArgKind {
2532 ArgKind::Arg("_".to_owned(), "_".to_owned())
2535 /// Creates an `ArgKind` from the expected type of an
2536 /// argument. It has no name (`_`) and an optional source span.
2537 pub fn from_expected_ty(t: Ty<'_>, span: Option<Span>) -> ArgKind {
2539 ty::Tuple(ref tys) => ArgKind::Tuple(
2542 .map(|ty| ("_".to_owned(), ty.to_string()))
2543 .collect::<Vec<_>>()
2545 _ => ArgKind::Arg("_".to_owned(), t.to_string()),