6 MismatchedProjectionTypes,
11 OnUnimplementedDirective,
13 OutputTypeParameterMismatch,
23 use crate::hir::def_id::DefId;
24 use crate::infer::{self, InferCtxt};
25 use crate::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
26 use crate::session::DiagnosticMessageId;
27 use crate::ty::{self, AdtKind, DefIdTree, ToPredicate, ToPolyTraitRef, Ty, TyCtxt, TypeFoldable};
28 use crate::ty::GenericParamDefKind;
29 use crate::ty::error::ExpectedFound;
30 use crate::ty::fast_reject;
31 use crate::ty::fold::TypeFolder;
32 use crate::ty::subst::Subst;
33 use crate::ty::SubtypePredicate;
34 use crate::util::nodemap::{FxHashMap, FxHashSet};
36 use errors::{Applicability, DiagnosticBuilder, pluralize, Style};
39 use syntax::symbol::{sym, kw};
40 use syntax_pos::{DUMMY_SP, Span, ExpnKind, MultiSpan};
41 use rustc::hir::def_id::LOCAL_CRATE;
42 use syntax_pos::source_map::SourceMap;
44 use rustc_error_codes::*;
46 impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
47 pub fn report_fulfillment_errors(
49 errors: &[FulfillmentError<'tcx>],
50 body_id: Option<hir::BodyId>,
51 fallback_has_occurred: bool,
54 struct ErrorDescriptor<'tcx> {
55 predicate: ty::Predicate<'tcx>,
56 index: Option<usize>, // None if this is an old error
59 let mut error_map: FxHashMap<_, Vec<_>> =
60 self.reported_trait_errors.borrow().iter().map(|(&span, predicates)| {
61 (span, predicates.iter().map(|predicate| ErrorDescriptor {
62 predicate: predicate.clone(),
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(
78 predicate: error.obligation.predicate.clone(),
83 self.reported_trait_errors.borrow_mut()
84 .entry(span).or_default()
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.
130 cond: &ty::Predicate<'tcx>,
131 error: &ty::Predicate<'tcx>,
137 let (cond, error) = match (cond, error) {
138 (&ty::Predicate::Trait(..), &ty::Predicate::Trait(ref error))
141 // FIXME: make this work in other cases too.
146 for implication in super::elaborate_predicates(self.tcx, vec![cond.clone()]) {
147 if let ty::Predicate::Trait(implication) = implication {
148 let error = error.to_poly_trait_ref();
149 let implication = implication.to_poly_trait_ref();
150 // FIXME: I'm just not taking associated types at all here.
151 // Eventually I'll need to implement param-env-aware
152 // `Γ₁ ⊦ φ₁ => Γ₂ ⊦ φ₂` logic.
153 let param_env = ty::ParamEnv::empty();
154 if self.can_sub(param_env, error, implication).is_ok() {
155 debug!("error_implies: {:?} -> {:?} -> {:?}", cond, error, implication);
164 fn report_fulfillment_error(
166 error: &FulfillmentError<'tcx>,
167 body_id: Option<hir::BodyId>,
168 fallback_has_occurred: bool,
170 debug!("report_fulfillment_error({:?})", error);
172 FulfillmentErrorCode::CodeSelectionError(ref selection_error) => {
173 self.report_selection_error(
176 fallback_has_occurred,
177 error.points_at_arg_span,
180 FulfillmentErrorCode::CodeProjectionError(ref e) => {
181 self.report_projection_error(&error.obligation, e);
183 FulfillmentErrorCode::CodeAmbiguity => {
184 self.maybe_report_ambiguity(&error.obligation, body_id);
186 FulfillmentErrorCode::CodeSubtypeError(ref expected_found, ref err) => {
187 self.report_mismatched_types(
188 &error.obligation.cause,
189 expected_found.expected,
190 expected_found.found,
197 fn report_projection_error(
199 obligation: &PredicateObligation<'tcx>,
200 error: &MismatchedProjectionTypes<'tcx>,
202 let predicate = self.resolve_vars_if_possible(&obligation.predicate);
204 if predicate.references_error() {
210 let mut err = &error.err;
211 let mut values = None;
213 // try to find the mismatched types to report the error with.
215 // this can fail if the problem was higher-ranked, in which
216 // cause I have no idea for a good error message.
217 if let ty::Predicate::Projection(ref data) = predicate {
218 let mut selcx = SelectionContext::new(self);
219 let (data, _) = self.replace_bound_vars_with_fresh_vars(
220 obligation.cause.span,
221 infer::LateBoundRegionConversionTime::HigherRankedType,
224 let mut obligations = vec![];
225 let normalized_ty = super::normalize_projection_type(
227 obligation.param_env,
229 obligation.cause.clone(),
234 debug!("report_projection_error obligation.cause={:?} obligation.param_env={:?}",
235 obligation.cause, obligation.param_env);
237 debug!("report_projection_error normalized_ty={:?} data.ty={:?}",
238 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)
248 .eq_exp(is_normalized_ty_expected, normalized_ty, data.ty)
250 values = Some(infer::ValuePairs::Types(
251 ExpectedFound::new(is_normalized_ty_expected, normalized_ty, data.ty)));
258 let msg = format!("type mismatch resolving `{}`", predicate);
260 DiagnosticMessageId::ErrorId(271),
261 Some(obligation.cause.span),
264 let fresh = self.tcx.sess.one_time_diagnostics.borrow_mut().insert(error_id);
266 let mut diag = struct_span_err!(
268 obligation.cause.span,
270 "type mismatch resolving `{}`",
273 self.note_type_err(&mut diag, &obligation.cause, None, values, err);
274 self.note_obligation_cause(&mut diag, obligation);
280 fn fuzzy_match_tys(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
281 /// returns the fuzzy category of a given type, or None
282 /// if the type can be equated to any type.
283 fn type_category(t: Ty<'_>) -> Option<u32> {
288 ty::Int(..) | ty::Uint(..) | ty::Infer(ty::IntVar(..)) => Some(3),
289 ty::Float(..) | ty::Infer(ty::FloatVar(..)) => Some(4),
290 ty::Ref(..) | ty::RawPtr(..) => Some(5),
291 ty::Array(..) | ty::Slice(..) => Some(6),
292 ty::FnDef(..) | ty::FnPtr(..) => Some(7),
293 ty::Dynamic(..) => Some(8),
294 ty::Closure(..) => Some(9),
295 ty::Tuple(..) => Some(10),
296 ty::Projection(..) => Some(11),
297 ty::Param(..) => Some(12),
298 ty::Opaque(..) => Some(13),
299 ty::Never => Some(14),
300 ty::Adt(adt, ..) => match adt.adt_kind() {
301 AdtKind::Struct => Some(15),
302 AdtKind::Union => Some(16),
303 AdtKind::Enum => Some(17),
305 ty::Generator(..) => Some(18),
306 ty::Foreign(..) => Some(19),
307 ty::GeneratorWitness(..) => Some(20),
308 ty::Placeholder(..) | ty::Bound(..) | ty::Infer(..) | ty::Error => None,
309 ty::UnnormalizedProjection(..) => bug!("only used with chalk-engine"),
313 match (type_category(a), type_category(b)) {
314 (Some(cat_a), Some(cat_b)) => match (&a.kind, &b.kind) {
315 (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) => def_a == def_b,
318 // infer and error can be equated to all types
323 fn impl_similar_to(&self,
324 trait_ref: ty::PolyTraitRef<'tcx>,
325 obligation: &PredicateObligation<'tcx>)
329 let param_env = obligation.param_env;
330 let trait_ref = tcx.erase_late_bound_regions(&trait_ref);
331 let trait_self_ty = trait_ref.self_ty();
333 let mut self_match_impls = vec![];
334 let mut fuzzy_match_impls = vec![];
336 self.tcx.for_each_relevant_impl(
337 trait_ref.def_id, trait_self_ty, |def_id| {
338 let impl_substs = self.fresh_substs_for_item(obligation.cause.span, def_id);
339 let impl_trait_ref = tcx
340 .impl_trait_ref(def_id)
342 .subst(tcx, impl_substs);
344 let impl_self_ty = impl_trait_ref.self_ty();
346 if let Ok(..) = self.can_eq(param_env, trait_self_ty, impl_self_ty) {
347 self_match_impls.push(def_id);
349 if trait_ref.substs.types().skip(1)
350 .zip(impl_trait_ref.substs.types().skip(1))
351 .all(|(u,v)| self.fuzzy_match_tys(u, v))
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 if tcx.has_attr(impl_def_id, sym::rustc_on_unimplemented) {
373 fn describe_generator(&self, body_id: hir::BodyId) -> Option<&'static str> {
374 self.tcx.hir().body(body_id).generator_kind.map(|gen_kind| {
376 hir::GeneratorKind::Gen => "a generator",
377 hir::GeneratorKind::Async(hir::AsyncGeneratorKind::Block) => "an async block",
378 hir::GeneratorKind::Async(hir::AsyncGeneratorKind::Fn) => "an async function",
379 hir::GeneratorKind::Async(hir::AsyncGeneratorKind::Closure) => "an async closure",
384 /// Used to set on_unimplemented's `ItemContext`
385 /// to be the enclosing (async) block/function/closure
386 fn describe_enclosure(&self, hir_id: hir::HirId) -> Option<&'static str> {
387 let hir = &self.tcx.hir();
388 let node = hir.find(hir_id)?;
389 if let hir::Node::Item(
390 hir::Item{kind: hir::ItemKind::Fn(sig, _, body_id), .. }) = &node {
391 self.describe_generator(*body_id).or_else(||
392 Some(if let hir::FnHeader{ asyncness: hir::IsAsync::Async, .. } = sig.header {
398 } else if let hir::Node::Expr(hir::Expr {
399 kind: hir::ExprKind::Closure(_is_move, _, body_id, _, gen_movability), .. }) = &node {
400 self.describe_generator(*body_id).or_else(||
401 Some(if gen_movability.is_some() {
407 } else if let hir::Node::Expr(hir::Expr { .. }) = &node {
408 let parent_hid = hir.get_parent_node(hir_id);
409 if parent_hid != hir_id {
410 return self.describe_enclosure(parent_hid);
419 fn on_unimplemented_note(
421 trait_ref: ty::PolyTraitRef<'tcx>,
422 obligation: &PredicateObligation<'tcx>,
423 ) -> OnUnimplementedNote {
424 let def_id = self.impl_similar_to(trait_ref, obligation)
425 .unwrap_or_else(|| trait_ref.def_id());
426 let trait_ref = *trait_ref.skip_binder();
428 let mut flags = vec![];
429 flags.push((sym::item_context,
430 self.describe_enclosure(obligation.cause.body_id).map(|s|s.to_owned())));
432 match obligation.cause.code {
433 ObligationCauseCode::BuiltinDerivedObligation(..) |
434 ObligationCauseCode::ImplDerivedObligation(..) => {}
436 // this is a "direct", user-specified, rather than derived,
438 flags.push((sym::direct, None));
442 if let ObligationCauseCode::ItemObligation(item) = obligation.cause.code {
443 // FIXME: maybe also have some way of handling methods
444 // from other traits? That would require name resolution,
445 // which we might want to be some sort of hygienic.
447 // Currently I'm leaving it for what I need for `try`.
448 if self.tcx.trait_of_item(item) == Some(trait_ref.def_id) {
449 let method = self.tcx.item_name(item);
450 flags.push((sym::from_method, None));
451 flags.push((sym::from_method, Some(method.to_string())));
454 if let Some(t) = self.get_parent_trait_ref(&obligation.cause.code) {
455 flags.push((sym::parent_trait, Some(t)));
458 if let Some(k) = obligation.cause.span.desugaring_kind() {
459 flags.push((sym::from_desugaring, None));
460 flags.push((sym::from_desugaring, Some(format!("{:?}", k))));
462 let generics = self.tcx.generics_of(def_id);
463 let self_ty = trait_ref.self_ty();
464 // This is also included through the generics list as `Self`,
465 // but the parser won't allow you to use it
466 flags.push((sym::_Self, Some(self_ty.to_string())));
467 if let Some(def) = self_ty.ty_adt_def() {
468 // We also want to be able to select self's original
469 // signature with no type arguments resolved
470 flags.push((sym::_Self, Some(self.tcx.type_of(def.did).to_string())));
473 for param in generics.params.iter() {
474 let value = match param.kind {
475 GenericParamDefKind::Type { .. } |
476 GenericParamDefKind::Const => {
477 trait_ref.substs[param.index as usize].to_string()
479 GenericParamDefKind::Lifetime => continue,
481 let name = param.name;
482 flags.push((name, Some(value)));
485 if let Some(true) = self_ty.ty_adt_def().map(|def| def.did.is_local()) {
486 flags.push((sym::crate_local, None));
489 // Allow targeting all integers using `{integral}`, even if the exact type was resolved
490 if self_ty.is_integral() {
491 flags.push((sym::_Self, Some("{integral}".to_owned())));
494 if let ty::Array(aty, len) = self_ty.kind {
495 flags.push((sym::_Self, Some("[]".to_owned())));
496 flags.push((sym::_Self, Some(format!("[{}]", aty))));
497 if let Some(def) = aty.ty_adt_def() {
498 // We also want to be able to select the array's type's original
499 // signature with no type arguments resolved
502 Some(format!("[{}]", self.tcx.type_of(def.did).to_string())),
505 if let Some(len) = len.try_eval_usize(tcx, ty::ParamEnv::empty()) {
508 Some(format!("[{}; {}]", self.tcx.type_of(def.did).to_string(), len)),
513 Some(format!("[{}; _]", self.tcx.type_of(def.did).to_string())),
519 if let Ok(Some(command)) = OnUnimplementedDirective::of_item(
520 self.tcx, trait_ref.def_id, def_id
522 command.evaluate(self.tcx, trait_ref, &flags[..])
524 OnUnimplementedNote::default()
528 fn find_similar_impl_candidates(
530 trait_ref: ty::PolyTraitRef<'tcx>,
531 ) -> Vec<ty::TraitRef<'tcx>> {
532 let simp = fast_reject::simplify_type(self.tcx, trait_ref.skip_binder().self_ty(), true);
533 let all_impls = self.tcx.all_impls(trait_ref.def_id());
536 Some(simp) => all_impls.iter().filter_map(|&def_id| {
537 let imp = self.tcx.impl_trait_ref(def_id).unwrap();
538 let imp_simp = fast_reject::simplify_type(self.tcx, imp.self_ty(), true);
539 if let Some(imp_simp) = imp_simp {
540 if simp != imp_simp {
547 None => all_impls.iter().map(|&def_id|
548 self.tcx.impl_trait_ref(def_id).unwrap()
553 fn report_similar_impl_candidates(
555 impl_candidates: Vec<ty::TraitRef<'tcx>>,
556 err: &mut DiagnosticBuilder<'_>,
558 if impl_candidates.is_empty() {
562 let len = impl_candidates.len();
563 let end = if impl_candidates.len() <= 5 {
564 impl_candidates.len()
569 let normalize = |candidate| self.tcx.infer_ctxt().enter(|ref infcx| {
570 let normalized = infcx
571 .at(&ObligationCause::dummy(), ty::ParamEnv::empty())
572 .normalize(candidate)
575 Some(normalized) => format!("\n {:?}", normalized.value),
576 None => format!("\n {:?}", candidate),
580 // Sort impl candidates so that ordering is consistent for UI tests.
581 let mut normalized_impl_candidates = impl_candidates
584 .collect::<Vec<String>>();
586 // Sort before taking the `..end` range,
587 // because the ordering of `impl_candidates` may not be deterministic:
588 // https://github.com/rust-lang/rust/pull/57475#issuecomment-455519507
589 normalized_impl_candidates.sort();
591 err.help(&format!("the following implementations were found:{}{}",
592 normalized_impl_candidates[..end].join(""),
594 format!("\nand {} others", len - 4)
601 /// Reports that an overflow has occurred and halts compilation. We
602 /// halt compilation unconditionally because it is important that
603 /// overflows never be masked -- they basically represent computations
604 /// whose result could not be truly determined and thus we can't say
605 /// if the program type checks or not -- and they are unusual
606 /// occurrences in any case.
607 pub fn report_overflow_error<T>(
609 obligation: &Obligation<'tcx, T>,
610 suggest_increasing_limit: bool,
612 where T: fmt::Display + TypeFoldable<'tcx>
615 self.resolve_vars_if_possible(&obligation.predicate);
616 let mut err = struct_span_err!(
618 obligation.cause.span,
620 "overflow evaluating the requirement `{}`",
624 if suggest_increasing_limit {
625 self.suggest_new_overflow_limit(&mut err);
628 self.note_obligation_cause_code(
630 &obligation.predicate,
631 &obligation.cause.code,
636 self.tcx.sess.abort_if_errors();
640 /// Reports that a cycle was detected which led to overflow and halts
641 /// compilation. This is equivalent to `report_overflow_error` except
642 /// that we can give a more helpful error message (and, in particular,
643 /// we do not suggest increasing the overflow limit, which is not
645 pub fn report_overflow_error_cycle(&self, cycle: &[PredicateObligation<'tcx>]) -> ! {
646 let cycle = self.resolve_vars_if_possible(&cycle.to_owned());
647 assert!(cycle.len() > 0);
649 debug!("report_overflow_error_cycle: cycle={:?}", cycle);
651 self.report_overflow_error(&cycle[0], false);
654 pub fn report_extra_impl_obligation(&self,
656 item_name: ast::Name,
657 _impl_item_def_id: DefId,
658 trait_item_def_id: DefId,
659 requirement: &dyn fmt::Display)
660 -> DiagnosticBuilder<'tcx>
662 let msg = "impl has stricter requirements than trait";
663 let sp = self.tcx.sess.source_map().def_span(error_span);
665 let mut err = struct_span_err!(self.tcx.sess, sp, E0276, "{}", msg);
667 if let Some(trait_item_span) = self.tcx.hir().span_if_local(trait_item_def_id) {
668 let span = self.tcx.sess.source_map().def_span(trait_item_span);
669 err.span_label(span, format!("definition of `{}` from trait", item_name));
672 err.span_label(sp, format!("impl has extra requirement {}", requirement));
678 /// Gets the parent trait chain start
679 fn get_parent_trait_ref(&self, code: &ObligationCauseCode<'tcx>) -> Option<String> {
681 &ObligationCauseCode::BuiltinDerivedObligation(ref data) => {
682 let parent_trait_ref = self.resolve_vars_if_possible(
683 &data.parent_trait_ref);
684 match self.get_parent_trait_ref(&data.parent_code) {
686 None => Some(parent_trait_ref.skip_binder().self_ty().to_string()),
693 pub fn report_selection_error(
695 obligation: &PredicateObligation<'tcx>,
696 error: &SelectionError<'tcx>,
697 fallback_has_occurred: bool,
701 let span = obligation.cause.span;
703 let mut err = match *error {
704 SelectionError::Unimplemented => {
705 if let ObligationCauseCode::CompareImplMethodObligation {
706 item_name, impl_item_def_id, trait_item_def_id,
707 } = obligation.cause.code {
708 self.report_extra_impl_obligation(
713 &format!("`{}`", obligation.predicate))
717 match obligation.predicate {
718 ty::Predicate::Trait(ref trait_predicate) => {
719 let trait_predicate = self.resolve_vars_if_possible(trait_predicate);
721 if self.tcx.sess.has_errors() && trait_predicate.references_error() {
724 let trait_ref = trait_predicate.to_poly_trait_ref();
728 ) = self.get_parent_trait_ref(&obligation.cause.code)
729 .map(|t| (format!(" in `{}`", t), format!("within `{}`, ", t)))
730 .unwrap_or_default();
732 let OnUnimplementedNote {
737 } = self.on_unimplemented_note(trait_ref, obligation);
738 let have_alt_message = message.is_some() || label.is_some();
739 let is_try = self.tcx.sess.source_map().span_to_snippet(span)
743 format!("{}", trait_ref.print_only_trait_path())
744 .starts_with("std::convert::From<");
745 let (message, note) = if is_try && is_from {
747 "`?` couldn't convert the error to `{}`",
750 "the question mark operation (`?`) implicitly performs a \
751 conversion on the error value using the `From` trait".to_owned()
757 let mut err = struct_span_err!(
762 message.unwrap_or_else(|| format!(
763 "the trait bound `{}` is not satisfied{}",
764 trait_ref.to_predicate(),
769 if obligation.cause.code == ObligationCauseCode::MainFunctionType {
770 "consider using `()`, or a `Result`".to_owned()
773 "{}the trait `{}` is not implemented for `{}`",
775 trait_ref.print_only_trait_path(),
780 if self.suggest_add_reference_to_arg(
787 self.note_obligation_cause(&mut err, obligation);
791 if let Some(ref s) = label {
792 // If it has a custom `#[rustc_on_unimplemented]`
793 // error message, let's display it as the label!
794 err.span_label(span, s.as_str());
795 err.help(&explanation);
797 err.span_label(span, explanation);
799 if let Some(ref s) = note {
800 // If it has a custom `#[rustc_on_unimplemented]` note, let's display it
801 err.note(s.as_str());
803 if let Some(ref s) = enclosing_scope {
804 let enclosing_scope_span = tcx.def_span(
806 .opt_local_def_id(obligation.cause.body_id)
808 tcx.hir().body_owner_def_id(hir::BodyId {
809 hir_id: obligation.cause.body_id,
814 err.span_label(enclosing_scope_span, s.as_str());
817 self.suggest_borrow_on_unsized_slice(&obligation.cause.code, &mut err);
818 self.suggest_fn_call(&obligation, &mut err, &trait_ref, points_at_arg);
819 self.suggest_remove_reference(&obligation, &mut err, &trait_ref);
820 self.suggest_semicolon_removal(&obligation, &mut err, span, &trait_ref);
821 self.note_version_mismatch(&mut err, &trait_ref);
823 // Try to report a help message
824 if !trait_ref.has_infer_types() &&
825 self.predicate_can_apply(obligation.param_env, trait_ref) {
826 // If a where-clause may be useful, remind the
827 // user that they can add it.
829 // don't display an on-unimplemented note, as
830 // these notes will often be of the form
831 // "the type `T` can't be frobnicated"
832 // which is somewhat confusing.
833 self.suggest_restricting_param_bound(
836 obligation.cause.body_id,
839 if !have_alt_message {
840 // Can't show anything else useful, try to find similar impls.
841 let impl_candidates = self.find_similar_impl_candidates(trait_ref);
842 self.report_similar_impl_candidates(impl_candidates, &mut err);
844 self.suggest_change_mut(
852 // If this error is due to `!: Trait` not implemented but `(): Trait` is
853 // implemented, and fallback has occurred, then it could be due to a
854 // variable that used to fallback to `()` now falling back to `!`. Issue a
855 // note informing about the change in behaviour.
856 if trait_predicate.skip_binder().self_ty().is_never()
857 && fallback_has_occurred
859 let predicate = trait_predicate.map_bound(|mut trait_pred| {
860 trait_pred.trait_ref.substs = self.tcx.mk_substs_trait(
862 &trait_pred.trait_ref.substs[1..],
866 let unit_obligation = Obligation {
867 predicate: ty::Predicate::Trait(predicate),
868 .. obligation.clone()
870 if self.predicate_may_hold(&unit_obligation) {
871 err.note("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.");
883 ty::Predicate::Subtype(ref predicate) => {
884 // Errors for Subtype predicates show up as
885 // `FulfillmentErrorCode::CodeSubtypeError`,
886 // not selection error.
887 span_bug!(span, "subtype requirement gave wrong error: `{:?}`", predicate)
890 ty::Predicate::RegionOutlives(ref predicate) => {
891 let predicate = self.resolve_vars_if_possible(predicate);
892 let err = self.region_outlives_predicate(&obligation.cause,
893 &predicate).err().unwrap();
895 self.tcx.sess, span, E0279,
896 "the requirement `{}` is not satisfied (`{}`)",
901 ty::Predicate::Projection(..) | ty::Predicate::TypeOutlives(..) => {
903 self.resolve_vars_if_possible(&obligation.predicate);
904 struct_span_err!(self.tcx.sess, span, E0280,
905 "the requirement `{}` is not satisfied",
909 ty::Predicate::ObjectSafe(trait_def_id) => {
910 let violations = self.tcx.object_safety_violations(trait_def_id);
911 self.tcx.report_object_safety_error(
918 ty::Predicate::ClosureKind(closure_def_id, closure_substs, kind) => {
919 let found_kind = self.closure_kind(closure_def_id, closure_substs).unwrap();
920 let closure_span = self.tcx.sess.source_map()
921 .def_span(self.tcx.hir().span_if_local(closure_def_id).unwrap());
922 let hir_id = self.tcx.hir().as_local_hir_id(closure_def_id).unwrap();
923 let mut err = struct_span_err!(
924 self.tcx.sess, closure_span, E0525,
925 "expected a closure that implements the `{}` trait, \
926 but this closure only implements `{}`",
932 format!("this closure implements `{}`, not `{}`", found_kind, kind));
934 obligation.cause.span,
935 format!("the requirement to implement `{}` derives from here", kind));
937 // Additional context information explaining why the closure only implements
938 // a particular trait.
939 if let Some(tables) = self.in_progress_tables {
940 let tables = tables.borrow();
941 match (found_kind, tables.closure_kind_origins().get(hir_id)) {
942 (ty::ClosureKind::FnOnce, Some((span, name))) => {
943 err.span_label(*span, format!(
944 "closure is `FnOnce` because it moves the \
945 variable `{}` out of its environment", name));
947 (ty::ClosureKind::FnMut, Some((span, name))) => {
948 err.span_label(*span, format!(
949 "closure is `FnMut` because it mutates the \
950 variable `{}` here", name));
960 ty::Predicate::WellFormed(ty) => {
961 if !self.tcx.sess.opts.debugging_opts.chalk {
962 // WF predicates cannot themselves make
963 // errors. They can only block due to
964 // ambiguity; otherwise, they always
965 // degenerate into other obligations
967 span_bug!(span, "WF predicate not satisfied for {:?}", ty);
969 // FIXME: we'll need a better message which takes into account
970 // which bounds actually failed to hold.
971 self.tcx.sess.struct_span_err(
973 &format!("the type `{}` is not well-formed (chalk)", ty)
978 ty::Predicate::ConstEvaluatable(..) => {
979 // Errors for `ConstEvaluatable` predicates show up as
980 // `SelectionError::ConstEvalFailure`,
981 // not `Unimplemented`.
983 "const-evaluatable requirement gave wrong error: `{:?}`", obligation)
988 OutputTypeParameterMismatch(ref found_trait_ref, ref expected_trait_ref, _) => {
989 let found_trait_ref = self.resolve_vars_if_possible(&*found_trait_ref);
990 let expected_trait_ref = self.resolve_vars_if_possible(&*expected_trait_ref);
992 if expected_trait_ref.self_ty().references_error() {
996 let found_trait_ty = found_trait_ref.self_ty();
998 let found_did = match found_trait_ty.kind {
999 ty::Closure(did, _) | ty::Foreign(did) | ty::FnDef(did, _) => Some(did),
1000 ty::Adt(def, _) => Some(def.did),
1004 let found_span = found_did.and_then(|did|
1005 self.tcx.hir().span_if_local(did)
1006 ).map(|sp| self.tcx.sess.source_map().def_span(sp)); // the sp could be an fn def
1008 if self.reported_closure_mismatch.borrow().contains(&(span, found_span)) {
1009 // We check closures twice, with obligations flowing in different directions,
1010 // but we want to complain about them only once.
1014 self.reported_closure_mismatch.borrow_mut().insert((span, found_span));
1016 let found = match found_trait_ref.skip_binder().substs.type_at(1).kind {
1017 ty::Tuple(ref tys) => vec![ArgKind::empty(); tys.len()],
1018 _ => vec![ArgKind::empty()],
1021 let expected_ty = expected_trait_ref.skip_binder().substs.type_at(1);
1022 let expected = match expected_ty.kind {
1023 ty::Tuple(ref tys) => tys.iter()
1024 .map(|t| ArgKind::from_expected_ty(t.expect_ty(), Some(span))).collect(),
1025 _ => vec![ArgKind::Arg("_".to_owned(), expected_ty.to_string())],
1028 if found.len() == expected.len() {
1029 self.report_closure_arg_mismatch(span,
1034 let (closure_span, found) = found_did
1035 .and_then(|did| self.tcx.hir().get_if_local(did))
1037 let (found_span, found) = self.get_fn_like_arguments(node);
1038 (Some(found_span), found)
1039 }).unwrap_or((found_span, found));
1041 self.report_arg_count_mismatch(span,
1045 found_trait_ty.is_closure())
1049 TraitNotObjectSafe(did) => {
1050 let violations = self.tcx.object_safety_violations(did);
1051 self.tcx.report_object_safety_error(span, did, violations)
1054 // already reported in the query
1055 ConstEvalFailure(err) => {
1056 self.tcx.sess.delay_span_bug(
1058 &format!("constant in type had an ignored error: {:?}", err),
1064 bug!("overflow should be handled before the `report_selection_error` path");
1068 self.note_obligation_cause(&mut err, obligation);
1073 /// If the `Self` type of the unsatisfied trait `trait_ref` implements a trait
1074 /// with the same path as `trait_ref`, a help message about
1075 /// a probable version mismatch is added to `err`
1076 fn note_version_mismatch(
1078 err: &mut DiagnosticBuilder<'_>,
1079 trait_ref: &ty::PolyTraitRef<'tcx>,
1081 let get_trait_impl = |trait_def_id| {
1082 let mut trait_impl = None;
1083 self.tcx.for_each_relevant_impl(trait_def_id, trait_ref.self_ty(), |impl_def_id| {
1084 if trait_impl.is_none() {
1085 trait_impl = Some(impl_def_id);
1090 let required_trait_path = self.tcx.def_path_str(trait_ref.def_id());
1091 let all_traits = self.tcx.all_traits(LOCAL_CRATE);
1092 let traits_with_same_path: std::collections::BTreeSet<_> = all_traits
1094 .filter(|trait_def_id| **trait_def_id != trait_ref.def_id())
1095 .filter(|trait_def_id| self.tcx.def_path_str(**trait_def_id) == required_trait_path)
1097 for trait_with_same_path in traits_with_same_path {
1098 if let Some(impl_def_id) = get_trait_impl(*trait_with_same_path) {
1099 let impl_span = self.tcx.def_span(impl_def_id);
1100 err.span_help(impl_span, "trait impl with same name found");
1101 let trait_crate = self.tcx.crate_name(trait_with_same_path.krate);
1102 let crate_msg = format!(
1103 "Perhaps two different versions of crate `{}` are being used?",
1106 err.note(&crate_msg);
1110 fn suggest_restricting_param_bound(
1112 mut err: &mut DiagnosticBuilder<'_>,
1113 trait_ref: &ty::PolyTraitRef<'_>,
1114 body_id: hir::HirId,
1116 let self_ty = trait_ref.self_ty();
1117 let (param_ty, projection) = match &self_ty.kind {
1118 ty::Param(_) => (true, None),
1119 ty::Projection(projection) => (false, Some(projection)),
1123 let suggest_restriction = |
1124 generics: &hir::Generics,
1126 err: &mut DiagnosticBuilder<'_>,
1128 let span = generics.where_clause.span_for_predicates_or_empty_place();
1129 if !span.from_expansion() && span.desugaring_kind().is_none() {
1130 err.span_suggestion(
1131 generics.where_clause.span_for_predicates_or_empty_place().shrink_to_hi(),
1132 &format!("consider further restricting {}", msg),
1135 if !generics.where_clause.predicates.is_empty() {
1140 trait_ref.to_predicate(),
1142 Applicability::MachineApplicable,
1147 // FIXME: Add check for trait bound that is already present, particularly `?Sized` so we
1148 // don't suggest `T: Sized + ?Sized`.
1149 let mut hir_id = body_id;
1150 while let Some(node) = self.tcx.hir().find(hir_id) {
1152 hir::Node::TraitItem(hir::TraitItem {
1154 kind: hir::TraitItemKind::Method(..), ..
1155 }) if param_ty && self_ty == self.tcx.types.self_param => {
1156 // Restricting `Self` for a single method.
1157 suggest_restriction(&generics, "`Self`", err);
1161 hir::Node::Item(hir::Item {
1162 kind: hir::ItemKind::Fn(_, generics, _), ..
1164 hir::Node::TraitItem(hir::TraitItem {
1166 kind: hir::TraitItemKind::Method(..), ..
1168 hir::Node::ImplItem(hir::ImplItem {
1170 kind: hir::ImplItemKind::Method(..), ..
1172 hir::Node::Item(hir::Item {
1173 kind: hir::ItemKind::Trait(_, _, generics, _, _), ..
1175 hir::Node::Item(hir::Item {
1176 kind: hir::ItemKind::Impl(_, _, _, generics, ..), ..
1177 }) if projection.is_some() => {
1178 // Missing associated type bound.
1179 suggest_restriction(&generics, "the associated type", err);
1183 hir::Node::Item(hir::Item { kind: hir::ItemKind::Struct(_, generics), span, .. }) |
1184 hir::Node::Item(hir::Item { kind: hir::ItemKind::Enum(_, generics), span, .. }) |
1185 hir::Node::Item(hir::Item { kind: hir::ItemKind::Union(_, generics), span, .. }) |
1186 hir::Node::Item(hir::Item {
1187 kind: hir::ItemKind::Trait(_, _, generics, ..), span, ..
1189 hir::Node::Item(hir::Item {
1190 kind: hir::ItemKind::Impl(_, _, _, generics, ..), span, ..
1192 hir::Node::Item(hir::Item {
1193 kind: hir::ItemKind::Fn(_, generics, _), span, ..
1195 hir::Node::Item(hir::Item {
1196 kind: hir::ItemKind::TyAlias(_, generics), span, ..
1198 hir::Node::Item(hir::Item {
1199 kind: hir::ItemKind::TraitAlias(generics, _), span, ..
1201 hir::Node::Item(hir::Item {
1202 kind: hir::ItemKind::OpaqueTy(hir::OpaqueTy { generics, .. }), span, ..
1204 hir::Node::TraitItem(hir::TraitItem { generics, span, .. }) |
1205 hir::Node::ImplItem(hir::ImplItem { generics, span, .. })
1207 // Missing generic type parameter bound.
1208 let param_name = self_ty.to_string();
1209 let constraint = trait_ref.print_only_trait_path().to_string();
1210 if suggest_constraining_type_param(
1215 self.tcx.sess.source_map(),
1222 hir::Node::Crate => return,
1227 hir_id = self.tcx.hir().get_parent_item(hir_id);
1231 /// When encountering an assignment of an unsized trait, like `let x = ""[..];`, provide a
1232 /// suggestion to borrow the initializer in order to use have a slice instead.
1233 fn suggest_borrow_on_unsized_slice(
1235 code: &ObligationCauseCode<'tcx>,
1236 err: &mut DiagnosticBuilder<'tcx>,
1238 if let &ObligationCauseCode::VariableType(hir_id) = code {
1239 let parent_node = self.tcx.hir().get_parent_node(hir_id);
1240 if let Some(Node::Local(ref local)) = self.tcx.hir().find(parent_node) {
1241 if let Some(ref expr) = local.init {
1242 if let hir::ExprKind::Index(_, _) = expr.kind {
1243 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(expr.span) {
1244 err.span_suggestion(
1246 "consider borrowing here",
1247 format!("&{}", snippet),
1248 Applicability::MachineApplicable
1257 fn mk_obligation_for_def_id(
1260 output_ty: Ty<'tcx>,
1261 cause: ObligationCause<'tcx>,
1262 param_env: ty::ParamEnv<'tcx>,
1263 ) -> PredicateObligation<'tcx> {
1264 let new_trait_ref = ty::TraitRef {
1266 substs: self.tcx.mk_substs_trait(output_ty, &[]),
1268 Obligation::new(cause, param_env, new_trait_ref.to_predicate())
1271 /// Given a closure's `DefId`, return the given name of the closure.
1273 /// This doesn't account for reassignments, but it's only used for suggestions.
1274 fn get_closure_name(
1277 err: &mut DiagnosticBuilder<'_>,
1279 ) -> Option<String> {
1280 let get_name = |err: &mut DiagnosticBuilder<'_>, kind: &hir::PatKind| -> Option<String> {
1281 // Get the local name of this closure. This can be inaccurate because
1282 // of the possibility of reassignment, but this should be good enough.
1284 hir::PatKind::Binding(hir::BindingAnnotation::Unannotated, _, name, None) => {
1285 Some(format!("{}", name))
1294 let hir = self.tcx.hir();
1295 let hir_id = hir.as_local_hir_id(def_id)?;
1296 let parent_node = hir.get_parent_node(hir_id);
1297 match hir.find(parent_node) {
1298 Some(hir::Node::Stmt(hir::Stmt {
1299 kind: hir::StmtKind::Local(local), ..
1300 })) => get_name(err, &local.pat.kind),
1301 // Different to previous arm because one is `&hir::Local` and the other
1302 // is `P<hir::Local>`.
1303 Some(hir::Node::Local(local)) => get_name(err, &local.pat.kind),
1308 /// We tried to apply the bound to an `fn` or closure. Check whether calling it would
1309 /// evaluate to a type that *would* satisfy the trait binding. If it would, suggest calling
1310 /// it: `bar(foo)` → `bar(foo())`. This case is *very* likely to be hit if `foo` is `async`.
1313 obligation: &PredicateObligation<'tcx>,
1314 err: &mut DiagnosticBuilder<'_>,
1315 trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
1316 points_at_arg: bool,
1318 let self_ty = trait_ref.self_ty();
1319 let (def_id, output_ty, callable) = match self_ty.kind {
1320 ty::Closure(def_id, substs) => {
1321 (def_id, self.closure_sig(def_id, substs).output(), "closure")
1323 ty::FnDef(def_id, _) => {
1324 (def_id, self_ty.fn_sig(self.tcx).output(), "function")
1328 let msg = format!("use parentheses to call the {}", callable);
1330 let obligation = self.mk_obligation_for_def_id(
1332 output_ty.skip_binder(),
1333 obligation.cause.clone(),
1334 obligation.param_env,
1337 match self.evaluate_obligation(&obligation) {
1338 Ok(EvaluationResult::EvaluatedToOk) |
1339 Ok(EvaluationResult::EvaluatedToOkModuloRegions) |
1340 Ok(EvaluationResult::EvaluatedToAmbig) => {}
1343 let hir = self.tcx.hir();
1344 // Get the name of the callable and the arguments to be used in the suggestion.
1345 let snippet = match hir.get_if_local(def_id) {
1346 Some(hir::Node::Expr(hir::Expr {
1347 kind: hir::ExprKind::Closure(_, decl, _, span, ..),
1350 err.span_label(*span, "consider calling this closure");
1351 let name = match self.get_closure_name(def_id, err, &msg) {
1355 let args = decl.inputs.iter()
1357 .collect::<Vec<_>>()
1359 format!("{}({})", name, args)
1361 Some(hir::Node::Item(hir::Item {
1363 kind: hir::ItemKind::Fn(.., body_id),
1366 err.span_label(ident.span, "consider calling this function");
1367 let body = hir.body(*body_id);
1368 let args = body.params.iter()
1369 .map(|arg| match &arg.pat.kind {
1370 hir::PatKind::Binding(_, _, ident, None)
1371 // FIXME: provide a better suggestion when encountering `SelfLower`, it
1372 // should suggest a method call.
1373 if ident.name != kw::SelfLower => ident.to_string(),
1374 _ => "_".to_string(),
1376 .collect::<Vec<_>>()
1378 format!("{}({})", ident, args)
1383 // When the obligation error has been ensured to have been caused by
1384 // an argument, the `obligation.cause.span` points at the expression
1385 // of the argument, so we can provide a suggestion. This is signaled
1386 // by `points_at_arg`. Otherwise, we give a more general note.
1387 err.span_suggestion(
1388 obligation.cause.span,
1391 Applicability::HasPlaceholders,
1394 err.help(&format!("{}: `{}`", msg, snippet));
1398 fn suggest_add_reference_to_arg(
1400 obligation: &PredicateObligation<'tcx>,
1401 err: &mut DiagnosticBuilder<'tcx>,
1402 trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
1403 points_at_arg: bool,
1404 has_custom_message: bool,
1410 let span = obligation.cause.span;
1411 let param_env = obligation.param_env;
1412 let trait_ref = trait_ref.skip_binder();
1414 if let ObligationCauseCode::ImplDerivedObligation(obligation) = &obligation.cause.code {
1415 // Try to apply the original trait binding obligation by borrowing.
1416 let self_ty = trait_ref.self_ty();
1417 let found = self_ty.to_string();
1418 let new_self_ty = self.tcx.mk_imm_ref(self.tcx.lifetimes.re_static, self_ty);
1419 let substs = self.tcx.mk_substs_trait(new_self_ty, &[]);
1420 let new_trait_ref = ty::TraitRef::new(obligation.parent_trait_ref.def_id(), substs);
1421 let new_obligation = Obligation::new(
1422 ObligationCause::dummy(),
1424 new_trait_ref.to_predicate(),
1426 if self.predicate_must_hold_modulo_regions(&new_obligation) {
1427 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
1428 // We have a very specific type of error, where just borrowing this argument
1429 // might solve the problem. In cases like this, the important part is the
1430 // original type obligation, not the last one that failed, which is arbitrary.
1431 // Because of this, we modify the error to refer to the original obligation and
1432 // return early in the caller.
1434 "the trait bound `{}: {}` is not satisfied",
1436 obligation.parent_trait_ref.skip_binder().print_only_trait_path(),
1438 if has_custom_message {
1441 err.message = vec![(msg, Style::NoStyle)];
1443 if snippet.starts_with('&') {
1444 // This is already a literal borrow and the obligation is failing
1445 // somewhere else in the obligation chain. Do not suggest non-sense.
1448 err.span_label(span, &format!(
1449 "expected an implementor of trait `{}`",
1450 obligation.parent_trait_ref.skip_binder().print_only_trait_path(),
1452 err.span_suggestion(
1454 "consider borrowing here",
1455 format!("&{}", snippet),
1456 Applicability::MaybeIncorrect,
1465 /// Whenever references are used by mistake, like `for (i, e) in &vec.iter().enumerate()`,
1466 /// suggest removing these references until we reach a type that implements the trait.
1467 fn suggest_remove_reference(
1469 obligation: &PredicateObligation<'tcx>,
1470 err: &mut DiagnosticBuilder<'tcx>,
1471 trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
1473 let trait_ref = trait_ref.skip_binder();
1474 let span = obligation.cause.span;
1476 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
1477 let refs_number = snippet.chars()
1478 .filter(|c| !c.is_whitespace())
1479 .take_while(|c| *c == '&')
1481 if let Some('\'') = snippet.chars()
1482 .filter(|c| !c.is_whitespace())
1485 { // Do not suggest removal of borrow from type arguments.
1489 let mut trait_type = trait_ref.self_ty();
1491 for refs_remaining in 0..refs_number {
1492 if let ty::Ref(_, t_type, _) = trait_type.kind {
1493 trait_type = t_type;
1495 let new_obligation = self.mk_obligation_for_def_id(
1498 ObligationCause::dummy(),
1499 obligation.param_env,
1502 if self.predicate_may_hold(&new_obligation) {
1503 let sp = self.tcx.sess.source_map()
1504 .span_take_while(span, |c| c.is_whitespace() || *c == '&');
1506 let remove_refs = refs_remaining + 1;
1507 let format_str = format!("consider removing {} leading `&`-references",
1510 err.span_suggestion_short(
1511 sp, &format_str, String::new(), Applicability::MachineApplicable
1522 /// Check if the trait bound is implemented for a different mutability and note it in the
1524 fn suggest_change_mut(
1526 obligation: &PredicateObligation<'tcx>,
1527 err: &mut DiagnosticBuilder<'tcx>,
1528 trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
1529 points_at_arg: bool,
1531 let span = obligation.cause.span;
1532 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
1533 let refs_number = snippet.chars()
1534 .filter(|c| !c.is_whitespace())
1535 .take_while(|c| *c == '&')
1537 if let Some('\'') = snippet.chars()
1538 .filter(|c| !c.is_whitespace())
1541 { // Do not suggest removal of borrow from type arguments.
1544 let trait_ref = self.resolve_vars_if_possible(trait_ref);
1545 if trait_ref.has_infer_types() {
1546 // Do not ICE while trying to find if a reborrow would succeed on a trait with
1547 // unresolved bindings.
1551 if let ty::Ref(region, t_type, mutability) = trait_ref.skip_binder().self_ty().kind {
1552 let trait_type = match mutability {
1553 hir::Mutability::Mutable => self.tcx.mk_imm_ref(region, t_type),
1554 hir::Mutability::Immutable => self.tcx.mk_mut_ref(region, t_type),
1557 let new_obligation = self.mk_obligation_for_def_id(
1558 trait_ref.skip_binder().def_id,
1560 ObligationCause::dummy(),
1561 obligation.param_env,
1564 if self.evaluate_obligation_no_overflow(
1566 ).must_apply_modulo_regions() {
1567 let sp = self.tcx.sess.source_map()
1568 .span_take_while(span, |c| c.is_whitespace() || *c == '&');
1570 mutability == hir::Mutability::Immutable &&
1573 err.span_suggestion(
1575 "consider changing this borrow's mutability",
1576 "&mut ".to_string(),
1577 Applicability::MachineApplicable,
1581 "`{}` is implemented for `{:?}`, but not for `{:?}`",
1582 trait_ref.print_only_trait_path(),
1584 trait_ref.skip_binder().self_ty(),
1592 fn suggest_semicolon_removal(
1594 obligation: &PredicateObligation<'tcx>,
1595 err: &mut DiagnosticBuilder<'tcx>,
1597 trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
1599 let hir = self.tcx.hir();
1600 let parent_node = hir.get_parent_node(obligation.cause.body_id);
1601 let node = hir.find(parent_node);
1602 if let Some(hir::Node::Item(hir::Item {
1603 kind: hir::ItemKind::Fn(sig, _, body_id),
1606 let body = hir.body(*body_id);
1607 if let hir::ExprKind::Block(blk, _) = &body.value.kind {
1608 if sig.decl.output.span().overlaps(span) && blk.expr.is_none() &&
1609 "()" == &trait_ref.self_ty().to_string()
1611 // FIXME(estebank): When encountering a method with a trait
1612 // bound not satisfied in the return type with a body that has
1613 // no return, suggest removal of semicolon on last statement.
1614 // Once that is added, close #54771.
1615 if let Some(ref stmt) = blk.stmts.last() {
1616 let sp = self.tcx.sess.source_map().end_point(stmt.span);
1617 err.span_label(sp, "consider removing this semicolon");
1624 /// Given some node representing a fn-like thing in the HIR map,
1625 /// returns a span and `ArgKind` information that describes the
1626 /// arguments it expects. This can be supplied to
1627 /// `report_arg_count_mismatch`.
1628 pub fn get_fn_like_arguments(&self, node: Node<'_>) -> (Span, Vec<ArgKind>) {
1630 Node::Expr(&hir::Expr {
1631 kind: hir::ExprKind::Closure(_, ref _decl, id, span, _),
1634 (self.tcx.sess.source_map().def_span(span),
1635 self.tcx.hir().body(id).params.iter()
1638 kind: hir::PatKind::Tuple(ref args, _),
1644 args.iter().map(|pat| {
1645 let snippet = self.tcx.sess.source_map()
1646 .span_to_snippet(pat.span).unwrap();
1647 (snippet, "_".to_owned())
1648 }).collect::<Vec<_>>(),
1651 let name = self.tcx.sess.source_map()
1652 .span_to_snippet(arg.pat.span).unwrap();
1653 ArgKind::Arg(name, "_".to_owned())
1656 .collect::<Vec<ArgKind>>())
1658 Node::Item(&hir::Item {
1660 kind: hir::ItemKind::Fn(ref sig, ..),
1663 Node::ImplItem(&hir::ImplItem {
1665 kind: hir::ImplItemKind::Method(ref sig, _),
1668 Node::TraitItem(&hir::TraitItem {
1670 kind: hir::TraitItemKind::Method(ref sig, _),
1673 (self.tcx.sess.source_map().def_span(span), sig.decl.inputs.iter()
1674 .map(|arg| match arg.clone().kind {
1675 hir::TyKind::Tup(ref tys) => ArgKind::Tuple(
1677 vec![("_".to_owned(), "_".to_owned()); tys.len()]
1679 _ => ArgKind::empty()
1680 }).collect::<Vec<ArgKind>>())
1682 Node::Ctor(ref variant_data) => {
1683 let span = variant_data.ctor_hir_id()
1684 .map(|hir_id| self.tcx.hir().span(hir_id))
1685 .unwrap_or(DUMMY_SP);
1686 let span = self.tcx.sess.source_map().def_span(span);
1688 (span, vec![ArgKind::empty(); variant_data.fields().len()])
1690 _ => panic!("non-FnLike node found: {:?}", node),
1694 /// Reports an error when the number of arguments needed by a
1695 /// trait match doesn't match the number that the expression
1697 pub fn report_arg_count_mismatch(
1700 found_span: Option<Span>,
1701 expected_args: Vec<ArgKind>,
1702 found_args: Vec<ArgKind>,
1704 ) -> DiagnosticBuilder<'tcx> {
1705 let kind = if is_closure { "closure" } else { "function" };
1707 let args_str = |arguments: &[ArgKind], other: &[ArgKind]| {
1708 let arg_length = arguments.len();
1709 let distinct = match &other[..] {
1710 &[ArgKind::Tuple(..)] => true,
1713 match (arg_length, arguments.get(0)) {
1714 (1, Some(&ArgKind::Tuple(_, ref fields))) => {
1715 format!("a single {}-tuple as argument", fields.len())
1717 _ => format!("{} {}argument{}",
1719 if distinct && arg_length > 1 { "distinct " } else { "" },
1720 pluralize!(arg_length))
1724 let expected_str = args_str(&expected_args, &found_args);
1725 let found_str = args_str(&found_args, &expected_args);
1727 let mut err = struct_span_err!(
1731 "{} is expected to take {}, but it takes {}",
1737 err.span_label(span, format!("expected {} that takes {}", kind, expected_str));
1739 if let Some(found_span) = found_span {
1740 err.span_label(found_span, format!("takes {}", found_str));
1743 // ^^^^^^^^-- def_span
1747 let prefix_span = self.tcx.sess.source_map().span_until_non_whitespace(found_span);
1750 let pipe_span = if let Some(span) = found_span.trim_start(prefix_span) {
1756 // Suggest to take and ignore the arguments with expected_args_length `_`s if
1757 // found arguments is empty (assume the user just wants to ignore args in this case).
1758 // For example, if `expected_args_length` is 2, suggest `|_, _|`.
1759 if found_args.is_empty() && is_closure {
1760 let underscores = vec!["_"; expected_args.len()].join(", ");
1761 err.span_suggestion(
1764 "consider changing the closure to take and ignore the expected argument{}",
1765 if expected_args.len() < 2 {
1771 format!("|{}|", underscores),
1772 Applicability::MachineApplicable,
1776 if let &[ArgKind::Tuple(_, ref fields)] = &found_args[..] {
1777 if fields.len() == expected_args.len() {
1778 let sugg = fields.iter()
1779 .map(|(name, _)| name.to_owned())
1780 .collect::<Vec<String>>()
1782 err.span_suggestion(
1784 "change the closure to take multiple arguments instead of a single tuple",
1785 format!("|{}|", sugg),
1786 Applicability::MachineApplicable,
1790 if let &[ArgKind::Tuple(_, ref fields)] = &expected_args[..] {
1791 if fields.len() == found_args.len() && is_closure {
1795 .map(|arg| match arg {
1796 ArgKind::Arg(name, _) => name.to_owned(),
1797 _ => "_".to_owned(),
1799 .collect::<Vec<String>>()
1801 // add type annotations if available
1802 if found_args.iter().any(|arg| match arg {
1803 ArgKind::Arg(_, ty) => ty != "_",
1808 .map(|(_, ty)| ty.to_owned())
1809 .collect::<Vec<String>>()
1815 err.span_suggestion(
1817 "change the closure to accept a tuple instead of individual arguments",
1819 Applicability::MachineApplicable,
1828 fn report_closure_arg_mismatch(
1831 found_span: Option<Span>,
1832 expected_ref: ty::PolyTraitRef<'tcx>,
1833 found: ty::PolyTraitRef<'tcx>,
1834 ) -> DiagnosticBuilder<'tcx> {
1835 fn build_fn_sig_string<'tcx>(tcx: TyCtxt<'tcx>, trait_ref: &ty::TraitRef<'tcx>) -> String {
1836 let inputs = trait_ref.substs.type_at(1);
1837 let sig = if let ty::Tuple(inputs) = inputs.kind {
1839 inputs.iter().map(|k| k.expect_ty()),
1840 tcx.mk_ty_infer(ty::TyVar(ty::TyVid { index: 0 })),
1842 hir::Unsafety::Normal,
1843 ::rustc_target::spec::abi::Abi::Rust
1847 ::std::iter::once(inputs),
1848 tcx.mk_ty_infer(ty::TyVar(ty::TyVid { index: 0 })),
1850 hir::Unsafety::Normal,
1851 ::rustc_target::spec::abi::Abi::Rust
1854 ty::Binder::bind(sig).to_string()
1857 let argument_is_closure = expected_ref.skip_binder().substs.type_at(0).is_closure();
1858 let mut err = struct_span_err!(self.tcx.sess, span, E0631,
1859 "type mismatch in {} arguments",
1860 if argument_is_closure { "closure" } else { "function" });
1862 let found_str = format!(
1863 "expected signature of `{}`",
1864 build_fn_sig_string(self.tcx, found.skip_binder())
1866 err.span_label(span, found_str);
1868 let found_span = found_span.unwrap_or(span);
1869 let expected_str = format!(
1870 "found signature of `{}`",
1871 build_fn_sig_string(self.tcx, expected_ref.skip_binder())
1873 err.span_label(found_span, expected_str);
1879 impl<'tcx> TyCtxt<'tcx> {
1880 pub fn recursive_type_with_infinite_size_error(self,
1882 -> DiagnosticBuilder<'tcx>
1884 assert!(type_def_id.is_local());
1885 let span = self.hir().span_if_local(type_def_id).unwrap();
1886 let span = self.sess.source_map().def_span(span);
1887 let mut err = struct_span_err!(self.sess, span, E0072,
1888 "recursive type `{}` has infinite size",
1889 self.def_path_str(type_def_id));
1890 err.span_label(span, "recursive type has infinite size");
1891 err.help(&format!("insert indirection (e.g., a `Box`, `Rc`, or `&`) \
1892 at some point to make `{}` representable",
1893 self.def_path_str(type_def_id)));
1897 pub fn report_object_safety_error(
1900 trait_def_id: DefId,
1901 violations: Vec<ObjectSafetyViolation>,
1902 ) -> DiagnosticBuilder<'tcx> {
1903 let trait_str = self.def_path_str(trait_def_id);
1904 let span = self.sess.source_map().def_span(span);
1905 let mut err = struct_span_err!(
1906 self.sess, span, E0038,
1907 "the trait `{}` cannot be made into an object",
1909 err.span_label(span, format!("the trait `{}` cannot be made into an object", trait_str));
1911 let mut reported_violations = FxHashSet::default();
1912 for violation in violations {
1913 if reported_violations.insert(violation.clone()) {
1914 match violation.span() {
1915 Some(span) => err.span_label(span, violation.error_msg()),
1916 None => err.note(&violation.error_msg()),
1921 if self.sess.trait_methods_not_found.borrow().contains(&span) {
1922 // Avoid emitting error caused by non-existing method (#58734)
1930 impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
1931 fn maybe_report_ambiguity(
1933 obligation: &PredicateObligation<'tcx>,
1934 body_id: Option<hir::BodyId>,
1936 // Unable to successfully determine, probably means
1937 // insufficient type information, but could mean
1938 // ambiguous impls. The latter *ought* to be a
1939 // coherence violation, so we don't report it here.
1941 let predicate = self.resolve_vars_if_possible(&obligation.predicate);
1942 let span = obligation.cause.span;
1945 "maybe_report_ambiguity(predicate={:?}, obligation={:?} body_id={:?}, code={:?})",
1949 obligation.cause.code,
1952 // Ambiguity errors are often caused as fallout from earlier
1953 // errors. So just ignore them if this infcx is tainted.
1954 if self.is_tainted_by_errors() {
1959 ty::Predicate::Trait(ref data) => {
1960 let trait_ref = data.to_poly_trait_ref();
1961 let self_ty = trait_ref.self_ty();
1962 debug!("self_ty {:?} {:?} trait_ref {:?}", self_ty, self_ty.kind, trait_ref);
1964 if predicate.references_error() {
1967 // Typically, this ambiguity should only happen if
1968 // there are unresolved type inference variables
1969 // (otherwise it would suggest a coherence
1970 // failure). But given #21974 that is not necessarily
1971 // the case -- we can have multiple where clauses that
1972 // are only distinguished by a region, which results
1973 // in an ambiguity even when all types are fully
1974 // known, since we don't dispatch based on region
1977 // This is kind of a hack: it frequently happens that some earlier
1978 // error prevents types from being fully inferred, and then we get
1979 // a bunch of uninteresting errors saying something like "<generic
1980 // #0> doesn't implement Sized". It may even be true that we
1981 // could just skip over all checks where the self-ty is an
1982 // inference variable, but I was afraid that there might be an
1983 // inference variable created, registered as an obligation, and
1984 // then never forced by writeback, and hence by skipping here we'd
1985 // be ignoring the fact that we don't KNOW the type works
1986 // out. Though even that would probably be harmless, given that
1987 // we're only talking about builtin traits, which are known to be
1988 // inhabited. We used to check for `self.tcx.sess.has_errors()` to
1989 // avoid inundating the user with unnecessary errors, but we now
1990 // check upstream for type errors and dont add the obligations to
1991 // begin with in those cases.
1993 self.tcx.lang_items().sized_trait()
1994 .map_or(false, |sized_id| sized_id == trait_ref.def_id())
1996 self.need_type_info_err(body_id, span, self_ty).emit();
1998 let mut err = struct_span_err!(
2002 "type annotations needed: cannot resolve `{}`",
2005 self.note_obligation_cause(&mut err, obligation);
2010 ty::Predicate::WellFormed(ty) => {
2011 // Same hacky approach as above to avoid deluging user
2012 // with error messages.
2013 if !ty.references_error() && !self.tcx.sess.has_errors() {
2014 self.need_type_info_err(body_id, span, ty).emit();
2018 ty::Predicate::Subtype(ref data) => {
2019 if data.references_error() || self.tcx.sess.has_errors() {
2020 // no need to overload user in such cases
2022 let &SubtypePredicate { a_is_expected: _, a, b } = data.skip_binder();
2023 // both must be type variables, or the other would've been instantiated
2024 assert!(a.is_ty_var() && b.is_ty_var());
2025 self.need_type_info_err(body_id,
2026 obligation.cause.span,
2032 if !self.tcx.sess.has_errors() {
2033 let mut err = struct_span_err!(
2035 obligation.cause.span,
2037 "type annotations needed: cannot resolve `{}`",
2040 self.note_obligation_cause(&mut err, obligation);
2047 /// Returns `true` if the trait predicate may apply for *some* assignment
2048 /// to the type parameters.
2049 fn predicate_can_apply(
2051 param_env: ty::ParamEnv<'tcx>,
2052 pred: ty::PolyTraitRef<'tcx>,
2054 struct ParamToVarFolder<'a, 'tcx> {
2055 infcx: &'a InferCtxt<'a, 'tcx>,
2056 var_map: FxHashMap<Ty<'tcx>, Ty<'tcx>>,
2059 impl<'a, 'tcx> TypeFolder<'tcx> for ParamToVarFolder<'a, 'tcx> {
2060 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> { self.infcx.tcx }
2062 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
2063 if let ty::Param(ty::ParamTy {name, .. }) = ty.kind {
2064 let infcx = self.infcx;
2065 self.var_map.entry(ty).or_insert_with(||
2067 TypeVariableOrigin {
2068 kind: TypeVariableOriginKind::TypeParameterDefinition(name),
2074 ty.super_fold_with(self)
2080 let mut selcx = SelectionContext::new(self);
2082 let cleaned_pred = pred.fold_with(&mut ParamToVarFolder {
2084 var_map: Default::default()
2087 let cleaned_pred = super::project::normalize(
2090 ObligationCause::dummy(),
2094 let obligation = Obligation::new(
2095 ObligationCause::dummy(),
2097 cleaned_pred.to_predicate()
2100 self.predicate_may_hold(&obligation)
2104 fn note_obligation_cause(
2106 err: &mut DiagnosticBuilder<'_>,
2107 obligation: &PredicateObligation<'tcx>,
2109 // First, attempt to add note to this error with an async-await-specific
2110 // message, and fall back to regular note otherwise.
2111 if !self.note_obligation_cause_for_async_await(err, obligation) {
2112 self.note_obligation_cause_code(err, &obligation.predicate, &obligation.cause.code,
2117 /// Adds an async-await specific note to the diagnostic:
2119 /// ```ignore (diagnostic)
2120 /// note: future does not implement `std::marker::Send` because this value is used across an
2122 /// --> $DIR/issue-64130-non-send-future-diags.rs:15:5
2124 /// LL | let g = x.lock().unwrap();
2125 /// | - has type `std::sync::MutexGuard<'_, u32>`
2126 /// LL | baz().await;
2127 /// | ^^^^^^^^^^^ await occurs here, with `g` maybe used later
2129 /// | - `g` is later dropped here
2132 /// Returns `true` if an async-await specific note was added to the diagnostic.
2133 fn note_obligation_cause_for_async_await(
2135 err: &mut DiagnosticBuilder<'_>,
2136 obligation: &PredicateObligation<'tcx>,
2138 debug!("note_obligation_cause_for_async_await: obligation.predicate={:?} \
2139 obligation.cause.span={:?}", obligation.predicate, obligation.cause.span);
2140 let source_map = self.tcx.sess.source_map();
2142 // Look into the obligation predicate to determine the type in the generator which meant
2143 // that the predicate was not satisifed.
2144 let (trait_ref, target_ty) = match obligation.predicate {
2145 ty::Predicate::Trait(trait_predicate) =>
2146 (trait_predicate.skip_binder().trait_ref, trait_predicate.skip_binder().self_ty()),
2149 debug!("note_obligation_cause_for_async_await: target_ty={:?}", target_ty);
2151 // Attempt to detect an async-await error by looking at the obligation causes, looking
2152 // for only generators, generator witnesses, opaque types or `std::future::GenFuture` to
2155 // When a future does not implement a trait because of a captured type in one of the
2156 // generators somewhere in the call stack, then the result is a chain of obligations.
2157 // Given a `async fn` A that calls a `async fn` B which captures a non-send type and that
2158 // future is passed as an argument to a function C which requires a `Send` type, then the
2159 // chain looks something like this:
2161 // - `BuiltinDerivedObligation` with a generator witness (B)
2162 // - `BuiltinDerivedObligation` with a generator (B)
2163 // - `BuiltinDerivedObligation` with `std::future::GenFuture` (B)
2164 // - `BuiltinDerivedObligation` with `impl std::future::Future` (B)
2165 // - `BuiltinDerivedObligation` with `impl std::future::Future` (B)
2166 // - `BuiltinDerivedObligation` with a generator witness (A)
2167 // - `BuiltinDerivedObligation` with a generator (A)
2168 // - `BuiltinDerivedObligation` with `std::future::GenFuture` (A)
2169 // - `BuiltinDerivedObligation` with `impl std::future::Future` (A)
2170 // - `BuiltinDerivedObligation` with `impl std::future::Future` (A)
2171 // - `BindingObligation` with `impl_send (Send requirement)
2173 // The first obligations in the chain can be used to get the details of the type that is
2174 // captured but the entire chain must be inspected to detect this case.
2175 let mut generator = None;
2176 let mut next_code = Some(&obligation.cause.code);
2177 while let Some(code) = next_code {
2178 debug!("note_obligation_cause_for_async_await: code={:?}", code);
2180 ObligationCauseCode::BuiltinDerivedObligation(derived_obligation) |
2181 ObligationCauseCode::ImplDerivedObligation(derived_obligation) => {
2182 debug!("note_obligation_cause_for_async_await: self_ty.kind={:?}",
2183 derived_obligation.parent_trait_ref.self_ty().kind);
2184 match derived_obligation.parent_trait_ref.self_ty().kind {
2185 ty::Adt(ty::AdtDef { did, .. }, ..) if
2186 self.tcx.is_diagnostic_item(sym::gen_future, *did) => {},
2187 ty::Generator(did, ..) => generator = generator.or(Some(did)),
2188 ty::GeneratorWitness(_) | ty::Opaque(..) => {},
2192 next_code = Some(derived_obligation.parent_code.as_ref());
2194 ObligationCauseCode::ItemObligation(_) | ObligationCauseCode::BindingObligation(..)
2195 if generator.is_some() => break,
2200 let generator_did = generator.expect("can only reach this if there was a generator");
2202 // Only continue to add a note if the generator is from an `async` function.
2203 let parent_node = self.tcx.parent(generator_did)
2204 .and_then(|parent_did| self.tcx.hir().get_if_local(parent_did));
2205 debug!("note_obligation_cause_for_async_await: parent_node={:?}", parent_node);
2206 if let Some(hir::Node::Item(hir::Item {
2207 kind: hir::ItemKind::Fn(sig, _, _),
2210 debug!("note_obligation_cause_for_async_await: header={:?}", sig.header);
2211 if sig.header.asyncness != hir::IsAsync::Async {
2216 let span = self.tcx.def_span(generator_did);
2217 let tables = self.tcx.typeck_tables_of(generator_did);
2218 debug!("note_obligation_cause_for_async_await: generator_did={:?} span={:?} ",
2219 generator_did, span);
2221 // Look for a type inside the generator interior that matches the target type to get
2223 let target_span = tables.generator_interior_types.iter()
2224 .find(|ty::GeneratorInteriorTypeCause { ty, .. }| ty::TyS::same_type(*ty, target_ty))
2225 .map(|ty::GeneratorInteriorTypeCause { span, scope_span, .. }|
2226 (span, source_map.span_to_snippet(*span), scope_span));
2227 if let Some((target_span, Ok(snippet), scope_span)) = target_span {
2228 // Look at the last interior type to get a span for the `.await`.
2229 let await_span = tables.generator_interior_types.iter().map(|i| i.span).last().unwrap();
2230 let mut span = MultiSpan::from_span(await_span);
2231 span.push_span_label(
2232 await_span, format!("await occurs here, with `{}` maybe used later", snippet));
2234 span.push_span_label(*target_span, format!("has type `{}`", target_ty));
2236 // If available, use the scope span to annotate the drop location.
2237 if let Some(scope_span) = scope_span {
2238 span.push_span_label(
2239 source_map.end_point(*scope_span),
2240 format!("`{}` is later dropped here", snippet),
2244 err.span_note(span, &format!(
2245 "future does not implement `{}` as this value is used across an await",
2246 trait_ref.print_only_trait_path(),
2249 // Add a note for the item obligation that remains - normally a note pointing to the
2250 // bound that introduced the obligation (e.g. `T: Send`).
2251 debug!("note_obligation_cause_for_async_await: next_code={:?}", next_code);
2252 self.note_obligation_cause_code(
2254 &obligation.predicate,
2265 fn note_obligation_cause_code<T>(&self,
2266 err: &mut DiagnosticBuilder<'_>,
2268 cause_code: &ObligationCauseCode<'tcx>,
2269 obligated_types: &mut Vec<&ty::TyS<'tcx>>)
2270 where T: fmt::Display
2274 ObligationCauseCode::ExprAssignable |
2275 ObligationCauseCode::MatchExpressionArm { .. } |
2276 ObligationCauseCode::MatchExpressionArmPattern { .. } |
2277 ObligationCauseCode::IfExpression { .. } |
2278 ObligationCauseCode::IfExpressionWithNoElse |
2279 ObligationCauseCode::MainFunctionType |
2280 ObligationCauseCode::StartFunctionType |
2281 ObligationCauseCode::IntrinsicType |
2282 ObligationCauseCode::MethodReceiver |
2283 ObligationCauseCode::ReturnNoExpression |
2284 ObligationCauseCode::MiscObligation => {}
2285 ObligationCauseCode::SliceOrArrayElem => {
2286 err.note("slice and array elements must have `Sized` type");
2288 ObligationCauseCode::TupleElem => {
2289 err.note("only the last element of a tuple may have a dynamically sized type");
2291 ObligationCauseCode::ProjectionWf(data) => {
2293 "required so that the projection `{}` is well-formed",
2297 ObligationCauseCode::ReferenceOutlivesReferent(ref_ty) => {
2299 "required so that reference `{}` does not outlive its referent",
2303 ObligationCauseCode::ObjectTypeBound(object_ty, region) => {
2305 "required so that the lifetime bound of `{}` for `{}` is satisfied",
2310 ObligationCauseCode::ItemObligation(item_def_id) => {
2311 let item_name = tcx.def_path_str(item_def_id);
2312 let msg = format!("required by `{}`", item_name);
2314 if let Some(sp) = tcx.hir().span_if_local(item_def_id) {
2315 let sp = tcx.sess.source_map().def_span(sp);
2316 err.span_label(sp, &msg);
2321 ObligationCauseCode::BindingObligation(item_def_id, span) => {
2322 let item_name = tcx.def_path_str(item_def_id);
2323 let msg = format!("required by this bound in `{}`", item_name);
2324 if let Some(ident) = tcx.opt_item_name(item_def_id) {
2325 err.span_label(ident.span, "");
2327 if span != DUMMY_SP {
2328 err.span_label(span, &msg);
2333 ObligationCauseCode::ObjectCastObligation(object_ty) => {
2334 err.note(&format!("required for the cast to the object type `{}`",
2335 self.ty_to_string(object_ty)));
2337 ObligationCauseCode::Coercion { source: _, target } => {
2338 err.note(&format!("required by cast to type `{}`",
2339 self.ty_to_string(target)));
2341 ObligationCauseCode::RepeatVec(suggest_const_in_array_repeat_expressions) => {
2342 err.note("the `Copy` trait is required because the \
2343 repeated element will be copied");
2344 if suggest_const_in_array_repeat_expressions {
2345 err.note("this array initializer can be evaluated at compile-time, for more \
2346 information, see issue \
2347 https://github.com/rust-lang/rust/issues/49147");
2348 if tcx.sess.opts.unstable_features.is_nightly_build() {
2349 err.help("add `#![feature(const_in_array_repeat_expressions)]` to the \
2350 crate attributes to enable");
2354 ObligationCauseCode::VariableType(_) => {
2355 err.note("all local variables must have a statically known size");
2356 if !self.tcx.features().unsized_locals {
2357 err.help("unsized locals are gated as an unstable feature");
2360 ObligationCauseCode::SizedArgumentType => {
2361 err.note("all function arguments must have a statically known size");
2362 if !self.tcx.features().unsized_locals {
2363 err.help("unsized locals are gated as an unstable feature");
2366 ObligationCauseCode::SizedReturnType => {
2367 err.note("the return type of a function must have a \
2368 statically known size");
2370 ObligationCauseCode::SizedYieldType => {
2371 err.note("the yield type of a generator must have a \
2372 statically known size");
2374 ObligationCauseCode::AssignmentLhsSized => {
2375 err.note("the left-hand-side of an assignment must have a statically known size");
2377 ObligationCauseCode::TupleInitializerSized => {
2378 err.note("tuples must have a statically known size to be initialized");
2380 ObligationCauseCode::StructInitializerSized => {
2381 err.note("structs must have a statically known size to be initialized");
2383 ObligationCauseCode::FieldSized { adt_kind: ref item, last } => {
2385 AdtKind::Struct => {
2387 err.note("the last field of a packed struct may only have a \
2388 dynamically sized type if it does not need drop to be run");
2390 err.note("only the last field of a struct may have a dynamically \
2395 err.note("no field of a union may have a dynamically sized type");
2398 err.note("no field of an enum variant may have a dynamically sized type");
2402 ObligationCauseCode::ConstSized => {
2403 err.note("constant expressions must have a statically known size");
2405 ObligationCauseCode::ConstPatternStructural => {
2406 err.note("constants used for pattern-matching must derive `PartialEq` and `Eq`");
2408 ObligationCauseCode::SharedStatic => {
2409 err.note("shared static variables must have a type that implements `Sync`");
2411 ObligationCauseCode::BuiltinDerivedObligation(ref data) => {
2412 let parent_trait_ref = self.resolve_vars_if_possible(&data.parent_trait_ref);
2413 let ty = parent_trait_ref.skip_binder().self_ty();
2414 err.note(&format!("required because it appears within the type `{}`", ty));
2415 obligated_types.push(ty);
2417 let parent_predicate = parent_trait_ref.to_predicate();
2418 if !self.is_recursive_obligation(obligated_types, &data.parent_code) {
2419 self.note_obligation_cause_code(err,
2425 ObligationCauseCode::ImplDerivedObligation(ref data) => {
2426 let parent_trait_ref = self.resolve_vars_if_possible(&data.parent_trait_ref);
2428 &format!("required because of the requirements on the impl of `{}` for `{}`",
2429 parent_trait_ref.print_only_trait_path(),
2430 parent_trait_ref.skip_binder().self_ty()));
2431 let parent_predicate = parent_trait_ref.to_predicate();
2432 self.note_obligation_cause_code(err,
2437 ObligationCauseCode::CompareImplMethodObligation { .. } => {
2439 &format!("the requirement `{}` appears on the impl method \
2440 but not on the corresponding trait method",
2443 ObligationCauseCode::ReturnType |
2444 ObligationCauseCode::ReturnValue(_) |
2445 ObligationCauseCode::BlockTailExpression(_) => (),
2446 ObligationCauseCode::TrivialBound => {
2447 err.help("see issue #48214");
2448 if tcx.sess.opts.unstable_features.is_nightly_build() {
2449 err.help("add `#![feature(trivial_bounds)]` to the \
2450 crate attributes to enable",
2454 ObligationCauseCode::AssocTypeBound(ref data) => {
2455 err.span_label(data.original, "associated type defined here");
2456 if let Some(sp) = data.impl_span {
2457 err.span_label(sp, "in this `impl` item");
2459 for sp in &data.bounds {
2460 err.span_label(*sp, "restricted in this bound");
2466 fn suggest_new_overflow_limit(&self, err: &mut DiagnosticBuilder<'_>) {
2467 let current_limit = self.tcx.sess.recursion_limit.get();
2468 let suggested_limit = current_limit * 2;
2469 err.help(&format!("consider adding a `#![recursion_limit=\"{}\"]` attribute to your crate",
2473 fn is_recursive_obligation(&self,
2474 obligated_types: &mut Vec<&ty::TyS<'tcx>>,
2475 cause_code: &ObligationCauseCode<'tcx>) -> bool {
2476 if let ObligationCauseCode::BuiltinDerivedObligation(ref data) = cause_code {
2477 let parent_trait_ref = self.resolve_vars_if_possible(&data.parent_trait_ref);
2479 if obligated_types.iter().any(|ot| ot == &parent_trait_ref.skip_binder().self_ty()) {
2487 /// Summarizes information
2490 /// An argument of non-tuple type. Parameters are (name, ty)
2491 Arg(String, String),
2493 /// An argument of tuple type. For a "found" argument, the span is
2494 /// the locationo in the source of the pattern. For a "expected"
2495 /// argument, it will be None. The vector is a list of (name, ty)
2496 /// strings for the components of the tuple.
2497 Tuple(Option<Span>, Vec<(String, String)>),
2501 fn empty() -> ArgKind {
2502 ArgKind::Arg("_".to_owned(), "_".to_owned())
2505 /// Creates an `ArgKind` from the expected type of an
2506 /// argument. It has no name (`_`) and an optional source span.
2507 pub fn from_expected_ty(t: Ty<'_>, span: Option<Span>) -> ArgKind {
2509 ty::Tuple(ref tys) => ArgKind::Tuple(
2512 .map(|ty| ("_".to_owned(), ty.to_string()))
2513 .collect::<Vec<_>>()
2515 _ => ArgKind::Arg("_".to_owned(), t.to_string()),
2520 /// Suggest restricting a type param with a new bound.
2521 pub fn suggest_constraining_type_param(
2522 generics: &hir::Generics,
2523 err: &mut DiagnosticBuilder<'_>,
2526 source_map: &SourceMap,
2529 let restrict_msg = "consider further restricting this bound";
2530 if let Some(param) = generics.params.iter().filter(|p| {
2531 p.name.ident().as_str() == param_name
2533 if param_name.starts_with("impl ") {
2534 // `impl Trait` in argument:
2535 // `fn foo(x: impl Trait) {}` → `fn foo(t: impl Trait + Trait2) {}`
2536 err.span_suggestion(
2539 // `impl CurrentTrait + MissingTrait`
2540 format!("{} + {}", param_name, constraint),
2541 Applicability::MachineApplicable,
2543 } else if generics.where_clause.predicates.is_empty() &&
2544 param.bounds.is_empty()
2546 // If there are no bounds whatsoever, suggest adding a constraint
2547 // to the type parameter:
2548 // `fn foo<T>(t: T) {}` → `fn foo<T: Trait>(t: T) {}`
2549 err.span_suggestion(
2551 "consider restricting this bound",
2552 format!("{}: {}", param_name, constraint),
2553 Applicability::MachineApplicable,
2555 } else if !generics.where_clause.predicates.is_empty() {
2556 // There is a `where` clause, so suggest expanding it:
2557 // `fn foo<T>(t: T) where T: Debug {}` →
2558 // `fn foo<T>(t: T) where T: Debug, T: Trait {}`
2559 err.span_suggestion(
2560 generics.where_clause.span().unwrap().shrink_to_hi(),
2561 &format!("consider further restricting type parameter `{}`", param_name),
2562 format!(", {}: {}", param_name, constraint),
2563 Applicability::MachineApplicable,
2566 // If there is no `where` clause lean towards constraining to the
2568 // `fn foo<X: Bar, T>(t: T, x: X) {}` → `fn foo<T: Trait>(t: T) {}`
2569 // `fn foo<T: Bar>(t: T) {}` → `fn foo<T: Bar + Trait>(t: T) {}`
2570 let sp = param.span.with_hi(span.hi());
2571 let span = source_map.span_through_char(sp, ':');
2572 if sp != param.span && sp != span {
2573 // Only suggest if we have high certainty that the span
2574 // covers the colon in `foo<T: Trait>`.
2575 err.span_suggestion(
2578 format!("{}: {} + ", param_name, constraint),
2579 Applicability::MachineApplicable,
2584 &format!("consider adding a `where {}: {}` bound", param_name, constraint),