1 pub mod on_unimplemented;
5 ConstEvalFailure, EvaluationResult, FulfillmentError, FulfillmentErrorCode,
6 MismatchedProjectionTypes, ObjectSafetyViolation, Obligation, ObligationCause,
7 ObligationCauseCode, OnUnimplementedDirective, OnUnimplementedNote,
8 OutputTypeParameterMismatch, Overflow, PredicateObligation, SelectionContext, SelectionError,
12 use crate::infer::error_reporting::{TyCategory, TypeAnnotationNeeded as ErrorCode};
13 use crate::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
14 use crate::infer::{self, InferCtxt, TyCtxtInferExt};
15 use rustc::mir::interpret::ErrorHandled;
16 use rustc::session::DiagnosticMessageId;
17 use rustc::ty::error::ExpectedFound;
18 use rustc::ty::fast_reject;
19 use rustc::ty::fold::TypeFolder;
20 use rustc::ty::SubtypePredicate;
22 self, AdtKind, ToPolyTraitRef, ToPredicate, Ty, TyCtxt, TypeFoldable, WithConstness,
24 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
25 use rustc_errors::{struct_span_err, Applicability, DiagnosticBuilder};
27 use rustc_hir::def_id::{DefId, LOCAL_CRATE};
28 use rustc_hir::{QPath, TyKind, WhereBoundPredicate, WherePredicate};
29 use rustc_span::source_map::SourceMap;
30 use rustc_span::{ExpnKind, Span, DUMMY_SP};
34 impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
35 pub fn report_fulfillment_errors(
37 errors: &[FulfillmentError<'tcx>],
38 body_id: Option<hir::BodyId>,
39 fallback_has_occurred: bool,
42 struct ErrorDescriptor<'tcx> {
43 predicate: ty::Predicate<'tcx>,
44 index: Option<usize>, // None if this is an old error
47 let mut error_map: FxHashMap<_, Vec<_>> = self
48 .reported_trait_errors
51 .map(|(&span, predicates)| {
56 .map(|&predicate| ErrorDescriptor { predicate, index: None })
62 for (index, error) in errors.iter().enumerate() {
63 // We want to ignore desugarings here: spans are equivalent even
64 // if one is the result of a desugaring and the other is not.
65 let mut span = error.obligation.cause.span;
66 let expn_data = span.ctxt().outer_expn_data();
67 if let ExpnKind::Desugaring(_) = expn_data.kind {
68 span = expn_data.call_site;
71 error_map.entry(span).or_default().push(ErrorDescriptor {
72 predicate: error.obligation.predicate,
76 self.reported_trait_errors
80 .push(error.obligation.predicate.clone());
83 // We do this in 2 passes because we want to display errors in order, though
84 // maybe it *is* better to sort errors by span or something.
85 let mut is_suppressed = vec![false; errors.len()];
86 for (_, error_set) in error_map.iter() {
87 // We want to suppress "duplicate" errors with the same span.
88 for error in error_set {
89 if let Some(index) = error.index {
90 // Suppress errors that are either:
91 // 1) strictly implied by another error.
92 // 2) implied by an error with a smaller index.
93 for error2 in error_set {
94 if error2.index.map_or(false, |index2| is_suppressed[index2]) {
95 // Avoid errors being suppressed by already-suppressed
96 // errors, to prevent all errors from being suppressed
101 if self.error_implies(&error2.predicate, &error.predicate)
102 && !(error2.index >= error.index
103 && self.error_implies(&error.predicate, &error2.predicate))
105 info!("skipping {:?} (implied by {:?})", error, error2);
106 is_suppressed[index] = true;
114 for (error, suppressed) in errors.iter().zip(is_suppressed) {
116 self.report_fulfillment_error(error, body_id, fallback_has_occurred);
121 // returns if `cond` not occurring implies that `error` does not occur - i.e., that
122 // `error` occurring implies that `cond` occurs.
123 fn error_implies(&self, cond: &ty::Predicate<'tcx>, error: &ty::Predicate<'tcx>) -> bool {
128 let (cond, error) = match (cond, error) {
129 (&ty::Predicate::Trait(..), &ty::Predicate::Trait(ref error, _)) => (cond, error),
131 // FIXME: make this work in other cases too.
136 for implication in super::elaborate_predicates(self.tcx, vec![*cond]) {
137 if let ty::Predicate::Trait(implication, _) = implication {
138 let error = error.to_poly_trait_ref();
139 let implication = implication.to_poly_trait_ref();
140 // FIXME: I'm just not taking associated types at all here.
141 // Eventually I'll need to implement param-env-aware
142 // `Γ₁ ⊦ φ₁ => Γ₂ ⊦ φ₂` logic.
143 let param_env = ty::ParamEnv::empty();
144 if self.can_sub(param_env, error, implication).is_ok() {
145 debug!("error_implies: {:?} -> {:?} -> {:?}", cond, error, implication);
154 fn report_fulfillment_error(
156 error: &FulfillmentError<'tcx>,
157 body_id: Option<hir::BodyId>,
158 fallback_has_occurred: bool,
160 debug!("report_fulfillment_error({:?})", error);
162 FulfillmentErrorCode::CodeSelectionError(ref selection_error) => {
163 self.report_selection_error(
166 fallback_has_occurred,
167 error.points_at_arg_span,
170 FulfillmentErrorCode::CodeProjectionError(ref e) => {
171 self.report_projection_error(&error.obligation, e);
173 FulfillmentErrorCode::CodeAmbiguity => {
174 self.maybe_report_ambiguity(&error.obligation, body_id);
176 FulfillmentErrorCode::CodeSubtypeError(ref expected_found, ref err) => {
177 self.report_mismatched_types(
178 &error.obligation.cause,
179 expected_found.expected,
180 expected_found.found,
188 fn report_projection_error(
190 obligation: &PredicateObligation<'tcx>,
191 error: &MismatchedProjectionTypes<'tcx>,
193 let predicate = self.resolve_vars_if_possible(&obligation.predicate);
195 if predicate.references_error() {
201 let mut err = &error.err;
202 let mut values = None;
204 // try to find the mismatched types to report the error with.
206 // this can fail if the problem was higher-ranked, in which
207 // cause I have no idea for a good error message.
208 if let ty::Predicate::Projection(ref data) = predicate {
209 let mut selcx = SelectionContext::new(self);
210 let (data, _) = self.replace_bound_vars_with_fresh_vars(
211 obligation.cause.span,
212 infer::LateBoundRegionConversionTime::HigherRankedType,
215 let mut obligations = vec![];
216 let normalized_ty = super::normalize_projection_type(
218 obligation.param_env,
220 obligation.cause.clone(),
226 "report_projection_error obligation.cause={:?} obligation.param_env={:?}",
227 obligation.cause, obligation.param_env
231 "report_projection_error normalized_ty={:?} data.ty={:?}",
232 normalized_ty, data.ty
235 let is_normalized_ty_expected = match &obligation.cause.code {
236 ObligationCauseCode::ItemObligation(_)
237 | ObligationCauseCode::BindingObligation(_, _)
238 | ObligationCauseCode::ObjectCastObligation(_) => false,
242 if let Err(error) = self.at(&obligation.cause, obligation.param_env).eq_exp(
243 is_normalized_ty_expected,
247 values = Some(infer::ValuePairs::Types(ExpectedFound::new(
248 is_normalized_ty_expected,
258 let msg = format!("type mismatch resolving `{}`", predicate);
259 let error_id = (DiagnosticMessageId::ErrorId(271), Some(obligation.cause.span), msg);
260 let fresh = self.tcx.sess.one_time_diagnostics.borrow_mut().insert(error_id);
262 let mut diag = struct_span_err!(
264 obligation.cause.span,
266 "type mismatch resolving `{}`",
269 self.note_type_err(&mut diag, &obligation.cause, None, values, err);
270 self.note_obligation_cause(&mut diag, obligation);
276 fn fuzzy_match_tys(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
277 /// returns the fuzzy category of a given type, or None
278 /// if the type can be equated to any type.
279 fn type_category(t: Ty<'_>) -> Option<u32> {
284 ty::Int(..) | ty::Uint(..) | ty::Infer(ty::IntVar(..)) => Some(3),
285 ty::Float(..) | ty::Infer(ty::FloatVar(..)) => Some(4),
286 ty::Ref(..) | ty::RawPtr(..) => Some(5),
287 ty::Array(..) | ty::Slice(..) => Some(6),
288 ty::FnDef(..) | ty::FnPtr(..) => Some(7),
289 ty::Dynamic(..) => Some(8),
290 ty::Closure(..) => Some(9),
291 ty::Tuple(..) => Some(10),
292 ty::Projection(..) => Some(11),
293 ty::Param(..) => Some(12),
294 ty::Opaque(..) => Some(13),
295 ty::Never => Some(14),
296 ty::Adt(adt, ..) => match adt.adt_kind() {
297 AdtKind::Struct => Some(15),
298 AdtKind::Union => Some(16),
299 AdtKind::Enum => Some(17),
301 ty::Generator(..) => Some(18),
302 ty::Foreign(..) => Some(19),
303 ty::GeneratorWitness(..) => Some(20),
304 ty::Placeholder(..) | ty::Bound(..) | ty::Infer(..) | ty::Error => None,
305 ty::UnnormalizedProjection(..) => bug!("only used with chalk-engine"),
309 match (type_category(a), type_category(b)) {
310 (Some(cat_a), Some(cat_b)) => match (&a.kind, &b.kind) {
311 (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) => def_a == def_b,
314 // infer and error can be equated to all types
319 fn describe_generator(&self, body_id: hir::BodyId) -> Option<&'static str> {
320 self.tcx.hir().body(body_id).generator_kind.map(|gen_kind| match gen_kind {
321 hir::GeneratorKind::Gen => "a generator",
322 hir::GeneratorKind::Async(hir::AsyncGeneratorKind::Block) => "an async block",
323 hir::GeneratorKind::Async(hir::AsyncGeneratorKind::Fn) => "an async function",
324 hir::GeneratorKind::Async(hir::AsyncGeneratorKind::Closure) => "an async closure",
328 fn find_similar_impl_candidates(
330 trait_ref: ty::PolyTraitRef<'tcx>,
331 ) -> Vec<ty::TraitRef<'tcx>> {
332 let simp = fast_reject::simplify_type(self.tcx, trait_ref.skip_binder().self_ty(), true);
333 let all_impls = self.tcx.all_impls(trait_ref.def_id());
336 Some(simp) => all_impls
338 .filter_map(|&def_id| {
339 let imp = self.tcx.impl_trait_ref(def_id).unwrap();
340 let imp_simp = fast_reject::simplify_type(self.tcx, imp.self_ty(), true);
341 if let Some(imp_simp) = imp_simp {
342 if simp != imp_simp {
351 all_impls.iter().map(|&def_id| self.tcx.impl_trait_ref(def_id).unwrap()).collect()
356 fn report_similar_impl_candidates(
358 impl_candidates: Vec<ty::TraitRef<'tcx>>,
359 err: &mut DiagnosticBuilder<'_>,
361 if impl_candidates.is_empty() {
365 let len = impl_candidates.len();
366 let end = if impl_candidates.len() <= 5 { impl_candidates.len() } else { 4 };
368 let normalize = |candidate| {
369 self.tcx.infer_ctxt().enter(|ref infcx| {
370 let normalized = infcx
371 .at(&ObligationCause::dummy(), ty::ParamEnv::empty())
372 .normalize(candidate)
375 Some(normalized) => format!("\n {:?}", normalized.value),
376 None => format!("\n {:?}", candidate),
381 // Sort impl candidates so that ordering is consistent for UI tests.
382 let mut normalized_impl_candidates =
383 impl_candidates.iter().map(normalize).collect::<Vec<String>>();
385 // Sort before taking the `..end` range,
386 // because the ordering of `impl_candidates` may not be deterministic:
387 // https://github.com/rust-lang/rust/pull/57475#issuecomment-455519507
388 normalized_impl_candidates.sort();
391 "the following implementations were found:{}{}",
392 normalized_impl_candidates[..end].join(""),
393 if len > 5 { format!("\nand {} others", len - 4) } else { String::new() }
397 /// Reports that an overflow has occurred and halts compilation. We
398 /// halt compilation unconditionally because it is important that
399 /// overflows never be masked -- they basically represent computations
400 /// whose result could not be truly determined and thus we can't say
401 /// if the program type checks or not -- and they are unusual
402 /// occurrences in any case.
403 pub fn report_overflow_error<T>(
405 obligation: &Obligation<'tcx, T>,
406 suggest_increasing_limit: bool,
409 T: fmt::Display + TypeFoldable<'tcx>,
411 let predicate = self.resolve_vars_if_possible(&obligation.predicate);
412 let mut err = struct_span_err!(
414 obligation.cause.span,
416 "overflow evaluating the requirement `{}`",
420 if suggest_increasing_limit {
421 self.suggest_new_overflow_limit(&mut err);
424 self.note_obligation_cause_code(
426 &obligation.predicate,
427 &obligation.cause.code,
432 self.tcx.sess.abort_if_errors();
436 /// Reports that a cycle was detected which led to overflow and halts
437 /// compilation. This is equivalent to `report_overflow_error` except
438 /// that we can give a more helpful error message (and, in particular,
439 /// we do not suggest increasing the overflow limit, which is not
441 pub fn report_overflow_error_cycle(&self, cycle: &[PredicateObligation<'tcx>]) -> ! {
442 let cycle = self.resolve_vars_if_possible(&cycle.to_owned());
443 assert!(cycle.len() > 0);
445 debug!("report_overflow_error_cycle: cycle={:?}", cycle);
447 self.report_overflow_error(&cycle[0], false);
450 pub fn report_extra_impl_obligation(
453 item_name: ast::Name,
454 _impl_item_def_id: DefId,
455 trait_item_def_id: DefId,
456 requirement: &dyn fmt::Display,
457 ) -> DiagnosticBuilder<'tcx> {
458 let msg = "impl has stricter requirements than trait";
459 let sp = self.tcx.sess.source_map().def_span(error_span);
461 let mut err = struct_span_err!(self.tcx.sess, sp, E0276, "{}", msg);
463 if let Some(trait_item_span) = self.tcx.hir().span_if_local(trait_item_def_id) {
464 let span = self.tcx.sess.source_map().def_span(trait_item_span);
465 err.span_label(span, format!("definition of `{}` from trait", item_name));
468 err.span_label(sp, format!("impl has extra requirement {}", requirement));
473 /// Gets the parent trait chain start
474 fn get_parent_trait_ref(
476 code: &ObligationCauseCode<'tcx>,
477 ) -> Option<(String, Option<Span>)> {
479 &ObligationCauseCode::BuiltinDerivedObligation(ref data) => {
480 let parent_trait_ref = self.resolve_vars_if_possible(&data.parent_trait_ref);
481 match self.get_parent_trait_ref(&data.parent_code) {
484 let ty = parent_trait_ref.skip_binder().self_ty();
486 TyCategory::from_ty(ty).map(|(_, def_id)| self.tcx.def_span(def_id));
487 Some((ty.to_string(), span))
495 pub fn report_selection_error(
497 obligation: &PredicateObligation<'tcx>,
498 error: &SelectionError<'tcx>,
499 fallback_has_occurred: bool,
503 let span = obligation.cause.span;
505 let mut err = match *error {
506 SelectionError::Unimplemented => {
507 if let ObligationCauseCode::CompareImplMethodObligation {
512 | ObligationCauseCode::CompareImplTypeObligation {
516 } = obligation.cause.code
518 self.report_extra_impl_obligation(
523 &format!("`{}`", obligation.predicate),
528 match obligation.predicate {
529 ty::Predicate::Trait(ref trait_predicate, _) => {
530 let trait_predicate = self.resolve_vars_if_possible(trait_predicate);
532 if self.tcx.sess.has_errors() && trait_predicate.references_error() {
535 let trait_ref = trait_predicate.to_poly_trait_ref();
536 let (post_message, pre_message, type_def) = self
537 .get_parent_trait_ref(&obligation.cause.code)
540 format!(" in `{}`", t),
541 format!("within `{}`, ", t),
542 s.map(|s| (format!("within this `{}`", t), s)),
545 .unwrap_or_default();
547 let OnUnimplementedNote { message, label, note, enclosing_scope } =
548 self.on_unimplemented_note(trait_ref, obligation);
549 let have_alt_message = message.is_some() || label.is_some();
554 .span_to_snippet(span)
557 let is_from = format!("{}", trait_ref.print_only_trait_path())
558 .starts_with("std::convert::From<");
559 let (message, note) = if is_try && is_from {
562 "`?` couldn't convert the error to `{}`",
566 "the question mark operation (`?`) implicitly performs a \
567 conversion on the error value using the `From` trait"
575 let mut err = struct_span_err!(
580 message.unwrap_or_else(|| format!(
581 "the trait bound `{}` is not satisfied{}",
582 trait_ref.without_const().to_predicate(),
588 if obligation.cause.code == ObligationCauseCode::MainFunctionType {
589 "consider using `()`, or a `Result`".to_owned()
592 "{}the trait `{}` is not implemented for `{}`",
594 trait_ref.print_only_trait_path(),
599 if self.suggest_add_reference_to_arg(
606 self.note_obligation_cause(&mut err, obligation);
610 if let Some(ref s) = label {
611 // If it has a custom `#[rustc_on_unimplemented]`
612 // error message, let's display it as the label!
613 err.span_label(span, s.as_str());
614 err.help(&explanation);
616 err.span_label(span, explanation);
618 if let Some((msg, span)) = type_def {
619 err.span_label(span, &msg);
621 if let Some(ref s) = note {
622 // If it has a custom `#[rustc_on_unimplemented]` note, let's display it
623 err.note(s.as_str());
625 if let Some(ref s) = enclosing_scope {
626 let enclosing_scope_span = tcx.def_span(
628 .opt_local_def_id(obligation.cause.body_id)
630 tcx.hir().body_owner_def_id(hir::BodyId {
631 hir_id: obligation.cause.body_id,
636 err.span_label(enclosing_scope_span, s.as_str());
639 self.suggest_borrow_on_unsized_slice(&obligation.cause.code, &mut err);
640 self.suggest_fn_call(&obligation, &mut err, &trait_ref, points_at_arg);
641 self.suggest_remove_reference(&obligation, &mut err, &trait_ref);
642 self.suggest_semicolon_removal(&obligation, &mut err, span, &trait_ref);
643 self.note_version_mismatch(&mut err, &trait_ref);
644 if self.suggest_impl_trait(&mut err, span, &obligation, &trait_ref) {
649 // Try to report a help message
650 if !trait_ref.has_infer_types()
651 && self.predicate_can_apply(obligation.param_env, trait_ref)
653 // If a where-clause may be useful, remind the
654 // user that they can add it.
656 // don't display an on-unimplemented note, as
657 // these notes will often be of the form
658 // "the type `T` can't be frobnicated"
659 // which is somewhat confusing.
660 self.suggest_restricting_param_bound(
663 obligation.cause.body_id,
666 if !have_alt_message {
667 // Can't show anything else useful, try to find similar impls.
668 let impl_candidates = self.find_similar_impl_candidates(trait_ref);
669 self.report_similar_impl_candidates(impl_candidates, &mut err);
671 self.suggest_change_mut(
679 // If this error is due to `!: Trait` not implemented but `(): Trait` is
680 // implemented, and fallback has occurred, then it could be due to a
681 // variable that used to fallback to `()` now falling back to `!`. Issue a
682 // note informing about the change in behaviour.
683 if trait_predicate.skip_binder().self_ty().is_never()
684 && fallback_has_occurred
686 let predicate = trait_predicate.map_bound(|mut trait_pred| {
687 trait_pred.trait_ref.substs = self.tcx.mk_substs_trait(
689 &trait_pred.trait_ref.substs[1..],
693 let unit_obligation = Obligation {
694 predicate: ty::Predicate::Trait(
696 hir::Constness::NotConst,
700 if self.predicate_may_hold(&unit_obligation) {
702 "the trait is implemented for `()`. \
703 Possibly this error has been caused by changes to \
704 Rust's type-inference algorithm (see issue #48950 \
705 <https://github.com/rust-lang/rust/issues/48950> \
706 for more information). Consider whether you meant to use \
707 the type `()` here instead.",
715 ty::Predicate::Subtype(ref predicate) => {
716 // Errors for Subtype predicates show up as
717 // `FulfillmentErrorCode::CodeSubtypeError`,
718 // not selection error.
719 span_bug!(span, "subtype requirement gave wrong error: `{:?}`", predicate)
722 ty::Predicate::RegionOutlives(ref predicate) => {
723 let predicate = self.resolve_vars_if_possible(predicate);
725 .region_outlives_predicate(&obligation.cause, &predicate)
732 "the requirement `{}` is not satisfied (`{}`)",
738 ty::Predicate::Projection(..) | ty::Predicate::TypeOutlives(..) => {
739 let predicate = self.resolve_vars_if_possible(&obligation.predicate);
744 "the requirement `{}` is not satisfied",
749 ty::Predicate::ObjectSafe(trait_def_id) => {
750 let violations = self.tcx.object_safety_violations(trait_def_id);
751 report_object_safety_error(self.tcx, span, trait_def_id, violations)
754 ty::Predicate::ClosureKind(closure_def_id, closure_substs, kind) => {
755 let found_kind = self.closure_kind(closure_def_id, closure_substs).unwrap();
756 let closure_span = self
760 .def_span(self.tcx.hir().span_if_local(closure_def_id).unwrap());
761 let hir_id = self.tcx.hir().as_local_hir_id(closure_def_id).unwrap();
762 let mut err = struct_span_err!(
766 "expected a closure that implements the `{}` trait, \
767 but this closure only implements `{}`",
774 format!("this closure implements `{}`, not `{}`", found_kind, kind),
777 obligation.cause.span,
778 format!("the requirement to implement `{}` derives from here", kind),
781 // Additional context information explaining why the closure only implements
782 // a particular trait.
783 if let Some(tables) = self.in_progress_tables {
784 let tables = tables.borrow();
785 match (found_kind, tables.closure_kind_origins().get(hir_id)) {
786 (ty::ClosureKind::FnOnce, Some((span, name))) => {
790 "closure is `FnOnce` because it moves the \
791 variable `{}` out of its environment",
796 (ty::ClosureKind::FnMut, Some((span, name))) => {
800 "closure is `FnMut` because it mutates the \
814 ty::Predicate::WellFormed(ty) => {
815 if !self.tcx.sess.opts.debugging_opts.chalk {
816 // WF predicates cannot themselves make
817 // errors. They can only block due to
818 // ambiguity; otherwise, they always
819 // degenerate into other obligations
821 span_bug!(span, "WF predicate not satisfied for {:?}", ty);
823 // FIXME: we'll need a better message which takes into account
824 // which bounds actually failed to hold.
825 self.tcx.sess.struct_span_err(
827 &format!("the type `{}` is not well-formed (chalk)", ty),
832 ty::Predicate::ConstEvaluatable(..) => {
833 // Errors for `ConstEvaluatable` predicates show up as
834 // `SelectionError::ConstEvalFailure`,
835 // not `Unimplemented`.
838 "const-evaluatable requirement gave wrong error: `{:?}`",
845 OutputTypeParameterMismatch(ref found_trait_ref, ref expected_trait_ref, _) => {
846 let found_trait_ref = self.resolve_vars_if_possible(&*found_trait_ref);
847 let expected_trait_ref = self.resolve_vars_if_possible(&*expected_trait_ref);
849 if expected_trait_ref.self_ty().references_error() {
853 let found_trait_ty = found_trait_ref.self_ty();
855 let found_did = match found_trait_ty.kind {
856 ty::Closure(did, _) | ty::Foreign(did) | ty::FnDef(did, _) => Some(did),
857 ty::Adt(def, _) => Some(def.did),
861 let found_span = found_did
862 .and_then(|did| self.tcx.hir().span_if_local(did))
863 .map(|sp| self.tcx.sess.source_map().def_span(sp)); // the sp could be an fn def
865 if self.reported_closure_mismatch.borrow().contains(&(span, found_span)) {
866 // We check closures twice, with obligations flowing in different directions,
867 // but we want to complain about them only once.
871 self.reported_closure_mismatch.borrow_mut().insert((span, found_span));
873 let found = match found_trait_ref.skip_binder().substs.type_at(1).kind {
874 ty::Tuple(ref tys) => vec![ArgKind::empty(); tys.len()],
875 _ => vec![ArgKind::empty()],
878 let expected_ty = expected_trait_ref.skip_binder().substs.type_at(1);
879 let expected = match expected_ty.kind {
880 ty::Tuple(ref tys) => tys
882 .map(|t| ArgKind::from_expected_ty(t.expect_ty(), Some(span)))
884 _ => vec![ArgKind::Arg("_".to_owned(), expected_ty.to_string())],
887 if found.len() == expected.len() {
888 self.report_closure_arg_mismatch(
895 let (closure_span, found) = found_did
896 .and_then(|did| self.tcx.hir().get_if_local(did))
898 let (found_span, found) = self.get_fn_like_arguments(node);
899 (Some(found_span), found)
901 .unwrap_or((found_span, found));
903 self.report_arg_count_mismatch(
908 found_trait_ty.is_closure(),
913 TraitNotObjectSafe(did) => {
914 let violations = self.tcx.object_safety_violations(did);
915 report_object_safety_error(self.tcx, span, did, violations)
918 ConstEvalFailure(ErrorHandled::TooGeneric) => {
919 // In this instance, we have a const expression containing an unevaluated
920 // generic parameter. We have no idea whether this expression is valid or
921 // not (e.g. it might result in an error), but we don't want to just assume
922 // that it's okay, because that might result in post-monomorphisation time
923 // errors. The onus is really on the caller to provide values that it can
924 // prove are well-formed.
928 .struct_span_err(span, "constant expression depends on a generic parameter");
929 // FIXME(const_generics): we should suggest to the user how they can resolve this
930 // issue. However, this is currently not actually possible
931 // (see https://github.com/rust-lang/rust/issues/66962#issuecomment-575907083).
932 err.note("this may fail depending on what value the parameter takes");
936 // Already reported in the query.
937 ConstEvalFailure(ErrorHandled::Reported) => {
940 .delay_span_bug(span, &format!("constant in type had an ignored error"));
945 bug!("overflow should be handled before the `report_selection_error` path");
949 self.note_obligation_cause(&mut err, obligation);
950 self.point_at_returns_when_relevant(&mut err, &obligation);
955 /// If the `Self` type of the unsatisfied trait `trait_ref` implements a trait
956 /// with the same path as `trait_ref`, a help message about
957 /// a probable version mismatch is added to `err`
958 fn note_version_mismatch(
960 err: &mut DiagnosticBuilder<'_>,
961 trait_ref: &ty::PolyTraitRef<'tcx>,
963 let get_trait_impl = |trait_def_id| {
964 let mut trait_impl = None;
965 self.tcx.for_each_relevant_impl(trait_def_id, trait_ref.self_ty(), |impl_def_id| {
966 if trait_impl.is_none() {
967 trait_impl = Some(impl_def_id);
972 let required_trait_path = self.tcx.def_path_str(trait_ref.def_id());
973 let all_traits = self.tcx.all_traits(LOCAL_CRATE);
974 let traits_with_same_path: std::collections::BTreeSet<_> = all_traits
976 .filter(|trait_def_id| **trait_def_id != trait_ref.def_id())
977 .filter(|trait_def_id| self.tcx.def_path_str(**trait_def_id) == required_trait_path)
979 for trait_with_same_path in traits_with_same_path {
980 if let Some(impl_def_id) = get_trait_impl(*trait_with_same_path) {
981 let impl_span = self.tcx.def_span(impl_def_id);
982 err.span_help(impl_span, "trait impl with same name found");
983 let trait_crate = self.tcx.crate_name(trait_with_same_path.krate);
984 let crate_msg = format!(
985 "perhaps two different versions of crate `{}` are being used?",
988 err.note(&crate_msg);
993 fn mk_obligation_for_def_id(
997 cause: ObligationCause<'tcx>,
998 param_env: ty::ParamEnv<'tcx>,
999 ) -> PredicateObligation<'tcx> {
1001 ty::TraitRef { def_id, substs: self.tcx.mk_substs_trait(output_ty, &[]) };
1002 Obligation::new(cause, param_env, new_trait_ref.without_const().to_predicate())
1006 pub fn recursive_type_with_infinite_size_error(
1009 ) -> DiagnosticBuilder<'tcx> {
1010 assert!(type_def_id.is_local());
1011 let span = tcx.hir().span_if_local(type_def_id).unwrap();
1012 let span = tcx.sess.source_map().def_span(span);
1013 let mut err = struct_span_err!(
1017 "recursive type `{}` has infinite size",
1018 tcx.def_path_str(type_def_id)
1020 err.span_label(span, "recursive type has infinite size");
1022 "insert indirection (e.g., a `Box`, `Rc`, or `&`) \
1023 at some point to make `{}` representable",
1024 tcx.def_path_str(type_def_id)
1029 pub fn report_object_safety_error(
1032 trait_def_id: DefId,
1033 violations: Vec<ObjectSafetyViolation>,
1034 ) -> DiagnosticBuilder<'tcx> {
1035 let trait_str = tcx.def_path_str(trait_def_id);
1036 let trait_span = tcx.hir().get_if_local(trait_def_id).and_then(|node| match node {
1037 hir::Node::Item(item) => Some(item.ident.span),
1040 let span = tcx.sess.source_map().def_span(span);
1041 let mut err = struct_span_err!(
1045 "the trait `{}` cannot be made into an object",
1048 err.span_label(span, format!("the trait `{}` cannot be made into an object", trait_str));
1050 let mut reported_violations = FxHashSet::default();
1051 let mut had_span_label = false;
1052 for violation in violations {
1053 if let ObjectSafetyViolation::SizedSelf(sp) = &violation {
1055 // Do not report `SizedSelf` without spans pointing at `SizedSelf` obligations
1057 reported_violations.insert(ObjectSafetyViolation::SizedSelf(vec![].into()));
1060 if reported_violations.insert(violation.clone()) {
1061 let spans = violation.spans();
1062 let msg = if trait_span.is_none() || spans.is_empty() {
1063 format!("the trait cannot be made into an object because {}", violation.error_msg())
1065 had_span_label = true;
1066 format!("...because {}", violation.error_msg())
1068 if spans.is_empty() {
1072 err.span_label(span, &msg);
1075 match (trait_span, violation.solution()) {
1076 (Some(_), Some((note, None))) => {
1079 (Some(_), Some((note, Some((sugg, span))))) => {
1080 err.span_suggestion(span, ¬e, sugg, Applicability::MachineApplicable);
1082 // Only provide the help if its a local trait, otherwise it's not actionable.
1087 if let (Some(trait_span), true) = (trait_span, had_span_label) {
1088 err.span_label(trait_span, "this trait cannot be made into an object...");
1091 if tcx.sess.trait_methods_not_found.borrow().contains(&span) {
1092 // Avoid emitting error caused by non-existing method (#58734)
1099 impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
1100 fn maybe_report_ambiguity(
1102 obligation: &PredicateObligation<'tcx>,
1103 body_id: Option<hir::BodyId>,
1105 // Unable to successfully determine, probably means
1106 // insufficient type information, but could mean
1107 // ambiguous impls. The latter *ought* to be a
1108 // coherence violation, so we don't report it here.
1110 let predicate = self.resolve_vars_if_possible(&obligation.predicate);
1111 let span = obligation.cause.span;
1114 "maybe_report_ambiguity(predicate={:?}, obligation={:?} body_id={:?}, code={:?})",
1115 predicate, obligation, body_id, obligation.cause.code,
1118 // Ambiguity errors are often caused as fallout from earlier
1119 // errors. So just ignore them if this infcx is tainted.
1120 if self.is_tainted_by_errors() {
1124 let mut err = match predicate {
1125 ty::Predicate::Trait(ref data, _) => {
1126 let trait_ref = data.to_poly_trait_ref();
1127 let self_ty = trait_ref.self_ty();
1128 debug!("self_ty {:?} {:?} trait_ref {:?}", self_ty, self_ty.kind, trait_ref);
1130 if predicate.references_error() {
1133 // Typically, this ambiguity should only happen if
1134 // there are unresolved type inference variables
1135 // (otherwise it would suggest a coherence
1136 // failure). But given #21974 that is not necessarily
1137 // the case -- we can have multiple where clauses that
1138 // are only distinguished by a region, which results
1139 // in an ambiguity even when all types are fully
1140 // known, since we don't dispatch based on region
1143 // This is kind of a hack: it frequently happens that some earlier
1144 // error prevents types from being fully inferred, and then we get
1145 // a bunch of uninteresting errors saying something like "<generic
1146 // #0> doesn't implement Sized". It may even be true that we
1147 // could just skip over all checks where the self-ty is an
1148 // inference variable, but I was afraid that there might be an
1149 // inference variable created, registered as an obligation, and
1150 // then never forced by writeback, and hence by skipping here we'd
1151 // be ignoring the fact that we don't KNOW the type works
1152 // out. Though even that would probably be harmless, given that
1153 // we're only talking about builtin traits, which are known to be
1154 // inhabited. We used to check for `self.tcx.sess.has_errors()` to
1155 // avoid inundating the user with unnecessary errors, but we now
1156 // check upstream for type errors and dont add the obligations to
1157 // begin with in those cases.
1162 .map_or(false, |sized_id| sized_id == trait_ref.def_id())
1164 self.need_type_info_err(body_id, span, self_ty, ErrorCode::E0282).emit();
1167 let mut err = self.need_type_info_err(body_id, span, self_ty, ErrorCode::E0283);
1168 err.note(&format!("cannot resolve `{}`", predicate));
1169 if let ObligationCauseCode::ItemObligation(def_id) = obligation.cause.code {
1170 self.suggest_fully_qualified_path(&mut err, def_id, span, trait_ref.def_id());
1173 ObligationCauseCode::BindingObligation(ref def_id, _),
1175 (self.tcx.sess.source_map().span_to_snippet(span), &obligation.cause.code)
1177 let generics = self.tcx.generics_of(*def_id);
1178 if !generics.params.is_empty() && !snippet.ends_with('>') {
1179 // FIXME: To avoid spurious suggestions in functions where type arguments
1180 // where already supplied, we check the snippet to make sure it doesn't
1181 // end with a turbofish. Ideally we would have access to a `PathSegment`
1182 // instead. Otherwise we would produce the following output:
1184 // error[E0283]: type annotations needed
1185 // --> $DIR/issue-54954.rs:3:24
1187 // LL | const ARR_LEN: usize = Tt::const_val::<[i8; 123]>();
1188 // | ^^^^^^^^^^^^^^^^^^^^^^^^^^
1190 // | cannot infer type
1191 // | help: consider specifying the type argument
1192 // | in the function call:
1193 // | `Tt::const_val::<[i8; 123]>::<T>`
1195 // LL | const fn const_val<T: Sized>() -> usize {
1196 // | --------- - required by this bound in `Tt::const_val`
1198 // = note: cannot resolve `_: Tt`
1200 err.span_suggestion(
1203 "consider specifying the type argument{} in the function call",
1204 if generics.params.len() > 1 { "s" } else { "" },
1212 .map(|p| p.name.to_string())
1213 .collect::<Vec<String>>()
1216 Applicability::HasPlaceholders,
1223 ty::Predicate::WellFormed(ty) => {
1224 // Same hacky approach as above to avoid deluging user
1225 // with error messages.
1226 if ty.references_error() || self.tcx.sess.has_errors() {
1229 self.need_type_info_err(body_id, span, ty, ErrorCode::E0282)
1232 ty::Predicate::Subtype(ref data) => {
1233 if data.references_error() || self.tcx.sess.has_errors() {
1234 // no need to overload user in such cases
1237 let &SubtypePredicate { a_is_expected: _, a, b } = data.skip_binder();
1238 // both must be type variables, or the other would've been instantiated
1239 assert!(a.is_ty_var() && b.is_ty_var());
1240 self.need_type_info_err(body_id, span, a, ErrorCode::E0282)
1242 ty::Predicate::Projection(ref data) => {
1243 let trait_ref = data.to_poly_trait_ref(self.tcx);
1244 let self_ty = trait_ref.self_ty();
1245 if predicate.references_error() {
1248 let mut err = self.need_type_info_err(body_id, span, self_ty, ErrorCode::E0284);
1249 err.note(&format!("cannot resolve `{}`", predicate));
1254 if self.tcx.sess.has_errors() {
1257 let mut err = struct_span_err!(
1261 "type annotations needed: cannot resolve `{}`",
1264 err.span_label(span, &format!("cannot resolve `{}`", predicate));
1268 self.note_obligation_cause(&mut err, obligation);
1272 /// Returns `true` if the trait predicate may apply for *some* assignment
1273 /// to the type parameters.
1274 fn predicate_can_apply(
1276 param_env: ty::ParamEnv<'tcx>,
1277 pred: ty::PolyTraitRef<'tcx>,
1279 struct ParamToVarFolder<'a, 'tcx> {
1280 infcx: &'a InferCtxt<'a, 'tcx>,
1281 var_map: FxHashMap<Ty<'tcx>, Ty<'tcx>>,
1284 impl<'a, 'tcx> TypeFolder<'tcx> for ParamToVarFolder<'a, 'tcx> {
1285 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
1289 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1290 if let ty::Param(ty::ParamTy { name, .. }) = ty.kind {
1291 let infcx = self.infcx;
1292 self.var_map.entry(ty).or_insert_with(|| {
1293 infcx.next_ty_var(TypeVariableOrigin {
1294 kind: TypeVariableOriginKind::TypeParameterDefinition(name, None),
1299 ty.super_fold_with(self)
1305 let mut selcx = SelectionContext::new(self);
1308 pred.fold_with(&mut ParamToVarFolder { infcx: self, var_map: Default::default() });
1310 let cleaned_pred = super::project::normalize(
1313 ObligationCause::dummy(),
1318 let obligation = Obligation::new(
1319 ObligationCause::dummy(),
1321 cleaned_pred.without_const().to_predicate(),
1324 self.predicate_may_hold(&obligation)
1328 fn note_obligation_cause(
1330 err: &mut DiagnosticBuilder<'_>,
1331 obligation: &PredicateObligation<'tcx>,
1333 // First, attempt to add note to this error with an async-await-specific
1334 // message, and fall back to regular note otherwise.
1335 if !self.maybe_note_obligation_cause_for_async_await(err, obligation) {
1336 self.note_obligation_cause_code(
1338 &obligation.predicate,
1339 &obligation.cause.code,
1342 self.suggest_unsized_bound_if_applicable(err, obligation);
1346 fn suggest_unsized_bound_if_applicable(
1348 err: &mut DiagnosticBuilder<'_>,
1349 obligation: &PredicateObligation<'tcx>,
1352 ty::Predicate::Trait(pred, _),
1353 ObligationCauseCode::BindingObligation(item_def_id, span),
1354 ) = (&obligation.predicate, &obligation.cause.code)
1356 if let (Some(generics), true) = (
1357 self.tcx.hir().get_if_local(*item_def_id).as_ref().and_then(|n| n.generics()),
1358 Some(pred.def_id()) == self.tcx.lang_items().sized_trait(),
1360 for param in generics.params {
1361 if param.span == *span
1362 && !param.bounds.iter().any(|bound| {
1363 bound.trait_def_id() == self.tcx.lang_items().sized_trait()
1366 let (span, separator) = match param.bounds {
1367 [] => (span.shrink_to_hi(), ":"),
1368 [.., bound] => (bound.span().shrink_to_hi(), " + "),
1370 err.span_suggestion(
1372 "consider relaxing the implicit `Sized` restriction",
1373 format!("{} ?Sized", separator),
1374 Applicability::MachineApplicable,
1383 fn is_recursive_obligation(
1385 obligated_types: &mut Vec<&ty::TyS<'tcx>>,
1386 cause_code: &ObligationCauseCode<'tcx>,
1388 if let ObligationCauseCode::BuiltinDerivedObligation(ref data) = cause_code {
1389 let parent_trait_ref = self.resolve_vars_if_possible(&data.parent_trait_ref);
1391 if obligated_types.iter().any(|ot| ot == &parent_trait_ref.skip_binder().self_ty()) {
1399 /// Summarizes information
1402 /// An argument of non-tuple type. Parameters are (name, ty)
1403 Arg(String, String),
1405 /// An argument of tuple type. For a "found" argument, the span is
1406 /// the locationo in the source of the pattern. For a "expected"
1407 /// argument, it will be None. The vector is a list of (name, ty)
1408 /// strings for the components of the tuple.
1409 Tuple(Option<Span>, Vec<(String, String)>),
1413 fn empty() -> ArgKind {
1414 ArgKind::Arg("_".to_owned(), "_".to_owned())
1417 /// Creates an `ArgKind` from the expected type of an
1418 /// argument. It has no name (`_`) and an optional source span.
1419 pub fn from_expected_ty(t: Ty<'_>, span: Option<Span>) -> ArgKind {
1421 ty::Tuple(ref tys) => ArgKind::Tuple(
1423 tys.iter().map(|ty| ("_".to_owned(), ty.to_string())).collect::<Vec<_>>(),
1425 _ => ArgKind::Arg("_".to_owned(), t.to_string()),
1430 /// Suggest restricting a type param with a new bound.
1431 pub fn suggest_constraining_type_param(
1433 generics: &hir::Generics<'_>,
1434 err: &mut DiagnosticBuilder<'_>,
1437 source_map: &SourceMap,
1439 def_id: Option<DefId>,
1441 const MSG_RESTRICT_BOUND_FURTHER: &str = "consider further restricting this bound with";
1442 const MSG_RESTRICT_TYPE: &str = "consider restricting this type parameter with";
1443 const MSG_RESTRICT_TYPE_FURTHER: &str = "consider further restricting this type parameter with";
1445 let param = generics.params.iter().find(|p| p.name.ident().as_str() == param_name);
1447 let param = if let Some(param) = param {
1453 if def_id == tcx.lang_items().sized_trait() {
1454 // Type parameters are already `Sized` by default.
1455 err.span_label(param.span, &format!("this type parameter needs to be `{}`", constraint));
1459 if param_name.starts_with("impl ") {
1460 // If there's an `impl Trait` used in argument position, suggest
1463 // fn foo(t: impl Foo) { ... }
1466 // help: consider further restricting this bound with `+ Bar`
1468 // Suggestion for tools in this case is:
1470 // fn foo(t: impl Foo) { ... }
1473 // replace with: `impl Foo + Bar`
1475 err.span_help(param.span, &format!("{} `+ {}`", MSG_RESTRICT_BOUND_FURTHER, constraint));
1477 err.tool_only_span_suggestion(
1479 MSG_RESTRICT_BOUND_FURTHER,
1480 format!("{} + {}", param_name, constraint),
1481 Applicability::MachineApplicable,
1487 if generics.where_clause.predicates.is_empty() {
1488 if let Some(bounds_span) = param.bounds_span() {
1489 // If user has provided some bounds, suggest restricting them:
1491 // fn foo<T: Foo>(t: T) { ... }
1494 // help: consider further restricting this bound with `+ Bar`
1496 // Suggestion for tools in this case is:
1498 // fn foo<T: Foo>(t: T) { ... }
1501 // replace with: `T: Bar +`
1505 &format!("{} `+ {}`", MSG_RESTRICT_BOUND_FURTHER, constraint),
1508 let span_hi = param.span.with_hi(span.hi());
1509 let span_with_colon = source_map.span_through_char(span_hi, ':');
1511 if span_hi != param.span && span_with_colon != span_hi {
1512 err.tool_only_span_suggestion(
1514 MSG_RESTRICT_BOUND_FURTHER,
1515 format!("{}: {} + ", param_name, constraint),
1516 Applicability::MachineApplicable,
1520 // If user hasn't provided any bounds, suggest adding a new one:
1522 // fn foo<T>(t: T) { ... }
1523 // - help: consider restricting this type parameter with `T: Foo`
1527 &format!("{} `{}: {}`", MSG_RESTRICT_TYPE, param_name, constraint),
1530 err.tool_only_span_suggestion(
1533 format!("{}: {}", param_name, constraint),
1534 Applicability::MachineApplicable,
1540 // This part is a bit tricky, because using the `where` clause user can
1541 // provide zero, one or many bounds for the same type parameter, so we
1542 // have following cases to consider:
1544 // 1) When the type parameter has been provided zero bounds
1547 // fn foo<X, Y>(x: X, y: Y) where Y: Foo { ... }
1548 // - help: consider restricting this type parameter with `where X: Bar`
1551 // fn foo<X, Y>(x: X, y: Y) where Y: Foo { ... }
1552 // - insert: `, X: Bar`
1555 // 2) When the type parameter has been provided one bound
1558 // fn foo<T>(t: T) where T: Foo { ... }
1561 // help: consider further restricting this bound with `+ Bar`
1564 // fn foo<T>(t: T) where T: Foo { ... }
1567 // replace with: `T: Bar +`
1570 // 3) When the type parameter has been provided many bounds
1573 // fn foo<T>(t: T) where T: Foo, T: Bar {... }
1574 // - help: consider further restricting this type parameter with `where T: Zar`
1577 // fn foo<T>(t: T) where T: Foo, T: Bar {... }
1578 // - insert: `, T: Zar`
1580 let mut param_spans = Vec::new();
1582 for predicate in generics.where_clause.predicates {
1583 if let WherePredicate::BoundPredicate(WhereBoundPredicate {
1584 span, bounded_ty, ..
1587 if let TyKind::Path(QPath::Resolved(_, path)) = &bounded_ty.kind {
1588 if let Some(segment) = path.segments.first() {
1589 if segment.ident.to_string() == param_name {
1590 param_spans.push(span);
1597 let where_clause_span =
1598 generics.where_clause.span_for_predicates_or_empty_place().shrink_to_hi();
1600 match ¶m_spans[..] {
1604 &format!("{} `where {}: {}`", MSG_RESTRICT_TYPE, param_name, constraint),
1607 err.tool_only_span_suggestion(
1610 format!(", {}: {}", param_name, constraint),
1611 Applicability::MachineApplicable,
1618 &format!("{} `+ {}`", MSG_RESTRICT_BOUND_FURTHER, constraint),
1621 let span_hi = param_span.with_hi(span.hi());
1622 let span_with_colon = source_map.span_through_char(span_hi, ':');
1624 if span_hi != param_span && span_with_colon != span_hi {
1625 err.tool_only_span_suggestion(
1627 MSG_RESTRICT_BOUND_FURTHER,
1628 format!("{}: {} +", param_name, constraint),
1629 Applicability::MachineApplicable,
1638 "{} `where {}: {}`",
1639 MSG_RESTRICT_TYPE_FURTHER, param_name, constraint,
1643 err.tool_only_span_suggestion(
1645 MSG_RESTRICT_BOUND_FURTHER,
1646 format!(", {}: {}", param_name, constraint),
1647 Applicability::MachineApplicable,