2 ConstEvalFailure, EvaluationResult, FulfillmentError, FulfillmentErrorCode,
3 MismatchedProjectionTypes, ObjectSafetyViolation, Obligation, ObligationCause,
4 ObligationCauseCode, OnUnimplementedDirective, OnUnimplementedNote,
5 OutputTypeParameterMismatch, Overflow, PredicateObligation, SelectionContext, SelectionError,
10 use crate::hir::def_id::DefId;
12 use crate::infer::error_reporting::TypeAnnotationNeeded as ErrorCode;
13 use crate::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
14 use crate::infer::{self, InferCtxt};
15 use crate::session::DiagnosticMessageId;
16 use crate::ty::error::ExpectedFound;
17 use crate::ty::fast_reject;
18 use crate::ty::fold::TypeFolder;
19 use crate::ty::subst::Subst;
20 use crate::ty::GenericParamDefKind;
21 use crate::ty::SubtypePredicate;
22 use crate::ty::TypeckTables;
23 use crate::ty::{self, AdtKind, DefIdTree, ToPolyTraitRef, ToPredicate, Ty, TyCtxt, TypeFoldable};
25 use errors::{pluralize, Applicability, DiagnosticBuilder, Style};
26 use rustc::hir::def_id::LOCAL_CRATE;
27 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
28 use rustc_span::source_map::SourceMap;
29 use rustc_span::symbol::{kw, sym};
30 use rustc_span::{ExpnKind, MultiSpan, Span, DUMMY_SP};
34 use rustc_error_codes::*;
36 impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
37 pub fn report_fulfillment_errors(
39 errors: &[FulfillmentError<'tcx>],
40 body_id: Option<hir::BodyId>,
41 fallback_has_occurred: bool,
44 struct ErrorDescriptor<'tcx> {
45 predicate: ty::Predicate<'tcx>,
46 index: Option<usize>, // None if this is an old error
49 let mut error_map: FxHashMap<_, Vec<_>> = self
50 .reported_trait_errors
53 .map(|(&span, predicates)| {
58 .map(|predicate| ErrorDescriptor {
59 predicate: predicate.clone(),
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;
76 error_map.entry(span).or_default().push(ErrorDescriptor {
77 predicate: error.obligation.predicate.clone(),
81 self.reported_trait_errors
85 .push(error.obligation.predicate.clone());
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
106 if self.error_implies(&error2.predicate, &error.predicate)
107 && !(error2.index >= error.index
108 && self.error_implies(&error.predicate, &error2.predicate))
110 info!("skipping {:?} (implied by {:?})", error, error2);
111 is_suppressed[index] = true;
119 for (error, suppressed) in errors.iter().zip(is_suppressed) {
121 self.report_fulfillment_error(error, body_id, fallback_has_occurred);
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(&self, cond: &ty::Predicate<'tcx>, error: &ty::Predicate<'tcx>) -> bool {
133 let (cond, error) = match (cond, error) {
134 (&ty::Predicate::Trait(..), &ty::Predicate::Trait(ref error)) => (cond, error),
136 // FIXME: make this work in other cases too.
141 for implication in super::elaborate_predicates(self.tcx, vec![cond.clone()]) {
142 if let ty::Predicate::Trait(implication) = implication {
143 let error = error.to_poly_trait_ref();
144 let implication = implication.to_poly_trait_ref();
145 // FIXME: I'm just not taking associated types at all here.
146 // Eventually I'll need to implement param-env-aware
147 // `Γ₁ ⊦ φ₁ => Γ₂ ⊦ φ₂` logic.
148 let param_env = ty::ParamEnv::empty();
149 if self.can_sub(param_env, error, implication).is_ok() {
150 debug!("error_implies: {:?} -> {:?} -> {:?}", cond, error, implication);
159 fn report_fulfillment_error(
161 error: &FulfillmentError<'tcx>,
162 body_id: Option<hir::BodyId>,
163 fallback_has_occurred: bool,
165 debug!("report_fulfillment_error({:?})", error);
167 FulfillmentErrorCode::CodeSelectionError(ref selection_error) => {
168 self.report_selection_error(
171 fallback_has_occurred,
172 error.points_at_arg_span,
175 FulfillmentErrorCode::CodeProjectionError(ref e) => {
176 self.report_projection_error(&error.obligation, e);
178 FulfillmentErrorCode::CodeAmbiguity => {
179 self.maybe_report_ambiguity(&error.obligation, body_id);
181 FulfillmentErrorCode::CodeSubtypeError(ref expected_found, ref err) => {
182 self.report_mismatched_types(
183 &error.obligation.cause,
184 expected_found.expected,
185 expected_found.found,
193 fn report_projection_error(
195 obligation: &PredicateObligation<'tcx>,
196 error: &MismatchedProjectionTypes<'tcx>,
198 let predicate = self.resolve_vars_if_possible(&obligation.predicate);
200 if predicate.references_error() {
206 let mut err = &error.err;
207 let mut values = None;
209 // try to find the mismatched types to report the error with.
211 // this can fail if the problem was higher-ranked, in which
212 // cause I have no idea for a good error message.
213 if let ty::Predicate::Projection(ref data) = predicate {
214 let mut selcx = SelectionContext::new(self);
215 let (data, _) = self.replace_bound_vars_with_fresh_vars(
216 obligation.cause.span,
217 infer::LateBoundRegionConversionTime::HigherRankedType,
220 let mut obligations = vec![];
221 let normalized_ty = super::normalize_projection_type(
223 obligation.param_env,
225 obligation.cause.clone(),
231 "report_projection_error obligation.cause={:?} obligation.param_env={:?}",
232 obligation.cause, obligation.param_env
236 "report_projection_error normalized_ty={:?} data.ty={:?}",
237 normalized_ty, data.ty
240 let is_normalized_ty_expected = match &obligation.cause.code {
241 ObligationCauseCode::ItemObligation(_)
242 | ObligationCauseCode::BindingObligation(_, _)
243 | ObligationCauseCode::ObjectCastObligation(_) => false,
247 if let Err(error) = self.at(&obligation.cause, obligation.param_env).eq_exp(
248 is_normalized_ty_expected,
252 values = Some(infer::ValuePairs::Types(ExpectedFound::new(
253 is_normalized_ty_expected,
263 let msg = format!("type mismatch resolving `{}`", predicate);
264 let error_id = (DiagnosticMessageId::ErrorId(271), Some(obligation.cause.span), msg);
265 let fresh = self.tcx.sess.one_time_diagnostics.borrow_mut().insert(error_id);
267 let mut diag = struct_span_err!(
269 obligation.cause.span,
271 "type mismatch resolving `{}`",
274 self.note_type_err(&mut diag, &obligation.cause, None, values, err);
275 self.note_obligation_cause(&mut diag, obligation);
281 fn fuzzy_match_tys(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
282 /// returns the fuzzy category of a given type, or None
283 /// if the type can be equated to any type.
284 fn type_category(t: Ty<'_>) -> Option<u32> {
289 ty::Int(..) | ty::Uint(..) | ty::Infer(ty::IntVar(..)) => Some(3),
290 ty::Float(..) | ty::Infer(ty::FloatVar(..)) => Some(4),
291 ty::Ref(..) | ty::RawPtr(..) => Some(5),
292 ty::Array(..) | ty::Slice(..) => Some(6),
293 ty::FnDef(..) | ty::FnPtr(..) => Some(7),
294 ty::Dynamic(..) => Some(8),
295 ty::Closure(..) => Some(9),
296 ty::Tuple(..) => Some(10),
297 ty::Projection(..) => Some(11),
298 ty::Param(..) => Some(12),
299 ty::Opaque(..) => Some(13),
300 ty::Never => Some(14),
301 ty::Adt(adt, ..) => match adt.adt_kind() {
302 AdtKind::Struct => Some(15),
303 AdtKind::Union => Some(16),
304 AdtKind::Enum => Some(17),
306 ty::Generator(..) => Some(18),
307 ty::Foreign(..) => Some(19),
308 ty::GeneratorWitness(..) => Some(20),
309 ty::Placeholder(..) | ty::Bound(..) | ty::Infer(..) | ty::Error => None,
310 ty::UnnormalizedProjection(..) => bug!("only used with chalk-engine"),
314 match (type_category(a), type_category(b)) {
315 (Some(cat_a), Some(cat_b)) => match (&a.kind, &b.kind) {
316 (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) => def_a == def_b,
319 // infer and error can be equated to all types
326 trait_ref: ty::PolyTraitRef<'tcx>,
327 obligation: &PredicateObligation<'tcx>,
330 let param_env = obligation.param_env;
331 let trait_ref = tcx.erase_late_bound_regions(&trait_ref);
332 let trait_self_ty = trait_ref.self_ty();
334 let mut self_match_impls = vec![];
335 let mut fuzzy_match_impls = vec![];
337 self.tcx.for_each_relevant_impl(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.impl_trait_ref(def_id).unwrap().subst(tcx, impl_substs);
341 let impl_self_ty = impl_trait_ref.self_ty();
343 if let Ok(..) = self.can_eq(param_env, trait_self_ty, impl_self_ty) {
344 self_match_impls.push(def_id);
350 .zip(impl_trait_ref.substs.types().skip(1))
351 .all(|(u, v)| self.fuzzy_match_tys(u, v))
353 fuzzy_match_impls.push(def_id);
358 let impl_def_id = if self_match_impls.len() == 1 {
360 } else if fuzzy_match_impls.len() == 1 {
366 tcx.has_attr(impl_def_id, sym::rustc_on_unimplemented).then_some(impl_def_id)
369 fn describe_generator(&self, body_id: hir::BodyId) -> Option<&'static str> {
370 self.tcx.hir().body(body_id).generator_kind.map(|gen_kind| match gen_kind {
371 hir::GeneratorKind::Gen => "a generator",
372 hir::GeneratorKind::Async(hir::AsyncGeneratorKind::Block) => "an async block",
373 hir::GeneratorKind::Async(hir::AsyncGeneratorKind::Fn) => "an async function",
374 hir::GeneratorKind::Async(hir::AsyncGeneratorKind::Closure) => "an async closure",
378 /// Used to set on_unimplemented's `ItemContext`
379 /// to be the enclosing (async) block/function/closure
380 fn describe_enclosure(&self, hir_id: hir::HirId) -> Option<&'static str> {
381 let hir = &self.tcx.hir();
382 let node = hir.find(hir_id)?;
383 if let hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(sig, _, body_id), .. }) = &node {
384 self.describe_generator(*body_id).or_else(|| {
385 Some(if let hir::FnHeader { asyncness: hir::IsAsync::Async, .. } = sig.header {
391 } else if let hir::Node::Expr(hir::Expr {
392 kind: hir::ExprKind::Closure(_is_move, _, body_id, _, gen_movability),
396 self.describe_generator(*body_id).or_else(|| {
397 Some(if gen_movability.is_some() { "an async closure" } else { "a closure" })
399 } else if let hir::Node::Expr(hir::Expr { .. }) = &node {
400 let parent_hid = hir.get_parent_node(hir_id);
401 if parent_hid != hir_id {
402 return self.describe_enclosure(parent_hid);
411 fn on_unimplemented_note(
413 trait_ref: ty::PolyTraitRef<'tcx>,
414 obligation: &PredicateObligation<'tcx>,
415 ) -> OnUnimplementedNote {
417 self.impl_similar_to(trait_ref, obligation).unwrap_or_else(|| trait_ref.def_id());
418 let trait_ref = *trait_ref.skip_binder();
420 let mut flags = vec![];
423 self.describe_enclosure(obligation.cause.body_id).map(|s| s.to_owned()),
426 match obligation.cause.code {
427 ObligationCauseCode::BuiltinDerivedObligation(..)
428 | ObligationCauseCode::ImplDerivedObligation(..) => {}
430 // this is a "direct", user-specified, rather than derived,
432 flags.push((sym::direct, None));
436 if let ObligationCauseCode::ItemObligation(item) = obligation.cause.code {
437 // FIXME: maybe also have some way of handling methods
438 // from other traits? That would require name resolution,
439 // which we might want to be some sort of hygienic.
441 // Currently I'm leaving it for what I need for `try`.
442 if self.tcx.trait_of_item(item) == Some(trait_ref.def_id) {
443 let method = self.tcx.item_name(item);
444 flags.push((sym::from_method, None));
445 flags.push((sym::from_method, Some(method.to_string())));
448 if let Some(t) = self.get_parent_trait_ref(&obligation.cause.code) {
449 flags.push((sym::parent_trait, Some(t)));
452 if let Some(k) = obligation.cause.span.desugaring_kind() {
453 flags.push((sym::from_desugaring, None));
454 flags.push((sym::from_desugaring, Some(format!("{:?}", k))));
456 let generics = self.tcx.generics_of(def_id);
457 let self_ty = trait_ref.self_ty();
458 // This is also included through the generics list as `Self`,
459 // but the parser won't allow you to use it
460 flags.push((sym::_Self, Some(self_ty.to_string())));
461 if let Some(def) = self_ty.ty_adt_def() {
462 // We also want to be able to select self's original
463 // signature with no type arguments resolved
464 flags.push((sym::_Self, Some(self.tcx.type_of(def.did).to_string())));
467 for param in generics.params.iter() {
468 let value = match param.kind {
469 GenericParamDefKind::Type { .. } | GenericParamDefKind::Const => {
470 trait_ref.substs[param.index as usize].to_string()
472 GenericParamDefKind::Lifetime => continue,
474 let name = param.name;
475 flags.push((name, Some(value)));
478 if let Some(true) = self_ty.ty_adt_def().map(|def| def.did.is_local()) {
479 flags.push((sym::crate_local, None));
482 // Allow targeting all integers using `{integral}`, even if the exact type was resolved
483 if self_ty.is_integral() {
484 flags.push((sym::_Self, Some("{integral}".to_owned())));
487 if let ty::Array(aty, len) = self_ty.kind {
488 flags.push((sym::_Self, Some("[]".to_owned())));
489 flags.push((sym::_Self, Some(format!("[{}]", aty))));
490 if let Some(def) = aty.ty_adt_def() {
491 // We also want to be able to select the array's type's original
492 // signature with no type arguments resolved
495 Some(format!("[{}]", self.tcx.type_of(def.did).to_string())),
498 if let Some(len) = len.try_eval_usize(tcx, ty::ParamEnv::empty()) {
501 Some(format!("[{}; {}]", self.tcx.type_of(def.did).to_string(), len)),
506 Some(format!("[{}; _]", self.tcx.type_of(def.did).to_string())),
512 if let Ok(Some(command)) =
513 OnUnimplementedDirective::of_item(self.tcx, trait_ref.def_id, def_id)
515 command.evaluate(self.tcx, trait_ref, &flags[..])
517 OnUnimplementedNote::default()
521 fn find_similar_impl_candidates(
523 trait_ref: ty::PolyTraitRef<'tcx>,
524 ) -> Vec<ty::TraitRef<'tcx>> {
525 let simp = fast_reject::simplify_type(self.tcx, trait_ref.skip_binder().self_ty(), true);
526 let all_impls = self.tcx.all_impls(trait_ref.def_id());
529 Some(simp) => all_impls
531 .filter_map(|&def_id| {
532 let imp = self.tcx.impl_trait_ref(def_id).unwrap();
533 let imp_simp = fast_reject::simplify_type(self.tcx, imp.self_ty(), true);
534 if let Some(imp_simp) = imp_simp {
535 if simp != imp_simp {
544 all_impls.iter().map(|&def_id| self.tcx.impl_trait_ref(def_id).unwrap()).collect()
549 fn report_similar_impl_candidates(
551 impl_candidates: Vec<ty::TraitRef<'tcx>>,
552 err: &mut DiagnosticBuilder<'_>,
554 if impl_candidates.is_empty() {
558 let len = impl_candidates.len();
559 let end = if impl_candidates.len() <= 5 { impl_candidates.len() } else { 4 };
561 let normalize = |candidate| {
562 self.tcx.infer_ctxt().enter(|ref infcx| {
563 let normalized = infcx
564 .at(&ObligationCause::dummy(), ty::ParamEnv::empty())
565 .normalize(candidate)
568 Some(normalized) => format!("\n {:?}", normalized.value),
569 None => format!("\n {:?}", candidate),
574 // Sort impl candidates so that ordering is consistent for UI tests.
575 let mut normalized_impl_candidates =
576 impl_candidates.iter().map(normalize).collect::<Vec<String>>();
578 // Sort before taking the `..end` range,
579 // because the ordering of `impl_candidates` may not be deterministic:
580 // https://github.com/rust-lang/rust/pull/57475#issuecomment-455519507
581 normalized_impl_candidates.sort();
584 "the following implementations were found:{}{}",
585 normalized_impl_candidates[..end].join(""),
586 if len > 5 { format!("\nand {} others", len - 4) } else { String::new() }
590 /// Reports that an overflow has occurred and halts compilation. We
591 /// halt compilation unconditionally because it is important that
592 /// overflows never be masked -- they basically represent computations
593 /// whose result could not be truly determined and thus we can't say
594 /// if the program type checks or not -- and they are unusual
595 /// occurrences in any case.
596 pub fn report_overflow_error<T>(
598 obligation: &Obligation<'tcx, T>,
599 suggest_increasing_limit: bool,
602 T: fmt::Display + TypeFoldable<'tcx>,
604 let predicate = self.resolve_vars_if_possible(&obligation.predicate);
605 let mut err = struct_span_err!(
607 obligation.cause.span,
609 "overflow evaluating the requirement `{}`",
613 if suggest_increasing_limit {
614 self.suggest_new_overflow_limit(&mut err);
617 self.note_obligation_cause_code(
619 &obligation.predicate,
620 &obligation.cause.code,
625 self.tcx.sess.abort_if_errors();
629 /// Reports that a cycle was detected which led to overflow and halts
630 /// compilation. This is equivalent to `report_overflow_error` except
631 /// that we can give a more helpful error message (and, in particular,
632 /// we do not suggest increasing the overflow limit, which is not
634 pub fn report_overflow_error_cycle(&self, cycle: &[PredicateObligation<'tcx>]) -> ! {
635 let cycle = self.resolve_vars_if_possible(&cycle.to_owned());
636 assert!(cycle.len() > 0);
638 debug!("report_overflow_error_cycle: cycle={:?}", cycle);
640 self.report_overflow_error(&cycle[0], false);
643 pub fn report_extra_impl_obligation(
646 item_name: ast::Name,
647 _impl_item_def_id: DefId,
648 trait_item_def_id: DefId,
649 requirement: &dyn fmt::Display,
650 ) -> DiagnosticBuilder<'tcx> {
651 let msg = "impl has stricter requirements than trait";
652 let sp = self.tcx.sess.source_map().def_span(error_span);
654 let mut err = struct_span_err!(self.tcx.sess, sp, E0276, "{}", msg);
656 if let Some(trait_item_span) = self.tcx.hir().span_if_local(trait_item_def_id) {
657 let span = self.tcx.sess.source_map().def_span(trait_item_span);
658 err.span_label(span, format!("definition of `{}` from trait", item_name));
661 err.span_label(sp, format!("impl has extra requirement {}", requirement));
666 /// Gets the parent trait chain start
667 fn get_parent_trait_ref(&self, code: &ObligationCauseCode<'tcx>) -> Option<String> {
669 &ObligationCauseCode::BuiltinDerivedObligation(ref data) => {
670 let parent_trait_ref = self.resolve_vars_if_possible(&data.parent_trait_ref);
671 match self.get_parent_trait_ref(&data.parent_code) {
673 None => Some(parent_trait_ref.skip_binder().self_ty().to_string()),
680 pub fn report_selection_error(
682 obligation: &PredicateObligation<'tcx>,
683 error: &SelectionError<'tcx>,
684 fallback_has_occurred: bool,
688 let span = obligation.cause.span;
690 let mut err = match *error {
691 SelectionError::Unimplemented => {
692 if let ObligationCauseCode::CompareImplMethodObligation {
697 | ObligationCauseCode::CompareImplTypeObligation {
701 } = obligation.cause.code
703 self.report_extra_impl_obligation(
708 &format!("`{}`", obligation.predicate),
713 match obligation.predicate {
714 ty::Predicate::Trait(ref trait_predicate) => {
715 let trait_predicate = self.resolve_vars_if_possible(trait_predicate);
717 if self.tcx.sess.has_errors() && trait_predicate.references_error() {
720 let trait_ref = trait_predicate.to_poly_trait_ref();
721 let (post_message, pre_message) = self
722 .get_parent_trait_ref(&obligation.cause.code)
723 .map(|t| (format!(" in `{}`", t), format!("within `{}`, ", t)))
724 .unwrap_or_default();
726 let OnUnimplementedNote { message, label, note, enclosing_scope } =
727 self.on_unimplemented_note(trait_ref, obligation);
728 let have_alt_message = message.is_some() || label.is_some();
733 .span_to_snippet(span)
736 let is_from = format!("{}", trait_ref.print_only_trait_path())
737 .starts_with("std::convert::From<");
738 let (message, note) = if is_try && is_from {
741 "`?` couldn't convert the error to `{}`",
745 "the question mark operation (`?`) implicitly performs a \
746 conversion on the error value using the `From` trait"
754 let mut err = struct_span_err!(
759 message.unwrap_or_else(|| format!(
760 "the trait bound `{}` is not satisfied{}",
761 trait_ref.to_predicate(),
767 if obligation.cause.code == ObligationCauseCode::MainFunctionType {
768 "consider using `()`, or a `Result`".to_owned()
771 "{}the trait `{}` is not implemented for `{}`",
773 trait_ref.print_only_trait_path(),
778 if self.suggest_add_reference_to_arg(
785 self.note_obligation_cause(&mut err, obligation);
789 if let Some(ref s) = label {
790 // If it has a custom `#[rustc_on_unimplemented]`
791 // error message, let's display it as the label!
792 err.span_label(span, s.as_str());
793 err.help(&explanation);
795 err.span_label(span, explanation);
797 if let Some(ref s) = note {
798 // If it has a custom `#[rustc_on_unimplemented]` note, let's display it
799 err.note(s.as_str());
801 if let Some(ref s) = enclosing_scope {
802 let enclosing_scope_span = tcx.def_span(
804 .opt_local_def_id(obligation.cause.body_id)
806 tcx.hir().body_owner_def_id(hir::BodyId {
807 hir_id: obligation.cause.body_id,
812 err.span_label(enclosing_scope_span, s.as_str());
815 self.suggest_borrow_on_unsized_slice(&obligation.cause.code, &mut err);
816 self.suggest_fn_call(&obligation, &mut err, &trait_ref, points_at_arg);
817 self.suggest_remove_reference(&obligation, &mut err, &trait_ref);
818 self.suggest_semicolon_removal(&obligation, &mut err, span, &trait_ref);
819 self.note_version_mismatch(&mut err, &trait_ref);
821 // Try to report a help message
822 if !trait_ref.has_infer_types()
823 && self.predicate_can_apply(obligation.param_env, trait_ref)
825 // If a where-clause may be useful, remind the
826 // user that they can add it.
828 // don't display an on-unimplemented note, as
829 // these notes will often be of the form
830 // "the type `T` can't be frobnicated"
831 // which is somewhat confusing.
832 self.suggest_restricting_param_bound(
835 obligation.cause.body_id,
838 if !have_alt_message {
839 // Can't show anything else useful, try to find similar impls.
840 let impl_candidates = self.find_similar_impl_candidates(trait_ref);
841 self.report_similar_impl_candidates(impl_candidates, &mut err);
843 self.suggest_change_mut(
851 // If this error is due to `!: Trait` not implemented but `(): Trait` is
852 // implemented, and fallback has occurred, then it could be due to a
853 // variable that used to fallback to `()` now falling back to `!`. Issue a
854 // note informing about the change in behaviour.
855 if trait_predicate.skip_binder().self_ty().is_never()
856 && fallback_has_occurred
858 let predicate = trait_predicate.map_bound(|mut trait_pred| {
859 trait_pred.trait_ref.substs = self.tcx.mk_substs_trait(
861 &trait_pred.trait_ref.substs[1..],
865 let unit_obligation = Obligation {
866 predicate: ty::Predicate::Trait(predicate),
869 if self.predicate_may_hold(&unit_obligation) {
871 "the trait is implemented for `()`. \
872 Possibly this error has been caused by changes to \
873 Rust's type-inference algorithm \
874 (see: https://github.com/rust-lang/rust/issues/48950 \
875 for more info). Consider whether you meant to use the \
876 type `()` here instead.",
884 ty::Predicate::Subtype(ref predicate) => {
885 // Errors for Subtype predicates show up as
886 // `FulfillmentErrorCode::CodeSubtypeError`,
887 // not selection error.
888 span_bug!(span, "subtype requirement gave wrong error: `{:?}`", predicate)
891 ty::Predicate::RegionOutlives(ref predicate) => {
892 let predicate = self.resolve_vars_if_possible(predicate);
894 .region_outlives_predicate(&obligation.cause, &predicate)
901 "the requirement `{}` is not satisfied (`{}`)",
907 ty::Predicate::Projection(..) | ty::Predicate::TypeOutlives(..) => {
908 let predicate = self.resolve_vars_if_possible(&obligation.predicate);
913 "the requirement `{}` is not satisfied",
918 ty::Predicate::ObjectSafe(trait_def_id) => {
919 let violations = self.tcx.object_safety_violations(trait_def_id);
920 self.tcx.report_object_safety_error(span, trait_def_id, violations)
923 ty::Predicate::ClosureKind(closure_def_id, closure_substs, kind) => {
924 let found_kind = self.closure_kind(closure_def_id, closure_substs).unwrap();
925 let closure_span = self
929 .def_span(self.tcx.hir().span_if_local(closure_def_id).unwrap());
930 let hir_id = self.tcx.hir().as_local_hir_id(closure_def_id).unwrap();
931 let mut err = struct_span_err!(
935 "expected a closure that implements the `{}` trait, \
936 but this closure only implements `{}`",
943 format!("this closure implements `{}`, not `{}`", found_kind, kind),
946 obligation.cause.span,
947 format!("the requirement to implement `{}` derives from here", kind),
950 // Additional context information explaining why the closure only implements
951 // a particular trait.
952 if let Some(tables) = self.in_progress_tables {
953 let tables = tables.borrow();
954 match (found_kind, tables.closure_kind_origins().get(hir_id)) {
955 (ty::ClosureKind::FnOnce, Some((span, name))) => {
959 "closure is `FnOnce` because it moves the \
960 variable `{}` out of its environment",
965 (ty::ClosureKind::FnMut, Some((span, name))) => {
969 "closure is `FnMut` because it mutates the \
983 ty::Predicate::WellFormed(ty) => {
984 if !self.tcx.sess.opts.debugging_opts.chalk {
985 // WF predicates cannot themselves make
986 // errors. They can only block due to
987 // ambiguity; otherwise, they always
988 // degenerate into other obligations
990 span_bug!(span, "WF predicate not satisfied for {:?}", ty);
992 // FIXME: we'll need a better message which takes into account
993 // which bounds actually failed to hold.
994 self.tcx.sess.struct_span_err(
996 &format!("the type `{}` is not well-formed (chalk)", ty),
1001 ty::Predicate::ConstEvaluatable(..) => {
1002 // Errors for `ConstEvaluatable` predicates show up as
1003 // `SelectionError::ConstEvalFailure`,
1004 // not `Unimplemented`.
1007 "const-evaluatable requirement gave wrong error: `{:?}`",
1014 OutputTypeParameterMismatch(ref found_trait_ref, ref expected_trait_ref, _) => {
1015 let found_trait_ref = self.resolve_vars_if_possible(&*found_trait_ref);
1016 let expected_trait_ref = self.resolve_vars_if_possible(&*expected_trait_ref);
1018 if expected_trait_ref.self_ty().references_error() {
1022 let found_trait_ty = found_trait_ref.self_ty();
1024 let found_did = match found_trait_ty.kind {
1025 ty::Closure(did, _) | ty::Foreign(did) | ty::FnDef(did, _) => Some(did),
1026 ty::Adt(def, _) => Some(def.did),
1030 let found_span = found_did
1031 .and_then(|did| self.tcx.hir().span_if_local(did))
1032 .map(|sp| self.tcx.sess.source_map().def_span(sp)); // the sp could be an fn def
1034 if self.reported_closure_mismatch.borrow().contains(&(span, found_span)) {
1035 // We check closures twice, with obligations flowing in different directions,
1036 // but we want to complain about them only once.
1040 self.reported_closure_mismatch.borrow_mut().insert((span, found_span));
1042 let found = match found_trait_ref.skip_binder().substs.type_at(1).kind {
1043 ty::Tuple(ref tys) => vec![ArgKind::empty(); tys.len()],
1044 _ => vec![ArgKind::empty()],
1047 let expected_ty = expected_trait_ref.skip_binder().substs.type_at(1);
1048 let expected = match expected_ty.kind {
1049 ty::Tuple(ref tys) => tys
1051 .map(|t| ArgKind::from_expected_ty(t.expect_ty(), Some(span)))
1053 _ => vec![ArgKind::Arg("_".to_owned(), expected_ty.to_string())],
1056 if found.len() == expected.len() {
1057 self.report_closure_arg_mismatch(
1064 let (closure_span, found) = found_did
1065 .and_then(|did| self.tcx.hir().get_if_local(did))
1067 let (found_span, found) = self.get_fn_like_arguments(node);
1068 (Some(found_span), found)
1070 .unwrap_or((found_span, found));
1072 self.report_arg_count_mismatch(
1077 found_trait_ty.is_closure(),
1082 TraitNotObjectSafe(did) => {
1083 let violations = self.tcx.object_safety_violations(did);
1084 self.tcx.report_object_safety_error(span, did, violations)
1087 // already reported in the query
1088 ConstEvalFailure(err) => {
1089 self.tcx.sess.delay_span_bug(
1091 &format!("constant in type had an ignored error: {:?}", err),
1097 bug!("overflow should be handled before the `report_selection_error` path");
1101 self.note_obligation_cause(&mut err, obligation);
1106 /// If the `Self` type of the unsatisfied trait `trait_ref` implements a trait
1107 /// with the same path as `trait_ref`, a help message about
1108 /// a probable version mismatch is added to `err`
1109 fn note_version_mismatch(
1111 err: &mut DiagnosticBuilder<'_>,
1112 trait_ref: &ty::PolyTraitRef<'tcx>,
1114 let get_trait_impl = |trait_def_id| {
1115 let mut trait_impl = None;
1116 self.tcx.for_each_relevant_impl(trait_def_id, trait_ref.self_ty(), |impl_def_id| {
1117 if trait_impl.is_none() {
1118 trait_impl = Some(impl_def_id);
1123 let required_trait_path = self.tcx.def_path_str(trait_ref.def_id());
1124 let all_traits = self.tcx.all_traits(LOCAL_CRATE);
1125 let traits_with_same_path: std::collections::BTreeSet<_> = all_traits
1127 .filter(|trait_def_id| **trait_def_id != trait_ref.def_id())
1128 .filter(|trait_def_id| self.tcx.def_path_str(**trait_def_id) == required_trait_path)
1130 for trait_with_same_path in traits_with_same_path {
1131 if let Some(impl_def_id) = get_trait_impl(*trait_with_same_path) {
1132 let impl_span = self.tcx.def_span(impl_def_id);
1133 err.span_help(impl_span, "trait impl with same name found");
1134 let trait_crate = self.tcx.crate_name(trait_with_same_path.krate);
1135 let crate_msg = format!(
1136 "Perhaps two different versions of crate `{}` are being used?",
1139 err.note(&crate_msg);
1143 fn suggest_restricting_param_bound(
1145 mut err: &mut DiagnosticBuilder<'_>,
1146 trait_ref: &ty::PolyTraitRef<'_>,
1147 body_id: hir::HirId,
1149 let self_ty = trait_ref.self_ty();
1150 let (param_ty, projection) = match &self_ty.kind {
1151 ty::Param(_) => (true, None),
1152 ty::Projection(projection) => (false, Some(projection)),
1156 let suggest_restriction =
1157 |generics: &hir::Generics<'_>, msg, err: &mut DiagnosticBuilder<'_>| {
1158 let span = generics.where_clause.span_for_predicates_or_empty_place();
1159 if !span.from_expansion() && span.desugaring_kind().is_none() {
1160 err.span_suggestion(
1161 generics.where_clause.span_for_predicates_or_empty_place().shrink_to_hi(),
1162 &format!("consider further restricting {}", msg),
1165 if !generics.where_clause.predicates.is_empty() {
1170 trait_ref.to_predicate(),
1172 Applicability::MachineApplicable,
1177 // FIXME: Add check for trait bound that is already present, particularly `?Sized` so we
1178 // don't suggest `T: Sized + ?Sized`.
1179 let mut hir_id = body_id;
1180 while let Some(node) = self.tcx.hir().find(hir_id) {
1182 hir::Node::TraitItem(hir::TraitItem {
1184 kind: hir::TraitItemKind::Method(..),
1186 }) if param_ty && self_ty == self.tcx.types.self_param => {
1187 // Restricting `Self` for a single method.
1188 suggest_restriction(&generics, "`Self`", err);
1192 hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(_, generics, _), .. })
1193 | hir::Node::TraitItem(hir::TraitItem {
1195 kind: hir::TraitItemKind::Method(..),
1198 | hir::Node::ImplItem(hir::ImplItem {
1200 kind: hir::ImplItemKind::Method(..),
1203 | hir::Node::Item(hir::Item {
1204 kind: hir::ItemKind::Trait(_, _, generics, _, _),
1207 | hir::Node::Item(hir::Item {
1208 kind: hir::ItemKind::Impl(_, _, _, generics, ..),
1210 }) if projection.is_some() => {
1211 // Missing associated type bound.
1212 suggest_restriction(&generics, "the associated type", err);
1216 hir::Node::Item(hir::Item {
1217 kind: hir::ItemKind::Struct(_, generics),
1221 | hir::Node::Item(hir::Item {
1222 kind: hir::ItemKind::Enum(_, generics), span, ..
1224 | hir::Node::Item(hir::Item {
1225 kind: hir::ItemKind::Union(_, generics),
1229 | hir::Node::Item(hir::Item {
1230 kind: hir::ItemKind::Trait(_, _, generics, ..),
1234 | hir::Node::Item(hir::Item {
1235 kind: hir::ItemKind::Impl(_, _, _, generics, ..),
1239 | hir::Node::Item(hir::Item {
1240 kind: hir::ItemKind::Fn(_, generics, _),
1244 | hir::Node::Item(hir::Item {
1245 kind: hir::ItemKind::TyAlias(_, generics),
1249 | hir::Node::Item(hir::Item {
1250 kind: hir::ItemKind::TraitAlias(generics, _),
1254 | hir::Node::Item(hir::Item {
1255 kind: hir::ItemKind::OpaqueTy(hir::OpaqueTy { generics, .. }),
1259 | hir::Node::TraitItem(hir::TraitItem { generics, span, .. })
1260 | hir::Node::ImplItem(hir::ImplItem { generics, span, .. })
1263 // Missing generic type parameter bound.
1264 let param_name = self_ty.to_string();
1265 let constraint = trait_ref.print_only_trait_path().to_string();
1266 if suggest_constraining_type_param(
1271 self.tcx.sess.source_map(),
1278 hir::Node::Crate => return,
1283 hir_id = self.tcx.hir().get_parent_item(hir_id);
1287 /// When encountering an assignment of an unsized trait, like `let x = ""[..];`, provide a
1288 /// suggestion to borrow the initializer in order to use have a slice instead.
1289 fn suggest_borrow_on_unsized_slice(
1291 code: &ObligationCauseCode<'tcx>,
1292 err: &mut DiagnosticBuilder<'tcx>,
1294 if let &ObligationCauseCode::VariableType(hir_id) = code {
1295 let parent_node = self.tcx.hir().get_parent_node(hir_id);
1296 if let Some(Node::Local(ref local)) = self.tcx.hir().find(parent_node) {
1297 if let Some(ref expr) = local.init {
1298 if let hir::ExprKind::Index(_, _) = expr.kind {
1299 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(expr.span) {
1300 err.span_suggestion(
1302 "consider borrowing here",
1303 format!("&{}", snippet),
1304 Applicability::MachineApplicable,
1313 fn mk_obligation_for_def_id(
1316 output_ty: Ty<'tcx>,
1317 cause: ObligationCause<'tcx>,
1318 param_env: ty::ParamEnv<'tcx>,
1319 ) -> PredicateObligation<'tcx> {
1321 ty::TraitRef { def_id, substs: self.tcx.mk_substs_trait(output_ty, &[]) };
1322 Obligation::new(cause, param_env, new_trait_ref.to_predicate())
1325 /// Given a closure's `DefId`, return the given name of the closure.
1327 /// This doesn't account for reassignments, but it's only used for suggestions.
1328 fn get_closure_name(
1331 err: &mut DiagnosticBuilder<'_>,
1333 ) -> Option<String> {
1335 |err: &mut DiagnosticBuilder<'_>, kind: &hir::PatKind<'_>| -> Option<String> {
1336 // Get the local name of this closure. This can be inaccurate because
1337 // of the possibility of reassignment, but this should be good enough.
1339 hir::PatKind::Binding(hir::BindingAnnotation::Unannotated, _, name, None) => {
1340 Some(format!("{}", name))
1349 let hir = self.tcx.hir();
1350 let hir_id = hir.as_local_hir_id(def_id)?;
1351 let parent_node = hir.get_parent_node(hir_id);
1352 match hir.find(parent_node) {
1353 Some(hir::Node::Stmt(hir::Stmt { kind: hir::StmtKind::Local(local), .. })) => {
1354 get_name(err, &local.pat.kind)
1356 // Different to previous arm because one is `&hir::Local` and the other
1357 // is `P<hir::Local>`.
1358 Some(hir::Node::Local(local)) => get_name(err, &local.pat.kind),
1363 /// We tried to apply the bound to an `fn` or closure. Check whether calling it would
1364 /// evaluate to a type that *would* satisfy the trait binding. If it would, suggest calling
1365 /// it: `bar(foo)` → `bar(foo())`. This case is *very* likely to be hit if `foo` is `async`.
1368 obligation: &PredicateObligation<'tcx>,
1369 err: &mut DiagnosticBuilder<'_>,
1370 trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
1371 points_at_arg: bool,
1373 let self_ty = trait_ref.self_ty();
1374 let (def_id, output_ty, callable) = match self_ty.kind {
1375 ty::Closure(def_id, substs) => {
1376 (def_id, self.closure_sig(def_id, substs).output(), "closure")
1378 ty::FnDef(def_id, _) => (def_id, self_ty.fn_sig(self.tcx).output(), "function"),
1381 let msg = format!("use parentheses to call the {}", callable);
1383 let obligation = self.mk_obligation_for_def_id(
1385 output_ty.skip_binder(),
1386 obligation.cause.clone(),
1387 obligation.param_env,
1390 match self.evaluate_obligation(&obligation) {
1391 Ok(EvaluationResult::EvaluatedToOk)
1392 | Ok(EvaluationResult::EvaluatedToOkModuloRegions)
1393 | Ok(EvaluationResult::EvaluatedToAmbig) => {}
1396 let hir = self.tcx.hir();
1397 // Get the name of the callable and the arguments to be used in the suggestion.
1398 let snippet = match hir.get_if_local(def_id) {
1399 Some(hir::Node::Expr(hir::Expr {
1400 kind: hir::ExprKind::Closure(_, decl, _, span, ..),
1403 err.span_label(*span, "consider calling this closure");
1404 let name = match self.get_closure_name(def_id, err, &msg) {
1408 let args = decl.inputs.iter().map(|_| "_").collect::<Vec<_>>().join(", ");
1409 format!("{}({})", name, args)
1411 Some(hir::Node::Item(hir::Item {
1413 kind: hir::ItemKind::Fn(.., body_id),
1416 err.span_label(ident.span, "consider calling this function");
1417 let body = hir.body(*body_id);
1421 .map(|arg| match &arg.pat.kind {
1422 hir::PatKind::Binding(_, _, ident, None)
1423 // FIXME: provide a better suggestion when encountering `SelfLower`, it
1424 // should suggest a method call.
1425 if ident.name != kw::SelfLower => ident.to_string(),
1426 _ => "_".to_string(),
1428 .collect::<Vec<_>>()
1430 format!("{}({})", ident, args)
1435 // When the obligation error has been ensured to have been caused by
1436 // an argument, the `obligation.cause.span` points at the expression
1437 // of the argument, so we can provide a suggestion. This is signaled
1438 // by `points_at_arg`. Otherwise, we give a more general note.
1439 err.span_suggestion(
1440 obligation.cause.span,
1443 Applicability::HasPlaceholders,
1446 err.help(&format!("{}: `{}`", msg, snippet));
1450 fn suggest_add_reference_to_arg(
1452 obligation: &PredicateObligation<'tcx>,
1453 err: &mut DiagnosticBuilder<'tcx>,
1454 trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
1455 points_at_arg: bool,
1456 has_custom_message: bool,
1462 let span = obligation.cause.span;
1463 let param_env = obligation.param_env;
1464 let trait_ref = trait_ref.skip_binder();
1466 if let ObligationCauseCode::ImplDerivedObligation(obligation) = &obligation.cause.code {
1467 // Try to apply the original trait binding obligation by borrowing.
1468 let self_ty = trait_ref.self_ty();
1469 let found = self_ty.to_string();
1470 let new_self_ty = self.tcx.mk_imm_ref(self.tcx.lifetimes.re_static, self_ty);
1471 let substs = self.tcx.mk_substs_trait(new_self_ty, &[]);
1472 let new_trait_ref = ty::TraitRef::new(obligation.parent_trait_ref.def_id(), substs);
1473 let new_obligation =
1474 Obligation::new(ObligationCause::dummy(), param_env, new_trait_ref.to_predicate());
1475 if self.predicate_must_hold_modulo_regions(&new_obligation) {
1476 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
1477 // We have a very specific type of error, where just borrowing this argument
1478 // might solve the problem. In cases like this, the important part is the
1479 // original type obligation, not the last one that failed, which is arbitrary.
1480 // Because of this, we modify the error to refer to the original obligation and
1481 // return early in the caller.
1483 "the trait bound `{}: {}` is not satisfied",
1485 obligation.parent_trait_ref.skip_binder().print_only_trait_path(),
1487 if has_custom_message {
1490 err.message = vec![(msg, Style::NoStyle)];
1492 if snippet.starts_with('&') {
1493 // This is already a literal borrow and the obligation is failing
1494 // somewhere else in the obligation chain. Do not suggest non-sense.
1500 "expected an implementor of trait `{}`",
1501 obligation.parent_trait_ref.skip_binder().print_only_trait_path(),
1504 err.span_suggestion(
1506 "consider borrowing here",
1507 format!("&{}", snippet),
1508 Applicability::MaybeIncorrect,
1517 /// Whenever references are used by mistake, like `for (i, e) in &vec.iter().enumerate()`,
1518 /// suggest removing these references until we reach a type that implements the trait.
1519 fn suggest_remove_reference(
1521 obligation: &PredicateObligation<'tcx>,
1522 err: &mut DiagnosticBuilder<'tcx>,
1523 trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
1525 let trait_ref = trait_ref.skip_binder();
1526 let span = obligation.cause.span;
1528 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
1530 snippet.chars().filter(|c| !c.is_whitespace()).take_while(|c| *c == '&').count();
1532 snippet.chars().filter(|c| !c.is_whitespace()).skip(refs_number).next()
1534 // Do not suggest removal of borrow from type arguments.
1538 let mut trait_type = trait_ref.self_ty();
1540 for refs_remaining in 0..refs_number {
1541 if let ty::Ref(_, t_type, _) = trait_type.kind {
1542 trait_type = t_type;
1544 let new_obligation = self.mk_obligation_for_def_id(
1547 ObligationCause::dummy(),
1548 obligation.param_env,
1551 if self.predicate_may_hold(&new_obligation) {
1556 .span_take_while(span, |c| c.is_whitespace() || *c == '&');
1558 let remove_refs = refs_remaining + 1;
1560 format!("consider removing {} leading `&`-references", remove_refs);
1562 err.span_suggestion_short(
1566 Applicability::MachineApplicable,
1577 /// Check if the trait bound is implemented for a different mutability and note it in the
1579 fn suggest_change_mut(
1581 obligation: &PredicateObligation<'tcx>,
1582 err: &mut DiagnosticBuilder<'tcx>,
1583 trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
1584 points_at_arg: bool,
1586 let span = obligation.cause.span;
1587 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
1589 snippet.chars().filter(|c| !c.is_whitespace()).take_while(|c| *c == '&').count();
1591 snippet.chars().filter(|c| !c.is_whitespace()).skip(refs_number).next()
1593 // Do not suggest removal of borrow from type arguments.
1596 let trait_ref = self.resolve_vars_if_possible(trait_ref);
1597 if trait_ref.has_infer_types() {
1598 // Do not ICE while trying to find if a reborrow would succeed on a trait with
1599 // unresolved bindings.
1603 if let ty::Ref(region, t_type, mutability) = trait_ref.skip_binder().self_ty().kind {
1604 let trait_type = match mutability {
1605 hir::Mutability::Mut => self.tcx.mk_imm_ref(region, t_type),
1606 hir::Mutability::Not => self.tcx.mk_mut_ref(region, t_type),
1609 let new_obligation = self.mk_obligation_for_def_id(
1610 trait_ref.skip_binder().def_id,
1612 ObligationCause::dummy(),
1613 obligation.param_env,
1616 if self.evaluate_obligation_no_overflow(&new_obligation).must_apply_modulo_regions()
1622 .span_take_while(span, |c| c.is_whitespace() || *c == '&');
1623 if points_at_arg && mutability == hir::Mutability::Not && refs_number > 0 {
1624 err.span_suggestion(
1626 "consider changing this borrow's mutability",
1627 "&mut ".to_string(),
1628 Applicability::MachineApplicable,
1632 "`{}` is implemented for `{:?}`, but not for `{:?}`",
1633 trait_ref.print_only_trait_path(),
1635 trait_ref.skip_binder().self_ty(),
1643 fn suggest_semicolon_removal(
1645 obligation: &PredicateObligation<'tcx>,
1646 err: &mut DiagnosticBuilder<'tcx>,
1648 trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
1650 let hir = self.tcx.hir();
1651 let parent_node = hir.get_parent_node(obligation.cause.body_id);
1652 let node = hir.find(parent_node);
1653 if let Some(hir::Node::Item(hir::Item {
1654 kind: hir::ItemKind::Fn(sig, _, body_id), ..
1657 let body = hir.body(*body_id);
1658 if let hir::ExprKind::Block(blk, _) = &body.value.kind {
1659 if sig.decl.output.span().overlaps(span)
1660 && blk.expr.is_none()
1661 && "()" == &trait_ref.self_ty().to_string()
1663 // FIXME(estebank): When encountering a method with a trait
1664 // bound not satisfied in the return type with a body that has
1665 // no return, suggest removal of semicolon on last statement.
1666 // Once that is added, close #54771.
1667 if let Some(ref stmt) = blk.stmts.last() {
1668 let sp = self.tcx.sess.source_map().end_point(stmt.span);
1669 err.span_label(sp, "consider removing this semicolon");
1676 /// Given some node representing a fn-like thing in the HIR map,
1677 /// returns a span and `ArgKind` information that describes the
1678 /// arguments it expects. This can be supplied to
1679 /// `report_arg_count_mismatch`.
1680 pub fn get_fn_like_arguments(&self, node: Node<'_>) -> (Span, Vec<ArgKind>) {
1682 Node::Expr(&hir::Expr {
1683 kind: hir::ExprKind::Closure(_, ref _decl, id, span, _),
1686 self.tcx.sess.source_map().def_span(span),
1693 if let hir::Pat { kind: hir::PatKind::Tuple(ref args, _), span, .. } =
1704 .span_to_snippet(pat.span)
1706 (snippet, "_".to_owned())
1708 .collect::<Vec<_>>(),
1712 self.tcx.sess.source_map().span_to_snippet(arg.pat.span).unwrap();
1713 ArgKind::Arg(name, "_".to_owned())
1716 .collect::<Vec<ArgKind>>(),
1718 Node::Item(&hir::Item { span, kind: hir::ItemKind::Fn(ref sig, ..), .. })
1719 | Node::ImplItem(&hir::ImplItem {
1721 kind: hir::ImplItemKind::Method(ref sig, _),
1724 | Node::TraitItem(&hir::TraitItem {
1726 kind: hir::TraitItemKind::Method(ref sig, _),
1729 self.tcx.sess.source_map().def_span(span),
1733 .map(|arg| match arg.clone().kind {
1734 hir::TyKind::Tup(ref tys) => ArgKind::Tuple(
1736 vec![("_".to_owned(), "_".to_owned()); tys.len()],
1738 _ => ArgKind::empty(),
1740 .collect::<Vec<ArgKind>>(),
1742 Node::Ctor(ref variant_data) => {
1743 let span = variant_data
1745 .map(|hir_id| self.tcx.hir().span(hir_id))
1746 .unwrap_or(DUMMY_SP);
1747 let span = self.tcx.sess.source_map().def_span(span);
1749 (span, vec![ArgKind::empty(); variant_data.fields().len()])
1751 _ => panic!("non-FnLike node found: {:?}", node),
1755 /// Reports an error when the number of arguments needed by a
1756 /// trait match doesn't match the number that the expression
1758 pub fn report_arg_count_mismatch(
1761 found_span: Option<Span>,
1762 expected_args: Vec<ArgKind>,
1763 found_args: Vec<ArgKind>,
1765 ) -> DiagnosticBuilder<'tcx> {
1766 let kind = if is_closure { "closure" } else { "function" };
1768 let args_str = |arguments: &[ArgKind], other: &[ArgKind]| {
1769 let arg_length = arguments.len();
1770 let distinct = match &other[..] {
1771 &[ArgKind::Tuple(..)] => true,
1774 match (arg_length, arguments.get(0)) {
1775 (1, Some(&ArgKind::Tuple(_, ref fields))) => {
1776 format!("a single {}-tuple as argument", fields.len())
1781 if distinct && arg_length > 1 { "distinct " } else { "" },
1782 pluralize!(arg_length)
1787 let expected_str = args_str(&expected_args, &found_args);
1788 let found_str = args_str(&found_args, &expected_args);
1790 let mut err = struct_span_err!(
1794 "{} is expected to take {}, but it takes {}",
1800 err.span_label(span, format!("expected {} that takes {}", kind, expected_str));
1802 if let Some(found_span) = found_span {
1803 err.span_label(found_span, format!("takes {}", found_str));
1806 // ^^^^^^^^-- def_span
1810 let prefix_span = self.tcx.sess.source_map().span_until_non_whitespace(found_span);
1814 if let Some(span) = found_span.trim_start(prefix_span) { span } else { found_span };
1816 // Suggest to take and ignore the arguments with expected_args_length `_`s if
1817 // found arguments is empty (assume the user just wants to ignore args in this case).
1818 // For example, if `expected_args_length` is 2, suggest `|_, _|`.
1819 if found_args.is_empty() && is_closure {
1820 let underscores = vec!["_"; expected_args.len()].join(", ");
1821 err.span_suggestion(
1824 "consider changing the closure to take and ignore the expected argument{}",
1825 if expected_args.len() < 2 { "" } else { "s" }
1827 format!("|{}|", underscores),
1828 Applicability::MachineApplicable,
1832 if let &[ArgKind::Tuple(_, ref fields)] = &found_args[..] {
1833 if fields.len() == expected_args.len() {
1836 .map(|(name, _)| name.to_owned())
1837 .collect::<Vec<String>>()
1839 err.span_suggestion(
1841 "change the closure to take multiple arguments instead of a single tuple",
1842 format!("|{}|", sugg),
1843 Applicability::MachineApplicable,
1847 if let &[ArgKind::Tuple(_, ref fields)] = &expected_args[..] {
1848 if fields.len() == found_args.len() && is_closure {
1853 .map(|arg| match arg {
1854 ArgKind::Arg(name, _) => name.to_owned(),
1855 _ => "_".to_owned(),
1857 .collect::<Vec<String>>()
1859 // add type annotations if available
1860 if found_args.iter().any(|arg| match arg {
1861 ArgKind::Arg(_, ty) => ty != "_",
1868 .map(|(_, ty)| ty.to_owned())
1869 .collect::<Vec<String>>()
1876 err.span_suggestion(
1878 "change the closure to accept a tuple instead of individual arguments",
1880 Applicability::MachineApplicable,
1889 fn report_closure_arg_mismatch(
1892 found_span: Option<Span>,
1893 expected_ref: ty::PolyTraitRef<'tcx>,
1894 found: ty::PolyTraitRef<'tcx>,
1895 ) -> DiagnosticBuilder<'tcx> {
1896 fn build_fn_sig_string<'tcx>(tcx: TyCtxt<'tcx>, trait_ref: &ty::TraitRef<'tcx>) -> String {
1897 let inputs = trait_ref.substs.type_at(1);
1898 let sig = if let ty::Tuple(inputs) = inputs.kind {
1900 inputs.iter().map(|k| k.expect_ty()),
1901 tcx.mk_ty_infer(ty::TyVar(ty::TyVid { index: 0 })),
1903 hir::Unsafety::Normal,
1904 ::rustc_target::spec::abi::Abi::Rust,
1908 ::std::iter::once(inputs),
1909 tcx.mk_ty_infer(ty::TyVar(ty::TyVid { index: 0 })),
1911 hir::Unsafety::Normal,
1912 ::rustc_target::spec::abi::Abi::Rust,
1915 ty::Binder::bind(sig).to_string()
1918 let argument_is_closure = expected_ref.skip_binder().substs.type_at(0).is_closure();
1919 let mut err = struct_span_err!(
1923 "type mismatch in {} arguments",
1924 if argument_is_closure { "closure" } else { "function" }
1927 let found_str = format!(
1928 "expected signature of `{}`",
1929 build_fn_sig_string(self.tcx, found.skip_binder())
1931 err.span_label(span, found_str);
1933 let found_span = found_span.unwrap_or(span);
1934 let expected_str = format!(
1935 "found signature of `{}`",
1936 build_fn_sig_string(self.tcx, expected_ref.skip_binder())
1938 err.span_label(found_span, expected_str);
1944 impl<'tcx> TyCtxt<'tcx> {
1945 pub fn recursive_type_with_infinite_size_error(
1948 ) -> DiagnosticBuilder<'tcx> {
1949 assert!(type_def_id.is_local());
1950 let span = self.hir().span_if_local(type_def_id).unwrap();
1951 let span = self.sess.source_map().def_span(span);
1952 let mut err = struct_span_err!(
1956 "recursive type `{}` has infinite size",
1957 self.def_path_str(type_def_id)
1959 err.span_label(span, "recursive type has infinite size");
1961 "insert indirection (e.g., a `Box`, `Rc`, or `&`) \
1962 at some point to make `{}` representable",
1963 self.def_path_str(type_def_id)
1968 pub fn report_object_safety_error(
1971 trait_def_id: DefId,
1972 violations: Vec<ObjectSafetyViolation>,
1973 ) -> DiagnosticBuilder<'tcx> {
1974 let trait_str = self.def_path_str(trait_def_id);
1975 let span = self.sess.source_map().def_span(span);
1976 let mut err = struct_span_err!(
1980 "the trait `{}` cannot be made into an object",
1983 err.span_label(span, format!("the trait `{}` cannot be made into an object", trait_str));
1985 let mut reported_violations = FxHashSet::default();
1986 for violation in violations {
1987 if reported_violations.insert(violation.clone()) {
1988 match violation.span() {
1989 Some(span) => err.span_label(span, violation.error_msg()),
1990 None => err.note(&violation.error_msg()),
1995 if self.sess.trait_methods_not_found.borrow().contains(&span) {
1996 // Avoid emitting error caused by non-existing method (#58734)
2004 impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
2005 fn maybe_report_ambiguity(
2007 obligation: &PredicateObligation<'tcx>,
2008 body_id: Option<hir::BodyId>,
2010 // Unable to successfully determine, probably means
2011 // insufficient type information, but could mean
2012 // ambiguous impls. The latter *ought* to be a
2013 // coherence violation, so we don't report it here.
2015 let predicate = self.resolve_vars_if_possible(&obligation.predicate);
2016 let span = obligation.cause.span;
2019 "maybe_report_ambiguity(predicate={:?}, obligation={:?} body_id={:?}, code={:?})",
2020 predicate, obligation, body_id, obligation.cause.code,
2023 // Ambiguity errors are often caused as fallout from earlier
2024 // errors. So just ignore them if this infcx is tainted.
2025 if self.is_tainted_by_errors() {
2029 let mut err = match predicate {
2030 ty::Predicate::Trait(ref data) => {
2031 let trait_ref = data.to_poly_trait_ref();
2032 let self_ty = trait_ref.self_ty();
2033 debug!("self_ty {:?} {:?} trait_ref {:?}", self_ty, self_ty.kind, trait_ref);
2035 if predicate.references_error() {
2038 // Typically, this ambiguity should only happen if
2039 // there are unresolved type inference variables
2040 // (otherwise it would suggest a coherence
2041 // failure). But given #21974 that is not necessarily
2042 // the case -- we can have multiple where clauses that
2043 // are only distinguished by a region, which results
2044 // in an ambiguity even when all types are fully
2045 // known, since we don't dispatch based on region
2048 // This is kind of a hack: it frequently happens that some earlier
2049 // error prevents types from being fully inferred, and then we get
2050 // a bunch of uninteresting errors saying something like "<generic
2051 // #0> doesn't implement Sized". It may even be true that we
2052 // could just skip over all checks where the self-ty is an
2053 // inference variable, but I was afraid that there might be an
2054 // inference variable created, registered as an obligation, and
2055 // then never forced by writeback, and hence by skipping here we'd
2056 // be ignoring the fact that we don't KNOW the type works
2057 // out. Though even that would probably be harmless, given that
2058 // we're only talking about builtin traits, which are known to be
2059 // inhabited. We used to check for `self.tcx.sess.has_errors()` to
2060 // avoid inundating the user with unnecessary errors, but we now
2061 // check upstream for type errors and dont add the obligations to
2062 // begin with in those cases.
2067 .map_or(false, |sized_id| sized_id == trait_ref.def_id())
2069 self.need_type_info_err(body_id, span, self_ty, ErrorCode::E0282).emit();
2072 let mut err = self.need_type_info_err(body_id, span, self_ty, ErrorCode::E0283);
2073 err.note(&format!("cannot resolve `{}`", predicate));
2074 if let (Ok(ref snippet), ObligationCauseCode::BindingObligation(ref def_id, _)) =
2075 (self.tcx.sess.source_map().span_to_snippet(span), &obligation.cause.code)
2077 let generics = self.tcx.generics_of(*def_id);
2078 if !generics.params.is_empty() && !snippet.ends_with('>') {
2079 // FIXME: To avoid spurious suggestions in functions where type arguments
2080 // where already supplied, we check the snippet to make sure it doesn't
2081 // end with a turbofish. Ideally we would have access to a `PathSegment`
2082 // instead. Otherwise we would produce the following output:
2084 // error[E0283]: type annotations needed
2085 // --> $DIR/issue-54954.rs:3:24
2087 // LL | const ARR_LEN: usize = Tt::const_val::<[i8; 123]>();
2088 // | ^^^^^^^^^^^^^^^^^^^^^^^^^^
2090 // | cannot infer type
2091 // | help: consider specifying the type argument
2092 // | in the function call:
2093 // | `Tt::const_val::<[i8; 123]>::<T>`
2095 // LL | const fn const_val<T: Sized>() -> usize {
2096 // | --------- - required by this bound in `Tt::const_val`
2098 // = note: cannot resolve `_: Tt`
2100 err.span_suggestion(
2103 "consider specifying the type argument{} in the function call",
2104 if generics.params.len() > 1 { "s" } else { "" },
2112 .map(|p| p.name.to_string())
2113 .collect::<Vec<String>>()
2116 Applicability::HasPlaceholders,
2123 ty::Predicate::WellFormed(ty) => {
2124 // Same hacky approach as above to avoid deluging user
2125 // with error messages.
2126 if ty.references_error() || self.tcx.sess.has_errors() {
2129 self.need_type_info_err(body_id, span, ty, ErrorCode::E0282)
2132 ty::Predicate::Subtype(ref data) => {
2133 if data.references_error() || self.tcx.sess.has_errors() {
2134 // no need to overload user in such cases
2137 let &SubtypePredicate { a_is_expected: _, a, b } = data.skip_binder();
2138 // both must be type variables, or the other would've been instantiated
2139 assert!(a.is_ty_var() && b.is_ty_var());
2140 self.need_type_info_err(body_id, span, a, ErrorCode::E0282)
2142 ty::Predicate::Projection(ref data) => {
2143 let trait_ref = data.to_poly_trait_ref(self.tcx);
2144 let self_ty = trait_ref.self_ty();
2145 if predicate.references_error() {
2148 let mut err = self.need_type_info_err(body_id, span, self_ty, ErrorCode::E0284);
2149 err.note(&format!("cannot resolve `{}`", predicate));
2154 if self.tcx.sess.has_errors() {
2157 let mut err = struct_span_err!(
2161 "type annotations needed: cannot resolve `{}`",
2164 err.span_label(span, &format!("cannot resolve `{}`", predicate));
2168 self.note_obligation_cause(&mut err, obligation);
2172 /// Returns `true` if the trait predicate may apply for *some* assignment
2173 /// to the type parameters.
2174 fn predicate_can_apply(
2176 param_env: ty::ParamEnv<'tcx>,
2177 pred: ty::PolyTraitRef<'tcx>,
2179 struct ParamToVarFolder<'a, 'tcx> {
2180 infcx: &'a InferCtxt<'a, 'tcx>,
2181 var_map: FxHashMap<Ty<'tcx>, Ty<'tcx>>,
2184 impl<'a, 'tcx> TypeFolder<'tcx> for ParamToVarFolder<'a, 'tcx> {
2185 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
2189 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
2190 if let ty::Param(ty::ParamTy { name, .. }) = ty.kind {
2191 let infcx = self.infcx;
2192 self.var_map.entry(ty).or_insert_with(|| {
2193 infcx.next_ty_var(TypeVariableOrigin {
2194 kind: TypeVariableOriginKind::TypeParameterDefinition(name, None),
2199 ty.super_fold_with(self)
2205 let mut selcx = SelectionContext::new(self);
2208 pred.fold_with(&mut ParamToVarFolder { infcx: self, var_map: Default::default() });
2210 let cleaned_pred = super::project::normalize(
2213 ObligationCause::dummy(),
2219 Obligation::new(ObligationCause::dummy(), param_env, cleaned_pred.to_predicate());
2221 self.predicate_may_hold(&obligation)
2225 fn note_obligation_cause(
2227 err: &mut DiagnosticBuilder<'_>,
2228 obligation: &PredicateObligation<'tcx>,
2230 // First, attempt to add note to this error with an async-await-specific
2231 // message, and fall back to regular note otherwise.
2232 if !self.maybe_note_obligation_cause_for_async_await(err, obligation) {
2233 self.note_obligation_cause_code(
2235 &obligation.predicate,
2236 &obligation.cause.code,
2242 /// Adds an async-await specific note to the diagnostic when the future does not implement
2243 /// an auto trait because of a captured type.
2245 /// ```ignore (diagnostic)
2246 /// note: future does not implement `Qux` as this value is used across an await
2247 /// --> $DIR/issue-64130-3-other.rs:17:5
2249 /// LL | let x = Foo;
2250 /// | - has type `Foo`
2251 /// LL | baz().await;
2252 /// | ^^^^^^^^^^^ await occurs here, with `x` maybe used later
2254 /// | - `x` is later dropped here
2257 /// When the diagnostic does not implement `Send` or `Sync` specifically, then the diagnostic
2258 /// is "replaced" with a different message and a more specific error.
2260 /// ```ignore (diagnostic)
2261 /// error: future cannot be sent between threads safely
2262 /// --> $DIR/issue-64130-2-send.rs:21:5
2264 /// LL | fn is_send<T: Send>(t: T) { }
2265 /// | ------- ---- required by this bound in `is_send`
2267 /// LL | is_send(bar());
2268 /// | ^^^^^^^ future returned by `bar` is not send
2270 /// = help: within `impl std::future::Future`, the trait `std::marker::Send` is not
2271 /// implemented for `Foo`
2272 /// note: future is not send as this value is used across an await
2273 /// --> $DIR/issue-64130-2-send.rs:15:5
2275 /// LL | let x = Foo;
2276 /// | - has type `Foo`
2277 /// LL | baz().await;
2278 /// | ^^^^^^^^^^^ await occurs here, with `x` maybe used later
2280 /// | - `x` is later dropped here
2283 /// Returns `true` if an async-await specific note was added to the diagnostic.
2284 fn maybe_note_obligation_cause_for_async_await(
2286 err: &mut DiagnosticBuilder<'_>,
2287 obligation: &PredicateObligation<'tcx>,
2290 "maybe_note_obligation_cause_for_async_await: obligation.predicate={:?} \
2291 obligation.cause.span={:?}",
2292 obligation.predicate, obligation.cause.span
2294 let source_map = self.tcx.sess.source_map();
2296 // Attempt to detect an async-await error by looking at the obligation causes, looking
2297 // for a generator to be present.
2299 // When a future does not implement a trait because of a captured type in one of the
2300 // generators somewhere in the call stack, then the result is a chain of obligations.
2302 // Given a `async fn` A that calls a `async fn` B which captures a non-send type and that
2303 // future is passed as an argument to a function C which requires a `Send` type, then the
2304 // chain looks something like this:
2306 // - `BuiltinDerivedObligation` with a generator witness (B)
2307 // - `BuiltinDerivedObligation` with a generator (B)
2308 // - `BuiltinDerivedObligation` with `std::future::GenFuture` (B)
2309 // - `BuiltinDerivedObligation` with `impl std::future::Future` (B)
2310 // - `BuiltinDerivedObligation` with `impl std::future::Future` (B)
2311 // - `BuiltinDerivedObligation` with a generator witness (A)
2312 // - `BuiltinDerivedObligation` with a generator (A)
2313 // - `BuiltinDerivedObligation` with `std::future::GenFuture` (A)
2314 // - `BuiltinDerivedObligation` with `impl std::future::Future` (A)
2315 // - `BuiltinDerivedObligation` with `impl std::future::Future` (A)
2316 // - `BindingObligation` with `impl_send (Send requirement)
2318 // The first obligation in the chain is the most useful and has the generator that captured
2319 // the type. The last generator has information about where the bound was introduced. At
2320 // least one generator should be present for this diagnostic to be modified.
2321 let (mut trait_ref, mut target_ty) = match obligation.predicate {
2322 ty::Predicate::Trait(p) => {
2323 (Some(p.skip_binder().trait_ref), Some(p.skip_binder().self_ty()))
2327 let mut generator = None;
2328 let mut last_generator = None;
2329 let mut next_code = Some(&obligation.cause.code);
2330 while let Some(code) = next_code {
2331 debug!("maybe_note_obligation_cause_for_async_await: code={:?}", code);
2333 ObligationCauseCode::BuiltinDerivedObligation(derived_obligation)
2334 | ObligationCauseCode::ImplDerivedObligation(derived_obligation) => {
2335 let ty = derived_obligation.parent_trait_ref.self_ty();
2337 "maybe_note_obligation_cause_for_async_await: \
2338 parent_trait_ref={:?} self_ty.kind={:?}",
2339 derived_obligation.parent_trait_ref, ty.kind
2343 ty::Generator(did, ..) => {
2344 generator = generator.or(Some(did));
2345 last_generator = Some(did);
2347 ty::GeneratorWitness(..) => {}
2348 _ if generator.is_none() => {
2349 trait_ref = Some(*derived_obligation.parent_trait_ref.skip_binder());
2350 target_ty = Some(ty);
2355 next_code = Some(derived_obligation.parent_code.as_ref());
2361 // Only continue if a generator was found.
2363 "maybe_note_obligation_cause_for_async_await: generator={:?} trait_ref={:?} \
2365 generator, trait_ref, target_ty
2367 let (generator_did, trait_ref, target_ty) = match (generator, trait_ref, target_ty) {
2368 (Some(generator_did), Some(trait_ref), Some(target_ty)) => {
2369 (generator_did, trait_ref, target_ty)
2374 let span = self.tcx.def_span(generator_did);
2376 // Do not ICE on closure typeck (#66868).
2377 if self.tcx.hir().as_local_hir_id(generator_did).is_none() {
2381 // Get the tables from the infcx if the generator is the function we are
2382 // currently type-checking; otherwise, get them by performing a query.
2383 // This is needed to avoid cycles.
2384 let in_progress_tables = self.in_progress_tables.map(|t| t.borrow());
2385 let generator_did_root = self.tcx.closure_base_def_id(generator_did);
2387 "maybe_note_obligation_cause_for_async_await: generator_did={:?} \
2388 generator_did_root={:?} in_progress_tables.local_id_root={:?} span={:?}",
2391 in_progress_tables.as_ref().map(|t| t.local_id_root),
2395 let tables: &TypeckTables<'tcx> = match &in_progress_tables {
2396 Some(t) if t.local_id_root == Some(generator_did_root) => t,
2398 query_tables = self.tcx.typeck_tables_of(generator_did);
2403 // Look for a type inside the generator interior that matches the target type to get
2405 let target_ty_erased = self.tcx.erase_regions(&target_ty);
2406 let target_span = tables
2407 .generator_interior_types
2409 .find(|ty::GeneratorInteriorTypeCause { ty, .. }| {
2410 // Careful: the regions for types that appear in the
2411 // generator interior are not generally known, so we
2412 // want to erase them when comparing (and anyway,
2413 // `Send` and other bounds are generally unaffected by
2414 // the choice of region). When erasing regions, we
2415 // also have to erase late-bound regions. This is
2416 // because the types that appear in the generator
2417 // interior generally contain "bound regions" to
2418 // represent regions that are part of the suspended
2419 // generator frame. Bound regions are preserved by
2420 // `erase_regions` and so we must also call
2421 // `erase_late_bound_regions`.
2422 let ty_erased = self.tcx.erase_late_bound_regions(&ty::Binder::bind(*ty));
2423 let ty_erased = self.tcx.erase_regions(&ty_erased);
2424 let eq = ty::TyS::same_type(ty_erased, target_ty_erased);
2426 "maybe_note_obligation_cause_for_async_await: ty_erased={:?} \
2427 target_ty_erased={:?} eq={:?}",
2428 ty_erased, target_ty_erased, eq
2432 .map(|ty::GeneratorInteriorTypeCause { span, scope_span, .. }| {
2433 (span, source_map.span_to_snippet(*span), scope_span)
2436 "maybe_note_obligation_cause_for_async_await: target_ty={:?} \
2437 generator_interior_types={:?} target_span={:?}",
2438 target_ty, tables.generator_interior_types, target_span
2440 if let Some((target_span, Ok(snippet), scope_span)) = target_span {
2441 self.note_obligation_cause_for_async_await(
2460 /// Unconditionally adds the diagnostic note described in
2461 /// `maybe_note_obligation_cause_for_async_await`'s documentation comment.
2462 fn note_obligation_cause_for_async_await(
2464 err: &mut DiagnosticBuilder<'_>,
2466 scope_span: &Option<Span>,
2468 first_generator: DefId,
2469 last_generator: Option<DefId>,
2470 trait_ref: ty::TraitRef<'_>,
2471 target_ty: Ty<'tcx>,
2472 tables: &ty::TypeckTables<'_>,
2473 obligation: &PredicateObligation<'tcx>,
2474 next_code: Option<&ObligationCauseCode<'tcx>>,
2476 let source_map = self.tcx.sess.source_map();
2478 let is_async_fn = self
2480 .parent(first_generator)
2481 .map(|parent_did| self.tcx.asyncness(parent_did))
2482 .map(|parent_asyncness| parent_asyncness == hir::IsAsync::Async)
2484 let is_async_move = self
2487 .as_local_hir_id(first_generator)
2488 .and_then(|hir_id| self.tcx.hir().maybe_body_owned_by(hir_id))
2489 .map(|body_id| self.tcx.hir().body(body_id))
2490 .and_then(|body| body.generator_kind())
2491 .map(|generator_kind| match generator_kind {
2492 hir::GeneratorKind::Async(..) => true,
2496 let await_or_yield = if is_async_fn || is_async_move { "await" } else { "yield" };
2498 // Special case the primary error message when send or sync is the trait that was
2500 let is_send = self.tcx.is_diagnostic_item(sym::send_trait, trait_ref.def_id);
2501 let is_sync = self.tcx.is_diagnostic_item(sym::sync_trait, trait_ref.def_id);
2502 let trait_explanation = if is_send || is_sync {
2503 let (trait_name, trait_verb) =
2504 if is_send { ("`Send`", "sent") } else { ("`Sync`", "shared") };
2507 err.set_primary_message(format!(
2508 "future cannot be {} between threads safely",
2512 let original_span = err.span.primary_span().unwrap();
2513 let mut span = MultiSpan::from_span(original_span);
2515 let message = if let Some(name) = last_generator
2516 .and_then(|generator_did| self.tcx.parent(generator_did))
2517 .and_then(|parent_did| self.tcx.hir().as_local_hir_id(parent_did))
2518 .and_then(|parent_hir_id| self.tcx.hir().opt_name(parent_hir_id))
2520 format!("future returned by `{}` is not {}", name, trait_name)
2522 format!("future is not {}", trait_name)
2525 span.push_span_label(original_span, message);
2528 format!("is not {}", trait_name)
2530 format!("does not implement `{}`", trait_ref.print_only_trait_path())
2533 // Look at the last interior type to get a span for the `.await`.
2534 let await_span = tables.generator_interior_types.iter().map(|i| i.span).last().unwrap();
2535 let mut span = MultiSpan::from_span(await_span);
2536 span.push_span_label(
2538 format!("{} occurs here, with `{}` maybe used later", await_or_yield, snippet),
2541 span.push_span_label(target_span, format!("has type `{}`", target_ty));
2543 // If available, use the scope span to annotate the drop location.
2544 if let Some(scope_span) = scope_span {
2545 span.push_span_label(
2546 source_map.end_point(*scope_span),
2547 format!("`{}` is later dropped here", snippet),
2554 "future {} as this value is used across an {}",
2555 trait_explanation, await_or_yield,
2559 // Add a note for the item obligation that remains - normally a note pointing to the
2560 // bound that introduced the obligation (e.g. `T: Send`).
2561 debug!("note_obligation_cause_for_async_await: next_code={:?}", next_code);
2562 self.note_obligation_cause_code(
2564 &obligation.predicate,
2570 fn note_obligation_cause_code<T>(
2572 err: &mut DiagnosticBuilder<'_>,
2574 cause_code: &ObligationCauseCode<'tcx>,
2575 obligated_types: &mut Vec<&ty::TyS<'tcx>>,
2581 ObligationCauseCode::ExprAssignable
2582 | ObligationCauseCode::MatchExpressionArm { .. }
2583 | ObligationCauseCode::Pattern { .. }
2584 | ObligationCauseCode::IfExpression { .. }
2585 | ObligationCauseCode::IfExpressionWithNoElse
2586 | ObligationCauseCode::MainFunctionType
2587 | ObligationCauseCode::StartFunctionType
2588 | ObligationCauseCode::IntrinsicType
2589 | ObligationCauseCode::MethodReceiver
2590 | ObligationCauseCode::ReturnNoExpression
2591 | ObligationCauseCode::MiscObligation => {}
2592 ObligationCauseCode::SliceOrArrayElem => {
2593 err.note("slice and array elements must have `Sized` type");
2595 ObligationCauseCode::TupleElem => {
2596 err.note("only the last element of a tuple may have a dynamically sized type");
2598 ObligationCauseCode::ProjectionWf(data) => {
2599 err.note(&format!("required so that the projection `{}` is well-formed", data,));
2601 ObligationCauseCode::ReferenceOutlivesReferent(ref_ty) => {
2603 "required so that reference `{}` does not outlive its referent",
2607 ObligationCauseCode::ObjectTypeBound(object_ty, region) => {
2609 "required so that the lifetime bound of `{}` for `{}` is satisfied",
2613 ObligationCauseCode::ItemObligation(item_def_id) => {
2614 let item_name = tcx.def_path_str(item_def_id);
2615 let msg = format!("required by `{}`", item_name);
2617 if let Some(sp) = tcx.hir().span_if_local(item_def_id) {
2618 let sp = tcx.sess.source_map().def_span(sp);
2619 err.span_label(sp, &msg);
2624 ObligationCauseCode::BindingObligation(item_def_id, span) => {
2625 let item_name = tcx.def_path_str(item_def_id);
2626 let msg = format!("required by this bound in `{}`", item_name);
2627 if let Some(ident) = tcx.opt_item_name(item_def_id) {
2628 err.span_label(ident.span, "");
2630 if span != DUMMY_SP {
2631 err.span_label(span, &msg);
2636 ObligationCauseCode::ObjectCastObligation(object_ty) => {
2638 "required for the cast to the object type `{}`",
2639 self.ty_to_string(object_ty)
2642 ObligationCauseCode::Coercion { source: _, target } => {
2643 err.note(&format!("required by cast to type `{}`", self.ty_to_string(target)));
2645 ObligationCauseCode::RepeatVec(suggest_const_in_array_repeat_expressions) => {
2647 "the `Copy` trait is required because the \
2648 repeated element will be copied",
2650 if suggest_const_in_array_repeat_expressions {
2652 "this array initializer can be evaluated at compile-time, for more \
2653 information, see issue \
2654 https://github.com/rust-lang/rust/issues/49147",
2656 if tcx.sess.opts.unstable_features.is_nightly_build() {
2658 "add `#![feature(const_in_array_repeat_expressions)]` to the \
2659 crate attributes to enable",
2664 ObligationCauseCode::VariableType(_) => {
2665 err.note("all local variables must have a statically known size");
2666 if !self.tcx.features().unsized_locals {
2667 err.help("unsized locals are gated as an unstable feature");
2670 ObligationCauseCode::SizedArgumentType => {
2671 err.note("all function arguments must have a statically known size");
2672 if !self.tcx.features().unsized_locals {
2673 err.help("unsized locals are gated as an unstable feature");
2676 ObligationCauseCode::SizedReturnType => {
2678 "the return type of a function must have a \
2679 statically known size",
2682 ObligationCauseCode::SizedYieldType => {
2684 "the yield type of a generator must have a \
2685 statically known size",
2688 ObligationCauseCode::AssignmentLhsSized => {
2689 err.note("the left-hand-side of an assignment must have a statically known size");
2691 ObligationCauseCode::TupleInitializerSized => {
2692 err.note("tuples must have a statically known size to be initialized");
2694 ObligationCauseCode::StructInitializerSized => {
2695 err.note("structs must have a statically known size to be initialized");
2697 ObligationCauseCode::FieldSized { adt_kind: ref item, last } => match *item {
2698 AdtKind::Struct => {
2701 "the last field of a packed struct may only have a \
2702 dynamically sized type if it does not need drop to be run",
2706 "only the last field of a struct may have a dynamically \
2712 err.note("no field of a union may have a dynamically sized type");
2715 err.note("no field of an enum variant may have a dynamically sized type");
2718 ObligationCauseCode::ConstSized => {
2719 err.note("constant expressions must have a statically known size");
2721 ObligationCauseCode::ConstPatternStructural => {
2722 err.note("constants used for pattern-matching must derive `PartialEq` and `Eq`");
2724 ObligationCauseCode::SharedStatic => {
2725 err.note("shared static variables must have a type that implements `Sync`");
2727 ObligationCauseCode::BuiltinDerivedObligation(ref data) => {
2728 let parent_trait_ref = self.resolve_vars_if_possible(&data.parent_trait_ref);
2729 let ty = parent_trait_ref.skip_binder().self_ty();
2730 err.note(&format!("required because it appears within the type `{}`", ty));
2731 obligated_types.push(ty);
2733 let parent_predicate = parent_trait_ref.to_predicate();
2734 if !self.is_recursive_obligation(obligated_types, &data.parent_code) {
2735 self.note_obligation_cause_code(
2743 ObligationCauseCode::ImplDerivedObligation(ref data) => {
2744 let parent_trait_ref = self.resolve_vars_if_possible(&data.parent_trait_ref);
2746 "required because of the requirements on the impl of `{}` for `{}`",
2747 parent_trait_ref.print_only_trait_path(),
2748 parent_trait_ref.skip_binder().self_ty()
2750 let parent_predicate = parent_trait_ref.to_predicate();
2751 self.note_obligation_cause_code(
2758 ObligationCauseCode::CompareImplMethodObligation { .. } => {
2760 "the requirement `{}` appears on the impl method \
2761 but not on the corresponding trait method",
2765 ObligationCauseCode::CompareImplTypeObligation { .. } => {
2767 "the requirement `{}` appears on the associated impl type\
2768 but not on the corresponding associated trait type",
2772 ObligationCauseCode::ReturnType
2773 | ObligationCauseCode::ReturnValue(_)
2774 | ObligationCauseCode::BlockTailExpression(_) => (),
2775 ObligationCauseCode::TrivialBound => {
2776 err.help("see issue #48214");
2777 if tcx.sess.opts.unstable_features.is_nightly_build() {
2779 "add `#![feature(trivial_bounds)]` to the \
2780 crate attributes to enable",
2784 ObligationCauseCode::AssocTypeBound(ref data) => {
2785 err.span_label(data.original, "associated type defined here");
2786 if let Some(sp) = data.impl_span {
2787 err.span_label(sp, "in this `impl` item");
2789 for sp in &data.bounds {
2790 err.span_label(*sp, "restricted in this bound");
2796 fn suggest_new_overflow_limit(&self, err: &mut DiagnosticBuilder<'_>) {
2797 let current_limit = self.tcx.sess.recursion_limit.get();
2798 let suggested_limit = current_limit * 2;
2800 "consider adding a `#![recursion_limit=\"{}\"]` attribute to your crate",
2805 fn is_recursive_obligation(
2807 obligated_types: &mut Vec<&ty::TyS<'tcx>>,
2808 cause_code: &ObligationCauseCode<'tcx>,
2810 if let ObligationCauseCode::BuiltinDerivedObligation(ref data) = cause_code {
2811 let parent_trait_ref = self.resolve_vars_if_possible(&data.parent_trait_ref);
2813 if obligated_types.iter().any(|ot| ot == &parent_trait_ref.skip_binder().self_ty()) {
2821 /// Summarizes information
2824 /// An argument of non-tuple type. Parameters are (name, ty)
2825 Arg(String, String),
2827 /// An argument of tuple type. For a "found" argument, the span is
2828 /// the locationo in the source of the pattern. For a "expected"
2829 /// argument, it will be None. The vector is a list of (name, ty)
2830 /// strings for the components of the tuple.
2831 Tuple(Option<Span>, Vec<(String, String)>),
2835 fn empty() -> ArgKind {
2836 ArgKind::Arg("_".to_owned(), "_".to_owned())
2839 /// Creates an `ArgKind` from the expected type of an
2840 /// argument. It has no name (`_`) and an optional source span.
2841 pub fn from_expected_ty(t: Ty<'_>, span: Option<Span>) -> ArgKind {
2843 ty::Tuple(ref tys) => ArgKind::Tuple(
2845 tys.iter().map(|ty| ("_".to_owned(), ty.to_string())).collect::<Vec<_>>(),
2847 _ => ArgKind::Arg("_".to_owned(), t.to_string()),
2852 /// Suggest restricting a type param with a new bound.
2853 pub fn suggest_constraining_type_param(
2854 generics: &hir::Generics<'_>,
2855 err: &mut DiagnosticBuilder<'_>,
2858 source_map: &SourceMap,
2861 let restrict_msg = "consider further restricting this bound";
2862 if let Some(param) =
2863 generics.params.iter().filter(|p| p.name.ident().as_str() == param_name).next()
2865 if param_name.starts_with("impl ") {
2866 // `impl Trait` in argument:
2867 // `fn foo(x: impl Trait) {}` → `fn foo(t: impl Trait + Trait2) {}`
2868 err.span_suggestion(
2871 // `impl CurrentTrait + MissingTrait`
2872 format!("{} + {}", param_name, constraint),
2873 Applicability::MachineApplicable,
2875 } else if generics.where_clause.predicates.is_empty() && param.bounds.is_empty() {
2876 // If there are no bounds whatsoever, suggest adding a constraint
2877 // to the type parameter:
2878 // `fn foo<T>(t: T) {}` → `fn foo<T: Trait>(t: T) {}`
2879 err.span_suggestion(
2881 "consider restricting this bound",
2882 format!("{}: {}", param_name, constraint),
2883 Applicability::MachineApplicable,
2885 } else if !generics.where_clause.predicates.is_empty() {
2886 // There is a `where` clause, so suggest expanding it:
2887 // `fn foo<T>(t: T) where T: Debug {}` →
2888 // `fn foo<T>(t: T) where T: Debug, T: Trait {}`
2889 err.span_suggestion(
2890 generics.where_clause.span().unwrap().shrink_to_hi(),
2891 &format!("consider further restricting type parameter `{}`", param_name),
2892 format!(", {}: {}", param_name, constraint),
2893 Applicability::MachineApplicable,
2896 // If there is no `where` clause lean towards constraining to the
2898 // `fn foo<X: Bar, T>(t: T, x: X) {}` → `fn foo<T: Trait>(t: T) {}`
2899 // `fn foo<T: Bar>(t: T) {}` → `fn foo<T: Bar + Trait>(t: T) {}`
2900 let sp = param.span.with_hi(span.hi());
2901 let span = source_map.span_through_char(sp, ':');
2902 if sp != param.span && sp != span {
2903 // Only suggest if we have high certainty that the span
2904 // covers the colon in `foo<T: Trait>`.
2905 err.span_suggestion(
2908 format!("{}: {} + ", param_name, constraint),
2909 Applicability::MachineApplicable,
2914 &format!("consider adding a `where {}: {}` bound", param_name, constraint),