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, pluralise};
39 use syntax::symbol::{sym, kw};
40 use syntax_pos::{DUMMY_SP, Span, ExpnKind, MultiSpan};
42 impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
43 pub fn report_fulfillment_errors(
45 errors: &[FulfillmentError<'tcx>],
46 body_id: Option<hir::BodyId>,
47 fallback_has_occurred: bool,
50 struct ErrorDescriptor<'tcx> {
51 predicate: ty::Predicate<'tcx>,
52 index: Option<usize>, // None if this is an old error
55 let mut error_map: FxHashMap<_, Vec<_>> =
56 self.reported_trait_errors.borrow().iter().map(|(&span, predicates)| {
57 (span, predicates.iter().map(|predicate| ErrorDescriptor {
58 predicate: predicate.clone(),
63 for (index, error) in errors.iter().enumerate() {
64 // We want to ignore desugarings here: spans are equivalent even
65 // if one is the result of a desugaring and the other is not.
66 let mut span = error.obligation.cause.span;
67 let expn_data = span.ctxt().outer_expn_data();
68 if let ExpnKind::Desugaring(_) = expn_data.kind {
69 span = expn_data.call_site;
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.
126 cond: &ty::Predicate<'tcx>,
127 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(
162 error: &FulfillmentError<'tcx>,
163 body_id: Option<hir::BodyId>,
164 fallback_has_occurred: bool,
166 debug!("report_fulfillment_errors({:?})", error);
168 FulfillmentErrorCode::CodeSelectionError(ref selection_error) => {
169 self.report_selection_error(
172 fallback_has_occurred,
173 error.points_at_arg_span,
176 FulfillmentErrorCode::CodeProjectionError(ref e) => {
177 self.report_projection_error(&error.obligation, e);
179 FulfillmentErrorCode::CodeAmbiguity => {
180 self.maybe_report_ambiguity(&error.obligation, body_id);
182 FulfillmentErrorCode::CodeSubtypeError(ref expected_found, ref err) => {
183 self.report_mismatched_types(
184 &error.obligation.cause,
185 expected_found.expected,
186 expected_found.found,
193 fn report_projection_error(
195 obligation: &PredicateObligation<'tcx>,
196 error: &MismatchedProjectionTypes<'tcx>,
199 self.resolve_vars_if_possible(&obligation.predicate);
201 if predicate.references_error() {
207 let mut err = &error.err;
208 let mut values = None;
210 // try to find the mismatched types to report the error with.
212 // this can fail if the problem was higher-ranked, in which
213 // cause I have no idea for a good error message.
214 if let ty::Predicate::Projection(ref data) = predicate {
215 let mut selcx = SelectionContext::new(self);
216 let (data, _) = self.replace_bound_vars_with_fresh_vars(
217 obligation.cause.span,
218 infer::LateBoundRegionConversionTime::HigherRankedType,
221 let mut obligations = vec![];
222 let normalized_ty = super::normalize_projection_type(
224 obligation.param_env,
226 obligation.cause.clone(),
230 if let Err(error) = self.at(&obligation.cause, obligation.param_env)
231 .eq(normalized_ty, data.ty) {
232 values = Some(infer::ValuePairs::Types(ExpectedFound {
233 expected: normalized_ty,
241 let msg = format!("type mismatch resolving `{}`", predicate);
242 let error_id = (DiagnosticMessageId::ErrorId(271),
243 Some(obligation.cause.span), msg);
244 let fresh = self.tcx.sess.one_time_diagnostics.borrow_mut().insert(error_id);
246 let mut diag = struct_span_err!(
247 self.tcx.sess, obligation.cause.span, E0271,
248 "type mismatch resolving `{}`", predicate
250 self.note_type_err(&mut diag, &obligation.cause, None, values, err);
251 self.note_obligation_cause(&mut diag, obligation);
257 fn fuzzy_match_tys(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
258 /// returns the fuzzy category of a given type, or None
259 /// if the type can be equated to any type.
260 fn type_category(t: Ty<'_>) -> Option<u32> {
265 ty::Int(..) | ty::Uint(..) | ty::Infer(ty::IntVar(..)) => Some(3),
266 ty::Float(..) | ty::Infer(ty::FloatVar(..)) => Some(4),
267 ty::Ref(..) | ty::RawPtr(..) => Some(5),
268 ty::Array(..) | ty::Slice(..) => Some(6),
269 ty::FnDef(..) | ty::FnPtr(..) => Some(7),
270 ty::Dynamic(..) => Some(8),
271 ty::Closure(..) => Some(9),
272 ty::Tuple(..) => Some(10),
273 ty::Projection(..) => Some(11),
274 ty::Param(..) => Some(12),
275 ty::Opaque(..) => Some(13),
276 ty::Never => Some(14),
277 ty::Adt(adt, ..) => match adt.adt_kind() {
278 AdtKind::Struct => Some(15),
279 AdtKind::Union => Some(16),
280 AdtKind::Enum => Some(17),
282 ty::Generator(..) => Some(18),
283 ty::Foreign(..) => Some(19),
284 ty::GeneratorWitness(..) => Some(20),
285 ty::Placeholder(..) | ty::Bound(..) | ty::Infer(..) | ty::Error => None,
286 ty::UnnormalizedProjection(..) => bug!("only used with chalk-engine"),
290 match (type_category(a), type_category(b)) {
291 (Some(cat_a), Some(cat_b)) => match (&a.kind, &b.kind) {
292 (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) => def_a == def_b,
295 // infer and error can be equated to all types
300 fn impl_similar_to(&self,
301 trait_ref: ty::PolyTraitRef<'tcx>,
302 obligation: &PredicateObligation<'tcx>)
306 let param_env = obligation.param_env;
307 let trait_ref = tcx.erase_late_bound_regions(&trait_ref);
308 let trait_self_ty = trait_ref.self_ty();
310 let mut self_match_impls = vec![];
311 let mut fuzzy_match_impls = vec![];
313 self.tcx.for_each_relevant_impl(
314 trait_ref.def_id, trait_self_ty, |def_id| {
315 let impl_substs = self.fresh_substs_for_item(obligation.cause.span, def_id);
316 let impl_trait_ref = tcx
317 .impl_trait_ref(def_id)
319 .subst(tcx, impl_substs);
321 let impl_self_ty = impl_trait_ref.self_ty();
323 if let Ok(..) = self.can_eq(param_env, trait_self_ty, impl_self_ty) {
324 self_match_impls.push(def_id);
326 if trait_ref.substs.types().skip(1)
327 .zip(impl_trait_ref.substs.types().skip(1))
328 .all(|(u,v)| self.fuzzy_match_tys(u, v))
330 fuzzy_match_impls.push(def_id);
335 let impl_def_id = if self_match_impls.len() == 1 {
337 } else if fuzzy_match_impls.len() == 1 {
343 if tcx.has_attr(impl_def_id, sym::rustc_on_unimplemented) {
350 fn on_unimplemented_note(
352 trait_ref: ty::PolyTraitRef<'tcx>,
353 obligation: &PredicateObligation<'tcx>,
354 ) -> OnUnimplementedNote {
355 let def_id = self.impl_similar_to(trait_ref, obligation)
356 .unwrap_or_else(|| trait_ref.def_id());
357 let trait_ref = *trait_ref.skip_binder();
359 let mut flags = vec![];
360 match obligation.cause.code {
361 ObligationCauseCode::BuiltinDerivedObligation(..) |
362 ObligationCauseCode::ImplDerivedObligation(..) => {}
364 // this is a "direct", user-specified, rather than derived,
366 flags.push((sym::direct, None));
370 if let ObligationCauseCode::ItemObligation(item) = obligation.cause.code {
371 // FIXME: maybe also have some way of handling methods
372 // from other traits? That would require name resolution,
373 // which we might want to be some sort of hygienic.
375 // Currently I'm leaving it for what I need for `try`.
376 if self.tcx.trait_of_item(item) == Some(trait_ref.def_id) {
377 let method = self.tcx.item_name(item);
378 flags.push((sym::from_method, None));
379 flags.push((sym::from_method, Some(method.to_string())));
382 if let Some(t) = self.get_parent_trait_ref(&obligation.cause.code) {
383 flags.push((sym::parent_trait, Some(t)));
386 if let Some(k) = obligation.cause.span.desugaring_kind() {
387 flags.push((sym::from_desugaring, None));
388 flags.push((sym::from_desugaring, Some(format!("{:?}", k))));
390 let generics = self.tcx.generics_of(def_id);
391 let self_ty = trait_ref.self_ty();
392 // This is also included through the generics list as `Self`,
393 // but the parser won't allow you to use it
394 flags.push((sym::_Self, Some(self_ty.to_string())));
395 if let Some(def) = self_ty.ty_adt_def() {
396 // We also want to be able to select self's original
397 // signature with no type arguments resolved
398 flags.push((sym::_Self, Some(self.tcx.type_of(def.did).to_string())));
401 for param in generics.params.iter() {
402 let value = match param.kind {
403 GenericParamDefKind::Type { .. } |
404 GenericParamDefKind::Const => {
405 trait_ref.substs[param.index as usize].to_string()
407 GenericParamDefKind::Lifetime => continue,
409 let name = param.name.as_symbol();
410 flags.push((name, Some(value)));
413 if let Some(true) = self_ty.ty_adt_def().map(|def| def.did.is_local()) {
414 flags.push((sym::crate_local, None));
417 // Allow targeting all integers using `{integral}`, even if the exact type was resolved
418 if self_ty.is_integral() {
419 flags.push((sym::_Self, Some("{integral}".to_owned())));
422 if let ty::Array(aty, len) = self_ty.kind {
423 flags.push((sym::_Self, Some("[]".to_owned())));
424 flags.push((sym::_Self, Some(format!("[{}]", aty))));
425 if let Some(def) = aty.ty_adt_def() {
426 // We also want to be able to select the array's type's original
427 // signature with no type arguments resolved
430 Some(format!("[{}]", self.tcx.type_of(def.did).to_string())),
433 if let Some(len) = len.try_eval_usize(tcx, ty::ParamEnv::empty()) {
436 Some(format!("[{}; {}]", self.tcx.type_of(def.did).to_string(), len)),
441 Some(format!("[{}; _]", self.tcx.type_of(def.did).to_string())),
447 if let Ok(Some(command)) = OnUnimplementedDirective::of_item(
448 self.tcx, trait_ref.def_id, def_id
450 command.evaluate(self.tcx, trait_ref, &flags[..])
452 OnUnimplementedNote::empty()
456 fn find_similar_impl_candidates(
458 trait_ref: ty::PolyTraitRef<'tcx>,
459 ) -> Vec<ty::TraitRef<'tcx>> {
460 let simp = fast_reject::simplify_type(self.tcx, trait_ref.skip_binder().self_ty(), true);
461 let all_impls = self.tcx.all_impls(trait_ref.def_id());
464 Some(simp) => all_impls.iter().filter_map(|&def_id| {
465 let imp = self.tcx.impl_trait_ref(def_id).unwrap();
466 let imp_simp = fast_reject::simplify_type(self.tcx, imp.self_ty(), true);
467 if let Some(imp_simp) = imp_simp {
468 if simp != imp_simp {
475 None => all_impls.iter().map(|&def_id|
476 self.tcx.impl_trait_ref(def_id).unwrap()
481 fn report_similar_impl_candidates(
483 impl_candidates: Vec<ty::TraitRef<'tcx>>,
484 err: &mut DiagnosticBuilder<'_>,
486 if impl_candidates.is_empty() {
490 let len = impl_candidates.len();
491 let end = if impl_candidates.len() <= 5 {
492 impl_candidates.len()
497 let normalize = |candidate| self.tcx.infer_ctxt().enter(|ref infcx| {
498 let normalized = infcx
499 .at(&ObligationCause::dummy(), ty::ParamEnv::empty())
500 .normalize(candidate)
503 Some(normalized) => format!("\n {:?}", normalized.value),
504 None => format!("\n {:?}", candidate),
508 // Sort impl candidates so that ordering is consistent for UI tests.
509 let mut normalized_impl_candidates = impl_candidates
512 .collect::<Vec<String>>();
514 // Sort before taking the `..end` range,
515 // because the ordering of `impl_candidates` may not be deterministic:
516 // https://github.com/rust-lang/rust/pull/57475#issuecomment-455519507
517 normalized_impl_candidates.sort();
519 err.help(&format!("the following implementations were found:{}{}",
520 normalized_impl_candidates[..end].join(""),
522 format!("\nand {} others", len - 4)
529 /// Reports that an overflow has occurred and halts compilation. We
530 /// halt compilation unconditionally because it is important that
531 /// overflows never be masked -- they basically represent computations
532 /// whose result could not be truly determined and thus we can't say
533 /// if the program type checks or not -- and they are unusual
534 /// occurrences in any case.
535 pub fn report_overflow_error<T>(&self,
536 obligation: &Obligation<'tcx, T>,
537 suggest_increasing_limit: bool) -> !
538 where T: fmt::Display + TypeFoldable<'tcx>
541 self.resolve_vars_if_possible(&obligation.predicate);
542 let mut err = struct_span_err!(self.tcx.sess, obligation.cause.span, E0275,
543 "overflow evaluating the requirement `{}`",
546 if suggest_increasing_limit {
547 self.suggest_new_overflow_limit(&mut err);
550 self.note_obligation_cause_code(&mut err, &obligation.predicate, &obligation.cause.code,
554 self.tcx.sess.abort_if_errors();
558 /// Reports that a cycle was detected which led to overflow and halts
559 /// compilation. This is equivalent to `report_overflow_error` except
560 /// that we can give a more helpful error message (and, in particular,
561 /// we do not suggest increasing the overflow limit, which is not
563 pub fn report_overflow_error_cycle(&self, cycle: &[PredicateObligation<'tcx>]) -> ! {
564 let cycle = self.resolve_vars_if_possible(&cycle.to_owned());
565 assert!(cycle.len() > 0);
567 debug!("report_overflow_error_cycle: cycle={:?}", cycle);
569 self.report_overflow_error(&cycle[0], false);
572 pub fn report_extra_impl_obligation(&self,
574 item_name: ast::Name,
575 _impl_item_def_id: DefId,
576 trait_item_def_id: DefId,
577 requirement: &dyn fmt::Display)
578 -> DiagnosticBuilder<'tcx>
580 let msg = "impl has stricter requirements than trait";
581 let sp = self.tcx.sess.source_map().def_span(error_span);
583 let mut err = struct_span_err!(self.tcx.sess, sp, E0276, "{}", msg);
585 if let Some(trait_item_span) = self.tcx.hir().span_if_local(trait_item_def_id) {
586 let span = self.tcx.sess.source_map().def_span(trait_item_span);
587 err.span_label(span, format!("definition of `{}` from trait", item_name));
590 err.span_label(sp, format!("impl has extra requirement {}", requirement));
596 /// Gets the parent trait chain start
597 fn get_parent_trait_ref(&self, code: &ObligationCauseCode<'tcx>) -> Option<String> {
599 &ObligationCauseCode::BuiltinDerivedObligation(ref data) => {
600 let parent_trait_ref = self.resolve_vars_if_possible(
601 &data.parent_trait_ref);
602 match self.get_parent_trait_ref(&data.parent_code) {
604 None => Some(parent_trait_ref.skip_binder().self_ty().to_string()),
611 pub fn report_selection_error(
613 obligation: &PredicateObligation<'tcx>,
614 error: &SelectionError<'tcx>,
615 fallback_has_occurred: bool,
618 let span = obligation.cause.span;
620 let mut err = match *error {
621 SelectionError::Unimplemented => {
622 if let ObligationCauseCode::CompareImplMethodObligation {
623 item_name, impl_item_def_id, trait_item_def_id,
624 } = obligation.cause.code {
625 self.report_extra_impl_obligation(
630 &format!("`{}`", obligation.predicate))
634 match obligation.predicate {
635 ty::Predicate::Trait(ref trait_predicate) => {
636 let trait_predicate =
637 self.resolve_vars_if_possible(trait_predicate);
639 if self.tcx.sess.has_errors() && trait_predicate.references_error() {
642 let trait_ref = trait_predicate.to_poly_trait_ref();
643 let (post_message, pre_message) =
644 self.get_parent_trait_ref(&obligation.cause.code)
645 .map(|t| (format!(" in `{}`", t), format!("within `{}`, ", t)))
646 .unwrap_or_default();
648 let OnUnimplementedNote { message, label, note }
649 = self.on_unimplemented_note(trait_ref, obligation);
650 let have_alt_message = message.is_some() || label.is_some();
651 let is_try = self.tcx.sess.source_map().span_to_snippet(span)
654 let is_from = format!("{}", trait_ref).starts_with("std::convert::From<");
655 let (message, note) = if is_try && is_from {
657 "`?` couldn't convert the error to `{}`",
660 "the question mark operation (`?`) implicitly performs a \
661 conversion on the error value using the `From` trait".to_owned()
667 let mut err = struct_span_err!(
672 message.unwrap_or_else(|| format!(
673 "the trait bound `{}` is not satisfied{}",
674 trait_ref.to_predicate(),
679 if obligation.cause.code == ObligationCauseCode::MainFunctionType {
680 "consider using `()`, or a `Result`".to_owned()
683 "{}the trait `{}` is not implemented for `{}`",
690 if let Some(ref s) = label {
691 // If it has a custom `#[rustc_on_unimplemented]`
692 // error message, let's display it as the label!
693 err.span_label(span, s.as_str());
694 err.help(&explanation);
696 err.span_label(span, explanation);
698 if let Some(ref s) = note {
699 // If it has a custom `#[rustc_on_unimplemented]` note, let's display it
700 err.note(s.as_str());
703 self.suggest_borrow_on_unsized_slice(&obligation.cause.code, &mut err);
704 self.suggest_fn_call(&obligation, &mut err, &trait_ref, points_at_arg);
705 self.suggest_remove_reference(&obligation, &mut err, &trait_ref);
706 self.suggest_semicolon_removal(&obligation, &mut err, span, &trait_ref);
708 // Try to report a help message
709 if !trait_ref.has_infer_types() &&
710 self.predicate_can_apply(obligation.param_env, trait_ref) {
711 // If a where-clause may be useful, remind the
712 // user that they can add it.
714 // don't display an on-unimplemented note, as
715 // these notes will often be of the form
716 // "the type `T` can't be frobnicated"
717 // which is somewhat confusing.
718 self.suggest_restricting_param_bound(
721 obligation.cause.body_id,
724 if !have_alt_message {
725 // Can't show anything else useful, try to find similar impls.
726 let impl_candidates = self.find_similar_impl_candidates(trait_ref);
727 self.report_similar_impl_candidates(impl_candidates, &mut err);
729 self.suggest_change_mut(
737 // If this error is due to `!: Trait` not implemented but `(): Trait` is
738 // implemented, and fallback has occurred, then it could be due to a
739 // variable that used to fallback to `()` now falling back to `!`. Issue a
740 // note informing about the change in behaviour.
741 if trait_predicate.skip_binder().self_ty().is_never()
742 && fallback_has_occurred
744 let predicate = trait_predicate.map_bound(|mut trait_pred| {
745 trait_pred.trait_ref.substs = self.tcx.mk_substs_trait(
747 &trait_pred.trait_ref.substs[1..],
751 let unit_obligation = Obligation {
752 predicate: ty::Predicate::Trait(predicate),
753 .. obligation.clone()
755 if self.predicate_may_hold(&unit_obligation) {
756 err.note("the trait is implemented for `()`. \
757 Possibly this error has been caused by changes to \
758 Rust's type-inference algorithm \
759 (see: https://github.com/rust-lang/rust/issues/48950 \
760 for more info). Consider whether you meant to use the \
761 type `()` here instead.");
768 ty::Predicate::Subtype(ref predicate) => {
769 // Errors for Subtype predicates show up as
770 // `FulfillmentErrorCode::CodeSubtypeError`,
771 // not selection error.
772 span_bug!(span, "subtype requirement gave wrong error: `{:?}`", predicate)
775 ty::Predicate::RegionOutlives(ref predicate) => {
776 let predicate = self.resolve_vars_if_possible(predicate);
777 let err = self.region_outlives_predicate(&obligation.cause,
778 &predicate).err().unwrap();
780 self.tcx.sess, span, E0279,
781 "the requirement `{}` is not satisfied (`{}`)",
786 ty::Predicate::Projection(..) | ty::Predicate::TypeOutlives(..) => {
788 self.resolve_vars_if_possible(&obligation.predicate);
789 struct_span_err!(self.tcx.sess, span, E0280,
790 "the requirement `{}` is not satisfied",
794 ty::Predicate::ObjectSafe(trait_def_id) => {
795 let violations = self.tcx.object_safety_violations(trait_def_id);
796 if let Some(err) = self.tcx.report_object_safety_error(
807 ty::Predicate::ClosureKind(closure_def_id, closure_substs, kind) => {
808 let found_kind = self.closure_kind(closure_def_id, closure_substs).unwrap();
809 let closure_span = self.tcx.sess.source_map()
810 .def_span(self.tcx.hir().span_if_local(closure_def_id).unwrap());
811 let hir_id = self.tcx.hir().as_local_hir_id(closure_def_id).unwrap();
812 let mut err = struct_span_err!(
813 self.tcx.sess, closure_span, E0525,
814 "expected a closure that implements the `{}` trait, \
815 but this closure only implements `{}`",
821 format!("this closure implements `{}`, not `{}`", found_kind, kind));
823 obligation.cause.span,
824 format!("the requirement to implement `{}` derives from here", kind));
826 // Additional context information explaining why the closure only implements
827 // a particular trait.
828 if let Some(tables) = self.in_progress_tables {
829 let tables = tables.borrow();
830 match (found_kind, tables.closure_kind_origins().get(hir_id)) {
831 (ty::ClosureKind::FnOnce, Some((span, name))) => {
832 err.span_label(*span, format!(
833 "closure is `FnOnce` because it moves the \
834 variable `{}` out of its environment", name));
836 (ty::ClosureKind::FnMut, Some((span, name))) => {
837 err.span_label(*span, format!(
838 "closure is `FnMut` because it mutates the \
839 variable `{}` here", name));
849 ty::Predicate::WellFormed(ty) => {
850 if !self.tcx.sess.opts.debugging_opts.chalk {
851 // WF predicates cannot themselves make
852 // errors. They can only block due to
853 // ambiguity; otherwise, they always
854 // degenerate into other obligations
856 span_bug!(span, "WF predicate not satisfied for {:?}", ty);
858 // FIXME: we'll need a better message which takes into account
859 // which bounds actually failed to hold.
860 self.tcx.sess.struct_span_err(
862 &format!("the type `{}` is not well-formed (chalk)", ty)
867 ty::Predicate::ConstEvaluatable(..) => {
868 // Errors for `ConstEvaluatable` predicates show up as
869 // `SelectionError::ConstEvalFailure`,
870 // not `Unimplemented`.
872 "const-evaluatable requirement gave wrong error: `{:?}`", obligation)
877 OutputTypeParameterMismatch(ref found_trait_ref, ref expected_trait_ref, _) => {
878 let found_trait_ref = self.resolve_vars_if_possible(&*found_trait_ref);
879 let expected_trait_ref = self.resolve_vars_if_possible(&*expected_trait_ref);
881 if expected_trait_ref.self_ty().references_error() {
885 let found_trait_ty = found_trait_ref.self_ty();
887 let found_did = match found_trait_ty.kind {
888 ty::Closure(did, _) | ty::Foreign(did) | ty::FnDef(did, _) => Some(did),
889 ty::Adt(def, _) => Some(def.did),
893 let found_span = found_did.and_then(|did|
894 self.tcx.hir().span_if_local(did)
895 ).map(|sp| self.tcx.sess.source_map().def_span(sp)); // the sp could be an fn def
897 if self.reported_closure_mismatch.borrow().contains(&(span, found_span)) {
898 // We check closures twice, with obligations flowing in different directions,
899 // but we want to complain about them only once.
903 self.reported_closure_mismatch.borrow_mut().insert((span, found_span));
905 let found = match found_trait_ref.skip_binder().substs.type_at(1).kind {
906 ty::Tuple(ref tys) => vec![ArgKind::empty(); tys.len()],
907 _ => vec![ArgKind::empty()],
910 let expected_ty = expected_trait_ref.skip_binder().substs.type_at(1);
911 let expected = match expected_ty.kind {
912 ty::Tuple(ref tys) => tys.iter()
913 .map(|t| ArgKind::from_expected_ty(t.expect_ty(), Some(span))).collect(),
914 _ => vec![ArgKind::Arg("_".to_owned(), expected_ty.to_string())],
917 if found.len() == expected.len() {
918 self.report_closure_arg_mismatch(span,
923 let (closure_span, found) = found_did
924 .and_then(|did| self.tcx.hir().get_if_local(did))
926 let (found_span, found) = self.get_fn_like_arguments(node);
927 (Some(found_span), found)
928 }).unwrap_or((found_span, found));
930 self.report_arg_count_mismatch(span,
934 found_trait_ty.is_closure())
938 TraitNotObjectSafe(did) => {
939 let violations = self.tcx.object_safety_violations(did);
940 if let Some(err) = self.tcx.report_object_safety_error(span, did, violations) {
947 // already reported in the query
948 ConstEvalFailure(err) => {
949 self.tcx.sess.delay_span_bug(
951 &format!("constant in type had an ignored error: {:?}", err),
957 bug!("overflow should be handled before the `report_selection_error` path");
961 self.note_obligation_cause(&mut err, obligation);
966 fn suggest_restricting_param_bound(
968 err: &mut DiagnosticBuilder<'_>,
969 trait_ref: &ty::PolyTraitRef<'_>,
972 let self_ty = trait_ref.self_ty();
973 let (param_ty, projection) = match &self_ty.kind {
974 ty::Param(_) => (true, None),
975 ty::Projection(projection) => (false, Some(projection)),
979 let mut suggest_restriction = |generics: &hir::Generics, msg| {
980 let span = generics.where_clause.span_for_predicates_or_empty_place();
981 if !span.from_expansion() && span.desugaring_kind().is_none() {
983 generics.where_clause.span_for_predicates_or_empty_place().shrink_to_hi(),
984 &format!("consider further restricting {}", msg),
987 if !generics.where_clause.predicates.is_empty() {
992 trait_ref.to_predicate(),
994 Applicability::MachineApplicable,
999 // FIXME: Add check for trait bound that is already present, particularly `?Sized` so we
1000 // don't suggest `T: Sized + ?Sized`.
1001 let mut hir_id = body_id;
1002 while let Some(node) = self.tcx.hir().find(hir_id) {
1004 hir::Node::TraitItem(hir::TraitItem {
1006 kind: hir::TraitItemKind::Method(..), ..
1007 }) if param_ty && self_ty == self.tcx.types.self_param => {
1008 // Restricting `Self` for a single method.
1009 suggest_restriction(&generics, "`Self`");
1013 hir::Node::Item(hir::Item {
1014 kind: hir::ItemKind::Fn(_, _, generics, _), ..
1016 hir::Node::TraitItem(hir::TraitItem {
1018 kind: hir::TraitItemKind::Method(..), ..
1020 hir::Node::ImplItem(hir::ImplItem {
1022 kind: hir::ImplItemKind::Method(..), ..
1024 hir::Node::Item(hir::Item {
1025 kind: hir::ItemKind::Trait(_, _, generics, _, _), ..
1027 hir::Node::Item(hir::Item {
1028 kind: hir::ItemKind::Impl(_, _, _, generics, ..), ..
1029 }) if projection.is_some() => {
1030 // Missing associated type bound.
1031 suggest_restriction(&generics, "the associated type");
1035 hir::Node::Item(hir::Item { kind: hir::ItemKind::Struct(_, generics), span, .. }) |
1036 hir::Node::Item(hir::Item { kind: hir::ItemKind::Enum(_, generics), span, .. }) |
1037 hir::Node::Item(hir::Item { kind: hir::ItemKind::Union(_, generics), span, .. }) |
1038 hir::Node::Item(hir::Item {
1039 kind: hir::ItemKind::Trait(_, _, generics, ..), span, ..
1041 hir::Node::Item(hir::Item {
1042 kind: hir::ItemKind::Impl(_, _, _, generics, ..), span, ..
1044 hir::Node::Item(hir::Item {
1045 kind: hir::ItemKind::Fn(_, _, generics, _), span, ..
1047 hir::Node::Item(hir::Item {
1048 kind: hir::ItemKind::TyAlias(_, generics), span, ..
1050 hir::Node::Item(hir::Item {
1051 kind: hir::ItemKind::TraitAlias(generics, _), span, ..
1053 hir::Node::Item(hir::Item {
1054 kind: hir::ItemKind::OpaqueTy(hir::OpaqueTy { generics, .. }), span, ..
1056 hir::Node::TraitItem(hir::TraitItem { generics, span, .. }) |
1057 hir::Node::ImplItem(hir::ImplItem { generics, span, .. })
1059 // Missing generic type parameter bound.
1060 let restrict_msg = "consider further restricting this bound";
1061 let param_name = self_ty.to_string();
1062 for param in generics.params.iter().filter(|p| {
1063 ¶m_name == std::convert::AsRef::<str>::as_ref(&p.name.ident().as_str())
1065 if param_name.starts_with("impl ") {
1066 // `impl Trait` in argument:
1067 // `fn foo(x: impl Trait) {}` → `fn foo(t: impl Trait + Trait2) {}`
1068 err.span_suggestion(
1071 // `impl CurrentTrait + MissingTrait`
1072 format!("{} + {}", param.name.ident(), trait_ref),
1073 Applicability::MachineApplicable,
1075 } else if generics.where_clause.predicates.is_empty() &&
1076 param.bounds.is_empty()
1078 // If there are no bounds whatsoever, suggest adding a constraint
1079 // to the type parameter:
1080 // `fn foo<T>(t: T) {}` → `fn foo<T: Trait>(t: T) {}`
1081 err.span_suggestion(
1083 "consider restricting this bound",
1084 format!("{}", trait_ref.to_predicate()),
1085 Applicability::MachineApplicable,
1087 } else if !generics.where_clause.predicates.is_empty() {
1088 // There is a `where` clause, so suggest expanding it:
1089 // `fn foo<T>(t: T) where T: Debug {}` →
1090 // `fn foo<T>(t: T) where T: Debug, T: Trait {}`
1091 err.span_suggestion(
1092 generics.where_clause.span().unwrap().shrink_to_hi(),
1094 "consider further restricting type parameter `{}`",
1097 format!(", {}", trait_ref.to_predicate()),
1098 Applicability::MachineApplicable,
1101 // If there is no `where` clause lean towards constraining to the
1103 // `fn foo<X: Bar, T>(t: T, x: X) {}` → `fn foo<T: Trait>(t: T) {}`
1104 // `fn foo<T: Bar>(t: T) {}` → `fn foo<T: Bar + Trait>(t: T) {}`
1105 let sp = param.span.with_hi(span.hi());
1106 let span = self.tcx.sess.source_map()
1107 .span_through_char(sp, ':');
1108 if sp != param.span && sp != span {
1109 // Only suggest if we have high certainty that the span
1110 // covers the colon in `foo<T: Trait>`.
1111 err.span_suggestion(span, restrict_msg, format!(
1113 trait_ref.to_predicate(),
1114 ), Applicability::MachineApplicable);
1116 err.span_label(param.span, &format!(
1117 "consider adding a `where {}` bound",
1118 trait_ref.to_predicate(),
1126 hir::Node::Crate => return,
1131 hir_id = self.tcx.hir().get_parent_item(hir_id);
1135 /// When encountering an assignment of an unsized trait, like `let x = ""[..];`, provide a
1136 /// suggestion to borrow the initializer in order to use have a slice instead.
1137 fn suggest_borrow_on_unsized_slice(
1139 code: &ObligationCauseCode<'tcx>,
1140 err: &mut DiagnosticBuilder<'tcx>,
1142 if let &ObligationCauseCode::VariableType(hir_id) = code {
1143 let parent_node = self.tcx.hir().get_parent_node(hir_id);
1144 if let Some(Node::Local(ref local)) = self.tcx.hir().find(parent_node) {
1145 if let Some(ref expr) = local.init {
1146 if let hir::ExprKind::Index(_, _) = expr.kind {
1147 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(expr.span) {
1148 err.span_suggestion(
1150 "consider borrowing here",
1151 format!("&{}", snippet),
1152 Applicability::MachineApplicable
1163 obligation: &PredicateObligation<'tcx>,
1164 err: &mut DiagnosticBuilder<'tcx>,
1165 trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
1166 points_at_arg: bool,
1168 let self_ty = trait_ref.self_ty();
1169 match self_ty.kind {
1170 ty::FnDef(def_id, _) => {
1171 // We tried to apply the bound to an `fn`. Check whether calling it would evaluate
1172 // to a type that *would* satisfy the trait binding. If it would, suggest calling
1173 // it: `bar(foo)` -> `bar(foo)`. This case is *very* likely to be hit if `foo` is
1175 let output_ty = self_ty.fn_sig(self.tcx).output();
1176 let new_trait_ref = ty::TraitRef {
1177 def_id: trait_ref.def_id(),
1178 substs: self.tcx.mk_substs_trait(output_ty.skip_binder(), &[]),
1180 let obligation = Obligation::new(
1181 obligation.cause.clone(),
1182 obligation.param_env,
1183 new_trait_ref.to_predicate(),
1185 match self.evaluate_obligation(&obligation) {
1186 Ok(EvaluationResult::EvaluatedToOk) |
1187 Ok(EvaluationResult::EvaluatedToOkModuloRegions) |
1188 Ok(EvaluationResult::EvaluatedToAmbig) => {
1189 if let Some(hir::Node::Item(hir::Item {
1191 kind: hir::ItemKind::Fn(.., body_id),
1193 })) = self.tcx.hir().get_if_local(def_id) {
1194 let body = self.tcx.hir().body(*body_id);
1195 let msg = "use parentheses to call the function";
1196 let snippet = format!(
1200 .map(|arg| match &arg.pat.kind {
1201 hir::PatKind::Binding(_, _, ident, None)
1202 if ident.name != kw::SelfLower => ident.to_string(),
1203 _ => "_".to_string(),
1204 }).collect::<Vec<_>>().join(", "),
1206 // When the obligation error has been ensured to have been caused by
1207 // an argument, the `obligation.cause.span` points at the expression
1208 // of the argument, so we can provide a suggestion. This is signaled
1209 // by `points_at_arg`. Otherwise, we give a more general note.
1211 err.span_suggestion(
1212 obligation.cause.span,
1215 Applicability::HasPlaceholders,
1218 err.help(&format!("{}: `{}`", msg, snippet));
1229 /// Whenever references are used by mistake, like `for (i, e) in &vec.iter().enumerate()`,
1230 /// suggest removing these references until we reach a type that implements the trait.
1231 fn suggest_remove_reference(
1233 obligation: &PredicateObligation<'tcx>,
1234 err: &mut DiagnosticBuilder<'tcx>,
1235 trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
1237 let trait_ref = trait_ref.skip_binder();
1238 let span = obligation.cause.span;
1240 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
1241 let refs_number = snippet.chars()
1242 .filter(|c| !c.is_whitespace())
1243 .take_while(|c| *c == '&')
1245 if let Some('\'') = snippet.chars()
1246 .filter(|c| !c.is_whitespace())
1249 { // Do not suggest removal of borrow from type arguments.
1253 let mut trait_type = trait_ref.self_ty();
1255 for refs_remaining in 0..refs_number {
1256 if let ty::Ref(_, t_type, _) = trait_type.kind {
1257 trait_type = t_type;
1259 let substs = self.tcx.mk_substs_trait(trait_type, &[]);
1260 let new_trait_ref = ty::TraitRef::new(trait_ref.def_id, substs);
1261 let new_obligation = Obligation::new(
1262 ObligationCause::dummy(),
1263 obligation.param_env,
1264 new_trait_ref.to_predicate(),
1267 if self.predicate_may_hold(&new_obligation) {
1268 let sp = self.tcx.sess.source_map()
1269 .span_take_while(span, |c| c.is_whitespace() || *c == '&');
1271 let remove_refs = refs_remaining + 1;
1272 let format_str = format!("consider removing {} leading `&`-references",
1275 err.span_suggestion_short(
1276 sp, &format_str, String::new(), Applicability::MachineApplicable
1287 /// Check if the trait bound is implemented for a different mutability and note it in the
1289 fn suggest_change_mut(
1291 obligation: &PredicateObligation<'tcx>,
1292 err: &mut DiagnosticBuilder<'tcx>,
1293 trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
1294 points_at_arg: bool,
1296 let span = obligation.cause.span;
1297 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
1298 let refs_number = snippet.chars()
1299 .filter(|c| !c.is_whitespace())
1300 .take_while(|c| *c == '&')
1302 if let Some('\'') = snippet.chars()
1303 .filter(|c| !c.is_whitespace())
1306 { // Do not suggest removal of borrow from type arguments.
1309 let trait_ref = self.resolve_vars_if_possible(trait_ref);
1310 if trait_ref.has_infer_types() {
1311 // Do not ICE while trying to find if a reborrow would succeed on a trait with
1312 // unresolved bindings.
1316 if let ty::Ref(region, t_type, mutability) = trait_ref.skip_binder().self_ty().kind {
1317 let trait_type = match mutability {
1318 hir::Mutability::MutMutable => self.tcx.mk_imm_ref(region, t_type),
1319 hir::Mutability::MutImmutable => self.tcx.mk_mut_ref(region, t_type),
1322 let substs = self.tcx.mk_substs_trait(&trait_type, &[]);
1323 let new_trait_ref = ty::TraitRef::new(trait_ref.skip_binder().def_id, substs);
1324 let new_obligation = Obligation::new(
1325 ObligationCause::dummy(),
1326 obligation.param_env,
1327 new_trait_ref.to_predicate(),
1330 if self.evaluate_obligation_no_overflow(
1332 ).must_apply_modulo_regions() {
1333 let sp = self.tcx.sess.source_map()
1334 .span_take_while(span, |c| c.is_whitespace() || *c == '&');
1336 mutability == hir::Mutability::MutImmutable &&
1339 err.span_suggestion(
1341 "consider changing this borrow's mutability",
1342 "&mut ".to_string(),
1343 Applicability::MachineApplicable,
1347 "`{}` is implemented for `{:?}`, but not for `{:?}`",
1350 trait_ref.skip_binder().self_ty(),
1358 fn suggest_semicolon_removal(
1360 obligation: &PredicateObligation<'tcx>,
1361 err: &mut DiagnosticBuilder<'tcx>,
1363 trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
1365 let hir = self.tcx.hir();
1366 let parent_node = hir.get_parent_node(obligation.cause.body_id);
1367 let node = hir.find(parent_node);
1368 if let Some(hir::Node::Item(hir::Item {
1369 kind: hir::ItemKind::Fn(decl, _, _, body_id),
1372 let body = hir.body(*body_id);
1373 if let hir::ExprKind::Block(blk, _) = &body.value.kind {
1374 if decl.output.span().overlaps(span) && blk.expr.is_none() &&
1375 "()" == &trait_ref.self_ty().to_string()
1377 // FIXME(estebank): When encountering a method with a trait
1378 // bound not satisfied in the return type with a body that has
1379 // no return, suggest removal of semicolon on last statement.
1380 // Once that is added, close #54771.
1381 if let Some(ref stmt) = blk.stmts.last() {
1382 let sp = self.tcx.sess.source_map().end_point(stmt.span);
1383 err.span_label(sp, "consider removing this semicolon");
1390 /// Given some node representing a fn-like thing in the HIR map,
1391 /// returns a span and `ArgKind` information that describes the
1392 /// arguments it expects. This can be supplied to
1393 /// `report_arg_count_mismatch`.
1394 pub fn get_fn_like_arguments(&self, node: Node<'_>) -> (Span, Vec<ArgKind>) {
1396 Node::Expr(&hir::Expr {
1397 kind: hir::ExprKind::Closure(_, ref _decl, id, span, _),
1400 (self.tcx.sess.source_map().def_span(span),
1401 self.tcx.hir().body(id).params.iter()
1404 kind: hir::PatKind::Tuple(ref args, _),
1410 args.iter().map(|pat| {
1411 let snippet = self.tcx.sess.source_map()
1412 .span_to_snippet(pat.span).unwrap();
1413 (snippet, "_".to_owned())
1414 }).collect::<Vec<_>>(),
1417 let name = self.tcx.sess.source_map()
1418 .span_to_snippet(arg.pat.span).unwrap();
1419 ArgKind::Arg(name, "_".to_owned())
1422 .collect::<Vec<ArgKind>>())
1424 Node::Item(&hir::Item {
1426 kind: hir::ItemKind::Fn(ref decl, ..),
1429 Node::ImplItem(&hir::ImplItem {
1431 kind: hir::ImplItemKind::Method(hir::MethodSig { ref decl, .. }, _),
1434 Node::TraitItem(&hir::TraitItem {
1436 kind: hir::TraitItemKind::Method(hir::MethodSig { ref decl, .. }, _),
1439 (self.tcx.sess.source_map().def_span(span), decl.inputs.iter()
1440 .map(|arg| match arg.clone().kind {
1441 hir::TyKind::Tup(ref tys) => ArgKind::Tuple(
1443 vec![("_".to_owned(), "_".to_owned()); tys.len()]
1445 _ => ArgKind::empty()
1446 }).collect::<Vec<ArgKind>>())
1448 Node::Ctor(ref variant_data) => {
1449 let span = variant_data.ctor_hir_id()
1450 .map(|hir_id| self.tcx.hir().span(hir_id))
1451 .unwrap_or(DUMMY_SP);
1452 let span = self.tcx.sess.source_map().def_span(span);
1454 (span, vec![ArgKind::empty(); variant_data.fields().len()])
1456 _ => panic!("non-FnLike node found: {:?}", node),
1460 /// Reports an error when the number of arguments needed by a
1461 /// trait match doesn't match the number that the expression
1463 pub fn report_arg_count_mismatch(
1466 found_span: Option<Span>,
1467 expected_args: Vec<ArgKind>,
1468 found_args: Vec<ArgKind>,
1470 ) -> DiagnosticBuilder<'tcx> {
1471 let kind = if is_closure { "closure" } else { "function" };
1473 let args_str = |arguments: &[ArgKind], other: &[ArgKind]| {
1474 let arg_length = arguments.len();
1475 let distinct = match &other[..] {
1476 &[ArgKind::Tuple(..)] => true,
1479 match (arg_length, arguments.get(0)) {
1480 (1, Some(&ArgKind::Tuple(_, ref fields))) => {
1481 format!("a single {}-tuple as argument", fields.len())
1483 _ => format!("{} {}argument{}",
1485 if distinct && arg_length > 1 { "distinct " } else { "" },
1486 pluralise!(arg_length))
1490 let expected_str = args_str(&expected_args, &found_args);
1491 let found_str = args_str(&found_args, &expected_args);
1493 let mut err = struct_span_err!(
1497 "{} is expected to take {}, but it takes {}",
1503 err.span_label(span, format!("expected {} that takes {}", kind, expected_str));
1505 if let Some(found_span) = found_span {
1506 err.span_label(found_span, format!("takes {}", found_str));
1509 // ^^^^^^^^-- def_span
1513 let prefix_span = self.tcx.sess.source_map().span_until_non_whitespace(found_span);
1516 let pipe_span = if let Some(span) = found_span.trim_start(prefix_span) {
1522 // Suggest to take and ignore the arguments with expected_args_length `_`s if
1523 // found arguments is empty (assume the user just wants to ignore args in this case).
1524 // For example, if `expected_args_length` is 2, suggest `|_, _|`.
1525 if found_args.is_empty() && is_closure {
1526 let underscores = vec!["_"; expected_args.len()].join(", ");
1527 err.span_suggestion(
1530 "consider changing the closure to take and ignore the expected argument{}",
1531 if expected_args.len() < 2 {
1537 format!("|{}|", underscores),
1538 Applicability::MachineApplicable,
1542 if let &[ArgKind::Tuple(_, ref fields)] = &found_args[..] {
1543 if fields.len() == expected_args.len() {
1544 let sugg = fields.iter()
1545 .map(|(name, _)| name.to_owned())
1546 .collect::<Vec<String>>()
1548 err.span_suggestion(
1550 "change the closure to take multiple arguments instead of a single tuple",
1551 format!("|{}|", sugg),
1552 Applicability::MachineApplicable,
1556 if let &[ArgKind::Tuple(_, ref fields)] = &expected_args[..] {
1557 if fields.len() == found_args.len() && is_closure {
1561 .map(|arg| match arg {
1562 ArgKind::Arg(name, _) => name.to_owned(),
1563 _ => "_".to_owned(),
1565 .collect::<Vec<String>>()
1567 // add type annotations if available
1568 if found_args.iter().any(|arg| match arg {
1569 ArgKind::Arg(_, ty) => ty != "_",
1574 .map(|(_, ty)| ty.to_owned())
1575 .collect::<Vec<String>>()
1581 err.span_suggestion(
1583 "change the closure to accept a tuple instead of individual arguments",
1585 Applicability::MachineApplicable,
1594 fn report_closure_arg_mismatch(
1597 found_span: Option<Span>,
1598 expected_ref: ty::PolyTraitRef<'tcx>,
1599 found: ty::PolyTraitRef<'tcx>,
1600 ) -> DiagnosticBuilder<'tcx> {
1601 fn build_fn_sig_string<'tcx>(tcx: TyCtxt<'tcx>, trait_ref: &ty::TraitRef<'tcx>) -> String {
1602 let inputs = trait_ref.substs.type_at(1);
1603 let sig = if let ty::Tuple(inputs) = inputs.kind {
1605 inputs.iter().map(|k| k.expect_ty()),
1606 tcx.mk_ty_infer(ty::TyVar(ty::TyVid { index: 0 })),
1608 hir::Unsafety::Normal,
1609 ::rustc_target::spec::abi::Abi::Rust
1613 ::std::iter::once(inputs),
1614 tcx.mk_ty_infer(ty::TyVar(ty::TyVid { index: 0 })),
1616 hir::Unsafety::Normal,
1617 ::rustc_target::spec::abi::Abi::Rust
1620 ty::Binder::bind(sig).to_string()
1623 let argument_is_closure = expected_ref.skip_binder().substs.type_at(0).is_closure();
1624 let mut err = struct_span_err!(self.tcx.sess, span, E0631,
1625 "type mismatch in {} arguments",
1626 if argument_is_closure { "closure" } else { "function" });
1628 let found_str = format!(
1629 "expected signature of `{}`",
1630 build_fn_sig_string(self.tcx, found.skip_binder())
1632 err.span_label(span, found_str);
1634 let found_span = found_span.unwrap_or(span);
1635 let expected_str = format!(
1636 "found signature of `{}`",
1637 build_fn_sig_string(self.tcx, expected_ref.skip_binder())
1639 err.span_label(found_span, expected_str);
1645 impl<'tcx> TyCtxt<'tcx> {
1646 pub fn recursive_type_with_infinite_size_error(self,
1648 -> DiagnosticBuilder<'tcx>
1650 assert!(type_def_id.is_local());
1651 let span = self.hir().span_if_local(type_def_id).unwrap();
1652 let span = self.sess.source_map().def_span(span);
1653 let mut err = struct_span_err!(self.sess, span, E0072,
1654 "recursive type `{}` has infinite size",
1655 self.def_path_str(type_def_id));
1656 err.span_label(span, "recursive type has infinite size");
1657 err.help(&format!("insert indirection (e.g., a `Box`, `Rc`, or `&`) \
1658 at some point to make `{}` representable",
1659 self.def_path_str(type_def_id)));
1663 pub fn report_object_safety_error(
1666 trait_def_id: DefId,
1667 violations: Vec<ObjectSafetyViolation>,
1668 ) -> Option<DiagnosticBuilder<'tcx>> {
1669 if self.sess.trait_methods_not_found.borrow().contains(&span) {
1670 // Avoid emitting error caused by non-existing method (#58734)
1673 let trait_str = self.def_path_str(trait_def_id);
1674 let span = self.sess.source_map().def_span(span);
1675 let mut err = struct_span_err!(
1676 self.sess, span, E0038,
1677 "the trait `{}` cannot be made into an object",
1679 err.span_label(span, format!("the trait `{}` cannot be made into an object", trait_str));
1681 let mut reported_violations = FxHashSet::default();
1682 for violation in violations {
1683 if reported_violations.insert(violation.clone()) {
1684 match violation.span() {
1685 Some(span) => err.span_label(span, violation.error_msg()),
1686 None => err.note(&violation.error_msg()),
1694 impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
1695 fn maybe_report_ambiguity(
1697 obligation: &PredicateObligation<'tcx>,
1698 body_id: Option<hir::BodyId>,
1700 // Unable to successfully determine, probably means
1701 // insufficient type information, but could mean
1702 // ambiguous impls. The latter *ought* to be a
1703 // coherence violation, so we don't report it here.
1705 let predicate = self.resolve_vars_if_possible(&obligation.predicate);
1706 let span = obligation.cause.span;
1709 "maybe_report_ambiguity(predicate={:?}, obligation={:?} body_id={:?}, code={:?})",
1713 obligation.cause.code,
1716 // Ambiguity errors are often caused as fallout from earlier
1717 // errors. So just ignore them if this infcx is tainted.
1718 if self.is_tainted_by_errors() {
1723 ty::Predicate::Trait(ref data) => {
1724 let trait_ref = data.to_poly_trait_ref();
1725 let self_ty = trait_ref.self_ty();
1726 debug!("self_ty {:?} {:?} trait_ref {:?}", self_ty, self_ty.kind, trait_ref);
1728 if predicate.references_error() {
1731 // Typically, this ambiguity should only happen if
1732 // there are unresolved type inference variables
1733 // (otherwise it would suggest a coherence
1734 // failure). But given #21974 that is not necessarily
1735 // the case -- we can have multiple where clauses that
1736 // are only distinguished by a region, which results
1737 // in an ambiguity even when all types are fully
1738 // known, since we don't dispatch based on region
1741 // This is kind of a hack: it frequently happens that some earlier
1742 // error prevents types from being fully inferred, and then we get
1743 // a bunch of uninteresting errors saying something like "<generic
1744 // #0> doesn't implement Sized". It may even be true that we
1745 // could just skip over all checks where the self-ty is an
1746 // inference variable, but I was afraid that there might be an
1747 // inference variable created, registered as an obligation, and
1748 // then never forced by writeback, and hence by skipping here we'd
1749 // be ignoring the fact that we don't KNOW the type works
1750 // out. Though even that would probably be harmless, given that
1751 // we're only talking about builtin traits, which are known to be
1752 // inhabited. We used to check for `self.tcx.sess.has_errors()` to
1753 // avoid inundating the user with unnecessary errors, but we now
1754 // check upstream for type errors and dont add the obligations to
1755 // begin with in those cases.
1757 self.tcx.lang_items().sized_trait()
1758 .map_or(false, |sized_id| sized_id == trait_ref.def_id())
1760 self.need_type_info_err(body_id, span, self_ty).emit();
1762 let mut err = struct_span_err!(
1766 "type annotations needed: cannot resolve `{}`",
1769 self.note_obligation_cause(&mut err, obligation);
1774 ty::Predicate::WellFormed(ty) => {
1775 // Same hacky approach as above to avoid deluging user
1776 // with error messages.
1777 if !ty.references_error() && !self.tcx.sess.has_errors() {
1778 self.need_type_info_err(body_id, span, ty).emit();
1782 ty::Predicate::Subtype(ref data) => {
1783 if data.references_error() || self.tcx.sess.has_errors() {
1784 // no need to overload user in such cases
1786 let &SubtypePredicate { a_is_expected: _, a, b } = data.skip_binder();
1787 // both must be type variables, or the other would've been instantiated
1788 assert!(a.is_ty_var() && b.is_ty_var());
1789 self.need_type_info_err(body_id,
1790 obligation.cause.span,
1796 if !self.tcx.sess.has_errors() {
1797 let mut err = struct_span_err!(
1799 obligation.cause.span,
1801 "type annotations needed: cannot resolve `{}`",
1804 self.note_obligation_cause(&mut err, obligation);
1811 /// Returns `true` if the trait predicate may apply for *some* assignment
1812 /// to the type parameters.
1813 fn predicate_can_apply(
1815 param_env: ty::ParamEnv<'tcx>,
1816 pred: ty::PolyTraitRef<'tcx>,
1818 struct ParamToVarFolder<'a, 'tcx> {
1819 infcx: &'a InferCtxt<'a, 'tcx>,
1820 var_map: FxHashMap<Ty<'tcx>, Ty<'tcx>>,
1823 impl<'a, 'tcx> TypeFolder<'tcx> for ParamToVarFolder<'a, 'tcx> {
1824 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> { self.infcx.tcx }
1826 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1827 if let ty::Param(ty::ParamTy {name, .. }) = ty.kind {
1828 let infcx = self.infcx;
1829 self.var_map.entry(ty).or_insert_with(||
1831 TypeVariableOrigin {
1832 kind: TypeVariableOriginKind::TypeParameterDefinition(name),
1838 ty.super_fold_with(self)
1844 let mut selcx = SelectionContext::new(self);
1846 let cleaned_pred = pred.fold_with(&mut ParamToVarFolder {
1848 var_map: Default::default()
1851 let cleaned_pred = super::project::normalize(
1854 ObligationCause::dummy(),
1858 let obligation = Obligation::new(
1859 ObligationCause::dummy(),
1861 cleaned_pred.to_predicate()
1864 self.predicate_may_hold(&obligation)
1868 fn note_obligation_cause(
1870 err: &mut DiagnosticBuilder<'_>,
1871 obligation: &PredicateObligation<'tcx>,
1873 // First, attempt to add note to this error with an async-await-specific
1874 // message, and fall back to regular note otherwise.
1875 if !self.note_obligation_cause_for_async_await(err, obligation) {
1876 self.note_obligation_cause_code(err, &obligation.predicate, &obligation.cause.code,
1881 /// Adds an async-await specific note to the diagnostic:
1883 /// ```ignore (diagnostic)
1884 /// note: future does not implement `std::marker::Send` because this value is used across an
1886 /// --> $DIR/issue-64130-non-send-future-diags.rs:15:5
1888 /// LL | let g = x.lock().unwrap();
1889 /// | - has type `std::sync::MutexGuard<'_, u32>`
1890 /// LL | baz().await;
1891 /// | ^^^^^^^^^^^ await occurs here, with `g` maybe used later
1893 /// | - `g` is later dropped here
1896 /// Returns `true` if an async-await specific note was added to the diagnostic.
1897 fn note_obligation_cause_for_async_await(
1899 err: &mut DiagnosticBuilder<'_>,
1900 obligation: &PredicateObligation<'tcx>,
1902 debug!("note_obligation_cause_for_async_await: obligation.predicate={:?} \
1903 obligation.cause.span={:?}", obligation.predicate, obligation.cause.span);
1904 let source_map = self.tcx.sess.source_map();
1906 // Look into the obligation predicate to determine the type in the generator which meant
1907 // that the predicate was not satisifed.
1908 let (trait_ref, target_ty) = match obligation.predicate {
1909 ty::Predicate::Trait(trait_predicate) =>
1910 (trait_predicate.skip_binder().trait_ref, trait_predicate.skip_binder().self_ty()),
1913 debug!("note_obligation_cause_for_async_await: target_ty={:?}", target_ty);
1915 // Attempt to detect an async-await error by looking at the obligation causes, looking
1916 // for only generators, generator witnesses, opaque types or `std::future::GenFuture` to
1919 // When a future does not implement a trait because of a captured type in one of the
1920 // generators somewhere in the call stack, then the result is a chain of obligations.
1921 // Given a `async fn` A that calls a `async fn` B which captures a non-send type and that
1922 // future is passed as an argument to a function C which requires a `Send` type, then the
1923 // chain looks something like this:
1925 // - `BuiltinDerivedObligation` with a generator witness (B)
1926 // - `BuiltinDerivedObligation` with a generator (B)
1927 // - `BuiltinDerivedObligation` with `std::future::GenFuture` (B)
1928 // - `BuiltinDerivedObligation` with `impl std::future::Future` (B)
1929 // - `BuiltinDerivedObligation` with `impl std::future::Future` (B)
1930 // - `BuiltinDerivedObligation` with a generator witness (A)
1931 // - `BuiltinDerivedObligation` with a generator (A)
1932 // - `BuiltinDerivedObligation` with `std::future::GenFuture` (A)
1933 // - `BuiltinDerivedObligation` with `impl std::future::Future` (A)
1934 // - `BuiltinDerivedObligation` with `impl std::future::Future` (A)
1935 // - `BindingObligation` with `impl_send (Send requirement)
1937 // The first obligations in the chain can be used to get the details of the type that is
1938 // captured but the entire chain must be inspected to detect this case.
1939 let mut generator = None;
1940 let mut next_code = Some(&obligation.cause.code);
1941 while let Some(code) = next_code {
1942 debug!("note_obligation_cause_for_async_await: code={:?}", code);
1944 ObligationCauseCode::BuiltinDerivedObligation(derived_obligation) |
1945 ObligationCauseCode::ImplDerivedObligation(derived_obligation) => {
1946 debug!("note_obligation_cause_for_async_await: self_ty.kind={:?}",
1947 derived_obligation.parent_trait_ref.self_ty().kind);
1948 match derived_obligation.parent_trait_ref.self_ty().kind {
1949 ty::Adt(ty::AdtDef { did, .. }, ..) if
1950 self.tcx.is_diagnostic_item(sym::gen_future, *did) => {},
1951 ty::Generator(did, ..) => generator = generator.or(Some(did)),
1952 ty::GeneratorWitness(_) | ty::Opaque(..) => {},
1956 next_code = Some(derived_obligation.parent_code.as_ref());
1958 ObligationCauseCode::ItemObligation(_) | ObligationCauseCode::BindingObligation(..)
1959 if generator.is_some() => break,
1964 let generator_did = generator.expect("can only reach this if there was a generator");
1966 // Only continue to add a note if the generator is from an `async` function.
1967 let parent_node = self.tcx.parent(generator_did)
1968 .and_then(|parent_did| self.tcx.hir().get_if_local(parent_did));
1969 debug!("note_obligation_cause_for_async_await: parent_node={:?}", parent_node);
1970 if let Some(hir::Node::Item(hir::Item {
1971 kind: hir::ItemKind::Fn(_, header, _, _),
1974 debug!("note_obligation_cause_for_async_await: header={:?}", header);
1975 if header.asyncness != hir::IsAsync::Async {
1980 let span = self.tcx.def_span(generator_did);
1981 let tables = self.tcx.typeck_tables_of(generator_did);
1982 debug!("note_obligation_cause_for_async_await: generator_did={:?} span={:?} ",
1983 generator_did, span);
1985 // Look for a type inside the generator interior that matches the target type to get
1987 let target_span = tables.generator_interior_types.iter()
1988 .find(|ty::GeneratorInteriorTypeCause { ty, .. }| ty::TyS::same_type(*ty, target_ty))
1989 .map(|ty::GeneratorInteriorTypeCause { span, scope_span, .. }|
1990 (span, source_map.span_to_snippet(*span), scope_span));
1991 if let Some((target_span, Ok(snippet), scope_span)) = target_span {
1992 // Look at the last interior type to get a span for the `.await`.
1993 let await_span = tables.generator_interior_types.iter().map(|i| i.span).last().unwrap();
1994 let mut span = MultiSpan::from_span(await_span);
1995 span.push_span_label(
1996 await_span, format!("await occurs here, with `{}` maybe used later", snippet));
1998 span.push_span_label(*target_span, format!("has type `{}`", target_ty));
2000 // If available, use the scope span to annotate the drop location.
2001 if let Some(scope_span) = scope_span {
2002 span.push_span_label(
2003 source_map.end_point(*scope_span),
2004 format!("`{}` is later dropped here", snippet),
2008 err.span_note(span, &format!(
2009 "future does not implement `{}` as this value is used across an await",
2013 // Add a note for the item obligation that remains - normally a note pointing to the
2014 // bound that introduced the obligation (e.g. `T: Send`).
2015 debug!("note_obligation_cause_for_async_await: next_code={:?}", next_code);
2016 self.note_obligation_cause_code(
2018 &obligation.predicate,
2029 fn note_obligation_cause_code<T>(&self,
2030 err: &mut DiagnosticBuilder<'_>,
2032 cause_code: &ObligationCauseCode<'tcx>,
2033 obligated_types: &mut Vec<&ty::TyS<'tcx>>)
2034 where T: fmt::Display
2038 ObligationCauseCode::ExprAssignable |
2039 ObligationCauseCode::MatchExpressionArm { .. } |
2040 ObligationCauseCode::MatchExpressionArmPattern { .. } |
2041 ObligationCauseCode::IfExpression { .. } |
2042 ObligationCauseCode::IfExpressionWithNoElse |
2043 ObligationCauseCode::MainFunctionType |
2044 ObligationCauseCode::StartFunctionType |
2045 ObligationCauseCode::IntrinsicType |
2046 ObligationCauseCode::MethodReceiver |
2047 ObligationCauseCode::ReturnNoExpression |
2048 ObligationCauseCode::MiscObligation => {}
2049 ObligationCauseCode::SliceOrArrayElem => {
2050 err.note("slice and array elements must have `Sized` type");
2052 ObligationCauseCode::TupleElem => {
2053 err.note("only the last element of a tuple may have a dynamically sized type");
2055 ObligationCauseCode::ProjectionWf(data) => {
2057 "required so that the projection `{}` is well-formed",
2061 ObligationCauseCode::ReferenceOutlivesReferent(ref_ty) => {
2063 "required so that reference `{}` does not outlive its referent",
2067 ObligationCauseCode::ObjectTypeBound(object_ty, region) => {
2069 "required so that the lifetime bound of `{}` for `{}` is satisfied",
2074 ObligationCauseCode::ItemObligation(item_def_id) => {
2075 let item_name = tcx.def_path_str(item_def_id);
2076 let msg = format!("required by `{}`", item_name);
2078 if let Some(sp) = tcx.hir().span_if_local(item_def_id) {
2079 let sp = tcx.sess.source_map().def_span(sp);
2080 err.span_label(sp, &msg);
2085 ObligationCauseCode::BindingObligation(item_def_id, span) => {
2086 let item_name = tcx.def_path_str(item_def_id);
2087 let msg = format!("required by this bound in `{}`", item_name);
2088 if let Some(ident) = tcx.opt_item_name(item_def_id) {
2089 err.span_label(ident.span, "");
2091 if span != DUMMY_SP {
2092 err.span_label(span, &msg);
2097 ObligationCauseCode::ObjectCastObligation(object_ty) => {
2098 err.note(&format!("required for the cast to the object type `{}`",
2099 self.ty_to_string(object_ty)));
2101 ObligationCauseCode::RepeatVec => {
2102 err.note("the `Copy` trait is required because the \
2103 repeated element will be copied");
2105 ObligationCauseCode::VariableType(_) => {
2106 err.note("all local variables must have a statically known size");
2107 if !self.tcx.features().unsized_locals {
2108 err.help("unsized locals are gated as an unstable feature");
2111 ObligationCauseCode::SizedArgumentType => {
2112 err.note("all function arguments must have a statically known size");
2113 if !self.tcx.features().unsized_locals {
2114 err.help("unsized locals are gated as an unstable feature");
2117 ObligationCauseCode::SizedReturnType => {
2118 err.note("the return type of a function must have a \
2119 statically known size");
2121 ObligationCauseCode::SizedYieldType => {
2122 err.note("the yield type of a generator must have a \
2123 statically known size");
2125 ObligationCauseCode::AssignmentLhsSized => {
2126 err.note("the left-hand-side of an assignment must have a statically known size");
2128 ObligationCauseCode::TupleInitializerSized => {
2129 err.note("tuples must have a statically known size to be initialized");
2131 ObligationCauseCode::StructInitializerSized => {
2132 err.note("structs must have a statically known size to be initialized");
2134 ObligationCauseCode::FieldSized { adt_kind: ref item, last } => {
2136 AdtKind::Struct => {
2138 err.note("the last field of a packed struct may only have a \
2139 dynamically sized type if it does not need drop to be run");
2141 err.note("only the last field of a struct may have a dynamically \
2146 err.note("no field of a union may have a dynamically sized type");
2149 err.note("no field of an enum variant may have a dynamically sized type");
2153 ObligationCauseCode::ConstSized => {
2154 err.note("constant expressions must have a statically known size");
2156 ObligationCauseCode::SharedStatic => {
2157 err.note("shared static variables must have a type that implements `Sync`");
2159 ObligationCauseCode::BuiltinDerivedObligation(ref data) => {
2160 let parent_trait_ref = self.resolve_vars_if_possible(&data.parent_trait_ref);
2161 let ty = parent_trait_ref.skip_binder().self_ty();
2162 err.note(&format!("required because it appears within the type `{}`", ty));
2163 obligated_types.push(ty);
2165 let parent_predicate = parent_trait_ref.to_predicate();
2166 if !self.is_recursive_obligation(obligated_types, &data.parent_code) {
2167 self.note_obligation_cause_code(err,
2173 ObligationCauseCode::ImplDerivedObligation(ref data) => {
2174 let parent_trait_ref = self.resolve_vars_if_possible(&data.parent_trait_ref);
2176 &format!("required because of the requirements on the impl of `{}` for `{}`",
2178 parent_trait_ref.skip_binder().self_ty()));
2179 let parent_predicate = parent_trait_ref.to_predicate();
2180 self.note_obligation_cause_code(err,
2185 ObligationCauseCode::CompareImplMethodObligation { .. } => {
2187 &format!("the requirement `{}` appears on the impl method \
2188 but not on the corresponding trait method",
2191 ObligationCauseCode::ReturnType |
2192 ObligationCauseCode::ReturnValue(_) |
2193 ObligationCauseCode::BlockTailExpression(_) => (),
2194 ObligationCauseCode::TrivialBound => {
2195 err.help("see issue #48214");
2196 if tcx.sess.opts.unstable_features.is_nightly_build() {
2197 err.help("add `#![feature(trivial_bounds)]` to the \
2198 crate attributes to enable",
2205 fn suggest_new_overflow_limit(&self, err: &mut DiagnosticBuilder<'_>) {
2206 let current_limit = self.tcx.sess.recursion_limit.get();
2207 let suggested_limit = current_limit * 2;
2208 err.help(&format!("consider adding a `#![recursion_limit=\"{}\"]` attribute to your crate",
2212 fn is_recursive_obligation(&self,
2213 obligated_types: &mut Vec<&ty::TyS<'tcx>>,
2214 cause_code: &ObligationCauseCode<'tcx>) -> bool {
2215 if let ObligationCauseCode::BuiltinDerivedObligation(ref data) = cause_code {
2216 let parent_trait_ref = self.resolve_vars_if_possible(&data.parent_trait_ref);
2218 if obligated_types.iter().any(|ot| ot == &parent_trait_ref.skip_binder().self_ty()) {
2226 /// Summarizes information
2229 /// An argument of non-tuple type. Parameters are (name, ty)
2230 Arg(String, String),
2232 /// An argument of tuple type. For a "found" argument, the span is
2233 /// the locationo in the source of the pattern. For a "expected"
2234 /// argument, it will be None. The vector is a list of (name, ty)
2235 /// strings for the components of the tuple.
2236 Tuple(Option<Span>, Vec<(String, String)>),
2240 fn empty() -> ArgKind {
2241 ArgKind::Arg("_".to_owned(), "_".to_owned())
2244 /// Creates an `ArgKind` from the expected type of an
2245 /// argument. It has no name (`_`) and an optional source span.
2246 pub fn from_expected_ty(t: Ty<'_>, span: Option<Span>) -> ArgKind {
2248 ty::Tuple(ref tys) => ArgKind::Tuple(
2251 .map(|ty| ("_".to_owned(), ty.to_string()))
2252 .collect::<Vec<_>>()
2254 _ => ArgKind::Arg("_".to_owned(), t.to_string()),