6 MismatchedProjectionTypes,
11 OnUnimplementedDirective,
13 OutputTypeParameterMismatch,
23 use crate::hir::def_id::DefId;
24 use crate::infer::{self, InferCtxt};
25 use crate::infer::error_reporting::TypeAnnotationNeeded as ErrorCode;
26 use crate::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
27 use crate::session::DiagnosticMessageId;
28 use crate::ty::{self, AdtKind, DefIdTree, ToPredicate, ToPolyTraitRef, Ty, TyCtxt, TypeFoldable};
29 use crate::ty::TypeckTables;
30 use crate::ty::GenericParamDefKind;
31 use crate::ty::error::ExpectedFound;
32 use crate::ty::fast_reject;
33 use crate::ty::fold::TypeFolder;
34 use crate::ty::subst::Subst;
35 use crate::ty::SubtypePredicate;
36 use crate::util::nodemap::{FxHashMap, FxHashSet};
38 use errors::{Applicability, DiagnosticBuilder, pluralize, Style};
41 use syntax::symbol::{sym, kw};
42 use syntax_pos::{DUMMY_SP, Span, ExpnKind, MultiSpan};
43 use rustc::hir::def_id::LOCAL_CRATE;
44 use syntax_pos::source_map::SourceMap;
46 use rustc_error_codes::*;
48 impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
49 pub fn report_fulfillment_errors(
51 errors: &[FulfillmentError<'tcx>],
52 body_id: Option<hir::BodyId>,
53 fallback_has_occurred: bool,
56 struct ErrorDescriptor<'tcx> {
57 predicate: ty::Predicate<'tcx>,
58 index: Option<usize>, // None if this is an old error
61 let mut error_map: FxHashMap<_, Vec<_>> =
62 self.reported_trait_errors.borrow().iter().map(|(&span, predicates)| {
63 (span, predicates.iter().map(|predicate| ErrorDescriptor {
64 predicate: predicate.clone(),
69 for (index, error) in errors.iter().enumerate() {
70 // We want to ignore desugarings here: spans are equivalent even
71 // if one is the result of a desugaring and the other is not.
72 let mut span = error.obligation.cause.span;
73 let expn_data = span.ctxt().outer_expn_data();
74 if let ExpnKind::Desugaring(_) = expn_data.kind {
75 span = expn_data.call_site;
78 error_map.entry(span).or_default().push(
80 predicate: error.obligation.predicate.clone(),
85 self.reported_trait_errors.borrow_mut()
86 .entry(span).or_default()
87 .push(error.obligation.predicate.clone());
90 // We do this in 2 passes because we want to display errors in order, though
91 // maybe it *is* better to sort errors by span or something.
92 let mut is_suppressed = vec![false; errors.len()];
93 for (_, error_set) in error_map.iter() {
94 // We want to suppress "duplicate" errors with the same span.
95 for error in error_set {
96 if let Some(index) = error.index {
97 // Suppress errors that are either:
98 // 1) strictly implied by another error.
99 // 2) implied by an error with a smaller index.
100 for error2 in error_set {
101 if error2.index.map_or(false, |index2| is_suppressed[index2]) {
102 // Avoid errors being suppressed by already-suppressed
103 // errors, to prevent all errors from being suppressed
108 if self.error_implies(&error2.predicate, &error.predicate) &&
109 !(error2.index >= error.index &&
110 self.error_implies(&error.predicate, &error2.predicate))
112 info!("skipping {:?} (implied by {:?})", error, error2);
113 is_suppressed[index] = true;
121 for (error, suppressed) in errors.iter().zip(is_suppressed) {
123 self.report_fulfillment_error(error, body_id, fallback_has_occurred);
128 // returns if `cond` not occurring implies that `error` does not occur - i.e., that
129 // `error` occurring implies that `cond` occurs.
132 cond: &ty::Predicate<'tcx>,
133 error: &ty::Predicate<'tcx>,
139 let (cond, error) = match (cond, error) {
140 (&ty::Predicate::Trait(..), &ty::Predicate::Trait(ref error))
143 // FIXME: make this work in other cases too.
148 for implication in super::elaborate_predicates(self.tcx, vec![cond.clone()]) {
149 if let ty::Predicate::Trait(implication) = implication {
150 let error = error.to_poly_trait_ref();
151 let implication = implication.to_poly_trait_ref();
152 // FIXME: I'm just not taking associated types at all here.
153 // Eventually I'll need to implement param-env-aware
154 // `Γ₁ ⊦ φ₁ => Γ₂ ⊦ φ₂` logic.
155 let param_env = ty::ParamEnv::empty();
156 if self.can_sub(param_env, error, implication).is_ok() {
157 debug!("error_implies: {:?} -> {:?} -> {:?}", cond, error, implication);
166 fn report_fulfillment_error(
168 error: &FulfillmentError<'tcx>,
169 body_id: Option<hir::BodyId>,
170 fallback_has_occurred: bool,
172 debug!("report_fulfillment_error({:?})", error);
174 FulfillmentErrorCode::CodeSelectionError(ref selection_error) => {
175 self.report_selection_error(
178 fallback_has_occurred,
179 error.points_at_arg_span,
182 FulfillmentErrorCode::CodeProjectionError(ref e) => {
183 self.report_projection_error(&error.obligation, e);
185 FulfillmentErrorCode::CodeAmbiguity => {
186 self.maybe_report_ambiguity(&error.obligation, body_id);
188 FulfillmentErrorCode::CodeSubtypeError(ref expected_found, ref err) => {
189 self.report_mismatched_types(
190 &error.obligation.cause,
191 expected_found.expected,
192 expected_found.found,
199 fn report_projection_error(
201 obligation: &PredicateObligation<'tcx>,
202 error: &MismatchedProjectionTypes<'tcx>,
204 let predicate = self.resolve_vars_if_possible(&obligation.predicate);
206 if predicate.references_error() {
212 let mut err = &error.err;
213 let mut values = None;
215 // try to find the mismatched types to report the error with.
217 // this can fail if the problem was higher-ranked, in which
218 // cause I have no idea for a good error message.
219 if let ty::Predicate::Projection(ref data) = predicate {
220 let mut selcx = SelectionContext::new(self);
221 let (data, _) = self.replace_bound_vars_with_fresh_vars(
222 obligation.cause.span,
223 infer::LateBoundRegionConversionTime::HigherRankedType,
226 let mut obligations = vec![];
227 let normalized_ty = super::normalize_projection_type(
229 obligation.param_env,
231 obligation.cause.clone(),
236 debug!("report_projection_error obligation.cause={:?} obligation.param_env={:?}",
237 obligation.cause, obligation.param_env);
239 debug!("report_projection_error normalized_ty={:?} data.ty={:?}",
240 normalized_ty, data.ty);
242 let is_normalized_ty_expected = match &obligation.cause.code {
243 ObligationCauseCode::ItemObligation(_) |
244 ObligationCauseCode::BindingObligation(_, _) |
245 ObligationCauseCode::ObjectCastObligation(_) => false,
249 if let Err(error) = self.at(&obligation.cause, obligation.param_env)
250 .eq_exp(is_normalized_ty_expected, normalized_ty, data.ty)
252 values = Some(infer::ValuePairs::Types(
253 ExpectedFound::new(is_normalized_ty_expected, normalized_ty, data.ty)));
260 let msg = format!("type mismatch resolving `{}`", predicate);
262 DiagnosticMessageId::ErrorId(271),
263 Some(obligation.cause.span),
266 let fresh = self.tcx.sess.one_time_diagnostics.borrow_mut().insert(error_id);
268 let mut diag = struct_span_err!(
270 obligation.cause.span,
272 "type mismatch resolving `{}`",
275 self.note_type_err(&mut diag, &obligation.cause, None, values, err);
276 self.note_obligation_cause(&mut diag, obligation);
282 fn fuzzy_match_tys(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
283 /// returns the fuzzy category of a given type, or None
284 /// if the type can be equated to any type.
285 fn type_category(t: Ty<'_>) -> Option<u32> {
290 ty::Int(..) | ty::Uint(..) | ty::Infer(ty::IntVar(..)) => Some(3),
291 ty::Float(..) | ty::Infer(ty::FloatVar(..)) => Some(4),
292 ty::Ref(..) | ty::RawPtr(..) => Some(5),
293 ty::Array(..) | ty::Slice(..) => Some(6),
294 ty::FnDef(..) | ty::FnPtr(..) => Some(7),
295 ty::Dynamic(..) => Some(8),
296 ty::Closure(..) => Some(9),
297 ty::Tuple(..) => Some(10),
298 ty::Projection(..) => Some(11),
299 ty::Param(..) => Some(12),
300 ty::Opaque(..) => Some(13),
301 ty::Never => Some(14),
302 ty::Adt(adt, ..) => match adt.adt_kind() {
303 AdtKind::Struct => Some(15),
304 AdtKind::Union => Some(16),
305 AdtKind::Enum => Some(17),
307 ty::Generator(..) => Some(18),
308 ty::Foreign(..) => Some(19),
309 ty::GeneratorWitness(..) => Some(20),
310 ty::Placeholder(..) | ty::Bound(..) | ty::Infer(..) | ty::Error => None,
311 ty::UnnormalizedProjection(..) => bug!("only used with chalk-engine"),
315 match (type_category(a), type_category(b)) {
316 (Some(cat_a), Some(cat_b)) => match (&a.kind, &b.kind) {
317 (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) => def_a == def_b,
320 // infer and error can be equated to all types
325 fn impl_similar_to(&self,
326 trait_ref: ty::PolyTraitRef<'tcx>,
327 obligation: &PredicateObligation<'tcx>)
331 let param_env = obligation.param_env;
332 let trait_ref = tcx.erase_late_bound_regions(&trait_ref);
333 let trait_self_ty = trait_ref.self_ty();
335 let mut self_match_impls = vec![];
336 let mut fuzzy_match_impls = vec![];
338 self.tcx.for_each_relevant_impl(
339 trait_ref.def_id, trait_self_ty, |def_id| {
340 let impl_substs = self.fresh_substs_for_item(obligation.cause.span, def_id);
341 let impl_trait_ref = tcx
342 .impl_trait_ref(def_id)
344 .subst(tcx, impl_substs);
346 let impl_self_ty = impl_trait_ref.self_ty();
348 if let Ok(..) = self.can_eq(param_env, trait_self_ty, impl_self_ty) {
349 self_match_impls.push(def_id);
351 if trait_ref.substs.types().skip(1)
352 .zip(impl_trait_ref.substs.types().skip(1))
353 .all(|(u,v)| self.fuzzy_match_tys(u, v))
355 fuzzy_match_impls.push(def_id);
360 let impl_def_id = if self_match_impls.len() == 1 {
362 } else if fuzzy_match_impls.len() == 1 {
368 tcx.has_attr(impl_def_id, sym::rustc_on_unimplemented).then_some(impl_def_id)
371 fn describe_generator(&self, body_id: hir::BodyId) -> Option<&'static str> {
372 self.tcx.hir().body(body_id).generator_kind.map(|gen_kind| {
374 hir::GeneratorKind::Gen => "a generator",
375 hir::GeneratorKind::Async(hir::AsyncGeneratorKind::Block) => "an async block",
376 hir::GeneratorKind::Async(hir::AsyncGeneratorKind::Fn) => "an async function",
377 hir::GeneratorKind::Async(hir::AsyncGeneratorKind::Closure) => "an async closure",
382 /// Used to set on_unimplemented's `ItemContext`
383 /// to be the enclosing (async) block/function/closure
384 fn describe_enclosure(&self, hir_id: hir::HirId) -> Option<&'static str> {
385 let hir = &self.tcx.hir();
386 let node = hir.find(hir_id)?;
387 if let hir::Node::Item(
388 hir::Item{kind: hir::ItemKind::Fn(sig, _, body_id), .. }) = &node {
389 self.describe_generator(*body_id).or_else(||
390 Some(if let hir::FnHeader{ asyncness: hir::IsAsync::Async, .. } = sig.header {
396 } else if let hir::Node::Expr(hir::Expr {
397 kind: hir::ExprKind::Closure(_is_move, _, body_id, _, gen_movability), .. }) = &node {
398 self.describe_generator(*body_id).or_else(||
399 Some(if gen_movability.is_some() {
405 } else if let hir::Node::Expr(hir::Expr { .. }) = &node {
406 let parent_hid = hir.get_parent_node(hir_id);
407 if parent_hid != hir_id {
408 return self.describe_enclosure(parent_hid);
417 fn on_unimplemented_note(
419 trait_ref: ty::PolyTraitRef<'tcx>,
420 obligation: &PredicateObligation<'tcx>,
421 ) -> OnUnimplementedNote {
422 let def_id = self.impl_similar_to(trait_ref, obligation)
423 .unwrap_or_else(|| trait_ref.def_id());
424 let trait_ref = *trait_ref.skip_binder();
426 let mut flags = vec![];
427 flags.push((sym::item_context,
428 self.describe_enclosure(obligation.cause.body_id).map(|s|s.to_owned())));
430 match obligation.cause.code {
431 ObligationCauseCode::BuiltinDerivedObligation(..) |
432 ObligationCauseCode::ImplDerivedObligation(..) => {}
434 // this is a "direct", user-specified, rather than derived,
436 flags.push((sym::direct, None));
440 if let ObligationCauseCode::ItemObligation(item) = obligation.cause.code {
441 // FIXME: maybe also have some way of handling methods
442 // from other traits? That would require name resolution,
443 // which we might want to be some sort of hygienic.
445 // Currently I'm leaving it for what I need for `try`.
446 if self.tcx.trait_of_item(item) == Some(trait_ref.def_id) {
447 let method = self.tcx.item_name(item);
448 flags.push((sym::from_method, None));
449 flags.push((sym::from_method, Some(method.to_string())));
452 if let Some(t) = self.get_parent_trait_ref(&obligation.cause.code) {
453 flags.push((sym::parent_trait, Some(t)));
456 if let Some(k) = obligation.cause.span.desugaring_kind() {
457 flags.push((sym::from_desugaring, None));
458 flags.push((sym::from_desugaring, Some(format!("{:?}", k))));
460 let generics = self.tcx.generics_of(def_id);
461 let self_ty = trait_ref.self_ty();
462 // This is also included through the generics list as `Self`,
463 // but the parser won't allow you to use it
464 flags.push((sym::_Self, Some(self_ty.to_string())));
465 if let Some(def) = self_ty.ty_adt_def() {
466 // We also want to be able to select self's original
467 // signature with no type arguments resolved
468 flags.push((sym::_Self, Some(self.tcx.type_of(def.did).to_string())));
471 for param in generics.params.iter() {
472 let value = match param.kind {
473 GenericParamDefKind::Type { .. } |
474 GenericParamDefKind::Const => {
475 trait_ref.substs[param.index as usize].to_string()
477 GenericParamDefKind::Lifetime => continue,
479 let name = param.name;
480 flags.push((name, Some(value)));
483 if let Some(true) = self_ty.ty_adt_def().map(|def| def.did.is_local()) {
484 flags.push((sym::crate_local, None));
487 // Allow targeting all integers using `{integral}`, even if the exact type was resolved
488 if self_ty.is_integral() {
489 flags.push((sym::_Self, Some("{integral}".to_owned())));
492 if let ty::Array(aty, len) = self_ty.kind {
493 flags.push((sym::_Self, Some("[]".to_owned())));
494 flags.push((sym::_Self, Some(format!("[{}]", aty))));
495 if let Some(def) = aty.ty_adt_def() {
496 // We also want to be able to select the array's type's original
497 // signature with no type arguments resolved
500 Some(format!("[{}]", self.tcx.type_of(def.did).to_string())),
503 if let Some(len) = len.try_eval_usize(tcx, ty::ParamEnv::empty()) {
506 Some(format!("[{}; {}]", self.tcx.type_of(def.did).to_string(), len)),
511 Some(format!("[{}; _]", self.tcx.type_of(def.did).to_string())),
517 if let Ok(Some(command)) = OnUnimplementedDirective::of_item(
518 self.tcx, trait_ref.def_id, def_id
520 command.evaluate(self.tcx, trait_ref, &flags[..])
522 OnUnimplementedNote::default()
526 fn find_similar_impl_candidates(
528 trait_ref: ty::PolyTraitRef<'tcx>,
529 ) -> Vec<ty::TraitRef<'tcx>> {
530 let simp = fast_reject::simplify_type(self.tcx, trait_ref.skip_binder().self_ty(), true);
531 let all_impls = self.tcx.all_impls(trait_ref.def_id());
534 Some(simp) => all_impls.iter().filter_map(|&def_id| {
535 let imp = self.tcx.impl_trait_ref(def_id).unwrap();
536 let imp_simp = fast_reject::simplify_type(self.tcx, imp.self_ty(), true);
537 if let Some(imp_simp) = imp_simp {
538 if simp != imp_simp {
545 None => all_impls.iter().map(|&def_id|
546 self.tcx.impl_trait_ref(def_id).unwrap()
551 fn report_similar_impl_candidates(
553 impl_candidates: Vec<ty::TraitRef<'tcx>>,
554 err: &mut DiagnosticBuilder<'_>,
556 if impl_candidates.is_empty() {
560 let len = impl_candidates.len();
561 let end = if impl_candidates.len() <= 5 {
562 impl_candidates.len()
567 let normalize = |candidate| self.tcx.infer_ctxt().enter(|ref infcx| {
568 let normalized = infcx
569 .at(&ObligationCause::dummy(), ty::ParamEnv::empty())
570 .normalize(candidate)
573 Some(normalized) => format!("\n {:?}", normalized.value),
574 None => format!("\n {:?}", candidate),
578 // Sort impl candidates so that ordering is consistent for UI tests.
579 let mut normalized_impl_candidates = impl_candidates
582 .collect::<Vec<String>>();
584 // Sort before taking the `..end` range,
585 // because the ordering of `impl_candidates` may not be deterministic:
586 // https://github.com/rust-lang/rust/pull/57475#issuecomment-455519507
587 normalized_impl_candidates.sort();
589 err.help(&format!("the following implementations were found:{}{}",
590 normalized_impl_candidates[..end].join(""),
592 format!("\nand {} others", len - 4)
599 /// Reports that an overflow has occurred and halts compilation. We
600 /// halt compilation unconditionally because it is important that
601 /// overflows never be masked -- they basically represent computations
602 /// whose result could not be truly determined and thus we can't say
603 /// if the program type checks or not -- and they are unusual
604 /// occurrences in any case.
605 pub fn report_overflow_error<T>(
607 obligation: &Obligation<'tcx, T>,
608 suggest_increasing_limit: bool,
610 where T: fmt::Display + TypeFoldable<'tcx>
613 self.resolve_vars_if_possible(&obligation.predicate);
614 let mut err = struct_span_err!(
616 obligation.cause.span,
618 "overflow evaluating the requirement `{}`",
622 if suggest_increasing_limit {
623 self.suggest_new_overflow_limit(&mut err);
626 self.note_obligation_cause_code(
628 &obligation.predicate,
629 &obligation.cause.code,
634 self.tcx.sess.abort_if_errors();
638 /// Reports that a cycle was detected which led to overflow and halts
639 /// compilation. This is equivalent to `report_overflow_error` except
640 /// that we can give a more helpful error message (and, in particular,
641 /// we do not suggest increasing the overflow limit, which is not
643 pub fn report_overflow_error_cycle(&self, cycle: &[PredicateObligation<'tcx>]) -> ! {
644 let cycle = self.resolve_vars_if_possible(&cycle.to_owned());
645 assert!(cycle.len() > 0);
647 debug!("report_overflow_error_cycle: cycle={:?}", cycle);
649 self.report_overflow_error(&cycle[0], false);
652 pub fn report_extra_impl_obligation(&self,
654 item_name: ast::Name,
655 _impl_item_def_id: DefId,
656 trait_item_def_id: DefId,
657 requirement: &dyn fmt::Display)
658 -> DiagnosticBuilder<'tcx>
660 let msg = "impl has stricter requirements than trait";
661 let sp = self.tcx.sess.source_map().def_span(error_span);
663 let mut err = struct_span_err!(self.tcx.sess, sp, E0276, "{}", msg);
665 if let Some(trait_item_span) = self.tcx.hir().span_if_local(trait_item_def_id) {
666 let span = self.tcx.sess.source_map().def_span(trait_item_span);
667 err.span_label(span, format!("definition of `{}` from trait", item_name));
670 err.span_label(sp, format!("impl has extra requirement {}", requirement));
676 /// Gets the parent trait chain start
677 fn get_parent_trait_ref(&self, code: &ObligationCauseCode<'tcx>) -> Option<String> {
679 &ObligationCauseCode::BuiltinDerivedObligation(ref data) => {
680 let parent_trait_ref = self.resolve_vars_if_possible(
681 &data.parent_trait_ref);
682 match self.get_parent_trait_ref(&data.parent_code) {
684 None => Some(parent_trait_ref.skip_binder().self_ty().to_string()),
691 pub fn report_selection_error(
693 obligation: &PredicateObligation<'tcx>,
694 error: &SelectionError<'tcx>,
695 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 {
735 } = self.on_unimplemented_note(trait_ref, obligation);
736 let have_alt_message = message.is_some() || label.is_some();
737 let is_try = self.tcx.sess.source_map().span_to_snippet(span)
741 format!("{}", trait_ref.print_only_trait_path())
742 .starts_with("std::convert::From<");
743 let (message, note) = if is_try && is_from {
745 "`?` couldn't convert the error to `{}`",
748 "the question mark operation (`?`) implicitly performs a \
749 conversion on the error value using the `From` trait".to_owned()
755 let mut err = struct_span_err!(
760 message.unwrap_or_else(|| format!(
761 "the trait bound `{}` is not satisfied{}",
762 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) {
824 // If a where-clause may be useful, remind the
825 // user that they can add it.
827 // don't display an on-unimplemented note, as
828 // these notes will often be of the form
829 // "the type `T` can't be frobnicated"
830 // which is somewhat confusing.
831 self.suggest_restricting_param_bound(
834 obligation.cause.body_id,
837 if !have_alt_message {
838 // Can't show anything else useful, try to find similar impls.
839 let impl_candidates = self.find_similar_impl_candidates(trait_ref);
840 self.report_similar_impl_candidates(impl_candidates, &mut err);
842 self.suggest_change_mut(
850 // If this error is due to `!: Trait` not implemented but `(): Trait` is
851 // implemented, and fallback has occurred, then it could be due to a
852 // variable that used to fallback to `()` now falling back to `!`. Issue a
853 // note informing about the change in behaviour.
854 if trait_predicate.skip_binder().self_ty().is_never()
855 && fallback_has_occurred
857 let predicate = trait_predicate.map_bound(|mut trait_pred| {
858 trait_pred.trait_ref.substs = self.tcx.mk_substs_trait(
860 &trait_pred.trait_ref.substs[1..],
864 let unit_obligation = Obligation {
865 predicate: ty::Predicate::Trait(predicate),
866 .. obligation.clone()
868 if self.predicate_may_hold(&unit_obligation) {
869 err.note("the trait is implemented for `()`. \
870 Possibly this error has been caused by changes to \
871 Rust's type-inference algorithm \
872 (see: https://github.com/rust-lang/rust/issues/48950 \
873 for more info). Consider whether you meant to use the \
874 type `()` here instead.");
881 ty::Predicate::Subtype(ref predicate) => {
882 // Errors for Subtype predicates show up as
883 // `FulfillmentErrorCode::CodeSubtypeError`,
884 // not selection error.
885 span_bug!(span, "subtype requirement gave wrong error: `{:?}`", predicate)
888 ty::Predicate::RegionOutlives(ref predicate) => {
889 let predicate = self.resolve_vars_if_possible(predicate);
890 let err = self.region_outlives_predicate(&obligation.cause,
891 &predicate).err().unwrap();
893 self.tcx.sess, span, E0279,
894 "the requirement `{}` is not satisfied (`{}`)",
899 ty::Predicate::Projection(..) | ty::Predicate::TypeOutlives(..) => {
901 self.resolve_vars_if_possible(&obligation.predicate);
902 struct_span_err!(self.tcx.sess, span, E0280,
903 "the requirement `{}` is not satisfied",
907 ty::Predicate::ObjectSafe(trait_def_id) => {
908 let violations = self.tcx.object_safety_violations(trait_def_id);
909 self.tcx.report_object_safety_error(
916 ty::Predicate::ClosureKind(closure_def_id, closure_substs, kind) => {
917 let found_kind = self.closure_kind(closure_def_id, closure_substs).unwrap();
918 let closure_span = self.tcx.sess.source_map()
919 .def_span(self.tcx.hir().span_if_local(closure_def_id).unwrap());
920 let hir_id = self.tcx.hir().as_local_hir_id(closure_def_id).unwrap();
921 let mut err = struct_span_err!(
922 self.tcx.sess, closure_span, E0525,
923 "expected a closure that implements the `{}` trait, \
924 but this closure only implements `{}`",
930 format!("this closure implements `{}`, not `{}`", found_kind, kind));
932 obligation.cause.span,
933 format!("the requirement to implement `{}` derives from here", kind));
935 // Additional context information explaining why the closure only implements
936 // a particular trait.
937 if let Some(tables) = self.in_progress_tables {
938 let tables = tables.borrow();
939 match (found_kind, tables.closure_kind_origins().get(hir_id)) {
940 (ty::ClosureKind::FnOnce, Some((span, name))) => {
941 err.span_label(*span, format!(
942 "closure is `FnOnce` because it moves the \
943 variable `{}` out of its environment", name));
945 (ty::ClosureKind::FnMut, Some((span, name))) => {
946 err.span_label(*span, format!(
947 "closure is `FnMut` because it mutates the \
948 variable `{}` here", name));
958 ty::Predicate::WellFormed(ty) => {
959 if !self.tcx.sess.opts.debugging_opts.chalk {
960 // WF predicates cannot themselves make
961 // errors. They can only block due to
962 // ambiguity; otherwise, they always
963 // degenerate into other obligations
965 span_bug!(span, "WF predicate not satisfied for {:?}", ty);
967 // FIXME: we'll need a better message which takes into account
968 // which bounds actually failed to hold.
969 self.tcx.sess.struct_span_err(
971 &format!("the type `{}` is not well-formed (chalk)", ty)
976 ty::Predicate::ConstEvaluatable(..) => {
977 // Errors for `ConstEvaluatable` predicates show up as
978 // `SelectionError::ConstEvalFailure`,
979 // not `Unimplemented`.
981 "const-evaluatable requirement gave wrong error: `{:?}`", obligation)
986 OutputTypeParameterMismatch(ref found_trait_ref, ref expected_trait_ref, _) => {
987 let found_trait_ref = self.resolve_vars_if_possible(&*found_trait_ref);
988 let expected_trait_ref = self.resolve_vars_if_possible(&*expected_trait_ref);
990 if expected_trait_ref.self_ty().references_error() {
994 let found_trait_ty = found_trait_ref.self_ty();
996 let found_did = match found_trait_ty.kind {
997 ty::Closure(did, _) | ty::Foreign(did) | ty::FnDef(did, _) => Some(did),
998 ty::Adt(def, _) => Some(def.did),
1002 let found_span = found_did.and_then(|did|
1003 self.tcx.hir().span_if_local(did)
1004 ).map(|sp| self.tcx.sess.source_map().def_span(sp)); // the sp could be an fn def
1006 if self.reported_closure_mismatch.borrow().contains(&(span, found_span)) {
1007 // We check closures twice, with obligations flowing in different directions,
1008 // but we want to complain about them only once.
1012 self.reported_closure_mismatch.borrow_mut().insert((span, found_span));
1014 let found = match found_trait_ref.skip_binder().substs.type_at(1).kind {
1015 ty::Tuple(ref tys) => vec![ArgKind::empty(); tys.len()],
1016 _ => vec![ArgKind::empty()],
1019 let expected_ty = expected_trait_ref.skip_binder().substs.type_at(1);
1020 let expected = match expected_ty.kind {
1021 ty::Tuple(ref tys) => tys.iter()
1022 .map(|t| ArgKind::from_expected_ty(t.expect_ty(), Some(span))).collect(),
1023 _ => vec![ArgKind::Arg("_".to_owned(), expected_ty.to_string())],
1026 if found.len() == expected.len() {
1027 self.report_closure_arg_mismatch(span,
1032 let (closure_span, found) = found_did
1033 .and_then(|did| self.tcx.hir().get_if_local(did))
1035 let (found_span, found) = self.get_fn_like_arguments(node);
1036 (Some(found_span), found)
1037 }).unwrap_or((found_span, found));
1039 self.report_arg_count_mismatch(span,
1043 found_trait_ty.is_closure())
1047 TraitNotObjectSafe(did) => {
1048 let violations = self.tcx.object_safety_violations(did);
1049 self.tcx.report_object_safety_error(span, did, violations)
1052 // already reported in the query
1053 ConstEvalFailure(err) => {
1054 self.tcx.sess.delay_span_bug(
1056 &format!("constant in type had an ignored error: {:?}", err),
1062 bug!("overflow should be handled before the `report_selection_error` path");
1066 self.note_obligation_cause(&mut err, obligation);
1071 /// If the `Self` type of the unsatisfied trait `trait_ref` implements a trait
1072 /// with the same path as `trait_ref`, a help message about
1073 /// a probable version mismatch is added to `err`
1074 fn note_version_mismatch(
1076 err: &mut DiagnosticBuilder<'_>,
1077 trait_ref: &ty::PolyTraitRef<'tcx>,
1079 let get_trait_impl = |trait_def_id| {
1080 let mut trait_impl = None;
1081 self.tcx.for_each_relevant_impl(trait_def_id, trait_ref.self_ty(), |impl_def_id| {
1082 if trait_impl.is_none() {
1083 trait_impl = Some(impl_def_id);
1088 let required_trait_path = self.tcx.def_path_str(trait_ref.def_id());
1089 let all_traits = self.tcx.all_traits(LOCAL_CRATE);
1090 let traits_with_same_path: std::collections::BTreeSet<_> = all_traits
1092 .filter(|trait_def_id| **trait_def_id != trait_ref.def_id())
1093 .filter(|trait_def_id| self.tcx.def_path_str(**trait_def_id) == required_trait_path)
1095 for trait_with_same_path in traits_with_same_path {
1096 if let Some(impl_def_id) = get_trait_impl(*trait_with_same_path) {
1097 let impl_span = self.tcx.def_span(impl_def_id);
1098 err.span_help(impl_span, "trait impl with same name found");
1099 let trait_crate = self.tcx.crate_name(trait_with_same_path.krate);
1100 let crate_msg = format!(
1101 "Perhaps two different versions of crate `{}` are being used?",
1104 err.note(&crate_msg);
1108 fn suggest_restricting_param_bound(
1110 mut err: &mut DiagnosticBuilder<'_>,
1111 trait_ref: &ty::PolyTraitRef<'_>,
1112 body_id: hir::HirId,
1114 let self_ty = trait_ref.self_ty();
1115 let (param_ty, projection) = match &self_ty.kind {
1116 ty::Param(_) => (true, None),
1117 ty::Projection(projection) => (false, Some(projection)),
1121 let suggest_restriction = |
1122 generics: &hir::Generics,
1124 err: &mut DiagnosticBuilder<'_>,
1126 let span = generics.where_clause.span_for_predicates_or_empty_place();
1127 if !span.from_expansion() && span.desugaring_kind().is_none() {
1128 err.span_suggestion(
1129 generics.where_clause.span_for_predicates_or_empty_place().shrink_to_hi(),
1130 &format!("consider further restricting {}", msg),
1133 if !generics.where_clause.predicates.is_empty() {
1138 trait_ref.to_predicate(),
1140 Applicability::MachineApplicable,
1145 // FIXME: Add check for trait bound that is already present, particularly `?Sized` so we
1146 // don't suggest `T: Sized + ?Sized`.
1147 let mut hir_id = body_id;
1148 while let Some(node) = self.tcx.hir().find(hir_id) {
1150 hir::Node::TraitItem(hir::TraitItem {
1152 kind: hir::TraitItemKind::Method(..), ..
1153 }) if param_ty && self_ty == self.tcx.types.self_param => {
1154 // Restricting `Self` for a single method.
1155 suggest_restriction(&generics, "`Self`", err);
1159 hir::Node::Item(hir::Item {
1160 kind: hir::ItemKind::Fn(_, generics, _), ..
1162 hir::Node::TraitItem(hir::TraitItem {
1164 kind: hir::TraitItemKind::Method(..), ..
1166 hir::Node::ImplItem(hir::ImplItem {
1168 kind: hir::ImplItemKind::Method(..), ..
1170 hir::Node::Item(hir::Item {
1171 kind: hir::ItemKind::Trait(_, _, generics, _, _), ..
1173 hir::Node::Item(hir::Item {
1174 kind: hir::ItemKind::Impl(_, _, _, generics, ..), ..
1175 }) if projection.is_some() => {
1176 // Missing associated type bound.
1177 suggest_restriction(&generics, "the associated type", err);
1181 hir::Node::Item(hir::Item { kind: hir::ItemKind::Struct(_, generics), span, .. }) |
1182 hir::Node::Item(hir::Item { kind: hir::ItemKind::Enum(_, generics), span, .. }) |
1183 hir::Node::Item(hir::Item { kind: hir::ItemKind::Union(_, generics), span, .. }) |
1184 hir::Node::Item(hir::Item {
1185 kind: hir::ItemKind::Trait(_, _, generics, ..), span, ..
1187 hir::Node::Item(hir::Item {
1188 kind: hir::ItemKind::Impl(_, _, _, generics, ..), span, ..
1190 hir::Node::Item(hir::Item {
1191 kind: hir::ItemKind::Fn(_, generics, _), span, ..
1193 hir::Node::Item(hir::Item {
1194 kind: hir::ItemKind::TyAlias(_, generics), span, ..
1196 hir::Node::Item(hir::Item {
1197 kind: hir::ItemKind::TraitAlias(generics, _), span, ..
1199 hir::Node::Item(hir::Item {
1200 kind: hir::ItemKind::OpaqueTy(hir::OpaqueTy { generics, .. }), span, ..
1202 hir::Node::TraitItem(hir::TraitItem { generics, span, .. }) |
1203 hir::Node::ImplItem(hir::ImplItem { generics, span, .. })
1205 // Missing generic type parameter bound.
1206 let param_name = self_ty.to_string();
1207 let constraint = trait_ref.print_only_trait_path().to_string();
1208 if suggest_constraining_type_param(
1213 self.tcx.sess.source_map(),
1220 hir::Node::Crate => return,
1225 hir_id = self.tcx.hir().get_parent_item(hir_id);
1229 /// When encountering an assignment of an unsized trait, like `let x = ""[..];`, provide a
1230 /// suggestion to borrow the initializer in order to use have a slice instead.
1231 fn suggest_borrow_on_unsized_slice(
1233 code: &ObligationCauseCode<'tcx>,
1234 err: &mut DiagnosticBuilder<'tcx>,
1236 if let &ObligationCauseCode::VariableType(hir_id) = code {
1237 let parent_node = self.tcx.hir().get_parent_node(hir_id);
1238 if let Some(Node::Local(ref local)) = self.tcx.hir().find(parent_node) {
1239 if let Some(ref expr) = local.init {
1240 if let hir::ExprKind::Index(_, _) = expr.kind {
1241 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(expr.span) {
1242 err.span_suggestion(
1244 "consider borrowing here",
1245 format!("&{}", snippet),
1246 Applicability::MachineApplicable
1255 fn mk_obligation_for_def_id(
1258 output_ty: Ty<'tcx>,
1259 cause: ObligationCause<'tcx>,
1260 param_env: ty::ParamEnv<'tcx>,
1261 ) -> PredicateObligation<'tcx> {
1262 let new_trait_ref = ty::TraitRef {
1264 substs: self.tcx.mk_substs_trait(output_ty, &[]),
1266 Obligation::new(cause, param_env, new_trait_ref.to_predicate())
1269 /// Given a closure's `DefId`, return the given name of the closure.
1271 /// This doesn't account for reassignments, but it's only used for suggestions.
1272 fn get_closure_name(
1275 err: &mut DiagnosticBuilder<'_>,
1277 ) -> Option<String> {
1278 let get_name = |err: &mut DiagnosticBuilder<'_>, kind: &hir::PatKind| -> Option<String> {
1279 // Get the local name of this closure. This can be inaccurate because
1280 // of the possibility of reassignment, but this should be good enough.
1282 hir::PatKind::Binding(hir::BindingAnnotation::Unannotated, _, name, None) => {
1283 Some(format!("{}", name))
1292 let hir = self.tcx.hir();
1293 let hir_id = hir.as_local_hir_id(def_id)?;
1294 let parent_node = hir.get_parent_node(hir_id);
1295 match hir.find(parent_node) {
1296 Some(hir::Node::Stmt(hir::Stmt {
1297 kind: hir::StmtKind::Local(local), ..
1298 })) => get_name(err, &local.pat.kind),
1299 // Different to previous arm because one is `&hir::Local` and the other
1300 // is `P<hir::Local>`.
1301 Some(hir::Node::Local(local)) => get_name(err, &local.pat.kind),
1306 /// We tried to apply the bound to an `fn` or closure. Check whether calling it would
1307 /// evaluate to a type that *would* satisfy the trait binding. If it would, suggest calling
1308 /// it: `bar(foo)` → `bar(foo())`. This case is *very* likely to be hit if `foo` is `async`.
1311 obligation: &PredicateObligation<'tcx>,
1312 err: &mut DiagnosticBuilder<'_>,
1313 trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
1314 points_at_arg: bool,
1316 let self_ty = trait_ref.self_ty();
1317 let (def_id, output_ty, callable) = match self_ty.kind {
1318 ty::Closure(def_id, substs) => {
1319 (def_id, self.closure_sig(def_id, substs).output(), "closure")
1321 ty::FnDef(def_id, _) => {
1322 (def_id, self_ty.fn_sig(self.tcx).output(), "function")
1326 let msg = format!("use parentheses to call the {}", callable);
1328 let obligation = self.mk_obligation_for_def_id(
1330 output_ty.skip_binder(),
1331 obligation.cause.clone(),
1332 obligation.param_env,
1335 match self.evaluate_obligation(&obligation) {
1336 Ok(EvaluationResult::EvaluatedToOk) |
1337 Ok(EvaluationResult::EvaluatedToOkModuloRegions) |
1338 Ok(EvaluationResult::EvaluatedToAmbig) => {}
1341 let hir = self.tcx.hir();
1342 // Get the name of the callable and the arguments to be used in the suggestion.
1343 let snippet = match hir.get_if_local(def_id) {
1344 Some(hir::Node::Expr(hir::Expr {
1345 kind: hir::ExprKind::Closure(_, decl, _, span, ..),
1348 err.span_label(*span, "consider calling this closure");
1349 let name = match self.get_closure_name(def_id, err, &msg) {
1353 let args = decl.inputs.iter()
1355 .collect::<Vec<_>>()
1357 format!("{}({})", name, args)
1359 Some(hir::Node::Item(hir::Item {
1361 kind: hir::ItemKind::Fn(.., body_id),
1364 err.span_label(ident.span, "consider calling this function");
1365 let body = hir.body(*body_id);
1366 let args = body.params.iter()
1367 .map(|arg| match &arg.pat.kind {
1368 hir::PatKind::Binding(_, _, ident, None)
1369 // FIXME: provide a better suggestion when encountering `SelfLower`, it
1370 // should suggest a method call.
1371 if ident.name != kw::SelfLower => ident.to_string(),
1372 _ => "_".to_string(),
1374 .collect::<Vec<_>>()
1376 format!("{}({})", ident, args)
1381 // When the obligation error has been ensured to have been caused by
1382 // an argument, the `obligation.cause.span` points at the expression
1383 // of the argument, so we can provide a suggestion. This is signaled
1384 // by `points_at_arg`. Otherwise, we give a more general note.
1385 err.span_suggestion(
1386 obligation.cause.span,
1389 Applicability::HasPlaceholders,
1392 err.help(&format!("{}: `{}`", msg, snippet));
1396 fn suggest_add_reference_to_arg(
1398 obligation: &PredicateObligation<'tcx>,
1399 err: &mut DiagnosticBuilder<'tcx>,
1400 trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
1401 points_at_arg: bool,
1402 has_custom_message: bool,
1408 let span = obligation.cause.span;
1409 let param_env = obligation.param_env;
1410 let trait_ref = trait_ref.skip_binder();
1412 if let ObligationCauseCode::ImplDerivedObligation(obligation) = &obligation.cause.code {
1413 // Try to apply the original trait binding obligation by borrowing.
1414 let self_ty = trait_ref.self_ty();
1415 let found = self_ty.to_string();
1416 let new_self_ty = self.tcx.mk_imm_ref(self.tcx.lifetimes.re_static, self_ty);
1417 let substs = self.tcx.mk_substs_trait(new_self_ty, &[]);
1418 let new_trait_ref = ty::TraitRef::new(obligation.parent_trait_ref.def_id(), substs);
1419 let new_obligation = Obligation::new(
1420 ObligationCause::dummy(),
1422 new_trait_ref.to_predicate(),
1424 if self.predicate_must_hold_modulo_regions(&new_obligation) {
1425 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
1426 // We have a very specific type of error, where just borrowing this argument
1427 // might solve the problem. In cases like this, the important part is the
1428 // original type obligation, not the last one that failed, which is arbitrary.
1429 // Because of this, we modify the error to refer to the original obligation and
1430 // return early in the caller.
1432 "the trait bound `{}: {}` is not satisfied",
1434 obligation.parent_trait_ref.skip_binder().print_only_trait_path(),
1436 if has_custom_message {
1439 err.message = vec![(msg, Style::NoStyle)];
1441 if snippet.starts_with('&') {
1442 // This is already a literal borrow and the obligation is failing
1443 // somewhere else in the obligation chain. Do not suggest non-sense.
1446 err.span_label(span, &format!(
1447 "expected an implementor of trait `{}`",
1448 obligation.parent_trait_ref.skip_binder().print_only_trait_path(),
1450 err.span_suggestion(
1452 "consider borrowing here",
1453 format!("&{}", snippet),
1454 Applicability::MaybeIncorrect,
1463 /// Whenever references are used by mistake, like `for (i, e) in &vec.iter().enumerate()`,
1464 /// suggest removing these references until we reach a type that implements the trait.
1465 fn suggest_remove_reference(
1467 obligation: &PredicateObligation<'tcx>,
1468 err: &mut DiagnosticBuilder<'tcx>,
1469 trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
1471 let trait_ref = trait_ref.skip_binder();
1472 let span = obligation.cause.span;
1474 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
1475 let refs_number = snippet.chars()
1476 .filter(|c| !c.is_whitespace())
1477 .take_while(|c| *c == '&')
1479 if let Some('\'') = snippet.chars()
1480 .filter(|c| !c.is_whitespace())
1483 { // Do not suggest removal of borrow from type arguments.
1487 let mut trait_type = trait_ref.self_ty();
1489 for refs_remaining in 0..refs_number {
1490 if let ty::Ref(_, t_type, _) = trait_type.kind {
1491 trait_type = t_type;
1493 let new_obligation = self.mk_obligation_for_def_id(
1496 ObligationCause::dummy(),
1497 obligation.param_env,
1500 if self.predicate_may_hold(&new_obligation) {
1501 let sp = self.tcx.sess.source_map()
1502 .span_take_while(span, |c| c.is_whitespace() || *c == '&');
1504 let remove_refs = refs_remaining + 1;
1505 let format_str = format!("consider removing {} leading `&`-references",
1508 err.span_suggestion_short(
1509 sp, &format_str, String::new(), Applicability::MachineApplicable
1520 /// Check if the trait bound is implemented for a different mutability and note it in the
1522 fn suggest_change_mut(
1524 obligation: &PredicateObligation<'tcx>,
1525 err: &mut DiagnosticBuilder<'tcx>,
1526 trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
1527 points_at_arg: bool,
1529 let span = obligation.cause.span;
1530 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
1531 let refs_number = snippet.chars()
1532 .filter(|c| !c.is_whitespace())
1533 .take_while(|c| *c == '&')
1535 if let Some('\'') = snippet.chars()
1536 .filter(|c| !c.is_whitespace())
1539 { // Do not suggest removal of borrow from type arguments.
1542 let trait_ref = self.resolve_vars_if_possible(trait_ref);
1543 if trait_ref.has_infer_types() {
1544 // Do not ICE while trying to find if a reborrow would succeed on a trait with
1545 // unresolved bindings.
1549 if let ty::Ref(region, t_type, mutability) = trait_ref.skip_binder().self_ty().kind {
1550 let trait_type = match mutability {
1551 hir::Mutability::Mutable => self.tcx.mk_imm_ref(region, t_type),
1552 hir::Mutability::Immutable => self.tcx.mk_mut_ref(region, t_type),
1555 let new_obligation = self.mk_obligation_for_def_id(
1556 trait_ref.skip_binder().def_id,
1558 ObligationCause::dummy(),
1559 obligation.param_env,
1562 if self.evaluate_obligation_no_overflow(
1564 ).must_apply_modulo_regions() {
1565 let sp = self.tcx.sess.source_map()
1566 .span_take_while(span, |c| c.is_whitespace() || *c == '&');
1568 mutability == hir::Mutability::Immutable &&
1571 err.span_suggestion(
1573 "consider changing this borrow's mutability",
1574 "&mut ".to_string(),
1575 Applicability::MachineApplicable,
1579 "`{}` is implemented for `{:?}`, but not for `{:?}`",
1580 trait_ref.print_only_trait_path(),
1582 trait_ref.skip_binder().self_ty(),
1590 fn suggest_semicolon_removal(
1592 obligation: &PredicateObligation<'tcx>,
1593 err: &mut DiagnosticBuilder<'tcx>,
1595 trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
1597 let hir = self.tcx.hir();
1598 let parent_node = hir.get_parent_node(obligation.cause.body_id);
1599 let node = hir.find(parent_node);
1600 if let Some(hir::Node::Item(hir::Item {
1601 kind: hir::ItemKind::Fn(sig, _, body_id),
1604 let body = hir.body(*body_id);
1605 if let hir::ExprKind::Block(blk, _) = &body.value.kind {
1606 if sig.decl.output.span().overlaps(span) && blk.expr.is_none() &&
1607 "()" == &trait_ref.self_ty().to_string()
1609 // FIXME(estebank): When encountering a method with a trait
1610 // bound not satisfied in the return type with a body that has
1611 // no return, suggest removal of semicolon on last statement.
1612 // Once that is added, close #54771.
1613 if let Some(ref stmt) = blk.stmts.last() {
1614 let sp = self.tcx.sess.source_map().end_point(stmt.span);
1615 err.span_label(sp, "consider removing this semicolon");
1622 /// Given some node representing a fn-like thing in the HIR map,
1623 /// returns a span and `ArgKind` information that describes the
1624 /// arguments it expects. This can be supplied to
1625 /// `report_arg_count_mismatch`.
1626 pub fn get_fn_like_arguments(&self, node: Node<'_>) -> (Span, Vec<ArgKind>) {
1628 Node::Expr(&hir::Expr {
1629 kind: hir::ExprKind::Closure(_, ref _decl, id, span, _),
1632 (self.tcx.sess.source_map().def_span(span),
1633 self.tcx.hir().body(id).params.iter()
1636 kind: hir::PatKind::Tuple(ref args, _),
1642 args.iter().map(|pat| {
1643 let snippet = self.tcx.sess.source_map()
1644 .span_to_snippet(pat.span).unwrap();
1645 (snippet, "_".to_owned())
1646 }).collect::<Vec<_>>(),
1649 let name = self.tcx.sess.source_map()
1650 .span_to_snippet(arg.pat.span).unwrap();
1651 ArgKind::Arg(name, "_".to_owned())
1654 .collect::<Vec<ArgKind>>())
1656 Node::Item(&hir::Item {
1658 kind: hir::ItemKind::Fn(ref sig, ..),
1661 Node::ImplItem(&hir::ImplItem {
1663 kind: hir::ImplItemKind::Method(ref sig, _),
1666 Node::TraitItem(&hir::TraitItem {
1668 kind: hir::TraitItemKind::Method(ref sig, _),
1671 (self.tcx.sess.source_map().def_span(span), sig.decl.inputs.iter()
1672 .map(|arg| match arg.clone().kind {
1673 hir::TyKind::Tup(ref tys) => ArgKind::Tuple(
1675 vec![("_".to_owned(), "_".to_owned()); tys.len()]
1677 _ => ArgKind::empty()
1678 }).collect::<Vec<ArgKind>>())
1680 Node::Ctor(ref variant_data) => {
1681 let span = variant_data.ctor_hir_id()
1682 .map(|hir_id| self.tcx.hir().span(hir_id))
1683 .unwrap_or(DUMMY_SP);
1684 let span = self.tcx.sess.source_map().def_span(span);
1686 (span, vec![ArgKind::empty(); variant_data.fields().len()])
1688 _ => panic!("non-FnLike node found: {:?}", node),
1692 /// Reports an error when the number of arguments needed by a
1693 /// trait match doesn't match the number that the expression
1695 pub fn report_arg_count_mismatch(
1698 found_span: Option<Span>,
1699 expected_args: Vec<ArgKind>,
1700 found_args: Vec<ArgKind>,
1702 ) -> DiagnosticBuilder<'tcx> {
1703 let kind = if is_closure { "closure" } else { "function" };
1705 let args_str = |arguments: &[ArgKind], other: &[ArgKind]| {
1706 let arg_length = arguments.len();
1707 let distinct = match &other[..] {
1708 &[ArgKind::Tuple(..)] => true,
1711 match (arg_length, arguments.get(0)) {
1712 (1, Some(&ArgKind::Tuple(_, ref fields))) => {
1713 format!("a single {}-tuple as argument", fields.len())
1715 _ => format!("{} {}argument{}",
1717 if distinct && arg_length > 1 { "distinct " } else { "" },
1718 pluralize!(arg_length))
1722 let expected_str = args_str(&expected_args, &found_args);
1723 let found_str = args_str(&found_args, &expected_args);
1725 let mut err = struct_span_err!(
1729 "{} is expected to take {}, but it takes {}",
1735 err.span_label(span, format!("expected {} that takes {}", kind, expected_str));
1737 if let Some(found_span) = found_span {
1738 err.span_label(found_span, format!("takes {}", found_str));
1741 // ^^^^^^^^-- def_span
1745 let prefix_span = self.tcx.sess.source_map().span_until_non_whitespace(found_span);
1748 let pipe_span = if let Some(span) = found_span.trim_start(prefix_span) {
1754 // Suggest to take and ignore the arguments with expected_args_length `_`s if
1755 // found arguments is empty (assume the user just wants to ignore args in this case).
1756 // For example, if `expected_args_length` is 2, suggest `|_, _|`.
1757 if found_args.is_empty() && is_closure {
1758 let underscores = vec!["_"; expected_args.len()].join(", ");
1759 err.span_suggestion(
1762 "consider changing the closure to take and ignore the expected argument{}",
1763 if expected_args.len() < 2 {
1769 format!("|{}|", underscores),
1770 Applicability::MachineApplicable,
1774 if let &[ArgKind::Tuple(_, ref fields)] = &found_args[..] {
1775 if fields.len() == expected_args.len() {
1776 let sugg = fields.iter()
1777 .map(|(name, _)| name.to_owned())
1778 .collect::<Vec<String>>()
1780 err.span_suggestion(
1782 "change the closure to take multiple arguments instead of a single tuple",
1783 format!("|{}|", sugg),
1784 Applicability::MachineApplicable,
1788 if let &[ArgKind::Tuple(_, ref fields)] = &expected_args[..] {
1789 if fields.len() == found_args.len() && is_closure {
1793 .map(|arg| match arg {
1794 ArgKind::Arg(name, _) => name.to_owned(),
1795 _ => "_".to_owned(),
1797 .collect::<Vec<String>>()
1799 // add type annotations if available
1800 if found_args.iter().any(|arg| match arg {
1801 ArgKind::Arg(_, ty) => ty != "_",
1806 .map(|(_, ty)| ty.to_owned())
1807 .collect::<Vec<String>>()
1813 err.span_suggestion(
1815 "change the closure to accept a tuple instead of individual arguments",
1817 Applicability::MachineApplicable,
1826 fn report_closure_arg_mismatch(
1829 found_span: Option<Span>,
1830 expected_ref: ty::PolyTraitRef<'tcx>,
1831 found: ty::PolyTraitRef<'tcx>,
1832 ) -> DiagnosticBuilder<'tcx> {
1833 fn build_fn_sig_string<'tcx>(tcx: TyCtxt<'tcx>, trait_ref: &ty::TraitRef<'tcx>) -> String {
1834 let inputs = trait_ref.substs.type_at(1);
1835 let sig = if let ty::Tuple(inputs) = inputs.kind {
1837 inputs.iter().map(|k| k.expect_ty()),
1838 tcx.mk_ty_infer(ty::TyVar(ty::TyVid { index: 0 })),
1840 hir::Unsafety::Normal,
1841 ::rustc_target::spec::abi::Abi::Rust
1845 ::std::iter::once(inputs),
1846 tcx.mk_ty_infer(ty::TyVar(ty::TyVid { index: 0 })),
1848 hir::Unsafety::Normal,
1849 ::rustc_target::spec::abi::Abi::Rust
1852 ty::Binder::bind(sig).to_string()
1855 let argument_is_closure = expected_ref.skip_binder().substs.type_at(0).is_closure();
1856 let mut err = struct_span_err!(self.tcx.sess, span, E0631,
1857 "type mismatch in {} arguments",
1858 if argument_is_closure { "closure" } else { "function" });
1860 let found_str = format!(
1861 "expected signature of `{}`",
1862 build_fn_sig_string(self.tcx, found.skip_binder())
1864 err.span_label(span, found_str);
1866 let found_span = found_span.unwrap_or(span);
1867 let expected_str = format!(
1868 "found signature of `{}`",
1869 build_fn_sig_string(self.tcx, expected_ref.skip_binder())
1871 err.span_label(found_span, expected_str);
1877 impl<'tcx> TyCtxt<'tcx> {
1878 pub fn recursive_type_with_infinite_size_error(self,
1880 -> DiagnosticBuilder<'tcx>
1882 assert!(type_def_id.is_local());
1883 let span = self.hir().span_if_local(type_def_id).unwrap();
1884 let span = self.sess.source_map().def_span(span);
1885 let mut err = struct_span_err!(self.sess, span, E0072,
1886 "recursive type `{}` has infinite size",
1887 self.def_path_str(type_def_id));
1888 err.span_label(span, "recursive type has infinite size");
1889 err.help(&format!("insert indirection (e.g., a `Box`, `Rc`, or `&`) \
1890 at some point to make `{}` representable",
1891 self.def_path_str(type_def_id)));
1895 pub fn report_object_safety_error(
1898 trait_def_id: DefId,
1899 violations: Vec<ObjectSafetyViolation>,
1900 ) -> DiagnosticBuilder<'tcx> {
1901 let trait_str = self.def_path_str(trait_def_id);
1902 let span = self.sess.source_map().def_span(span);
1903 let mut err = struct_span_err!(
1904 self.sess, span, E0038,
1905 "the trait `{}` cannot be made into an object",
1907 err.span_label(span, format!("the trait `{}` cannot be made into an object", trait_str));
1909 let mut reported_violations = FxHashSet::default();
1910 for violation in violations {
1911 if reported_violations.insert(violation.clone()) {
1912 match violation.span() {
1913 Some(span) => err.span_label(span, violation.error_msg()),
1914 None => err.note(&violation.error_msg()),
1919 if self.sess.trait_methods_not_found.borrow().contains(&span) {
1920 // Avoid emitting error caused by non-existing method (#58734)
1928 impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
1929 fn maybe_report_ambiguity(
1931 obligation: &PredicateObligation<'tcx>,
1932 body_id: Option<hir::BodyId>,
1934 // Unable to successfully determine, probably means
1935 // insufficient type information, but could mean
1936 // ambiguous impls. The latter *ought* to be a
1937 // coherence violation, so we don't report it here.
1939 let predicate = self.resolve_vars_if_possible(&obligation.predicate);
1940 let span = obligation.cause.span;
1943 "maybe_report_ambiguity(predicate={:?}, obligation={:?} body_id={:?}, code={:?})",
1947 obligation.cause.code,
1950 // Ambiguity errors are often caused as fallout from earlier
1951 // errors. So just ignore them if this infcx is tainted.
1952 if self.is_tainted_by_errors() {
1956 let mut err = match predicate {
1957 ty::Predicate::Trait(ref data) => {
1958 let trait_ref = data.to_poly_trait_ref();
1959 let self_ty = trait_ref.self_ty();
1960 debug!("self_ty {:?} {:?} trait_ref {:?}", self_ty, self_ty.kind, trait_ref);
1962 if predicate.references_error() {
1965 // Typically, this ambiguity should only happen if
1966 // there are unresolved type inference variables
1967 // (otherwise it would suggest a coherence
1968 // failure). But given #21974 that is not necessarily
1969 // the case -- we can have multiple where clauses that
1970 // are only distinguished by a region, which results
1971 // in an ambiguity even when all types are fully
1972 // known, since we don't dispatch based on region
1975 // This is kind of a hack: it frequently happens that some earlier
1976 // error prevents types from being fully inferred, and then we get
1977 // a bunch of uninteresting errors saying something like "<generic
1978 // #0> doesn't implement Sized". It may even be true that we
1979 // could just skip over all checks where the self-ty is an
1980 // inference variable, but I was afraid that there might be an
1981 // inference variable created, registered as an obligation, and
1982 // then never forced by writeback, and hence by skipping here we'd
1983 // be ignoring the fact that we don't KNOW the type works
1984 // out. Though even that would probably be harmless, given that
1985 // we're only talking about builtin traits, which are known to be
1986 // inhabited. We used to check for `self.tcx.sess.has_errors()` to
1987 // avoid inundating the user with unnecessary errors, but we now
1988 // check upstream for type errors and dont add the obligations to
1989 // begin with in those cases.
1990 if self.tcx.lang_items().sized_trait()
1991 .map_or(false, |sized_id| sized_id == trait_ref.def_id())
1993 self.need_type_info_err(body_id, span, self_ty, ErrorCode::E0282).emit();
1996 let mut err = self.need_type_info_err(body_id, span, self_ty, ErrorCode::E0283);
1997 err.note(&format!("cannot resolve `{}`", predicate));
1998 if let (Ok(ref snippet), ObligationCauseCode::BindingObligation(ref def_id, _)) = (
1999 self.tcx.sess.source_map().span_to_snippet(span),
2000 &obligation.cause.code,
2002 let generics = self.tcx.generics_of(*def_id);
2003 if !generics.params.is_empty() && !snippet.ends_with('>'){
2004 // FIXME: To avoid spurious suggestions in functions where type arguments
2005 // where already supplied, we check the snippet to make sure it doesn't
2006 // end with a turbofish. Ideally we would have access to a `PathSegment`
2007 // instead. Otherwise we would produce the following output:
2009 // error[E0283]: type annotations needed
2010 // --> $DIR/issue-54954.rs:3:24
2012 // LL | const ARR_LEN: usize = Tt::const_val::<[i8; 123]>();
2013 // | ^^^^^^^^^^^^^^^^^^^^^^^^^^
2015 // | cannot infer type
2016 // | help: consider specifying the type argument
2017 // | in the function call:
2018 // | `Tt::const_val::<[i8; 123]>::<T>`
2020 // LL | const fn const_val<T: Sized>() -> usize {
2021 // | --------- - required by this bound in `Tt::const_val`
2023 // = note: cannot resolve `_: Tt`
2025 err.span_suggestion(
2028 "consider specifying the type argument{} in the function call",
2029 if generics.params.len() > 1 {
2035 format!("{}::<{}>", snippet, generics.params.iter()
2036 .map(|p| p.name.to_string())
2037 .collect::<Vec<String>>()
2039 Applicability::HasPlaceholders,
2046 ty::Predicate::WellFormed(ty) => {
2047 // Same hacky approach as above to avoid deluging user
2048 // with error messages.
2049 if ty.references_error() || self.tcx.sess.has_errors() {
2052 self.need_type_info_err(body_id, span, ty, ErrorCode::E0282)
2055 ty::Predicate::Subtype(ref data) => {
2056 if data.references_error() || self.tcx.sess.has_errors() {
2057 // no need to overload user in such cases
2060 let &SubtypePredicate { a_is_expected: _, a, b } = data.skip_binder();
2061 // both must be type variables, or the other would've been instantiated
2062 assert!(a.is_ty_var() && b.is_ty_var());
2063 self.need_type_info_err(body_id, span, a, ErrorCode::E0282)
2065 ty::Predicate::Projection(ref data) => {
2066 let trait_ref = data.to_poly_trait_ref(self.tcx);
2067 let self_ty = trait_ref.self_ty();
2068 if predicate.references_error() {
2071 let mut err = self.need_type_info_err(body_id, span, self_ty, ErrorCode::E0284);
2072 err.note(&format!("cannot resolve `{}`", predicate));
2077 if self.tcx.sess.has_errors() {
2080 let mut err = struct_span_err!(
2084 "type annotations needed: cannot resolve `{}`",
2087 err.span_label(span, &format!("cannot resolve `{}`", predicate));
2091 self.note_obligation_cause(&mut err, obligation);
2095 /// Returns `true` if the trait predicate may apply for *some* assignment
2096 /// to the type parameters.
2097 fn predicate_can_apply(
2099 param_env: ty::ParamEnv<'tcx>,
2100 pred: ty::PolyTraitRef<'tcx>,
2102 struct ParamToVarFolder<'a, 'tcx> {
2103 infcx: &'a InferCtxt<'a, 'tcx>,
2104 var_map: FxHashMap<Ty<'tcx>, Ty<'tcx>>,
2107 impl<'a, 'tcx> TypeFolder<'tcx> for ParamToVarFolder<'a, 'tcx> {
2108 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> { self.infcx.tcx }
2110 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
2111 if let ty::Param(ty::ParamTy {name, .. }) = ty.kind {
2112 let infcx = self.infcx;
2113 self.var_map.entry(ty).or_insert_with(||
2115 TypeVariableOrigin {
2116 kind: TypeVariableOriginKind::TypeParameterDefinition(name, None),
2122 ty.super_fold_with(self)
2128 let mut selcx = SelectionContext::new(self);
2130 let cleaned_pred = pred.fold_with(&mut ParamToVarFolder {
2132 var_map: Default::default()
2135 let cleaned_pred = super::project::normalize(
2138 ObligationCause::dummy(),
2142 let obligation = Obligation::new(
2143 ObligationCause::dummy(),
2145 cleaned_pred.to_predicate()
2148 self.predicate_may_hold(&obligation)
2152 fn note_obligation_cause(
2154 err: &mut DiagnosticBuilder<'_>,
2155 obligation: &PredicateObligation<'tcx>,
2157 // First, attempt to add note to this error with an async-await-specific
2158 // message, and fall back to regular note otherwise.
2159 if !self.maybe_note_obligation_cause_for_async_await(err, obligation) {
2160 self.note_obligation_cause_code(err, &obligation.predicate, &obligation.cause.code,
2165 /// Adds an async-await specific note to the diagnostic when the future does not implement
2166 /// an auto trait because of a captured type.
2168 /// ```ignore (diagnostic)
2169 /// note: future does not implement `Qux` as this value is used across an await
2170 /// --> $DIR/issue-64130-3-other.rs:17:5
2172 /// LL | let x = Foo;
2173 /// | - has type `Foo`
2174 /// LL | baz().await;
2175 /// | ^^^^^^^^^^^ await occurs here, with `x` maybe used later
2177 /// | - `x` is later dropped here
2180 /// When the diagnostic does not implement `Send` or `Sync` specifically, then the diagnostic
2181 /// is "replaced" with a different message and a more specific error.
2183 /// ```ignore (diagnostic)
2184 /// error: future cannot be sent between threads safely
2185 /// --> $DIR/issue-64130-2-send.rs:21:5
2187 /// LL | fn is_send<T: Send>(t: T) { }
2188 /// | ------- ---- required by this bound in `is_send`
2190 /// LL | is_send(bar());
2191 /// | ^^^^^^^ future returned by `bar` is not send
2193 /// = help: within `impl std::future::Future`, the trait `std::marker::Send` is not
2194 /// implemented for `Foo`
2195 /// note: future is not send as this value is used across an await
2196 /// --> $DIR/issue-64130-2-send.rs:15:5
2198 /// LL | let x = Foo;
2199 /// | - has type `Foo`
2200 /// LL | baz().await;
2201 /// | ^^^^^^^^^^^ await occurs here, with `x` maybe used later
2203 /// | - `x` is later dropped here
2206 /// Returns `true` if an async-await specific note was added to the diagnostic.
2207 fn maybe_note_obligation_cause_for_async_await(
2209 err: &mut DiagnosticBuilder<'_>,
2210 obligation: &PredicateObligation<'tcx>,
2212 debug!("maybe_note_obligation_cause_for_async_await: obligation.predicate={:?} \
2213 obligation.cause.span={:?}", obligation.predicate, obligation.cause.span);
2214 let source_map = self.tcx.sess.source_map();
2216 // Attempt to detect an async-await error by looking at the obligation causes, looking
2217 // for a generator to be present.
2219 // When a future does not implement a trait because of a captured type in one of the
2220 // generators somewhere in the call stack, then the result is a chain of obligations.
2222 // Given a `async fn` A that calls a `async fn` B which captures a non-send type and that
2223 // future is passed as an argument to a function C which requires a `Send` type, then the
2224 // chain looks something like this:
2226 // - `BuiltinDerivedObligation` with a generator witness (B)
2227 // - `BuiltinDerivedObligation` with a generator (B)
2228 // - `BuiltinDerivedObligation` with `std::future::GenFuture` (B)
2229 // - `BuiltinDerivedObligation` with `impl std::future::Future` (B)
2230 // - `BuiltinDerivedObligation` with `impl std::future::Future` (B)
2231 // - `BuiltinDerivedObligation` with a generator witness (A)
2232 // - `BuiltinDerivedObligation` with a generator (A)
2233 // - `BuiltinDerivedObligation` with `std::future::GenFuture` (A)
2234 // - `BuiltinDerivedObligation` with `impl std::future::Future` (A)
2235 // - `BuiltinDerivedObligation` with `impl std::future::Future` (A)
2236 // - `BindingObligation` with `impl_send (Send requirement)
2238 // The first obligation in the chain is the most useful and has the generator that captured
2239 // the type. The last generator has information about where the bound was introduced. At
2240 // least one generator should be present for this diagnostic to be modified.
2241 let (mut trait_ref, mut target_ty) = match obligation.predicate {
2242 ty::Predicate::Trait(p) =>
2243 (Some(p.skip_binder().trait_ref), Some(p.skip_binder().self_ty())),
2246 let mut generator = None;
2247 let mut last_generator = None;
2248 let mut next_code = Some(&obligation.cause.code);
2249 while let Some(code) = next_code {
2250 debug!("maybe_note_obligation_cause_for_async_await: code={:?}", code);
2252 ObligationCauseCode::BuiltinDerivedObligation(derived_obligation) |
2253 ObligationCauseCode::ImplDerivedObligation(derived_obligation) => {
2254 let ty = derived_obligation.parent_trait_ref.self_ty();
2255 debug!("maybe_note_obligation_cause_for_async_await: \
2256 parent_trait_ref={:?} self_ty.kind={:?}",
2257 derived_obligation.parent_trait_ref, ty.kind);
2260 ty::Generator(did, ..) => {
2261 generator = generator.or(Some(did));
2262 last_generator = Some(did);
2264 ty::GeneratorWitness(..) => {},
2265 _ if generator.is_none() => {
2266 trait_ref = Some(*derived_obligation.parent_trait_ref.skip_binder());
2267 target_ty = Some(ty);
2272 next_code = Some(derived_obligation.parent_code.as_ref());
2278 // Only continue if a generator was found.
2279 debug!("maybe_note_obligation_cause_for_async_await: generator={:?} trait_ref={:?} \
2280 target_ty={:?}", generator, trait_ref, target_ty);
2281 let (generator_did, trait_ref, target_ty) = match (generator, trait_ref, target_ty) {
2282 (Some(generator_did), Some(trait_ref), Some(target_ty)) =>
2283 (generator_did, trait_ref, target_ty),
2287 let span = self.tcx.def_span(generator_did);
2289 // Do not ICE on closure typeck (#66868).
2290 if let None = self.tcx.hir().as_local_hir_id(generator_did) {
2294 // Get the tables from the infcx if the generator is the function we are
2295 // currently type-checking; otherwise, get them by performing a query.
2296 // This is needed to avoid cycles.
2297 let in_progress_tables = self.in_progress_tables.map(|t| t.borrow());
2298 let generator_did_root = self.tcx.closure_base_def_id(generator_did);
2299 debug!("maybe_note_obligation_cause_for_async_await: generator_did={:?} \
2300 generator_did_root={:?} in_progress_tables.local_id_root={:?} span={:?}",
2301 generator_did, generator_did_root,
2302 in_progress_tables.as_ref().map(|t| t.local_id_root), span);
2304 let tables: &TypeckTables<'tcx> = match &in_progress_tables {
2305 Some(t) if t.local_id_root == Some(generator_did_root) => t,
2307 query_tables = self.tcx.typeck_tables_of(generator_did);
2312 // Look for a type inside the generator interior that matches the target type to get
2314 let target_ty_erased = self.tcx.erase_regions(&target_ty);
2315 let target_span = tables.generator_interior_types.iter()
2316 .find(|ty::GeneratorInteriorTypeCause { ty, .. }| {
2317 // Careful: the regions for types that appear in the
2318 // generator interior are not generally known, so we
2319 // want to erase them when comparing (and anyway,
2320 // `Send` and other bounds are generally unaffected by
2321 // the choice of region). When erasing regions, we
2322 // also have to erase late-bound regions. This is
2323 // because the types that appear in the generator
2324 // interior generally contain "bound regions" to
2325 // represent regions that are part of the suspended
2326 // generator frame. Bound regions are preserved by
2327 // `erase_regions` and so we must also call
2328 // `erase_late_bound_regions`.
2329 let ty_erased = self.tcx.erase_late_bound_regions(&ty::Binder::bind(*ty));
2330 let ty_erased = self.tcx.erase_regions(&ty_erased);
2331 let eq = ty::TyS::same_type(ty_erased, target_ty_erased);
2332 debug!("maybe_note_obligation_cause_for_async_await: ty_erased={:?} \
2333 target_ty_erased={:?} eq={:?}", ty_erased, target_ty_erased, eq);
2336 .map(|ty::GeneratorInteriorTypeCause { span, scope_span, .. }|
2337 (span, source_map.span_to_snippet(*span), scope_span));
2338 debug!("maybe_note_obligation_cause_for_async_await: target_ty={:?} \
2339 generator_interior_types={:?} target_span={:?}",
2340 target_ty, tables.generator_interior_types, target_span);
2341 if let Some((target_span, Ok(snippet), scope_span)) = target_span {
2342 self.note_obligation_cause_for_async_await(
2343 err, *target_span, scope_span, snippet, generator_did, last_generator,
2344 trait_ref, target_ty, tables, obligation, next_code,
2352 /// Unconditionally adds the diagnostic note described in
2353 /// `maybe_note_obligation_cause_for_async_await`'s documentation comment.
2354 fn note_obligation_cause_for_async_await(
2356 err: &mut DiagnosticBuilder<'_>,
2358 scope_span: &Option<Span>,
2360 first_generator: DefId,
2361 last_generator: Option<DefId>,
2362 trait_ref: ty::TraitRef<'_>,
2363 target_ty: Ty<'tcx>,
2364 tables: &ty::TypeckTables<'_>,
2365 obligation: &PredicateObligation<'tcx>,
2366 next_code: Option<&ObligationCauseCode<'tcx>>,
2368 let source_map = self.tcx.sess.source_map();
2370 let is_async_fn = self.tcx.parent(first_generator)
2371 .map(|parent_did| self.tcx.asyncness(parent_did))
2372 .map(|parent_asyncness| parent_asyncness == hir::IsAsync::Async)
2374 let is_async_move = self.tcx.hir().as_local_hir_id(first_generator)
2375 .and_then(|hir_id| self.tcx.hir().maybe_body_owned_by(hir_id))
2376 .map(|body_id| self.tcx.hir().body(body_id))
2377 .and_then(|body| body.generator_kind())
2378 .map(|generator_kind| match generator_kind {
2379 hir::GeneratorKind::Async(..) => true,
2383 let await_or_yield = if is_async_fn || is_async_move { "await" } else { "yield" };
2385 // Special case the primary error message when send or sync is the trait that was
2387 let is_send = self.tcx.is_diagnostic_item(sym::send_trait, trait_ref.def_id);
2388 let is_sync = self.tcx.is_diagnostic_item(sym::sync_trait, trait_ref.def_id);
2389 let trait_explanation = if is_send || is_sync {
2390 let (trait_name, trait_verb) = if is_send {
2393 ("`Sync`", "shared")
2397 err.set_primary_message(
2398 format!("future cannot be {} between threads safely", trait_verb)
2401 let original_span = err.span.primary_span().unwrap();
2402 let mut span = MultiSpan::from_span(original_span);
2404 let message = if let Some(name) = last_generator
2405 .and_then(|generator_did| self.tcx.parent(generator_did))
2406 .and_then(|parent_did| self.tcx.hir().as_local_hir_id(parent_did))
2407 .and_then(|parent_hir_id| self.tcx.hir().opt_name(parent_hir_id))
2409 format!("future returned by `{}` is not {}", name, trait_name)
2411 format!("future is not {}", trait_name)
2414 span.push_span_label(original_span, message);
2417 format!("is not {}", trait_name)
2419 format!("does not implement `{}`", trait_ref.print_only_trait_path())
2422 // Look at the last interior type to get a span for the `.await`.
2423 let await_span = tables.generator_interior_types.iter().map(|i| i.span).last().unwrap();
2424 let mut span = MultiSpan::from_span(await_span);
2425 span.push_span_label(
2427 format!("{} occurs here, with `{}` maybe used later", await_or_yield, snippet));
2429 span.push_span_label(target_span, format!("has type `{}`", target_ty));
2431 // If available, use the scope span to annotate the drop location.
2432 if let Some(scope_span) = scope_span {
2433 span.push_span_label(
2434 source_map.end_point(*scope_span),
2435 format!("`{}` is later dropped here", snippet),
2439 err.span_note(span, &format!(
2440 "future {} as this value is used across an {}",
2445 // Add a note for the item obligation that remains - normally a note pointing to the
2446 // bound that introduced the obligation (e.g. `T: Send`).
2447 debug!("note_obligation_cause_for_async_await: next_code={:?}", next_code);
2448 self.note_obligation_cause_code(
2450 &obligation.predicate,
2456 fn note_obligation_cause_code<T>(&self,
2457 err: &mut DiagnosticBuilder<'_>,
2459 cause_code: &ObligationCauseCode<'tcx>,
2460 obligated_types: &mut Vec<&ty::TyS<'tcx>>)
2461 where T: fmt::Display
2465 ObligationCauseCode::ExprAssignable |
2466 ObligationCauseCode::MatchExpressionArm { .. } |
2467 ObligationCauseCode::MatchExpressionArmPattern { .. } |
2468 ObligationCauseCode::IfExpression { .. } |
2469 ObligationCauseCode::IfExpressionWithNoElse |
2470 ObligationCauseCode::MainFunctionType |
2471 ObligationCauseCode::StartFunctionType |
2472 ObligationCauseCode::IntrinsicType |
2473 ObligationCauseCode::MethodReceiver |
2474 ObligationCauseCode::ReturnNoExpression |
2475 ObligationCauseCode::MiscObligation => {}
2476 ObligationCauseCode::SliceOrArrayElem => {
2477 err.note("slice and array elements must have `Sized` type");
2479 ObligationCauseCode::TupleElem => {
2480 err.note("only the last element of a tuple may have a dynamically sized type");
2482 ObligationCauseCode::ProjectionWf(data) => {
2484 "required so that the projection `{}` is well-formed",
2488 ObligationCauseCode::ReferenceOutlivesReferent(ref_ty) => {
2490 "required so that reference `{}` does not outlive its referent",
2494 ObligationCauseCode::ObjectTypeBound(object_ty, region) => {
2496 "required so that the lifetime bound of `{}` for `{}` is satisfied",
2501 ObligationCauseCode::ItemObligation(item_def_id) => {
2502 let item_name = tcx.def_path_str(item_def_id);
2503 let msg = format!("required by `{}`", item_name);
2505 if let Some(sp) = tcx.hir().span_if_local(item_def_id) {
2506 let sp = tcx.sess.source_map().def_span(sp);
2507 err.span_label(sp, &msg);
2512 ObligationCauseCode::BindingObligation(item_def_id, span) => {
2513 let item_name = tcx.def_path_str(item_def_id);
2514 let msg = format!("required by this bound in `{}`", item_name);
2515 if let Some(ident) = tcx.opt_item_name(item_def_id) {
2516 err.span_label(ident.span, "");
2518 if span != DUMMY_SP {
2519 err.span_label(span, &msg);
2524 ObligationCauseCode::ObjectCastObligation(object_ty) => {
2525 err.note(&format!("required for the cast to the object type `{}`",
2526 self.ty_to_string(object_ty)));
2528 ObligationCauseCode::Coercion { source: _, target } => {
2529 err.note(&format!("required by cast to type `{}`",
2530 self.ty_to_string(target)));
2532 ObligationCauseCode::RepeatVec(suggest_const_in_array_repeat_expressions) => {
2533 err.note("the `Copy` trait is required because the \
2534 repeated element will be copied");
2535 if suggest_const_in_array_repeat_expressions {
2536 err.note("this array initializer can be evaluated at compile-time, for more \
2537 information, see issue \
2538 https://github.com/rust-lang/rust/issues/49147");
2539 if tcx.sess.opts.unstable_features.is_nightly_build() {
2540 err.help("add `#![feature(const_in_array_repeat_expressions)]` to the \
2541 crate attributes to enable");
2545 ObligationCauseCode::VariableType(_) => {
2546 err.note("all local variables must have a statically known size");
2547 if !self.tcx.features().unsized_locals {
2548 err.help("unsized locals are gated as an unstable feature");
2551 ObligationCauseCode::SizedArgumentType => {
2552 err.note("all function arguments must have a statically known size");
2553 if !self.tcx.features().unsized_locals {
2554 err.help("unsized locals are gated as an unstable feature");
2557 ObligationCauseCode::SizedReturnType => {
2558 err.note("the return type of a function must have a \
2559 statically known size");
2561 ObligationCauseCode::SizedYieldType => {
2562 err.note("the yield type of a generator must have a \
2563 statically known size");
2565 ObligationCauseCode::AssignmentLhsSized => {
2566 err.note("the left-hand-side of an assignment must have a statically known size");
2568 ObligationCauseCode::TupleInitializerSized => {
2569 err.note("tuples must have a statically known size to be initialized");
2571 ObligationCauseCode::StructInitializerSized => {
2572 err.note("structs must have a statically known size to be initialized");
2574 ObligationCauseCode::FieldSized { adt_kind: ref item, last } => {
2576 AdtKind::Struct => {
2578 err.note("the last field of a packed struct may only have a \
2579 dynamically sized type if it does not need drop to be run");
2581 err.note("only the last field of a struct may have a dynamically \
2586 err.note("no field of a union may have a dynamically sized type");
2589 err.note("no field of an enum variant may have a dynamically sized type");
2593 ObligationCauseCode::ConstSized => {
2594 err.note("constant expressions must have a statically known size");
2596 ObligationCauseCode::ConstPatternStructural => {
2597 err.note("constants used for pattern-matching must derive `PartialEq` and `Eq`");
2599 ObligationCauseCode::SharedStatic => {
2600 err.note("shared static variables must have a type that implements `Sync`");
2602 ObligationCauseCode::BuiltinDerivedObligation(ref data) => {
2603 let parent_trait_ref = self.resolve_vars_if_possible(&data.parent_trait_ref);
2604 let ty = parent_trait_ref.skip_binder().self_ty();
2605 err.note(&format!("required because it appears within the type `{}`", ty));
2606 obligated_types.push(ty);
2608 let parent_predicate = parent_trait_ref.to_predicate();
2609 if !self.is_recursive_obligation(obligated_types, &data.parent_code) {
2610 self.note_obligation_cause_code(err,
2616 ObligationCauseCode::ImplDerivedObligation(ref data) => {
2617 let parent_trait_ref = self.resolve_vars_if_possible(&data.parent_trait_ref);
2619 &format!("required because of the requirements on the impl of `{}` for `{}`",
2620 parent_trait_ref.print_only_trait_path(),
2621 parent_trait_ref.skip_binder().self_ty()));
2622 let parent_predicate = parent_trait_ref.to_predicate();
2623 self.note_obligation_cause_code(err,
2628 ObligationCauseCode::CompareImplMethodObligation { .. } => {
2630 &format!("the requirement `{}` appears on the impl method \
2631 but not on the corresponding trait method",
2634 ObligationCauseCode::ReturnType |
2635 ObligationCauseCode::ReturnValue(_) |
2636 ObligationCauseCode::BlockTailExpression(_) => (),
2637 ObligationCauseCode::TrivialBound => {
2638 err.help("see issue #48214");
2639 if tcx.sess.opts.unstable_features.is_nightly_build() {
2640 err.help("add `#![feature(trivial_bounds)]` to the \
2641 crate attributes to enable",
2645 ObligationCauseCode::AssocTypeBound(ref data) => {
2646 err.span_label(data.original, "associated type defined here");
2647 if let Some(sp) = data.impl_span {
2648 err.span_label(sp, "in this `impl` item");
2650 for sp in &data.bounds {
2651 err.span_label(*sp, "restricted in this bound");
2657 fn suggest_new_overflow_limit(&self, err: &mut DiagnosticBuilder<'_>) {
2658 let current_limit = self.tcx.sess.recursion_limit.get();
2659 let suggested_limit = current_limit * 2;
2660 err.help(&format!("consider adding a `#![recursion_limit=\"{}\"]` attribute to your crate",
2664 fn is_recursive_obligation(&self,
2665 obligated_types: &mut Vec<&ty::TyS<'tcx>>,
2666 cause_code: &ObligationCauseCode<'tcx>) -> bool {
2667 if let ObligationCauseCode::BuiltinDerivedObligation(ref data) = cause_code {
2668 let parent_trait_ref = self.resolve_vars_if_possible(&data.parent_trait_ref);
2670 if obligated_types.iter().any(|ot| ot == &parent_trait_ref.skip_binder().self_ty()) {
2678 /// Summarizes information
2681 /// An argument of non-tuple type. Parameters are (name, ty)
2682 Arg(String, String),
2684 /// An argument of tuple type. For a "found" argument, the span is
2685 /// the locationo in the source of the pattern. For a "expected"
2686 /// argument, it will be None. The vector is a list of (name, ty)
2687 /// strings for the components of the tuple.
2688 Tuple(Option<Span>, Vec<(String, String)>),
2692 fn empty() -> ArgKind {
2693 ArgKind::Arg("_".to_owned(), "_".to_owned())
2696 /// Creates an `ArgKind` from the expected type of an
2697 /// argument. It has no name (`_`) and an optional source span.
2698 pub fn from_expected_ty(t: Ty<'_>, span: Option<Span>) -> ArgKind {
2700 ty::Tuple(ref tys) => ArgKind::Tuple(
2703 .map(|ty| ("_".to_owned(), ty.to_string()))
2704 .collect::<Vec<_>>()
2706 _ => ArgKind::Arg("_".to_owned(), t.to_string()),
2711 /// Suggest restricting a type param with a new bound.
2712 pub fn suggest_constraining_type_param(
2713 generics: &hir::Generics,
2714 err: &mut DiagnosticBuilder<'_>,
2717 source_map: &SourceMap,
2720 let restrict_msg = "consider further restricting this bound";
2721 if let Some(param) = generics.params.iter().filter(|p| {
2722 p.name.ident().as_str() == param_name
2724 if param_name.starts_with("impl ") {
2725 // `impl Trait` in argument:
2726 // `fn foo(x: impl Trait) {}` → `fn foo(t: impl Trait + Trait2) {}`
2727 err.span_suggestion(
2730 // `impl CurrentTrait + MissingTrait`
2731 format!("{} + {}", param_name, constraint),
2732 Applicability::MachineApplicable,
2734 } else if generics.where_clause.predicates.is_empty() &&
2735 param.bounds.is_empty()
2737 // If there are no bounds whatsoever, suggest adding a constraint
2738 // to the type parameter:
2739 // `fn foo<T>(t: T) {}` → `fn foo<T: Trait>(t: T) {}`
2740 err.span_suggestion(
2742 "consider restricting this bound",
2743 format!("{}: {}", param_name, constraint),
2744 Applicability::MachineApplicable,
2746 } else if !generics.where_clause.predicates.is_empty() {
2747 // There is a `where` clause, so suggest expanding it:
2748 // `fn foo<T>(t: T) where T: Debug {}` →
2749 // `fn foo<T>(t: T) where T: Debug, T: Trait {}`
2750 err.span_suggestion(
2751 generics.where_clause.span().unwrap().shrink_to_hi(),
2752 &format!("consider further restricting type parameter `{}`", param_name),
2753 format!(", {}: {}", param_name, constraint),
2754 Applicability::MachineApplicable,
2757 // If there is no `where` clause lean towards constraining to the
2759 // `fn foo<X: Bar, T>(t: T, x: X) {}` → `fn foo<T: Trait>(t: T) {}`
2760 // `fn foo<T: Bar>(t: T) {}` → `fn foo<T: Bar + Trait>(t: T) {}`
2761 let sp = param.span.with_hi(span.hi());
2762 let span = source_map.span_through_char(sp, ':');
2763 if sp != param.span && sp != span {
2764 // Only suggest if we have high certainty that the span
2765 // covers the colon in `foo<T: Trait>`.
2766 err.span_suggestion(
2769 format!("{}: {} + ", param_name, constraint),
2770 Applicability::MachineApplicable,
2775 &format!("consider adding a `where {}: {}` bound", param_name, constraint),