4 MismatchedProjectionTypes,
8 OnUnimplementedDirective,
10 OutputTypeParameterMismatch,
16 ObjectSafetyViolation,
22 use crate::hir::def_id::DefId;
23 use crate::infer::{self, InferCtxt};
24 use crate::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
25 use crate::session::DiagnosticMessageId;
26 use crate::ty::{self, AdtKind, ToPredicate, ToPolyTraitRef, Ty, TyCtxt, TypeFoldable};
27 use crate::ty::GenericParamDefKind;
28 use crate::ty::error::ExpectedFound;
29 use crate::ty::fast_reject;
30 use crate::ty::fold::TypeFolder;
31 use crate::ty::subst::Subst;
32 use crate::ty::SubtypePredicate;
33 use crate::util::nodemap::{FxHashMap, FxHashSet};
35 use errors::{Applicability, DiagnosticBuilder};
38 use syntax::symbol::sym;
39 use syntax_pos::{DUMMY_SP, Span, ExpnInfo, ExpnFormat};
41 impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
42 pub fn report_fulfillment_errors(&self,
43 errors: &[FulfillmentError<'tcx>],
44 body_id: Option<hir::BodyId>,
45 fallback_has_occurred: bool) {
47 struct ErrorDescriptor<'tcx> {
48 predicate: ty::Predicate<'tcx>,
49 index: Option<usize>, // None if this is an old error
52 let mut error_map: FxHashMap<_, Vec<_>> =
53 self.reported_trait_errors.borrow().iter().map(|(&span, predicates)| {
54 (span, predicates.iter().map(|predicate| ErrorDescriptor {
55 predicate: predicate.clone(),
60 for (index, error) in errors.iter().enumerate() {
61 // We want to ignore desugarings here: spans are equivalent even
62 // if one is the result of a desugaring and the other is not.
63 let mut span = error.obligation.cause.span;
64 if let Some(ExpnInfo {
65 format: ExpnFormat::CompilerDesugaring(_),
66 def_site: Some(def_span),
68 }) = span.ctxt().outer_expn_info() {
72 error_map.entry(span).or_default().push(
74 predicate: error.obligation.predicate.clone(),
79 self.reported_trait_errors.borrow_mut()
80 .entry(span).or_default()
81 .push(error.obligation.predicate.clone());
84 // We do this in 2 passes because we want to display errors in order, though
85 // maybe it *is* better to sort errors by span or something.
86 let mut is_suppressed = vec![false; errors.len()];
87 for (_, error_set) in error_map.iter() {
88 // We want to suppress "duplicate" errors with the same span.
89 for error in error_set {
90 if let Some(index) = error.index {
91 // Suppress errors that are either:
92 // 1) strictly implied by another error.
93 // 2) implied by an error with a smaller index.
94 for error2 in error_set {
95 if error2.index.map_or(false, |index2| is_suppressed[index2]) {
96 // Avoid errors being suppressed by already-suppressed
97 // errors, to prevent all errors from being suppressed
102 if self.error_implies(&error2.predicate, &error.predicate) &&
103 !(error2.index >= error.index &&
104 self.error_implies(&error.predicate, &error2.predicate))
106 info!("skipping {:?} (implied by {:?})", error, error2);
107 is_suppressed[index] = true;
115 for (error, suppressed) in errors.iter().zip(is_suppressed) {
117 self.report_fulfillment_error(error, body_id, fallback_has_occurred);
122 // returns if `cond` not occurring implies that `error` does not occur - i.e., that
123 // `error` occurring implies that `cond` occurs.
124 fn error_implies(&self,
125 cond: &ty::Predicate<'tcx>,
126 error: &ty::Predicate<'tcx>)
133 let (cond, error) = match (cond, error) {
134 (&ty::Predicate::Trait(..), &ty::Predicate::Trait(ref error))
137 // FIXME: make this work in other cases too.
142 for implication in super::elaborate_predicates(self.tcx, vec![cond.clone()]) {
143 if let ty::Predicate::Trait(implication) = implication {
144 let error = error.to_poly_trait_ref();
145 let implication = implication.to_poly_trait_ref();
146 // FIXME: I'm just not taking associated types at all here.
147 // Eventually I'll need to implement param-env-aware
148 // `Γ₁ ⊦ φ₁ => Γ₂ ⊦ φ₂` logic.
149 let param_env = ty::ParamEnv::empty();
150 if self.can_sub(param_env, error, implication).is_ok() {
151 debug!("error_implies: {:?} -> {:?} -> {:?}", cond, error, implication);
160 fn report_fulfillment_error(&self, error: &FulfillmentError<'tcx>,
161 body_id: Option<hir::BodyId>,
162 fallback_has_occurred: bool) {
163 debug!("report_fulfillment_errors({:?})", error);
165 FulfillmentErrorCode::CodeSelectionError(ref e) => {
166 self.report_selection_error(&error.obligation, e, fallback_has_occurred);
168 FulfillmentErrorCode::CodeProjectionError(ref e) => {
169 self.report_projection_error(&error.obligation, e);
171 FulfillmentErrorCode::CodeAmbiguity => {
172 self.maybe_report_ambiguity(&error.obligation, body_id);
174 FulfillmentErrorCode::CodeSubtypeError(ref expected_found, ref err) => {
175 self.report_mismatched_types(&error.obligation.cause,
176 expected_found.expected,
177 expected_found.found,
184 fn report_projection_error(&self,
185 obligation: &PredicateObligation<'tcx>,
186 error: &MismatchedProjectionTypes<'tcx>)
189 self.resolve_vars_if_possible(&obligation.predicate);
191 if predicate.references_error() {
197 let mut err = &error.err;
198 let mut values = None;
200 // try to find the mismatched types to report the error with.
202 // this can fail if the problem was higher-ranked, in which
203 // cause I have no idea for a good error message.
204 if let ty::Predicate::Projection(ref data) = predicate {
205 let mut selcx = SelectionContext::new(self);
206 let (data, _) = self.replace_bound_vars_with_fresh_vars(
207 obligation.cause.span,
208 infer::LateBoundRegionConversionTime::HigherRankedType,
211 let mut obligations = vec![];
212 let normalized_ty = super::normalize_projection_type(
214 obligation.param_env,
216 obligation.cause.clone(),
220 if let Err(error) = self.at(&obligation.cause, obligation.param_env)
221 .eq(normalized_ty, data.ty) {
222 values = Some(infer::ValuePairs::Types(ExpectedFound {
223 expected: normalized_ty,
231 let msg = format!("type mismatch resolving `{}`", predicate);
232 let error_id = (DiagnosticMessageId::ErrorId(271),
233 Some(obligation.cause.span), msg);
234 let fresh = self.tcx.sess.one_time_diagnostics.borrow_mut().insert(error_id);
236 let mut diag = struct_span_err!(
237 self.tcx.sess, obligation.cause.span, E0271,
238 "type mismatch resolving `{}`", predicate
240 self.note_type_err(&mut diag, &obligation.cause, None, values, err);
241 self.note_obligation_cause(&mut diag, obligation);
247 fn fuzzy_match_tys(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
248 /// returns the fuzzy category of a given type, or None
249 /// if the type can be equated to any type.
250 fn type_category<'tcx>(t: Ty<'tcx>) -> Option<u32> {
255 ty::Int(..) | ty::Uint(..) | ty::Infer(ty::IntVar(..)) => Some(3),
256 ty::Float(..) | ty::Infer(ty::FloatVar(..)) => Some(4),
257 ty::Ref(..) | ty::RawPtr(..) => Some(5),
258 ty::Array(..) | ty::Slice(..) => Some(6),
259 ty::FnDef(..) | ty::FnPtr(..) => Some(7),
260 ty::Dynamic(..) => Some(8),
261 ty::Closure(..) => Some(9),
262 ty::Tuple(..) => Some(10),
263 ty::Projection(..) => Some(11),
264 ty::Param(..) => Some(12),
265 ty::Opaque(..) => Some(13),
266 ty::Never => Some(14),
267 ty::Adt(adt, ..) => match adt.adt_kind() {
268 AdtKind::Struct => Some(15),
269 AdtKind::Union => Some(16),
270 AdtKind::Enum => Some(17),
272 ty::Generator(..) => Some(18),
273 ty::Foreign(..) => Some(19),
274 ty::GeneratorWitness(..) => Some(20),
275 ty::Placeholder(..) | ty::Bound(..) | ty::Infer(..) | ty::Error => None,
276 ty::UnnormalizedProjection(..) => bug!("only used with chalk-engine"),
280 match (type_category(a), type_category(b)) {
281 (Some(cat_a), Some(cat_b)) => match (&a.sty, &b.sty) {
282 (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) => def_a == def_b,
285 // infer and error can be equated to all types
290 fn impl_similar_to(&self,
291 trait_ref: ty::PolyTraitRef<'tcx>,
292 obligation: &PredicateObligation<'tcx>)
296 let param_env = obligation.param_env;
297 let trait_ref = tcx.erase_late_bound_regions(&trait_ref);
298 let trait_self_ty = trait_ref.self_ty();
300 let mut self_match_impls = vec![];
301 let mut fuzzy_match_impls = vec![];
303 self.tcx.for_each_relevant_impl(
304 trait_ref.def_id, trait_self_ty, |def_id| {
305 let impl_substs = self.fresh_substs_for_item(obligation.cause.span, def_id);
306 let impl_trait_ref = tcx
307 .impl_trait_ref(def_id)
309 .subst(tcx, impl_substs);
311 let impl_self_ty = impl_trait_ref.self_ty();
313 if let Ok(..) = self.can_eq(param_env, trait_self_ty, impl_self_ty) {
314 self_match_impls.push(def_id);
316 if trait_ref.substs.types().skip(1)
317 .zip(impl_trait_ref.substs.types().skip(1))
318 .all(|(u,v)| self.fuzzy_match_tys(u, v))
320 fuzzy_match_impls.push(def_id);
325 let impl_def_id = if self_match_impls.len() == 1 {
327 } else if fuzzy_match_impls.len() == 1 {
333 if tcx.has_attr(impl_def_id, sym::rustc_on_unimplemented) {
340 fn on_unimplemented_note(
342 trait_ref: ty::PolyTraitRef<'tcx>,
343 obligation: &PredicateObligation<'tcx>,
344 ) -> OnUnimplementedNote {
345 let def_id = self.impl_similar_to(trait_ref, obligation)
346 .unwrap_or_else(|| trait_ref.def_id());
347 let trait_ref = *trait_ref.skip_binder();
349 let mut flags = vec![];
350 match obligation.cause.code {
351 ObligationCauseCode::BuiltinDerivedObligation(..) |
352 ObligationCauseCode::ImplDerivedObligation(..) => {}
354 // this is a "direct", user-specified, rather than derived,
356 flags.push((sym::direct, None));
360 if let ObligationCauseCode::ItemObligation(item) = obligation.cause.code {
361 // FIXME: maybe also have some way of handling methods
362 // from other traits? That would require name resolution,
363 // which we might want to be some sort of hygienic.
365 // Currently I'm leaving it for what I need for `try`.
366 if self.tcx.trait_of_item(item) == Some(trait_ref.def_id) {
367 let method = self.tcx.item_name(item);
368 flags.push((sym::from_method, None));
369 flags.push((sym::from_method, Some(method.to_string())));
372 if let Some(t) = self.get_parent_trait_ref(&obligation.cause.code) {
373 flags.push((sym::parent_trait, Some(t)));
376 if let Some(k) = obligation.cause.span.compiler_desugaring_kind() {
377 flags.push((sym::from_desugaring, None));
378 flags.push((sym::from_desugaring, Some(k.name().to_string())));
380 let generics = self.tcx.generics_of(def_id);
381 let self_ty = trait_ref.self_ty();
382 // This is also included through the generics list as `Self`,
383 // but the parser won't allow you to use it
384 flags.push((sym::_Self, Some(self_ty.to_string())));
385 if let Some(def) = self_ty.ty_adt_def() {
386 // We also want to be able to select self's original
387 // signature with no type arguments resolved
388 flags.push((sym::_Self, Some(self.tcx.type_of(def.did).to_string())));
391 for param in generics.params.iter() {
392 let value = match param.kind {
393 GenericParamDefKind::Type { .. } |
394 GenericParamDefKind::Const => {
395 trait_ref.substs[param.index as usize].to_string()
397 GenericParamDefKind::Lifetime => continue,
399 let name = param.name.as_symbol();
400 flags.push((name, Some(value)));
403 if let Some(true) = self_ty.ty_adt_def().map(|def| def.did.is_local()) {
404 flags.push((sym::crate_local, None));
407 // Allow targeting all integers using `{integral}`, even if the exact type was resolved
408 if self_ty.is_integral() {
409 flags.push((sym::_Self, Some("{integral}".to_owned())));
412 if let ty::Array(aty, len) = self_ty.sty {
413 flags.push((sym::_Self, Some("[]".to_owned())));
414 flags.push((sym::_Self, Some(format!("[{}]", aty))));
415 if let Some(def) = aty.ty_adt_def() {
416 // We also want to be able to select the array's type's original
417 // signature with no type arguments resolved
420 Some(format!("[{}]", self.tcx.type_of(def.did).to_string())),
423 if let Some(len) = len.assert_usize(tcx) {
426 Some(format!("[{}; {}]", self.tcx.type_of(def.did).to_string(), len)),
431 Some(format!("[{}; _]", self.tcx.type_of(def.did).to_string())),
437 if let Ok(Some(command)) = OnUnimplementedDirective::of_item(
438 self.tcx, trait_ref.def_id, def_id
440 command.evaluate(self.tcx, trait_ref, &flags[..])
442 OnUnimplementedNote::empty()
446 fn find_similar_impl_candidates(&self,
447 trait_ref: ty::PolyTraitRef<'tcx>)
448 -> Vec<ty::TraitRef<'tcx>>
450 let simp = fast_reject::simplify_type(self.tcx,
451 trait_ref.skip_binder().self_ty(),
453 let all_impls = self.tcx.all_impls(trait_ref.def_id());
456 Some(simp) => all_impls.iter().filter_map(|&def_id| {
457 let imp = self.tcx.impl_trait_ref(def_id).unwrap();
458 let imp_simp = fast_reject::simplify_type(self.tcx,
461 if let Some(imp_simp) = imp_simp {
462 if simp != imp_simp {
469 None => all_impls.iter().map(|&def_id|
470 self.tcx.impl_trait_ref(def_id).unwrap()
475 fn report_similar_impl_candidates(&self,
476 impl_candidates: Vec<ty::TraitRef<'tcx>>,
477 err: &mut DiagnosticBuilder<'_>)
479 if impl_candidates.is_empty() {
483 let len = impl_candidates.len();
484 let end = if impl_candidates.len() <= 5 {
485 impl_candidates.len()
490 let normalize = |candidate| self.tcx.global_tcx().infer_ctxt().enter(|ref infcx| {
491 let normalized = infcx
492 .at(&ObligationCause::dummy(), ty::ParamEnv::empty())
493 .normalize(candidate)
496 Some(normalized) => format!("\n {:?}", normalized.value),
497 None => format!("\n {:?}", candidate),
501 // Sort impl candidates so that ordering is consistent for UI tests.
502 let mut normalized_impl_candidates = impl_candidates
505 .collect::<Vec<String>>();
507 // Sort before taking the `..end` range,
508 // because the ordering of `impl_candidates` may not be deterministic:
509 // https://github.com/rust-lang/rust/pull/57475#issuecomment-455519507
510 normalized_impl_candidates.sort();
512 err.help(&format!("the following implementations were found:{}{}",
513 normalized_impl_candidates[..end].join(""),
515 format!("\nand {} others", len - 4)
522 /// Reports that an overflow has occurred and halts compilation. We
523 /// halt compilation unconditionally because it is important that
524 /// overflows never be masked -- they basically represent computations
525 /// whose result could not be truly determined and thus we can't say
526 /// if the program type checks or not -- and they are unusual
527 /// occurrences in any case.
528 pub fn report_overflow_error<T>(&self,
529 obligation: &Obligation<'tcx, T>,
530 suggest_increasing_limit: bool) -> !
531 where T: fmt::Display + TypeFoldable<'tcx>
534 self.resolve_vars_if_possible(&obligation.predicate);
535 let mut err = struct_span_err!(self.tcx.sess, obligation.cause.span, E0275,
536 "overflow evaluating the requirement `{}`",
539 if suggest_increasing_limit {
540 self.suggest_new_overflow_limit(&mut err);
543 self.note_obligation_cause(&mut err, obligation);
546 self.tcx.sess.abort_if_errors();
550 /// Reports that a cycle was detected which led to overflow and halts
551 /// compilation. This is equivalent to `report_overflow_error` except
552 /// that we can give a more helpful error message (and, in particular,
553 /// we do not suggest increasing the overflow limit, which is not
555 pub fn report_overflow_error_cycle(&self, cycle: &[PredicateObligation<'tcx>]) -> ! {
556 let cycle = self.resolve_vars_if_possible(&cycle.to_owned());
557 assert!(cycle.len() > 0);
559 debug!("report_overflow_error_cycle: cycle={:?}", cycle);
561 self.report_overflow_error(&cycle[0], false);
564 pub fn report_extra_impl_obligation(&self,
566 item_name: ast::Name,
567 _impl_item_def_id: DefId,
568 trait_item_def_id: DefId,
569 requirement: &dyn fmt::Display)
570 -> DiagnosticBuilder<'tcx>
572 let msg = "impl has stricter requirements than trait";
573 let sp = self.tcx.sess.source_map().def_span(error_span);
575 let mut err = struct_span_err!(self.tcx.sess, sp, E0276, "{}", msg);
577 if let Some(trait_item_span) = self.tcx.hir().span_if_local(trait_item_def_id) {
578 let span = self.tcx.sess.source_map().def_span(trait_item_span);
579 err.span_label(span, format!("definition of `{}` from trait", item_name));
582 err.span_label(sp, format!("impl has extra requirement {}", requirement));
588 /// Gets the parent trait chain start
589 fn get_parent_trait_ref(&self, code: &ObligationCauseCode<'tcx>) -> Option<String> {
591 &ObligationCauseCode::BuiltinDerivedObligation(ref data) => {
592 let parent_trait_ref = self.resolve_vars_if_possible(
593 &data.parent_trait_ref);
594 match self.get_parent_trait_ref(&data.parent_code) {
596 None => Some(parent_trait_ref.skip_binder().self_ty().to_string()),
603 pub fn report_selection_error(
605 obligation: &PredicateObligation<'tcx>,
606 error: &SelectionError<'tcx>,
607 fallback_has_occurred: bool,
609 let span = obligation.cause.span;
611 let mut err = match *error {
612 SelectionError::Unimplemented => {
613 if let ObligationCauseCode::CompareImplMethodObligation {
614 item_name, impl_item_def_id, trait_item_def_id,
615 } = obligation.cause.code {
616 self.report_extra_impl_obligation(
621 &format!("`{}`", obligation.predicate))
625 match obligation.predicate {
626 ty::Predicate::Trait(ref trait_predicate) => {
627 let trait_predicate =
628 self.resolve_vars_if_possible(trait_predicate);
630 if self.tcx.sess.has_errors() && trait_predicate.references_error() {
633 let trait_ref = trait_predicate.to_poly_trait_ref();
634 let (post_message, pre_message) =
635 self.get_parent_trait_ref(&obligation.cause.code)
636 .map(|t| (format!(" in `{}`", t), format!("within `{}`, ", t)))
637 .unwrap_or_default();
639 let OnUnimplementedNote { message, label, note }
640 = self.on_unimplemented_note(trait_ref, obligation);
641 let have_alt_message = message.is_some() || label.is_some();
642 let is_try = self.tcx.sess.source_map().span_to_snippet(span)
645 let is_from = format!("{}", trait_ref).starts_with("std::convert::From<");
646 let (message, note) = if is_try && is_from {
648 "`?` couldn't convert the error to `{}`",
651 "the question mark operation (`?`) implicitly performs a \
652 conversion on the error value using the `From` trait".to_owned()
658 let mut err = struct_span_err!(
663 message.unwrap_or_else(||
664 format!("the trait bound `{}` is not satisfied{}",
665 trait_ref.to_predicate(), post_message)
669 if obligation.cause.code == ObligationCauseCode::MainFunctionType {
670 "consider using `()`, or a `Result`".to_owned()
672 format!("{}the trait `{}` is not implemented for `{}`",
678 if let Some(ref s) = label {
679 // If it has a custom `#[rustc_on_unimplemented]`
680 // error message, let's display it as the label!
681 err.span_label(span, s.as_str());
682 err.help(&explanation);
684 err.span_label(span, explanation);
686 if let Some(ref s) = note {
687 // If it has a custom `#[rustc_on_unimplemented]` note, let's display it
688 err.note(s.as_str());
691 self.suggest_borrow_on_unsized_slice(&obligation.cause.code, &mut err);
692 self.suggest_remove_reference(&obligation, &mut err, &trait_ref);
693 self.suggest_semicolon_removal(&obligation, &mut err, span, &trait_ref);
695 // Try to report a help message
696 if !trait_ref.has_infer_types() &&
697 self.predicate_can_apply(obligation.param_env, trait_ref) {
698 // If a where-clause may be useful, remind the
699 // user that they can add it.
701 // don't display an on-unimplemented note, as
702 // these notes will often be of the form
703 // "the type `T` can't be frobnicated"
704 // which is somewhat confusing.
705 err.help(&format!("consider adding a `where {}` bound",
706 trait_ref.to_predicate()));
707 } else if !have_alt_message {
708 // Can't show anything else useful, try to find similar impls.
709 let impl_candidates = self.find_similar_impl_candidates(trait_ref);
710 self.report_similar_impl_candidates(impl_candidates, &mut err);
713 // If this error is due to `!: Trait` not implemented but `(): Trait` is
714 // implemented, and fallback has occurred, then it could be due to a
715 // variable that used to fallback to `()` now falling back to `!`. Issue a
716 // note informing about the change in behaviour.
717 if trait_predicate.skip_binder().self_ty().is_never()
718 && fallback_has_occurred
720 let predicate = trait_predicate.map_bound(|mut trait_pred| {
721 trait_pred.trait_ref.substs = self.tcx.mk_substs_trait(
723 &trait_pred.trait_ref.substs[1..],
727 let unit_obligation = Obligation {
728 predicate: ty::Predicate::Trait(predicate),
729 .. obligation.clone()
731 if self.predicate_may_hold(&unit_obligation) {
732 err.note("the trait is implemented for `()`. \
733 Possibly this error has been caused by changes to \
734 Rust's type-inference algorithm \
735 (see: https://github.com/rust-lang/rust/issues/48950 \
736 for more info). Consider whether you meant to use the \
737 type `()` here instead.");
744 ty::Predicate::Subtype(ref predicate) => {
745 // Errors for Subtype predicates show up as
746 // `FulfillmentErrorCode::CodeSubtypeError`,
747 // not selection error.
748 span_bug!(span, "subtype requirement gave wrong error: `{:?}`", predicate)
751 ty::Predicate::RegionOutlives(ref predicate) => {
752 let predicate = self.resolve_vars_if_possible(predicate);
753 let err = self.region_outlives_predicate(&obligation.cause,
754 &predicate).err().unwrap();
756 self.tcx.sess, span, E0279,
757 "the requirement `{}` is not satisfied (`{}`)",
762 ty::Predicate::Projection(..) | ty::Predicate::TypeOutlives(..) => {
764 self.resolve_vars_if_possible(&obligation.predicate);
765 struct_span_err!(self.tcx.sess, span, E0280,
766 "the requirement `{}` is not satisfied",
770 ty::Predicate::ObjectSafe(trait_def_id) => {
771 let violations = self.tcx.global_tcx()
772 .object_safety_violations(trait_def_id);
773 if let Some(err) = self.tcx.report_object_safety_error(
784 ty::Predicate::ClosureKind(closure_def_id, closure_substs, kind) => {
785 let found_kind = self.closure_kind(closure_def_id, closure_substs).unwrap();
786 let closure_span = self.tcx.sess.source_map()
787 .def_span(self.tcx.hir().span_if_local(closure_def_id).unwrap());
788 let hir_id = self.tcx.hir().as_local_hir_id(closure_def_id).unwrap();
789 let mut err = struct_span_err!(
790 self.tcx.sess, closure_span, E0525,
791 "expected a closure that implements the `{}` trait, \
792 but this closure only implements `{}`",
798 format!("this closure implements `{}`, not `{}`", found_kind, kind));
800 obligation.cause.span,
801 format!("the requirement to implement `{}` derives from here", kind));
803 // Additional context information explaining why the closure only implements
804 // a particular trait.
805 if let Some(tables) = self.in_progress_tables {
806 let tables = tables.borrow();
807 match (found_kind, tables.closure_kind_origins().get(hir_id)) {
808 (ty::ClosureKind::FnOnce, Some((span, name))) => {
809 err.span_label(*span, format!(
810 "closure is `FnOnce` because it moves the \
811 variable `{}` out of its environment", name));
813 (ty::ClosureKind::FnMut, Some((span, name))) => {
814 err.span_label(*span, format!(
815 "closure is `FnMut` because it mutates the \
816 variable `{}` here", name));
826 ty::Predicate::WellFormed(ty) => {
827 if !self.tcx.sess.opts.debugging_opts.chalk {
828 // WF predicates cannot themselves make
829 // errors. They can only block due to
830 // ambiguity; otherwise, they always
831 // degenerate into other obligations
833 span_bug!(span, "WF predicate not satisfied for {:?}", ty);
835 // FIXME: we'll need a better message which takes into account
836 // which bounds actually failed to hold.
837 self.tcx.sess.struct_span_err(
839 &format!("the type `{}` is not well-formed (chalk)", ty)
844 ty::Predicate::ConstEvaluatable(..) => {
845 // Errors for `ConstEvaluatable` predicates show up as
846 // `SelectionError::ConstEvalFailure`,
847 // not `Unimplemented`.
849 "const-evaluatable requirement gave wrong error: `{:?}`", obligation)
854 OutputTypeParameterMismatch(ref found_trait_ref, ref expected_trait_ref, _) => {
855 let found_trait_ref = self.resolve_vars_if_possible(&*found_trait_ref);
856 let expected_trait_ref = self.resolve_vars_if_possible(&*expected_trait_ref);
858 if expected_trait_ref.self_ty().references_error() {
862 let found_trait_ty = found_trait_ref.self_ty();
864 let found_did = match found_trait_ty.sty {
865 ty::Closure(did, _) | ty::Foreign(did) | ty::FnDef(did, _) => Some(did),
866 ty::Adt(def, _) => Some(def.did),
870 let found_span = found_did.and_then(|did|
871 self.tcx.hir().span_if_local(did)
872 ).map(|sp| self.tcx.sess.source_map().def_span(sp)); // the sp could be an fn def
874 let found = match found_trait_ref.skip_binder().substs.type_at(1).sty {
875 ty::Tuple(ref tys) => vec![ArgKind::empty(); tys.len()],
876 _ => vec![ArgKind::empty()],
879 let expected_ty = expected_trait_ref.skip_binder().substs.type_at(1);
880 let expected = match expected_ty.sty {
881 ty::Tuple(ref tys) => tys.iter()
882 .map(|t| ArgKind::from_expected_ty(t.expect_ty(), Some(span))).collect(),
883 _ => vec![ArgKind::Arg("_".to_owned(), expected_ty.to_string())],
886 if found.len() == expected.len() {
887 self.report_closure_arg_mismatch(span,
892 let (closure_span, found) = found_did
893 .and_then(|did| self.tcx.hir().get_if_local(did))
895 let (found_span, found) = self.get_fn_like_arguments(node);
896 (Some(found_span), found)
897 }).unwrap_or((found_span, found));
899 self.report_arg_count_mismatch(span,
903 found_trait_ty.is_closure())
907 TraitNotObjectSafe(did) => {
908 let violations = self.tcx.global_tcx().object_safety_violations(did);
909 if let Some(err) = self.tcx.report_object_safety_error(span, did, violations) {
916 // already reported in the query
917 ConstEvalFailure(err) => {
918 self.tcx.sess.delay_span_bug(
920 &format!("constant in type had an ignored error: {:?}", err),
926 bug!("overflow should be handled before the `report_selection_error` path");
929 self.note_obligation_cause(&mut err, obligation);
933 /// When encountering an assignment of an unsized trait, like `let x = ""[..];`, provide a
934 /// suggestion to borrow the initializer in order to use have a slice instead.
935 fn suggest_borrow_on_unsized_slice(
937 code: &ObligationCauseCode<'tcx>,
938 err: &mut DiagnosticBuilder<'tcx>,
940 if let &ObligationCauseCode::VariableType(hir_id) = code {
941 let parent_node = self.tcx.hir().get_parent_node(hir_id);
942 if let Some(Node::Local(ref local)) = self.tcx.hir().find(parent_node) {
943 if let Some(ref expr) = local.init {
944 if let hir::ExprKind::Index(_, _) = expr.node {
945 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(expr.span) {
948 "consider borrowing here",
949 format!("&{}", snippet),
950 Applicability::MachineApplicable
959 /// Whenever references are used by mistake, like `for (i, e) in &vec.iter().enumerate()`,
960 /// suggest removing these references until we reach a type that implements the trait.
961 fn suggest_remove_reference(
963 obligation: &PredicateObligation<'tcx>,
964 err: &mut DiagnosticBuilder<'tcx>,
965 trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
967 let trait_ref = trait_ref.skip_binder();
968 let span = obligation.cause.span;
970 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
971 let refs_number = snippet.chars()
972 .filter(|c| !c.is_whitespace())
973 .take_while(|c| *c == '&')
976 let mut trait_type = trait_ref.self_ty();
978 for refs_remaining in 0..refs_number {
979 if let ty::Ref(_, t_type, _) = trait_type.sty {
982 let substs = self.tcx.mk_substs_trait(trait_type, &[]);
983 let new_trait_ref = ty::TraitRef::new(trait_ref.def_id, substs);
984 let new_obligation = Obligation::new(ObligationCause::dummy(),
985 obligation.param_env,
986 new_trait_ref.to_predicate());
988 if self.predicate_may_hold(&new_obligation) {
989 let sp = self.tcx.sess.source_map()
990 .span_take_while(span, |c| c.is_whitespace() || *c == '&');
992 let remove_refs = refs_remaining + 1;
993 let format_str = format!("consider removing {} leading `&`-references",
996 err.span_suggestion_short(
997 sp, &format_str, String::new(), Applicability::MachineApplicable
1008 fn suggest_semicolon_removal(
1010 obligation: &PredicateObligation<'tcx>,
1011 err: &mut DiagnosticBuilder<'tcx>,
1013 trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
1015 let hir = self.tcx.hir();
1016 let parent_node = hir.get_parent_node(obligation.cause.body_id);
1017 let node = hir.find(parent_node);
1018 if let Some(hir::Node::Item(hir::Item {
1019 node: hir::ItemKind::Fn(decl, _, _, body_id),
1022 let body = hir.body(*body_id);
1023 if let hir::ExprKind::Block(blk, _) = &body.value.node {
1024 if decl.output.span().overlaps(span) && blk.expr.is_none() &&
1025 "()" == &trait_ref.self_ty().to_string()
1027 // FIXME(estebank): When encountering a method with a trait
1028 // bound not satisfied in the return type with a body that has
1029 // no return, suggest removal of semicolon on last statement.
1030 // Once that is added, close #54771.
1031 if let Some(ref stmt) = blk.stmts.last() {
1032 let sp = self.tcx.sess.source_map().end_point(stmt.span);
1033 err.span_label(sp, "consider removing this semicolon");
1040 /// Given some node representing a fn-like thing in the HIR map,
1041 /// returns a span and `ArgKind` information that describes the
1042 /// arguments it expects. This can be supplied to
1043 /// `report_arg_count_mismatch`.
1044 pub fn get_fn_like_arguments(&self, node: Node<'_>) -> (Span, Vec<ArgKind>) {
1046 Node::Expr(&hir::Expr {
1047 node: hir::ExprKind::Closure(_, ref _decl, id, span, _),
1050 (self.tcx.sess.source_map().def_span(span), self.tcx.hir().body(id).arguments.iter()
1053 node: hir::PatKind::Tuple(ref args, _),
1059 args.iter().map(|pat| {
1060 let snippet = self.tcx.sess.source_map()
1061 .span_to_snippet(pat.span).unwrap();
1062 (snippet, "_".to_owned())
1063 }).collect::<Vec<_>>(),
1066 let name = self.tcx.sess.source_map()
1067 .span_to_snippet(arg.pat.span).unwrap();
1068 ArgKind::Arg(name, "_".to_owned())
1071 .collect::<Vec<ArgKind>>())
1073 Node::Item(&hir::Item {
1075 node: hir::ItemKind::Fn(ref decl, ..),
1078 Node::ImplItem(&hir::ImplItem {
1080 node: hir::ImplItemKind::Method(hir::MethodSig { ref decl, .. }, _),
1083 Node::TraitItem(&hir::TraitItem {
1085 node: hir::TraitItemKind::Method(hir::MethodSig { ref decl, .. }, _),
1088 (self.tcx.sess.source_map().def_span(span), decl.inputs.iter()
1089 .map(|arg| match arg.clone().node {
1090 hir::TyKind::Tup(ref tys) => ArgKind::Tuple(
1092 vec![("_".to_owned(), "_".to_owned()); tys.len()]
1094 _ => ArgKind::empty()
1095 }).collect::<Vec<ArgKind>>())
1097 Node::Ctor(ref variant_data) => {
1098 let span = variant_data.ctor_hir_id()
1099 .map(|hir_id| self.tcx.hir().span(hir_id))
1100 .unwrap_or(DUMMY_SP);
1101 let span = self.tcx.sess.source_map().def_span(span);
1103 (span, vec![ArgKind::empty(); variant_data.fields().len()])
1105 _ => panic!("non-FnLike node found: {:?}", node),
1109 /// Reports an error when the number of arguments needed by a
1110 /// trait match doesn't match the number that the expression
1112 pub fn report_arg_count_mismatch(
1115 found_span: Option<Span>,
1116 expected_args: Vec<ArgKind>,
1117 found_args: Vec<ArgKind>,
1119 ) -> DiagnosticBuilder<'tcx> {
1120 let kind = if is_closure { "closure" } else { "function" };
1122 let args_str = |arguments: &[ArgKind], other: &[ArgKind]| {
1123 let arg_length = arguments.len();
1124 let distinct = match &other[..] {
1125 &[ArgKind::Tuple(..)] => true,
1128 match (arg_length, arguments.get(0)) {
1129 (1, Some(&ArgKind::Tuple(_, ref fields))) => {
1130 format!("a single {}-tuple as argument", fields.len())
1132 _ => format!("{} {}argument{}",
1134 if distinct && arg_length > 1 { "distinct " } else { "" },
1135 if arg_length == 1 { "" } else { "s" }),
1139 let expected_str = args_str(&expected_args, &found_args);
1140 let found_str = args_str(&found_args, &expected_args);
1142 let mut err = struct_span_err!(
1146 "{} is expected to take {}, but it takes {}",
1152 err.span_label(span, format!("expected {} that takes {}", kind, expected_str));
1154 if let Some(found_span) = found_span {
1155 err.span_label(found_span, format!("takes {}", found_str));
1158 // ^^^^^^^^-- def_span
1162 let prefix_span = self.tcx.sess.source_map().span_until_non_whitespace(found_span);
1165 let pipe_span = if let Some(span) = found_span.trim_start(prefix_span) {
1171 // Suggest to take and ignore the arguments with expected_args_length `_`s if
1172 // found arguments is empty (assume the user just wants to ignore args in this case).
1173 // For example, if `expected_args_length` is 2, suggest `|_, _|`.
1174 if found_args.is_empty() && is_closure {
1175 let underscores = vec!["_"; expected_args.len()].join(", ");
1176 err.span_suggestion(
1179 "consider changing the closure to take and ignore the expected argument{}",
1180 if expected_args.len() < 2 {
1186 format!("|{}|", underscores),
1187 Applicability::MachineApplicable,
1191 if let &[ArgKind::Tuple(_, ref fields)] = &found_args[..] {
1192 if fields.len() == expected_args.len() {
1193 let sugg = fields.iter()
1194 .map(|(name, _)| name.to_owned())
1195 .collect::<Vec<String>>()
1197 err.span_suggestion(
1199 "change the closure to take multiple arguments instead of a single tuple",
1200 format!("|{}|", sugg),
1201 Applicability::MachineApplicable,
1205 if let &[ArgKind::Tuple(_, ref fields)] = &expected_args[..] {
1206 if fields.len() == found_args.len() && is_closure {
1210 .map(|arg| match arg {
1211 ArgKind::Arg(name, _) => name.to_owned(),
1212 _ => "_".to_owned(),
1214 .collect::<Vec<String>>()
1216 // add type annotations if available
1217 if found_args.iter().any(|arg| match arg {
1218 ArgKind::Arg(_, ty) => ty != "_",
1223 .map(|(_, ty)| ty.to_owned())
1224 .collect::<Vec<String>>()
1230 err.span_suggestion(
1232 "change the closure to accept a tuple instead of individual arguments",
1234 Applicability::MachineApplicable,
1243 fn report_closure_arg_mismatch(
1246 found_span: Option<Span>,
1247 expected_ref: ty::PolyTraitRef<'tcx>,
1248 found: ty::PolyTraitRef<'tcx>,
1249 ) -> DiagnosticBuilder<'tcx> {
1250 fn build_fn_sig_string<'tcx>(tcx: TyCtxt<'tcx>, trait_ref: &ty::TraitRef<'tcx>) -> String {
1251 let inputs = trait_ref.substs.type_at(1);
1252 let sig = if let ty::Tuple(inputs) = inputs.sty {
1254 inputs.iter().map(|k| k.expect_ty()),
1255 tcx.mk_ty_infer(ty::TyVar(ty::TyVid { index: 0 })),
1257 hir::Unsafety::Normal,
1258 ::rustc_target::spec::abi::Abi::Rust
1262 ::std::iter::once(inputs),
1263 tcx.mk_ty_infer(ty::TyVar(ty::TyVid { index: 0 })),
1265 hir::Unsafety::Normal,
1266 ::rustc_target::spec::abi::Abi::Rust
1269 ty::Binder::bind(sig).to_string()
1272 let argument_is_closure = expected_ref.skip_binder().substs.type_at(0).is_closure();
1273 let mut err = struct_span_err!(self.tcx.sess, span, E0631,
1274 "type mismatch in {} arguments",
1275 if argument_is_closure { "closure" } else { "function" });
1277 let found_str = format!(
1278 "expected signature of `{}`",
1279 build_fn_sig_string(self.tcx, found.skip_binder())
1281 err.span_label(span, found_str);
1283 let found_span = found_span.unwrap_or(span);
1284 let expected_str = format!(
1285 "found signature of `{}`",
1286 build_fn_sig_string(self.tcx, expected_ref.skip_binder())
1288 err.span_label(found_span, expected_str);
1294 impl<'tcx> TyCtxt<'tcx> {
1295 pub fn recursive_type_with_infinite_size_error(self,
1297 -> DiagnosticBuilder<'tcx>
1299 assert!(type_def_id.is_local());
1300 let span = self.hir().span_if_local(type_def_id).unwrap();
1301 let span = self.sess.source_map().def_span(span);
1302 let mut err = struct_span_err!(self.sess, span, E0072,
1303 "recursive type `{}` has infinite size",
1304 self.def_path_str(type_def_id));
1305 err.span_label(span, "recursive type has infinite size");
1306 err.help(&format!("insert indirection (e.g., a `Box`, `Rc`, or `&`) \
1307 at some point to make `{}` representable",
1308 self.def_path_str(type_def_id)));
1312 pub fn report_object_safety_error(
1315 trait_def_id: DefId,
1316 violations: Vec<ObjectSafetyViolation>,
1317 ) -> Option<DiagnosticBuilder<'tcx>> {
1318 if self.sess.trait_methods_not_found.borrow().contains(&span) {
1319 // Avoid emitting error caused by non-existing method (#58734)
1322 let trait_str = self.def_path_str(trait_def_id);
1323 let span = self.sess.source_map().def_span(span);
1324 let mut err = struct_span_err!(
1325 self.sess, span, E0038,
1326 "the trait `{}` cannot be made into an object",
1328 err.span_label(span, format!("the trait `{}` cannot be made into an object", trait_str));
1330 let mut reported_violations = FxHashSet::default();
1331 for violation in violations {
1332 if reported_violations.insert(violation.clone()) {
1333 err.note(&violation.error_msg());
1340 impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
1341 fn maybe_report_ambiguity(&self, obligation: &PredicateObligation<'tcx>,
1342 body_id: Option<hir::BodyId>) {
1343 // Unable to successfully determine, probably means
1344 // insufficient type information, but could mean
1345 // ambiguous impls. The latter *ought* to be a
1346 // coherence violation, so we don't report it here.
1348 let predicate = self.resolve_vars_if_possible(&obligation.predicate);
1349 let span = obligation.cause.span;
1351 debug!("maybe_report_ambiguity(predicate={:?}, obligation={:?})",
1355 // Ambiguity errors are often caused as fallout from earlier
1356 // errors. So just ignore them if this infcx is tainted.
1357 if self.is_tainted_by_errors() {
1362 ty::Predicate::Trait(ref data) => {
1363 let trait_ref = data.to_poly_trait_ref();
1364 let self_ty = trait_ref.self_ty();
1365 if predicate.references_error() {
1368 // Typically, this ambiguity should only happen if
1369 // there are unresolved type inference variables
1370 // (otherwise it would suggest a coherence
1371 // failure). But given #21974 that is not necessarily
1372 // the case -- we can have multiple where clauses that
1373 // are only distinguished by a region, which results
1374 // in an ambiguity even when all types are fully
1375 // known, since we don't dispatch based on region
1378 // This is kind of a hack: it frequently happens that some earlier
1379 // error prevents types from being fully inferred, and then we get
1380 // a bunch of uninteresting errors saying something like "<generic
1381 // #0> doesn't implement Sized". It may even be true that we
1382 // could just skip over all checks where the self-ty is an
1383 // inference variable, but I was afraid that there might be an
1384 // inference variable created, registered as an obligation, and
1385 // then never forced by writeback, and hence by skipping here we'd
1386 // be ignoring the fact that we don't KNOW the type works
1387 // out. Though even that would probably be harmless, given that
1388 // we're only talking about builtin traits, which are known to be
1389 // inhabited. But in any case I just threw in this check for
1390 // has_errors() to be sure that compilation isn't happening
1391 // anyway. In that case, why inundate the user.
1392 if !self.tcx.sess.has_errors() {
1394 self.tcx.lang_items().sized_trait()
1395 .map_or(false, |sized_id| sized_id == trait_ref.def_id())
1397 self.need_type_info_err(body_id, span, self_ty).emit();
1399 let mut err = struct_span_err!(self.tcx.sess,
1401 "type annotations required: \
1402 cannot resolve `{}`",
1404 self.note_obligation_cause(&mut err, obligation);
1410 ty::Predicate::WellFormed(ty) => {
1411 // Same hacky approach as above to avoid deluging user
1412 // with error messages.
1413 if !ty.references_error() && !self.tcx.sess.has_errors() {
1414 self.need_type_info_err(body_id, span, ty).emit();
1418 ty::Predicate::Subtype(ref data) => {
1419 if data.references_error() || self.tcx.sess.has_errors() {
1420 // no need to overload user in such cases
1422 let &SubtypePredicate { a_is_expected: _, a, b } = data.skip_binder();
1423 // both must be type variables, or the other would've been instantiated
1424 assert!(a.is_ty_var() && b.is_ty_var());
1425 self.need_type_info_err(body_id,
1426 obligation.cause.span,
1432 if !self.tcx.sess.has_errors() {
1433 let mut err = struct_span_err!(self.tcx.sess,
1434 obligation.cause.span, E0284,
1435 "type annotations required: \
1436 cannot resolve `{}`",
1438 self.note_obligation_cause(&mut err, obligation);
1445 /// Returns `true` if the trait predicate may apply for *some* assignment
1446 /// to the type parameters.
1447 fn predicate_can_apply(
1449 param_env: ty::ParamEnv<'tcx>,
1450 pred: ty::PolyTraitRef<'tcx>,
1452 struct ParamToVarFolder<'a, 'tcx> {
1453 infcx: &'a InferCtxt<'a, 'tcx>,
1454 var_map: FxHashMap<Ty<'tcx>, Ty<'tcx>>,
1457 impl<'a, 'tcx> TypeFolder<'tcx> for ParamToVarFolder<'a, 'tcx> {
1458 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> { self.infcx.tcx }
1460 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1461 if let ty::Param(ty::ParamTy {name, .. }) = ty.sty {
1462 let infcx = self.infcx;
1463 self.var_map.entry(ty).or_insert_with(||
1465 TypeVariableOrigin {
1466 kind: TypeVariableOriginKind::TypeParameterDefinition(name),
1472 ty.super_fold_with(self)
1478 let mut selcx = SelectionContext::new(self);
1480 let cleaned_pred = pred.fold_with(&mut ParamToVarFolder {
1482 var_map: Default::default()
1485 let cleaned_pred = super::project::normalize(
1488 ObligationCause::dummy(),
1492 let obligation = Obligation::new(
1493 ObligationCause::dummy(),
1495 cleaned_pred.to_predicate()
1498 self.predicate_may_hold(&obligation)
1502 fn note_obligation_cause<T>(&self,
1503 err: &mut DiagnosticBuilder<'_>,
1504 obligation: &Obligation<'tcx, T>)
1505 where T: fmt::Display
1507 self.note_obligation_cause_code(err,
1508 &obligation.predicate,
1509 &obligation.cause.code,
1513 fn note_obligation_cause_code<T>(&self,
1514 err: &mut DiagnosticBuilder<'_>,
1516 cause_code: &ObligationCauseCode<'tcx>,
1517 obligated_types: &mut Vec<&ty::TyS<'tcx>>)
1518 where T: fmt::Display
1522 ObligationCauseCode::ExprAssignable |
1523 ObligationCauseCode::MatchExpressionArm { .. } |
1524 ObligationCauseCode::MatchExpressionArmPattern { .. } |
1525 ObligationCauseCode::IfExpression { .. } |
1526 ObligationCauseCode::IfExpressionWithNoElse |
1527 ObligationCauseCode::MainFunctionType |
1528 ObligationCauseCode::StartFunctionType |
1529 ObligationCauseCode::IntrinsicType |
1530 ObligationCauseCode::MethodReceiver |
1531 ObligationCauseCode::ReturnNoExpression |
1532 ObligationCauseCode::MiscObligation => {}
1533 ObligationCauseCode::SliceOrArrayElem => {
1534 err.note("slice and array elements must have `Sized` type");
1536 ObligationCauseCode::TupleElem => {
1537 err.note("only the last element of a tuple may have a dynamically sized type");
1539 ObligationCauseCode::ProjectionWf(data) => {
1540 err.note(&format!("required so that the projection `{}` is well-formed",
1543 ObligationCauseCode::ReferenceOutlivesReferent(ref_ty) => {
1544 err.note(&format!("required so that reference `{}` does not outlive its referent",
1547 ObligationCauseCode::ObjectTypeBound(object_ty, region) => {
1548 err.note(&format!("required so that the lifetime bound of `{}` for `{}` \
1550 region, object_ty));
1552 ObligationCauseCode::ItemObligation(item_def_id) => {
1553 let item_name = tcx.def_path_str(item_def_id);
1554 let msg = format!("required by `{}`", item_name);
1556 if let Some(sp) = tcx.hir().span_if_local(item_def_id) {
1557 let sp = tcx.sess.source_map().def_span(sp);
1558 err.span_note(sp, &msg);
1563 ObligationCauseCode::ObjectCastObligation(object_ty) => {
1564 err.note(&format!("required for the cast to the object type `{}`",
1565 self.ty_to_string(object_ty)));
1567 ObligationCauseCode::RepeatVec => {
1568 err.note("the `Copy` trait is required because the \
1569 repeated element will be copied");
1571 ObligationCauseCode::VariableType(_) => {
1572 err.note("all local variables must have a statically known size");
1573 if !self.tcx.features().unsized_locals {
1574 err.help("unsized locals are gated as an unstable feature");
1577 ObligationCauseCode::SizedArgumentType => {
1578 err.note("all function arguments must have a statically known size");
1579 if !self.tcx.features().unsized_locals {
1580 err.help("unsized locals are gated as an unstable feature");
1583 ObligationCauseCode::SizedReturnType => {
1584 err.note("the return type of a function must have a \
1585 statically known size");
1587 ObligationCauseCode::SizedYieldType => {
1588 err.note("the yield type of a generator must have a \
1589 statically known size");
1591 ObligationCauseCode::AssignmentLhsSized => {
1592 err.note("the left-hand-side of an assignment must have a statically known size");
1594 ObligationCauseCode::TupleInitializerSized => {
1595 err.note("tuples must have a statically known size to be initialized");
1597 ObligationCauseCode::StructInitializerSized => {
1598 err.note("structs must have a statically known size to be initialized");
1600 ObligationCauseCode::FieldSized { adt_kind: ref item, last } => {
1602 AdtKind::Struct => {
1604 err.note("the last field of a packed struct may only have a \
1605 dynamically sized type if it does not need drop to be run");
1607 err.note("only the last field of a struct may have a dynamically \
1612 err.note("no field of a union may have a dynamically sized type");
1615 err.note("no field of an enum variant may have a dynamically sized type");
1619 ObligationCauseCode::ConstSized => {
1620 err.note("constant expressions must have a statically known size");
1622 ObligationCauseCode::SharedStatic => {
1623 err.note("shared static variables must have a type that implements `Sync`");
1625 ObligationCauseCode::BuiltinDerivedObligation(ref data) => {
1626 let parent_trait_ref = self.resolve_vars_if_possible(&data.parent_trait_ref);
1627 let ty = parent_trait_ref.skip_binder().self_ty();
1628 err.note(&format!("required because it appears within the type `{}`", ty));
1629 obligated_types.push(ty);
1631 let parent_predicate = parent_trait_ref.to_predicate();
1632 if !self.is_recursive_obligation(obligated_types, &data.parent_code) {
1633 self.note_obligation_cause_code(err,
1639 ObligationCauseCode::ImplDerivedObligation(ref data) => {
1640 let parent_trait_ref = self.resolve_vars_if_possible(&data.parent_trait_ref);
1642 &format!("required because of the requirements on the impl of `{}` for `{}`",
1644 parent_trait_ref.skip_binder().self_ty()));
1645 let parent_predicate = parent_trait_ref.to_predicate();
1646 self.note_obligation_cause_code(err,
1651 ObligationCauseCode::CompareImplMethodObligation { .. } => {
1653 &format!("the requirement `{}` appears on the impl method \
1654 but not on the corresponding trait method",
1657 ObligationCauseCode::ReturnType(_) |
1658 ObligationCauseCode::BlockTailExpression(_) => (),
1659 ObligationCauseCode::TrivialBound => {
1660 err.help("see issue #48214");
1661 if tcx.sess.opts.unstable_features.is_nightly_build() {
1662 err.help("add #![feature(trivial_bounds)] to the \
1663 crate attributes to enable",
1670 fn suggest_new_overflow_limit(&self, err: &mut DiagnosticBuilder<'_>) {
1671 let current_limit = self.tcx.sess.recursion_limit.get();
1672 let suggested_limit = current_limit * 2;
1673 err.help(&format!("consider adding a `#![recursion_limit=\"{}\"]` attribute to your crate",
1677 fn is_recursive_obligation(&self,
1678 obligated_types: &mut Vec<&ty::TyS<'tcx>>,
1679 cause_code: &ObligationCauseCode<'tcx>) -> bool {
1680 if let ObligationCauseCode::BuiltinDerivedObligation(ref data) = cause_code {
1681 let parent_trait_ref = self.resolve_vars_if_possible(&data.parent_trait_ref);
1683 if obligated_types.iter().any(|ot| ot == &parent_trait_ref.skip_binder().self_ty()) {
1691 /// Summarizes information
1694 /// An argument of non-tuple type. Parameters are (name, ty)
1695 Arg(String, String),
1697 /// An argument of tuple type. For a "found" argument, the span is
1698 /// the locationo in the source of the pattern. For a "expected"
1699 /// argument, it will be None. The vector is a list of (name, ty)
1700 /// strings for the components of the tuple.
1701 Tuple(Option<Span>, Vec<(String, String)>),
1705 fn empty() -> ArgKind {
1706 ArgKind::Arg("_".to_owned(), "_".to_owned())
1709 /// Creates an `ArgKind` from the expected type of an
1710 /// argument. It has no name (`_`) and an optional source span.
1711 pub fn from_expected_ty(t: Ty<'_>, span: Option<Span>) -> ArgKind {
1713 ty::Tuple(ref tys) => ArgKind::Tuple(
1716 .map(|ty| ("_".to_owned(), ty.to_string()))
1717 .collect::<Vec<_>>()
1719 _ => ArgKind::Arg("_".to_owned(), t.to_string()),