2 ConstEvalFailure, EvaluationResult, FulfillmentError, FulfillmentErrorCode,
3 MismatchedProjectionTypes, ObjectSafetyViolation, Obligation, ObligationCause,
4 ObligationCauseCode, OnUnimplementedDirective, OnUnimplementedNote,
5 OutputTypeParameterMismatch, Overflow, PredicateObligation, SelectionContext, SelectionError,
9 use crate::infer::error_reporting::TypeAnnotationNeeded as ErrorCode;
10 use crate::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
11 use crate::infer::{self, InferCtxt};
12 use crate::mir::interpret::ErrorHandled;
13 use crate::session::DiagnosticMessageId;
14 use crate::traits::object_safety_violations;
15 use crate::ty::error::ExpectedFound;
16 use crate::ty::fast_reject;
17 use crate::ty::fold::TypeFolder;
18 use crate::ty::subst::Subst;
19 use crate::ty::GenericParamDefKind;
20 use crate::ty::SubtypePredicate;
21 use crate::ty::TypeckTables;
22 use crate::ty::{self, AdtKind, DefIdTree, ToPolyTraitRef, ToPredicate, Ty, TyCtxt, TypeFoldable};
23 use errors::{pluralize, Applicability, DiagnosticBuilder, Style};
24 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
26 use rustc_hir::def_id::{DefId, LOCAL_CRATE};
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 = object_safety_violations(self.tcx, trait_def_id);
920 report_object_safety_error(self.tcx, 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 = object_safety_violations(self.tcx, did);
1084 report_object_safety_error(self.tcx, span, did, violations)
1087 // already reported in the query
1088 ConstEvalFailure(err) => {
1089 if let ErrorHandled::TooGeneric = err {
1090 // Silence this error, as it can be produced during intermediate steps
1091 // when a constant is not yet able to be evaluated (but will be later).
1094 self.tcx.sess.delay_span_bug(
1096 &format!("constant in type had an ignored error: {:?}", err),
1102 bug!("overflow should be handled before the `report_selection_error` path");
1106 self.note_obligation_cause(&mut err, obligation);
1111 /// If the `Self` type of the unsatisfied trait `trait_ref` implements a trait
1112 /// with the same path as `trait_ref`, a help message about
1113 /// a probable version mismatch is added to `err`
1114 fn note_version_mismatch(
1116 err: &mut DiagnosticBuilder<'_>,
1117 trait_ref: &ty::PolyTraitRef<'tcx>,
1119 let get_trait_impl = |trait_def_id| {
1120 let mut trait_impl = None;
1121 self.tcx.for_each_relevant_impl(trait_def_id, trait_ref.self_ty(), |impl_def_id| {
1122 if trait_impl.is_none() {
1123 trait_impl = Some(impl_def_id);
1128 let required_trait_path = self.tcx.def_path_str(trait_ref.def_id());
1129 let all_traits = self.tcx.all_traits(LOCAL_CRATE);
1130 let traits_with_same_path: std::collections::BTreeSet<_> = all_traits
1132 .filter(|trait_def_id| **trait_def_id != trait_ref.def_id())
1133 .filter(|trait_def_id| self.tcx.def_path_str(**trait_def_id) == required_trait_path)
1135 for trait_with_same_path in traits_with_same_path {
1136 if let Some(impl_def_id) = get_trait_impl(*trait_with_same_path) {
1137 let impl_span = self.tcx.def_span(impl_def_id);
1138 err.span_help(impl_span, "trait impl with same name found");
1139 let trait_crate = self.tcx.crate_name(trait_with_same_path.krate);
1140 let crate_msg = format!(
1141 "Perhaps two different versions of crate `{}` are being used?",
1144 err.note(&crate_msg);
1148 fn suggest_restricting_param_bound(
1150 mut err: &mut DiagnosticBuilder<'_>,
1151 trait_ref: &ty::PolyTraitRef<'_>,
1152 body_id: hir::HirId,
1154 let self_ty = trait_ref.self_ty();
1155 let (param_ty, projection) = match &self_ty.kind {
1156 ty::Param(_) => (true, None),
1157 ty::Projection(projection) => (false, Some(projection)),
1161 let suggest_restriction =
1162 |generics: &hir::Generics<'_>, msg, err: &mut DiagnosticBuilder<'_>| {
1163 let span = generics.where_clause.span_for_predicates_or_empty_place();
1164 if !span.from_expansion() && span.desugaring_kind().is_none() {
1165 err.span_suggestion(
1166 generics.where_clause.span_for_predicates_or_empty_place().shrink_to_hi(),
1167 &format!("consider further restricting {}", msg),
1170 if !generics.where_clause.predicates.is_empty() {
1175 trait_ref.to_predicate(),
1177 Applicability::MachineApplicable,
1182 // FIXME: Add check for trait bound that is already present, particularly `?Sized` so we
1183 // don't suggest `T: Sized + ?Sized`.
1184 let mut hir_id = body_id;
1185 while let Some(node) = self.tcx.hir().find(hir_id) {
1187 hir::Node::TraitItem(hir::TraitItem {
1189 kind: hir::TraitItemKind::Method(..),
1191 }) if param_ty && self_ty == self.tcx.types.self_param => {
1192 // Restricting `Self` for a single method.
1193 suggest_restriction(&generics, "`Self`", err);
1197 hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(_, generics, _), .. })
1198 | hir::Node::TraitItem(hir::TraitItem {
1200 kind: hir::TraitItemKind::Method(..),
1203 | hir::Node::ImplItem(hir::ImplItem {
1205 kind: hir::ImplItemKind::Method(..),
1208 | hir::Node::Item(hir::Item {
1209 kind: hir::ItemKind::Trait(_, _, generics, _, _),
1212 | hir::Node::Item(hir::Item {
1213 kind: hir::ItemKind::Impl(_, _, _, generics, ..),
1215 }) if projection.is_some() => {
1216 // Missing associated type bound.
1217 suggest_restriction(&generics, "the associated type", err);
1221 hir::Node::Item(hir::Item {
1222 kind: hir::ItemKind::Struct(_, generics),
1226 | hir::Node::Item(hir::Item {
1227 kind: hir::ItemKind::Enum(_, generics), span, ..
1229 | hir::Node::Item(hir::Item {
1230 kind: hir::ItemKind::Union(_, generics),
1234 | hir::Node::Item(hir::Item {
1235 kind: hir::ItemKind::Trait(_, _, generics, ..),
1239 | hir::Node::Item(hir::Item {
1240 kind: hir::ItemKind::Impl(_, _, _, generics, ..),
1244 | hir::Node::Item(hir::Item {
1245 kind: hir::ItemKind::Fn(_, generics, _),
1249 | hir::Node::Item(hir::Item {
1250 kind: hir::ItemKind::TyAlias(_, generics),
1254 | hir::Node::Item(hir::Item {
1255 kind: hir::ItemKind::TraitAlias(generics, _),
1259 | hir::Node::Item(hir::Item {
1260 kind: hir::ItemKind::OpaqueTy(hir::OpaqueTy { generics, .. }),
1264 | hir::Node::TraitItem(hir::TraitItem { generics, span, .. })
1265 | hir::Node::ImplItem(hir::ImplItem { generics, span, .. })
1268 // Missing generic type parameter bound.
1269 let param_name = self_ty.to_string();
1270 let constraint = trait_ref.print_only_trait_path().to_string();
1271 if suggest_constraining_type_param(
1276 self.tcx.sess.source_map(),
1283 hir::Node::Crate => return,
1288 hir_id = self.tcx.hir().get_parent_item(hir_id);
1292 /// When encountering an assignment of an unsized trait, like `let x = ""[..];`, provide a
1293 /// suggestion to borrow the initializer in order to use have a slice instead.
1294 fn suggest_borrow_on_unsized_slice(
1296 code: &ObligationCauseCode<'tcx>,
1297 err: &mut DiagnosticBuilder<'tcx>,
1299 if let &ObligationCauseCode::VariableType(hir_id) = code {
1300 let parent_node = self.tcx.hir().get_parent_node(hir_id);
1301 if let Some(Node::Local(ref local)) = self.tcx.hir().find(parent_node) {
1302 if let Some(ref expr) = local.init {
1303 if let hir::ExprKind::Index(_, _) = expr.kind {
1304 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(expr.span) {
1305 err.span_suggestion(
1307 "consider borrowing here",
1308 format!("&{}", snippet),
1309 Applicability::MachineApplicable,
1318 fn mk_obligation_for_def_id(
1321 output_ty: Ty<'tcx>,
1322 cause: ObligationCause<'tcx>,
1323 param_env: ty::ParamEnv<'tcx>,
1324 ) -> PredicateObligation<'tcx> {
1326 ty::TraitRef { def_id, substs: self.tcx.mk_substs_trait(output_ty, &[]) };
1327 Obligation::new(cause, param_env, new_trait_ref.to_predicate())
1330 /// Given a closure's `DefId`, return the given name of the closure.
1332 /// This doesn't account for reassignments, but it's only used for suggestions.
1333 fn get_closure_name(
1336 err: &mut DiagnosticBuilder<'_>,
1338 ) -> Option<String> {
1340 |err: &mut DiagnosticBuilder<'_>, kind: &hir::PatKind<'_>| -> Option<String> {
1341 // Get the local name of this closure. This can be inaccurate because
1342 // of the possibility of reassignment, but this should be good enough.
1344 hir::PatKind::Binding(hir::BindingAnnotation::Unannotated, _, name, None) => {
1345 Some(format!("{}", name))
1354 let hir = self.tcx.hir();
1355 let hir_id = hir.as_local_hir_id(def_id)?;
1356 let parent_node = hir.get_parent_node(hir_id);
1357 match hir.find(parent_node) {
1358 Some(hir::Node::Stmt(hir::Stmt { kind: hir::StmtKind::Local(local), .. })) => {
1359 get_name(err, &local.pat.kind)
1361 // Different to previous arm because one is `&hir::Local` and the other
1362 // is `P<hir::Local>`.
1363 Some(hir::Node::Local(local)) => get_name(err, &local.pat.kind),
1368 /// We tried to apply the bound to an `fn` or closure. Check whether calling it would
1369 /// evaluate to a type that *would* satisfy the trait binding. If it would, suggest calling
1370 /// it: `bar(foo)` → `bar(foo())`. This case is *very* likely to be hit if `foo` is `async`.
1373 obligation: &PredicateObligation<'tcx>,
1374 err: &mut DiagnosticBuilder<'_>,
1375 trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
1376 points_at_arg: bool,
1378 let self_ty = trait_ref.self_ty();
1379 let (def_id, output_ty, callable) = match self_ty.kind {
1380 ty::Closure(def_id, substs) => {
1381 (def_id, self.closure_sig(def_id, substs).output(), "closure")
1383 ty::FnDef(def_id, _) => (def_id, self_ty.fn_sig(self.tcx).output(), "function"),
1386 let msg = format!("use parentheses to call the {}", callable);
1388 let obligation = self.mk_obligation_for_def_id(
1390 output_ty.skip_binder(),
1391 obligation.cause.clone(),
1392 obligation.param_env,
1395 match self.evaluate_obligation(&obligation) {
1396 Ok(EvaluationResult::EvaluatedToOk)
1397 | Ok(EvaluationResult::EvaluatedToOkModuloRegions)
1398 | Ok(EvaluationResult::EvaluatedToAmbig) => {}
1401 let hir = self.tcx.hir();
1402 // Get the name of the callable and the arguments to be used in the suggestion.
1403 let snippet = match hir.get_if_local(def_id) {
1404 Some(hir::Node::Expr(hir::Expr {
1405 kind: hir::ExprKind::Closure(_, decl, _, span, ..),
1408 err.span_label(*span, "consider calling this closure");
1409 let name = match self.get_closure_name(def_id, err, &msg) {
1413 let args = decl.inputs.iter().map(|_| "_").collect::<Vec<_>>().join(", ");
1414 format!("{}({})", name, args)
1416 Some(hir::Node::Item(hir::Item {
1418 kind: hir::ItemKind::Fn(.., body_id),
1421 err.span_label(ident.span, "consider calling this function");
1422 let body = hir.body(*body_id);
1426 .map(|arg| match &arg.pat.kind {
1427 hir::PatKind::Binding(_, _, ident, None)
1428 // FIXME: provide a better suggestion when encountering `SelfLower`, it
1429 // should suggest a method call.
1430 if ident.name != kw::SelfLower => ident.to_string(),
1431 _ => "_".to_string(),
1433 .collect::<Vec<_>>()
1435 format!("{}({})", ident, args)
1440 // When the obligation error has been ensured to have been caused by
1441 // an argument, the `obligation.cause.span` points at the expression
1442 // of the argument, so we can provide a suggestion. This is signaled
1443 // by `points_at_arg`. Otherwise, we give a more general note.
1444 err.span_suggestion(
1445 obligation.cause.span,
1448 Applicability::HasPlaceholders,
1451 err.help(&format!("{}: `{}`", msg, snippet));
1455 fn suggest_add_reference_to_arg(
1457 obligation: &PredicateObligation<'tcx>,
1458 err: &mut DiagnosticBuilder<'tcx>,
1459 trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
1460 points_at_arg: bool,
1461 has_custom_message: bool,
1467 let span = obligation.cause.span;
1468 let param_env = obligation.param_env;
1469 let trait_ref = trait_ref.skip_binder();
1471 if let ObligationCauseCode::ImplDerivedObligation(obligation) = &obligation.cause.code {
1472 // Try to apply the original trait binding obligation by borrowing.
1473 let self_ty = trait_ref.self_ty();
1474 let found = self_ty.to_string();
1475 let new_self_ty = self.tcx.mk_imm_ref(self.tcx.lifetimes.re_static, self_ty);
1476 let substs = self.tcx.mk_substs_trait(new_self_ty, &[]);
1477 let new_trait_ref = ty::TraitRef::new(obligation.parent_trait_ref.def_id(), substs);
1478 let new_obligation =
1479 Obligation::new(ObligationCause::dummy(), param_env, new_trait_ref.to_predicate());
1480 if self.predicate_must_hold_modulo_regions(&new_obligation) {
1481 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
1482 // We have a very specific type of error, where just borrowing this argument
1483 // might solve the problem. In cases like this, the important part is the
1484 // original type obligation, not the last one that failed, which is arbitrary.
1485 // Because of this, we modify the error to refer to the original obligation and
1486 // return early in the caller.
1488 "the trait bound `{}: {}` is not satisfied",
1490 obligation.parent_trait_ref.skip_binder().print_only_trait_path(),
1492 if has_custom_message {
1495 err.message = vec![(msg, Style::NoStyle)];
1497 if snippet.starts_with('&') {
1498 // This is already a literal borrow and the obligation is failing
1499 // somewhere else in the obligation chain. Do not suggest non-sense.
1505 "expected an implementor of trait `{}`",
1506 obligation.parent_trait_ref.skip_binder().print_only_trait_path(),
1509 err.span_suggestion(
1511 "consider borrowing here",
1512 format!("&{}", snippet),
1513 Applicability::MaybeIncorrect,
1522 /// Whenever references are used by mistake, like `for (i, e) in &vec.iter().enumerate()`,
1523 /// suggest removing these references until we reach a type that implements the trait.
1524 fn suggest_remove_reference(
1526 obligation: &PredicateObligation<'tcx>,
1527 err: &mut DiagnosticBuilder<'tcx>,
1528 trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
1530 let trait_ref = trait_ref.skip_binder();
1531 let span = obligation.cause.span;
1533 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
1535 snippet.chars().filter(|c| !c.is_whitespace()).take_while(|c| *c == '&').count();
1537 snippet.chars().filter(|c| !c.is_whitespace()).skip(refs_number).next()
1539 // Do not suggest removal of borrow from type arguments.
1543 let mut trait_type = trait_ref.self_ty();
1545 for refs_remaining in 0..refs_number {
1546 if let ty::Ref(_, t_type, _) = trait_type.kind {
1547 trait_type = t_type;
1549 let new_obligation = self.mk_obligation_for_def_id(
1552 ObligationCause::dummy(),
1553 obligation.param_env,
1556 if self.predicate_may_hold(&new_obligation) {
1561 .span_take_while(span, |c| c.is_whitespace() || *c == '&');
1563 let remove_refs = refs_remaining + 1;
1565 format!("consider removing {} leading `&`-references", remove_refs);
1567 err.span_suggestion_short(
1571 Applicability::MachineApplicable,
1582 /// Check if the trait bound is implemented for a different mutability and note it in the
1584 fn suggest_change_mut(
1586 obligation: &PredicateObligation<'tcx>,
1587 err: &mut DiagnosticBuilder<'tcx>,
1588 trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
1589 points_at_arg: bool,
1591 let span = obligation.cause.span;
1592 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
1594 snippet.chars().filter(|c| !c.is_whitespace()).take_while(|c| *c == '&').count();
1596 snippet.chars().filter(|c| !c.is_whitespace()).skip(refs_number).next()
1598 // Do not suggest removal of borrow from type arguments.
1601 let trait_ref = self.resolve_vars_if_possible(trait_ref);
1602 if trait_ref.has_infer_types() {
1603 // Do not ICE while trying to find if a reborrow would succeed on a trait with
1604 // unresolved bindings.
1608 if let ty::Ref(region, t_type, mutability) = trait_ref.skip_binder().self_ty().kind {
1609 let trait_type = match mutability {
1610 hir::Mutability::Mut => self.tcx.mk_imm_ref(region, t_type),
1611 hir::Mutability::Not => self.tcx.mk_mut_ref(region, t_type),
1614 let new_obligation = self.mk_obligation_for_def_id(
1615 trait_ref.skip_binder().def_id,
1617 ObligationCause::dummy(),
1618 obligation.param_env,
1621 if self.evaluate_obligation_no_overflow(&new_obligation).must_apply_modulo_regions()
1627 .span_take_while(span, |c| c.is_whitespace() || *c == '&');
1628 if points_at_arg && mutability == hir::Mutability::Not && refs_number > 0 {
1629 err.span_suggestion(
1631 "consider changing this borrow's mutability",
1632 "&mut ".to_string(),
1633 Applicability::MachineApplicable,
1637 "`{}` is implemented for `{:?}`, but not for `{:?}`",
1638 trait_ref.print_only_trait_path(),
1640 trait_ref.skip_binder().self_ty(),
1648 fn suggest_semicolon_removal(
1650 obligation: &PredicateObligation<'tcx>,
1651 err: &mut DiagnosticBuilder<'tcx>,
1653 trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
1655 let hir = self.tcx.hir();
1656 let parent_node = hir.get_parent_node(obligation.cause.body_id);
1657 let node = hir.find(parent_node);
1658 if let Some(hir::Node::Item(hir::Item {
1659 kind: hir::ItemKind::Fn(sig, _, body_id), ..
1662 let body = hir.body(*body_id);
1663 if let hir::ExprKind::Block(blk, _) = &body.value.kind {
1664 if sig.decl.output.span().overlaps(span)
1665 && blk.expr.is_none()
1666 && "()" == &trait_ref.self_ty().to_string()
1668 // FIXME(estebank): When encountering a method with a trait
1669 // bound not satisfied in the return type with a body that has
1670 // no return, suggest removal of semicolon on last statement.
1671 // Once that is added, close #54771.
1672 if let Some(ref stmt) = blk.stmts.last() {
1673 let sp = self.tcx.sess.source_map().end_point(stmt.span);
1674 err.span_label(sp, "consider removing this semicolon");
1681 /// Given some node representing a fn-like thing in the HIR map,
1682 /// returns a span and `ArgKind` information that describes the
1683 /// arguments it expects. This can be supplied to
1684 /// `report_arg_count_mismatch`.
1685 pub fn get_fn_like_arguments(&self, node: Node<'_>) -> (Span, Vec<ArgKind>) {
1687 Node::Expr(&hir::Expr {
1688 kind: hir::ExprKind::Closure(_, ref _decl, id, span, _),
1691 self.tcx.sess.source_map().def_span(span),
1698 if let hir::Pat { kind: hir::PatKind::Tuple(ref args, _), span, .. } =
1709 .span_to_snippet(pat.span)
1711 (snippet, "_".to_owned())
1713 .collect::<Vec<_>>(),
1717 self.tcx.sess.source_map().span_to_snippet(arg.pat.span).unwrap();
1718 ArgKind::Arg(name, "_".to_owned())
1721 .collect::<Vec<ArgKind>>(),
1723 Node::Item(&hir::Item { span, kind: hir::ItemKind::Fn(ref sig, ..), .. })
1724 | Node::ImplItem(&hir::ImplItem {
1726 kind: hir::ImplItemKind::Method(ref sig, _),
1729 | Node::TraitItem(&hir::TraitItem {
1731 kind: hir::TraitItemKind::Method(ref sig, _),
1734 self.tcx.sess.source_map().def_span(span),
1738 .map(|arg| match arg.clone().kind {
1739 hir::TyKind::Tup(ref tys) => ArgKind::Tuple(
1741 vec![("_".to_owned(), "_".to_owned()); tys.len()],
1743 _ => ArgKind::empty(),
1745 .collect::<Vec<ArgKind>>(),
1747 Node::Ctor(ref variant_data) => {
1748 let span = variant_data
1750 .map(|hir_id| self.tcx.hir().span(hir_id))
1751 .unwrap_or(DUMMY_SP);
1752 let span = self.tcx.sess.source_map().def_span(span);
1754 (span, vec![ArgKind::empty(); variant_data.fields().len()])
1756 _ => panic!("non-FnLike node found: {:?}", node),
1760 /// Reports an error when the number of arguments needed by a
1761 /// trait match doesn't match the number that the expression
1763 pub fn report_arg_count_mismatch(
1766 found_span: Option<Span>,
1767 expected_args: Vec<ArgKind>,
1768 found_args: Vec<ArgKind>,
1770 ) -> DiagnosticBuilder<'tcx> {
1771 let kind = if is_closure { "closure" } else { "function" };
1773 let args_str = |arguments: &[ArgKind], other: &[ArgKind]| {
1774 let arg_length = arguments.len();
1775 let distinct = match &other[..] {
1776 &[ArgKind::Tuple(..)] => true,
1779 match (arg_length, arguments.get(0)) {
1780 (1, Some(&ArgKind::Tuple(_, ref fields))) => {
1781 format!("a single {}-tuple as argument", fields.len())
1786 if distinct && arg_length > 1 { "distinct " } else { "" },
1787 pluralize!(arg_length)
1792 let expected_str = args_str(&expected_args, &found_args);
1793 let found_str = args_str(&found_args, &expected_args);
1795 let mut err = struct_span_err!(
1799 "{} is expected to take {}, but it takes {}",
1805 err.span_label(span, format!("expected {} that takes {}", kind, expected_str));
1807 if let Some(found_span) = found_span {
1808 err.span_label(found_span, format!("takes {}", found_str));
1811 // ^^^^^^^^-- def_span
1815 let prefix_span = self.tcx.sess.source_map().span_until_non_whitespace(found_span);
1819 if let Some(span) = found_span.trim_start(prefix_span) { span } else { found_span };
1821 // Suggest to take and ignore the arguments with expected_args_length `_`s if
1822 // found arguments is empty (assume the user just wants to ignore args in this case).
1823 // For example, if `expected_args_length` is 2, suggest `|_, _|`.
1824 if found_args.is_empty() && is_closure {
1825 let underscores = vec!["_"; expected_args.len()].join(", ");
1826 err.span_suggestion(
1829 "consider changing the closure to take and ignore the expected argument{}",
1830 if expected_args.len() < 2 { "" } else { "s" }
1832 format!("|{}|", underscores),
1833 Applicability::MachineApplicable,
1837 if let &[ArgKind::Tuple(_, ref fields)] = &found_args[..] {
1838 if fields.len() == expected_args.len() {
1841 .map(|(name, _)| name.to_owned())
1842 .collect::<Vec<String>>()
1844 err.span_suggestion(
1846 "change the closure to take multiple arguments instead of a single tuple",
1847 format!("|{}|", sugg),
1848 Applicability::MachineApplicable,
1852 if let &[ArgKind::Tuple(_, ref fields)] = &expected_args[..] {
1853 if fields.len() == found_args.len() && is_closure {
1858 .map(|arg| match arg {
1859 ArgKind::Arg(name, _) => name.to_owned(),
1860 _ => "_".to_owned(),
1862 .collect::<Vec<String>>()
1864 // add type annotations if available
1865 if found_args.iter().any(|arg| match arg {
1866 ArgKind::Arg(_, ty) => ty != "_",
1873 .map(|(_, ty)| ty.to_owned())
1874 .collect::<Vec<String>>()
1881 err.span_suggestion(
1883 "change the closure to accept a tuple instead of individual arguments",
1885 Applicability::MachineApplicable,
1894 fn report_closure_arg_mismatch(
1897 found_span: Option<Span>,
1898 expected_ref: ty::PolyTraitRef<'tcx>,
1899 found: ty::PolyTraitRef<'tcx>,
1900 ) -> DiagnosticBuilder<'tcx> {
1901 fn build_fn_sig_string<'tcx>(tcx: TyCtxt<'tcx>, trait_ref: &ty::TraitRef<'tcx>) -> String {
1902 let inputs = trait_ref.substs.type_at(1);
1903 let sig = if let ty::Tuple(inputs) = inputs.kind {
1905 inputs.iter().map(|k| k.expect_ty()),
1906 tcx.mk_ty_infer(ty::TyVar(ty::TyVid { index: 0 })),
1908 hir::Unsafety::Normal,
1909 ::rustc_target::spec::abi::Abi::Rust,
1913 ::std::iter::once(inputs),
1914 tcx.mk_ty_infer(ty::TyVar(ty::TyVid { index: 0 })),
1916 hir::Unsafety::Normal,
1917 ::rustc_target::spec::abi::Abi::Rust,
1920 ty::Binder::bind(sig).to_string()
1923 let argument_is_closure = expected_ref.skip_binder().substs.type_at(0).is_closure();
1924 let mut err = struct_span_err!(
1928 "type mismatch in {} arguments",
1929 if argument_is_closure { "closure" } else { "function" }
1932 let found_str = format!(
1933 "expected signature of `{}`",
1934 build_fn_sig_string(self.tcx, found.skip_binder())
1936 err.span_label(span, found_str);
1938 let found_span = found_span.unwrap_or(span);
1939 let expected_str = format!(
1940 "found signature of `{}`",
1941 build_fn_sig_string(self.tcx, expected_ref.skip_binder())
1943 err.span_label(found_span, expected_str);
1949 pub fn recursive_type_with_infinite_size_error(
1952 ) -> DiagnosticBuilder<'tcx> {
1953 assert!(type_def_id.is_local());
1954 let span = tcx.hir().span_if_local(type_def_id).unwrap();
1955 let span = tcx.sess.source_map().def_span(span);
1956 let mut err = struct_span_err!(
1960 "recursive type `{}` has infinite size",
1961 tcx.def_path_str(type_def_id)
1963 err.span_label(span, "recursive type has infinite size");
1965 "insert indirection (e.g., a `Box`, `Rc`, or `&`) \
1966 at some point to make `{}` representable",
1967 tcx.def_path_str(type_def_id)
1972 pub fn report_object_safety_error(
1975 trait_def_id: DefId,
1976 violations: Vec<ObjectSafetyViolation>,
1977 ) -> DiagnosticBuilder<'tcx> {
1978 let trait_str = tcx.def_path_str(trait_def_id);
1979 let span = tcx.sess.source_map().def_span(span);
1980 let mut err = struct_span_err!(
1984 "the trait `{}` cannot be made into an object",
1987 err.span_label(span, format!("the trait `{}` cannot be made into an object", trait_str));
1989 let mut reported_violations = FxHashSet::default();
1990 for violation in violations {
1991 if reported_violations.insert(violation.clone()) {
1992 match violation.span() {
1993 Some(span) => err.span_label(span, violation.error_msg()),
1994 None => err.note(&violation.error_msg()),
1999 if tcx.sess.trait_methods_not_found.borrow().contains(&span) {
2000 // Avoid emitting error caused by non-existing method (#58734)
2007 impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
2008 fn maybe_report_ambiguity(
2010 obligation: &PredicateObligation<'tcx>,
2011 body_id: Option<hir::BodyId>,
2013 // Unable to successfully determine, probably means
2014 // insufficient type information, but could mean
2015 // ambiguous impls. The latter *ought* to be a
2016 // coherence violation, so we don't report it here.
2018 let predicate = self.resolve_vars_if_possible(&obligation.predicate);
2019 let span = obligation.cause.span;
2022 "maybe_report_ambiguity(predicate={:?}, obligation={:?} body_id={:?}, code={:?})",
2023 predicate, obligation, body_id, obligation.cause.code,
2026 // Ambiguity errors are often caused as fallout from earlier
2027 // errors. So just ignore them if this infcx is tainted.
2028 if self.is_tainted_by_errors() {
2032 let mut err = match predicate {
2033 ty::Predicate::Trait(ref data) => {
2034 let trait_ref = data.to_poly_trait_ref();
2035 let self_ty = trait_ref.self_ty();
2036 debug!("self_ty {:?} {:?} trait_ref {:?}", self_ty, self_ty.kind, trait_ref);
2038 if predicate.references_error() {
2041 // Typically, this ambiguity should only happen if
2042 // there are unresolved type inference variables
2043 // (otherwise it would suggest a coherence
2044 // failure). But given #21974 that is not necessarily
2045 // the case -- we can have multiple where clauses that
2046 // are only distinguished by a region, which results
2047 // in an ambiguity even when all types are fully
2048 // known, since we don't dispatch based on region
2051 // This is kind of a hack: it frequently happens that some earlier
2052 // error prevents types from being fully inferred, and then we get
2053 // a bunch of uninteresting errors saying something like "<generic
2054 // #0> doesn't implement Sized". It may even be true that we
2055 // could just skip over all checks where the self-ty is an
2056 // inference variable, but I was afraid that there might be an
2057 // inference variable created, registered as an obligation, and
2058 // then never forced by writeback, and hence by skipping here we'd
2059 // be ignoring the fact that we don't KNOW the type works
2060 // out. Though even that would probably be harmless, given that
2061 // we're only talking about builtin traits, which are known to be
2062 // inhabited. We used to check for `self.tcx.sess.has_errors()` to
2063 // avoid inundating the user with unnecessary errors, but we now
2064 // check upstream for type errors and dont add the obligations to
2065 // begin with in those cases.
2070 .map_or(false, |sized_id| sized_id == trait_ref.def_id())
2072 self.need_type_info_err(body_id, span, self_ty, ErrorCode::E0282).emit();
2075 let mut err = self.need_type_info_err(body_id, span, self_ty, ErrorCode::E0283);
2076 err.note(&format!("cannot resolve `{}`", predicate));
2077 if let (Ok(ref snippet), ObligationCauseCode::BindingObligation(ref def_id, _)) =
2078 (self.tcx.sess.source_map().span_to_snippet(span), &obligation.cause.code)
2080 let generics = self.tcx.generics_of(*def_id);
2081 if !generics.params.is_empty() && !snippet.ends_with('>') {
2082 // FIXME: To avoid spurious suggestions in functions where type arguments
2083 // where already supplied, we check the snippet to make sure it doesn't
2084 // end with a turbofish. Ideally we would have access to a `PathSegment`
2085 // instead. Otherwise we would produce the following output:
2087 // error[E0283]: type annotations needed
2088 // --> $DIR/issue-54954.rs:3:24
2090 // LL | const ARR_LEN: usize = Tt::const_val::<[i8; 123]>();
2091 // | ^^^^^^^^^^^^^^^^^^^^^^^^^^
2093 // | cannot infer type
2094 // | help: consider specifying the type argument
2095 // | in the function call:
2096 // | `Tt::const_val::<[i8; 123]>::<T>`
2098 // LL | const fn const_val<T: Sized>() -> usize {
2099 // | --------- - required by this bound in `Tt::const_val`
2101 // = note: cannot resolve `_: Tt`
2103 err.span_suggestion(
2106 "consider specifying the type argument{} in the function call",
2107 if generics.params.len() > 1 { "s" } else { "" },
2115 .map(|p| p.name.to_string())
2116 .collect::<Vec<String>>()
2119 Applicability::HasPlaceholders,
2126 ty::Predicate::WellFormed(ty) => {
2127 // Same hacky approach as above to avoid deluging user
2128 // with error messages.
2129 if ty.references_error() || self.tcx.sess.has_errors() {
2132 self.need_type_info_err(body_id, span, ty, ErrorCode::E0282)
2135 ty::Predicate::Subtype(ref data) => {
2136 if data.references_error() || self.tcx.sess.has_errors() {
2137 // no need to overload user in such cases
2140 let &SubtypePredicate { a_is_expected: _, a, b } = data.skip_binder();
2141 // both must be type variables, or the other would've been instantiated
2142 assert!(a.is_ty_var() && b.is_ty_var());
2143 self.need_type_info_err(body_id, span, a, ErrorCode::E0282)
2145 ty::Predicate::Projection(ref data) => {
2146 let trait_ref = data.to_poly_trait_ref(self.tcx);
2147 let self_ty = trait_ref.self_ty();
2148 if predicate.references_error() {
2151 let mut err = self.need_type_info_err(body_id, span, self_ty, ErrorCode::E0284);
2152 err.note(&format!("cannot resolve `{}`", predicate));
2157 if self.tcx.sess.has_errors() {
2160 let mut err = struct_span_err!(
2164 "type annotations needed: cannot resolve `{}`",
2167 err.span_label(span, &format!("cannot resolve `{}`", predicate));
2171 self.note_obligation_cause(&mut err, obligation);
2175 /// Returns `true` if the trait predicate may apply for *some* assignment
2176 /// to the type parameters.
2177 fn predicate_can_apply(
2179 param_env: ty::ParamEnv<'tcx>,
2180 pred: ty::PolyTraitRef<'tcx>,
2182 struct ParamToVarFolder<'a, 'tcx> {
2183 infcx: &'a InferCtxt<'a, 'tcx>,
2184 var_map: FxHashMap<Ty<'tcx>, Ty<'tcx>>,
2187 impl<'a, 'tcx> TypeFolder<'tcx> for ParamToVarFolder<'a, 'tcx> {
2188 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
2192 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
2193 if let ty::Param(ty::ParamTy { name, .. }) = ty.kind {
2194 let infcx = self.infcx;
2195 self.var_map.entry(ty).or_insert_with(|| {
2196 infcx.next_ty_var(TypeVariableOrigin {
2197 kind: TypeVariableOriginKind::TypeParameterDefinition(name, None),
2202 ty.super_fold_with(self)
2208 let mut selcx = SelectionContext::new(self);
2211 pred.fold_with(&mut ParamToVarFolder { infcx: self, var_map: Default::default() });
2213 let cleaned_pred = super::project::normalize(
2216 ObligationCause::dummy(),
2222 Obligation::new(ObligationCause::dummy(), param_env, cleaned_pred.to_predicate());
2224 self.predicate_may_hold(&obligation)
2228 fn note_obligation_cause(
2230 err: &mut DiagnosticBuilder<'_>,
2231 obligation: &PredicateObligation<'tcx>,
2233 // First, attempt to add note to this error with an async-await-specific
2234 // message, and fall back to regular note otherwise.
2235 if !self.maybe_note_obligation_cause_for_async_await(err, obligation) {
2236 self.note_obligation_cause_code(
2238 &obligation.predicate,
2239 &obligation.cause.code,
2245 /// Adds an async-await specific note to the diagnostic when the future does not implement
2246 /// an auto trait because of a captured type.
2248 /// ```ignore (diagnostic)
2249 /// note: future does not implement `Qux` as this value is used across an await
2250 /// --> $DIR/issue-64130-3-other.rs:17:5
2252 /// LL | let x = Foo;
2253 /// | - has type `Foo`
2254 /// LL | baz().await;
2255 /// | ^^^^^^^^^^^ await occurs here, with `x` maybe used later
2257 /// | - `x` is later dropped here
2260 /// When the diagnostic does not implement `Send` or `Sync` specifically, then the diagnostic
2261 /// is "replaced" with a different message and a more specific error.
2263 /// ```ignore (diagnostic)
2264 /// error: future cannot be sent between threads safely
2265 /// --> $DIR/issue-64130-2-send.rs:21:5
2267 /// LL | fn is_send<T: Send>(t: T) { }
2268 /// | ------- ---- required by this bound in `is_send`
2270 /// LL | is_send(bar());
2271 /// | ^^^^^^^ future returned by `bar` is not send
2273 /// = help: within `impl std::future::Future`, the trait `std::marker::Send` is not
2274 /// implemented for `Foo`
2275 /// note: future is not send as this value is used across an await
2276 /// --> $DIR/issue-64130-2-send.rs:15:5
2278 /// LL | let x = Foo;
2279 /// | - has type `Foo`
2280 /// LL | baz().await;
2281 /// | ^^^^^^^^^^^ await occurs here, with `x` maybe used later
2283 /// | - `x` is later dropped here
2286 /// Returns `true` if an async-await specific note was added to the diagnostic.
2287 fn maybe_note_obligation_cause_for_async_await(
2289 err: &mut DiagnosticBuilder<'_>,
2290 obligation: &PredicateObligation<'tcx>,
2293 "maybe_note_obligation_cause_for_async_await: obligation.predicate={:?} \
2294 obligation.cause.span={:?}",
2295 obligation.predicate, obligation.cause.span
2297 let source_map = self.tcx.sess.source_map();
2299 // Attempt to detect an async-await error by looking at the obligation causes, looking
2300 // for a generator to be present.
2302 // When a future does not implement a trait because of a captured type in one of the
2303 // generators somewhere in the call stack, then the result is a chain of obligations.
2305 // Given a `async fn` A that calls a `async fn` B which captures a non-send type and that
2306 // future is passed as an argument to a function C which requires a `Send` type, then the
2307 // chain looks something like this:
2309 // - `BuiltinDerivedObligation` with a generator witness (B)
2310 // - `BuiltinDerivedObligation` with a generator (B)
2311 // - `BuiltinDerivedObligation` with `std::future::GenFuture` (B)
2312 // - `BuiltinDerivedObligation` with `impl std::future::Future` (B)
2313 // - `BuiltinDerivedObligation` with `impl std::future::Future` (B)
2314 // - `BuiltinDerivedObligation` with a generator witness (A)
2315 // - `BuiltinDerivedObligation` with a generator (A)
2316 // - `BuiltinDerivedObligation` with `std::future::GenFuture` (A)
2317 // - `BuiltinDerivedObligation` with `impl std::future::Future` (A)
2318 // - `BuiltinDerivedObligation` with `impl std::future::Future` (A)
2319 // - `BindingObligation` with `impl_send (Send requirement)
2321 // The first obligation in the chain is the most useful and has the generator that captured
2322 // the type. The last generator has information about where the bound was introduced. At
2323 // least one generator should be present for this diagnostic to be modified.
2324 let (mut trait_ref, mut target_ty) = match obligation.predicate {
2325 ty::Predicate::Trait(p) => {
2326 (Some(p.skip_binder().trait_ref), Some(p.skip_binder().self_ty()))
2330 let mut generator = None;
2331 let mut last_generator = None;
2332 let mut next_code = Some(&obligation.cause.code);
2333 while let Some(code) = next_code {
2334 debug!("maybe_note_obligation_cause_for_async_await: code={:?}", code);
2336 ObligationCauseCode::BuiltinDerivedObligation(derived_obligation)
2337 | ObligationCauseCode::ImplDerivedObligation(derived_obligation) => {
2338 let ty = derived_obligation.parent_trait_ref.self_ty();
2340 "maybe_note_obligation_cause_for_async_await: \
2341 parent_trait_ref={:?} self_ty.kind={:?}",
2342 derived_obligation.parent_trait_ref, ty.kind
2346 ty::Generator(did, ..) => {
2347 generator = generator.or(Some(did));
2348 last_generator = Some(did);
2350 ty::GeneratorWitness(..) => {}
2351 _ if generator.is_none() => {
2352 trait_ref = Some(*derived_obligation.parent_trait_ref.skip_binder());
2353 target_ty = Some(ty);
2358 next_code = Some(derived_obligation.parent_code.as_ref());
2364 // Only continue if a generator was found.
2366 "maybe_note_obligation_cause_for_async_await: generator={:?} trait_ref={:?} \
2368 generator, trait_ref, target_ty
2370 let (generator_did, trait_ref, target_ty) = match (generator, trait_ref, target_ty) {
2371 (Some(generator_did), Some(trait_ref), Some(target_ty)) => {
2372 (generator_did, trait_ref, target_ty)
2377 let span = self.tcx.def_span(generator_did);
2379 // Do not ICE on closure typeck (#66868).
2380 if self.tcx.hir().as_local_hir_id(generator_did).is_none() {
2384 // Get the tables from the infcx if the generator is the function we are
2385 // currently type-checking; otherwise, get them by performing a query.
2386 // This is needed to avoid cycles.
2387 let in_progress_tables = self.in_progress_tables.map(|t| t.borrow());
2388 let generator_did_root = self.tcx.closure_base_def_id(generator_did);
2390 "maybe_note_obligation_cause_for_async_await: generator_did={:?} \
2391 generator_did_root={:?} in_progress_tables.local_id_root={:?} span={:?}",
2394 in_progress_tables.as_ref().map(|t| t.local_id_root),
2398 let tables: &TypeckTables<'tcx> = match &in_progress_tables {
2399 Some(t) if t.local_id_root == Some(generator_did_root) => t,
2401 query_tables = self.tcx.typeck_tables_of(generator_did);
2406 // Look for a type inside the generator interior that matches the target type to get
2408 let target_ty_erased = self.tcx.erase_regions(&target_ty);
2409 let target_span = tables
2410 .generator_interior_types
2412 .find(|ty::GeneratorInteriorTypeCause { ty, .. }| {
2413 // Careful: the regions for types that appear in the
2414 // generator interior are not generally known, so we
2415 // want to erase them when comparing (and anyway,
2416 // `Send` and other bounds are generally unaffected by
2417 // the choice of region). When erasing regions, we
2418 // also have to erase late-bound regions. This is
2419 // because the types that appear in the generator
2420 // interior generally contain "bound regions" to
2421 // represent regions that are part of the suspended
2422 // generator frame. Bound regions are preserved by
2423 // `erase_regions` and so we must also call
2424 // `erase_late_bound_regions`.
2425 let ty_erased = self.tcx.erase_late_bound_regions(&ty::Binder::bind(*ty));
2426 let ty_erased = self.tcx.erase_regions(&ty_erased);
2427 let eq = ty::TyS::same_type(ty_erased, target_ty_erased);
2429 "maybe_note_obligation_cause_for_async_await: ty_erased={:?} \
2430 target_ty_erased={:?} eq={:?}",
2431 ty_erased, target_ty_erased, eq
2435 .map(|ty::GeneratorInteriorTypeCause { span, scope_span, .. }| {
2436 (span, source_map.span_to_snippet(*span), scope_span)
2439 "maybe_note_obligation_cause_for_async_await: target_ty={:?} \
2440 generator_interior_types={:?} target_span={:?}",
2441 target_ty, tables.generator_interior_types, target_span
2443 if let Some((target_span, Ok(snippet), scope_span)) = target_span {
2444 self.note_obligation_cause_for_async_await(
2463 /// Unconditionally adds the diagnostic note described in
2464 /// `maybe_note_obligation_cause_for_async_await`'s documentation comment.
2465 fn note_obligation_cause_for_async_await(
2467 err: &mut DiagnosticBuilder<'_>,
2469 scope_span: &Option<Span>,
2471 first_generator: DefId,
2472 last_generator: Option<DefId>,
2473 trait_ref: ty::TraitRef<'_>,
2474 target_ty: Ty<'tcx>,
2475 tables: &ty::TypeckTables<'_>,
2476 obligation: &PredicateObligation<'tcx>,
2477 next_code: Option<&ObligationCauseCode<'tcx>>,
2479 let source_map = self.tcx.sess.source_map();
2481 let is_async_fn = self
2483 .parent(first_generator)
2484 .map(|parent_did| self.tcx.asyncness(parent_did))
2485 .map(|parent_asyncness| parent_asyncness == hir::IsAsync::Async)
2487 let is_async_move = self
2490 .as_local_hir_id(first_generator)
2491 .and_then(|hir_id| self.tcx.hir().maybe_body_owned_by(hir_id))
2492 .map(|body_id| self.tcx.hir().body(body_id))
2493 .and_then(|body| body.generator_kind())
2494 .map(|generator_kind| match generator_kind {
2495 hir::GeneratorKind::Async(..) => true,
2499 let await_or_yield = if is_async_fn || is_async_move { "await" } else { "yield" };
2501 // Special case the primary error message when send or sync is the trait that was
2503 let is_send = self.tcx.is_diagnostic_item(sym::send_trait, trait_ref.def_id);
2504 let is_sync = self.tcx.is_diagnostic_item(sym::sync_trait, trait_ref.def_id);
2505 let trait_explanation = if is_send || is_sync {
2506 let (trait_name, trait_verb) =
2507 if is_send { ("`Send`", "sent") } else { ("`Sync`", "shared") };
2510 err.set_primary_message(format!(
2511 "future cannot be {} between threads safely",
2515 let original_span = err.span.primary_span().unwrap();
2516 let mut span = MultiSpan::from_span(original_span);
2518 let message = if let Some(name) = last_generator
2519 .and_then(|generator_did| self.tcx.parent(generator_did))
2520 .and_then(|parent_did| self.tcx.hir().as_local_hir_id(parent_did))
2521 .and_then(|parent_hir_id| self.tcx.hir().opt_name(parent_hir_id))
2523 format!("future returned by `{}` is not {}", name, trait_name)
2525 format!("future is not {}", trait_name)
2528 span.push_span_label(original_span, message);
2531 format!("is not {}", trait_name)
2533 format!("does not implement `{}`", trait_ref.print_only_trait_path())
2536 // Look at the last interior type to get a span for the `.await`.
2537 let await_span = tables.generator_interior_types.iter().map(|i| i.span).last().unwrap();
2538 let mut span = MultiSpan::from_span(await_span);
2539 span.push_span_label(
2541 format!("{} occurs here, with `{}` maybe used later", await_or_yield, snippet),
2544 span.push_span_label(target_span, format!("has type `{}`", target_ty));
2546 // If available, use the scope span to annotate the drop location.
2547 if let Some(scope_span) = scope_span {
2548 span.push_span_label(
2549 source_map.end_point(*scope_span),
2550 format!("`{}` is later dropped here", snippet),
2557 "future {} as this value is used across an {}",
2558 trait_explanation, await_or_yield,
2562 // Add a note for the item obligation that remains - normally a note pointing to the
2563 // bound that introduced the obligation (e.g. `T: Send`).
2564 debug!("note_obligation_cause_for_async_await: next_code={:?}", next_code);
2565 self.note_obligation_cause_code(
2567 &obligation.predicate,
2573 fn note_obligation_cause_code<T>(
2575 err: &mut DiagnosticBuilder<'_>,
2577 cause_code: &ObligationCauseCode<'tcx>,
2578 obligated_types: &mut Vec<&ty::TyS<'tcx>>,
2584 ObligationCauseCode::ExprAssignable
2585 | ObligationCauseCode::MatchExpressionArm { .. }
2586 | ObligationCauseCode::Pattern { .. }
2587 | ObligationCauseCode::IfExpression { .. }
2588 | ObligationCauseCode::IfExpressionWithNoElse
2589 | ObligationCauseCode::MainFunctionType
2590 | ObligationCauseCode::StartFunctionType
2591 | ObligationCauseCode::IntrinsicType
2592 | ObligationCauseCode::MethodReceiver
2593 | ObligationCauseCode::ReturnNoExpression
2594 | ObligationCauseCode::MiscObligation => {}
2595 ObligationCauseCode::SliceOrArrayElem => {
2596 err.note("slice and array elements must have `Sized` type");
2598 ObligationCauseCode::TupleElem => {
2599 err.note("only the last element of a tuple may have a dynamically sized type");
2601 ObligationCauseCode::ProjectionWf(data) => {
2602 err.note(&format!("required so that the projection `{}` is well-formed", data,));
2604 ObligationCauseCode::ReferenceOutlivesReferent(ref_ty) => {
2606 "required so that reference `{}` does not outlive its referent",
2610 ObligationCauseCode::ObjectTypeBound(object_ty, region) => {
2612 "required so that the lifetime bound of `{}` for `{}` is satisfied",
2616 ObligationCauseCode::ItemObligation(item_def_id) => {
2617 let item_name = tcx.def_path_str(item_def_id);
2618 let msg = format!("required by `{}`", item_name);
2620 if let Some(sp) = tcx.hir().span_if_local(item_def_id) {
2621 let sp = tcx.sess.source_map().def_span(sp);
2622 err.span_label(sp, &msg);
2627 ObligationCauseCode::BindingObligation(item_def_id, span) => {
2628 let item_name = tcx.def_path_str(item_def_id);
2629 let msg = format!("required by this bound in `{}`", item_name);
2630 if let Some(ident) = tcx.opt_item_name(item_def_id) {
2631 err.span_label(ident.span, "");
2633 if span != DUMMY_SP {
2634 err.span_label(span, &msg);
2639 ObligationCauseCode::ObjectCastObligation(object_ty) => {
2641 "required for the cast to the object type `{}`",
2642 self.ty_to_string(object_ty)
2645 ObligationCauseCode::Coercion { source: _, target } => {
2646 err.note(&format!("required by cast to type `{}`", self.ty_to_string(target)));
2648 ObligationCauseCode::RepeatVec(suggest_const_in_array_repeat_expressions) => {
2650 "the `Copy` trait is required because the \
2651 repeated element will be copied",
2653 if suggest_const_in_array_repeat_expressions {
2655 "this array initializer can be evaluated at compile-time, for more \
2656 information, see issue \
2657 https://github.com/rust-lang/rust/issues/49147",
2659 if tcx.sess.opts.unstable_features.is_nightly_build() {
2661 "add `#![feature(const_in_array_repeat_expressions)]` to the \
2662 crate attributes to enable",
2667 ObligationCauseCode::VariableType(_) => {
2668 err.note("all local variables must have a statically known size");
2669 if !self.tcx.features().unsized_locals {
2670 err.help("unsized locals are gated as an unstable feature");
2673 ObligationCauseCode::SizedArgumentType => {
2674 err.note("all function arguments must have a statically known size");
2675 if !self.tcx.features().unsized_locals {
2676 err.help("unsized locals are gated as an unstable feature");
2679 ObligationCauseCode::SizedReturnType => {
2681 "the return type of a function must have a \
2682 statically known size",
2685 ObligationCauseCode::SizedYieldType => {
2687 "the yield type of a generator must have a \
2688 statically known size",
2691 ObligationCauseCode::AssignmentLhsSized => {
2692 err.note("the left-hand-side of an assignment must have a statically known size");
2694 ObligationCauseCode::TupleInitializerSized => {
2695 err.note("tuples must have a statically known size to be initialized");
2697 ObligationCauseCode::StructInitializerSized => {
2698 err.note("structs must have a statically known size to be initialized");
2700 ObligationCauseCode::FieldSized { adt_kind: ref item, last } => match *item {
2701 AdtKind::Struct => {
2704 "the last field of a packed struct may only have a \
2705 dynamically sized type if it does not need drop to be run",
2709 "only the last field of a struct may have a dynamically \
2715 err.note("no field of a union may have a dynamically sized type");
2718 err.note("no field of an enum variant may have a dynamically sized type");
2721 ObligationCauseCode::ConstSized => {
2722 err.note("constant expressions must have a statically known size");
2724 ObligationCauseCode::ConstPatternStructural => {
2725 err.note("constants used for pattern-matching must derive `PartialEq` and `Eq`");
2727 ObligationCauseCode::SharedStatic => {
2728 err.note("shared static variables must have a type that implements `Sync`");
2730 ObligationCauseCode::BuiltinDerivedObligation(ref data) => {
2731 let parent_trait_ref = self.resolve_vars_if_possible(&data.parent_trait_ref);
2732 let ty = parent_trait_ref.skip_binder().self_ty();
2733 err.note(&format!("required because it appears within the type `{}`", ty));
2734 obligated_types.push(ty);
2736 let parent_predicate = parent_trait_ref.to_predicate();
2737 if !self.is_recursive_obligation(obligated_types, &data.parent_code) {
2738 self.note_obligation_cause_code(
2746 ObligationCauseCode::ImplDerivedObligation(ref data) => {
2747 let parent_trait_ref = self.resolve_vars_if_possible(&data.parent_trait_ref);
2749 "required because of the requirements on the impl of `{}` for `{}`",
2750 parent_trait_ref.print_only_trait_path(),
2751 parent_trait_ref.skip_binder().self_ty()
2753 let parent_predicate = parent_trait_ref.to_predicate();
2754 self.note_obligation_cause_code(
2761 ObligationCauseCode::CompareImplMethodObligation { .. } => {
2763 "the requirement `{}` appears on the impl method \
2764 but not on the corresponding trait method",
2768 ObligationCauseCode::CompareImplTypeObligation { .. } => {
2770 "the requirement `{}` appears on the associated impl type\
2771 but not on the corresponding associated trait type",
2775 ObligationCauseCode::ReturnType
2776 | ObligationCauseCode::ReturnValue(_)
2777 | ObligationCauseCode::BlockTailExpression(_) => (),
2778 ObligationCauseCode::TrivialBound => {
2779 err.help("see issue #48214");
2780 if tcx.sess.opts.unstable_features.is_nightly_build() {
2782 "add `#![feature(trivial_bounds)]` to the \
2783 crate attributes to enable",
2787 ObligationCauseCode::AssocTypeBound(ref data) => {
2788 err.span_label(data.original, "associated type defined here");
2789 if let Some(sp) = data.impl_span {
2790 err.span_label(sp, "in this `impl` item");
2792 for sp in &data.bounds {
2793 err.span_label(*sp, "restricted in this bound");
2799 fn suggest_new_overflow_limit(&self, err: &mut DiagnosticBuilder<'_>) {
2800 let current_limit = self.tcx.sess.recursion_limit.get();
2801 let suggested_limit = current_limit * 2;
2803 "consider adding a `#![recursion_limit=\"{}\"]` attribute to your crate",
2808 fn is_recursive_obligation(
2810 obligated_types: &mut Vec<&ty::TyS<'tcx>>,
2811 cause_code: &ObligationCauseCode<'tcx>,
2813 if let ObligationCauseCode::BuiltinDerivedObligation(ref data) = cause_code {
2814 let parent_trait_ref = self.resolve_vars_if_possible(&data.parent_trait_ref);
2816 if obligated_types.iter().any(|ot| ot == &parent_trait_ref.skip_binder().self_ty()) {
2824 /// Summarizes information
2827 /// An argument of non-tuple type. Parameters are (name, ty)
2828 Arg(String, String),
2830 /// An argument of tuple type. For a "found" argument, the span is
2831 /// the locationo in the source of the pattern. For a "expected"
2832 /// argument, it will be None. The vector is a list of (name, ty)
2833 /// strings for the components of the tuple.
2834 Tuple(Option<Span>, Vec<(String, String)>),
2838 fn empty() -> ArgKind {
2839 ArgKind::Arg("_".to_owned(), "_".to_owned())
2842 /// Creates an `ArgKind` from the expected type of an
2843 /// argument. It has no name (`_`) and an optional source span.
2844 pub fn from_expected_ty(t: Ty<'_>, span: Option<Span>) -> ArgKind {
2846 ty::Tuple(ref tys) => ArgKind::Tuple(
2848 tys.iter().map(|ty| ("_".to_owned(), ty.to_string())).collect::<Vec<_>>(),
2850 _ => ArgKind::Arg("_".to_owned(), t.to_string()),
2855 /// Suggest restricting a type param with a new bound.
2856 pub fn suggest_constraining_type_param(
2857 generics: &hir::Generics<'_>,
2858 err: &mut DiagnosticBuilder<'_>,
2861 source_map: &SourceMap,
2864 let restrict_msg = "consider further restricting this bound";
2865 if let Some(param) =
2866 generics.params.iter().filter(|p| p.name.ident().as_str() == param_name).next()
2868 if param_name.starts_with("impl ") {
2869 // `impl Trait` in argument:
2870 // `fn foo(x: impl Trait) {}` → `fn foo(t: impl Trait + Trait2) {}`
2871 err.span_suggestion(
2874 // `impl CurrentTrait + MissingTrait`
2875 format!("{} + {}", param_name, constraint),
2876 Applicability::MachineApplicable,
2878 } else if generics.where_clause.predicates.is_empty() && param.bounds.is_empty() {
2879 // If there are no bounds whatsoever, suggest adding a constraint
2880 // to the type parameter:
2881 // `fn foo<T>(t: T) {}` → `fn foo<T: Trait>(t: T) {}`
2882 err.span_suggestion(
2884 "consider restricting this bound",
2885 format!("{}: {}", param_name, constraint),
2886 Applicability::MachineApplicable,
2888 } else if !generics.where_clause.predicates.is_empty() {
2889 // There is a `where` clause, so suggest expanding it:
2890 // `fn foo<T>(t: T) where T: Debug {}` →
2891 // `fn foo<T>(t: T) where T: Debug, T: Trait {}`
2892 err.span_suggestion(
2893 generics.where_clause.span().unwrap().shrink_to_hi(),
2894 &format!("consider further restricting type parameter `{}`", param_name),
2895 format!(", {}: {}", param_name, constraint),
2896 Applicability::MachineApplicable,
2899 // If there is no `where` clause lean towards constraining to the
2901 // `fn foo<X: Bar, T>(t: T, x: X) {}` → `fn foo<T: Trait>(t: T) {}`
2902 // `fn foo<T: Bar>(t: T) {}` → `fn foo<T: Bar + Trait>(t: T) {}`
2903 let sp = param.span.with_hi(span.hi());
2904 let span = source_map.span_through_char(sp, ':');
2905 if sp != param.span && sp != span {
2906 // Only suggest if we have high certainty that the span
2907 // covers the colon in `foo<T: Trait>`.
2908 err.span_suggestion(
2911 format!("{}: {} + ", param_name, constraint),
2912 Applicability::MachineApplicable,
2917 &format!("consider adding a `where {}: {}` bound", param_name, constraint),