1pub mod ambiguity;
2pub mod call_kind;
3mod fulfillment_errors;
4pub mod on_unimplemented;
5pub mod on_unimplemented_condition;
6pub mod on_unimplemented_format;
7mod overflow;
8pub mod suggestions;
9
10use std::{fmt, iter};
11
12use rustc_data_structures::fx::{FxIndexMap, FxIndexSet};
13use rustc_errors::{Applicability, Diag, E0038, E0276, MultiSpan, struct_span_code_err};
14use rustc_hir::def_id::{DefId, LocalDefId};
15use rustc_hir::intravisit::Visitor;
16use rustc_hir::{self as hir, AmbigArg};
17use rustc_infer::traits::solve::Goal;
18use rustc_infer::traits::{
19 DynCompatibilityViolation, Obligation, ObligationCause, ObligationCauseCode,
20 PredicateObligation, SelectionError,
21};
22use rustc_middle::ty::print::{PrintTraitRefExt as _, with_no_trimmed_paths};
23use rustc_middle::ty::{self, Ty, TyCtxt};
24use rustc_span::{ErrorGuaranteed, ExpnKind, Span};
25use tracing::{info, instrument};
26
27pub use self::overflow::*;
28use crate::error_reporting::TypeErrCtxt;
29use crate::traits::{FulfillmentError, FulfillmentErrorCode};
30
31#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
36pub enum CandidateSimilarity {
37 Exact { ignoring_lifetimes: bool },
38 Fuzzy { ignoring_lifetimes: bool },
39}
40
41#[derive(Debug, Clone, Copy, PartialEq, Eq)]
42pub struct ImplCandidate<'tcx> {
43 pub trait_ref: ty::TraitRef<'tcx>,
44 pub similarity: CandidateSimilarity,
45 impl_def_id: DefId,
46}
47
48enum GetSafeTransmuteErrorAndReason {
49 Silent,
50 Default,
51 Error { err_msg: String, safe_transmute_explanation: Option<String> },
52}
53
54pub struct FindExprBySpan<'hir> {
56 pub span: Span,
57 pub result: Option<&'hir hir::Expr<'hir>>,
58 pub ty_result: Option<&'hir hir::Ty<'hir>>,
59 pub include_closures: bool,
60 pub tcx: TyCtxt<'hir>,
61}
62
63impl<'hir> FindExprBySpan<'hir> {
64 pub fn new(span: Span, tcx: TyCtxt<'hir>) -> Self {
65 Self { span, result: None, ty_result: None, tcx, include_closures: false }
66 }
67}
68
69impl<'v> Visitor<'v> for FindExprBySpan<'v> {
70 type NestedFilter = rustc_middle::hir::nested_filter::OnlyBodies;
71
72 fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
73 self.tcx
74 }
75
76 fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
77 if self.span == ex.span {
78 self.result = Some(ex);
79 } else {
80 if let hir::ExprKind::Closure(..) = ex.kind
81 && self.include_closures
82 && let closure_header_sp = self.span.with_hi(ex.span.hi())
83 && closure_header_sp == ex.span
84 {
85 self.result = Some(ex);
86 }
87 hir::intravisit::walk_expr(self, ex);
88 }
89 }
90
91 fn visit_ty(&mut self, ty: &'v hir::Ty<'v, AmbigArg>) {
92 if self.span == ty.span {
93 self.ty_result = Some(ty.as_unambig_ty());
94 } else {
95 hir::intravisit::walk_ty(self, ty);
96 }
97 }
98}
99
100#[derive(Clone)]
102pub enum ArgKind {
103 Arg(String, String),
105
106 Tuple(Option<Span>, Vec<(String, String)>),
111}
112
113impl ArgKind {
114 fn empty() -> ArgKind {
115 ArgKind::Arg("_".to_owned(), "_".to_owned())
116 }
117
118 pub fn from_expected_ty(t: Ty<'_>, span: Option<Span>) -> ArgKind {
121 match t.kind() {
122 ty::Tuple(tys) => ArgKind::Tuple(
123 span,
124 tys.iter().map(|ty| ("_".to_owned(), ty.to_string())).collect::<Vec<_>>(),
125 ),
126 _ => ArgKind::Arg("_".to_owned(), t.to_string()),
127 }
128 }
129}
130
131#[derive(Copy, Clone)]
132pub enum DefIdOrName {
133 DefId(DefId),
134 Name(&'static str),
135}
136
137impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
138 pub fn report_fulfillment_errors(
139 &self,
140 mut errors: Vec<FulfillmentError<'tcx>>,
141 ) -> ErrorGuaranteed {
142 self.sub_relations
143 .borrow_mut()
144 .add_constraints(self, errors.iter().map(|e| e.obligation.predicate));
145
146 #[derive(Debug)]
147 struct ErrorDescriptor<'tcx> {
148 goal: Goal<'tcx, ty::Predicate<'tcx>>,
149 index: Option<usize>, }
151
152 let mut error_map: FxIndexMap<_, Vec<_>> = self
153 .reported_trait_errors
154 .borrow()
155 .iter()
156 .map(|(&span, goals)| {
157 (span, goals.0.iter().map(|&goal| ErrorDescriptor { goal, index: None }).collect())
158 })
159 .collect();
160
161 errors.sort_by_key(|e| {
165 let maybe_sizedness_did = match e.obligation.predicate.kind().skip_binder() {
166 ty::PredicateKind::Clause(ty::ClauseKind::Trait(pred)) => Some(pred.def_id()),
167 ty::PredicateKind::Clause(ty::ClauseKind::HostEffect(pred)) => Some(pred.def_id()),
168 _ => None,
169 };
170
171 match e.obligation.predicate.kind().skip_binder() {
172 _ if maybe_sizedness_did == self.tcx.lang_items().sized_trait() => 1,
173 _ if maybe_sizedness_did == self.tcx.lang_items().meta_sized_trait() => 2,
174 _ if maybe_sizedness_did == self.tcx.lang_items().pointee_sized_trait() => 3,
175 ty::PredicateKind::Coerce(_) => 4,
176 ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(_)) => 5,
177 _ => 0,
178 }
179 });
180
181 for (index, error) in errors.iter().enumerate() {
182 let mut span = error.obligation.cause.span;
185 let expn_data = span.ctxt().outer_expn_data();
186 if let ExpnKind::Desugaring(_) = expn_data.kind {
187 span = expn_data.call_site;
188 }
189
190 error_map
191 .entry(span)
192 .or_default()
193 .push(ErrorDescriptor { goal: error.obligation.as_goal(), index: Some(index) });
194 }
195
196 let mut is_suppressed = vec![false; errors.len()];
199 for (_, error_set) in error_map.iter() {
200 for error in error_set {
202 if let Some(index) = error.index {
203 for error2 in error_set {
207 if error2.index.is_some_and(|index2| is_suppressed[index2]) {
208 continue;
212 }
213
214 if self.error_implies(error2.goal, error.goal)
215 && !(error2.index >= error.index
216 && self.error_implies(error.goal, error2.goal))
217 {
218 info!("skipping {:?} (implied by {:?})", error, error2);
219 is_suppressed[index] = true;
220 break;
221 }
222 }
223 }
224 }
225 }
226
227 let mut reported = None;
228
229 for from_expansion in [false, true] {
230 for (error, suppressed) in iter::zip(&errors, &is_suppressed) {
231 if !suppressed && error.obligation.cause.span.from_expansion() == from_expansion {
232 let guar = self.report_fulfillment_error(error);
233 self.infcx.set_tainted_by_errors(guar);
234 reported = Some(guar);
235 let mut span = error.obligation.cause.span;
238 let expn_data = span.ctxt().outer_expn_data();
239 if let ExpnKind::Desugaring(_) = expn_data.kind {
240 span = expn_data.call_site;
241 }
242 self.reported_trait_errors
243 .borrow_mut()
244 .entry(span)
245 .or_insert_with(|| (vec![], guar))
246 .0
247 .push(error.obligation.as_goal());
248 }
249 }
250 }
251
252 reported.unwrap_or_else(|| self.dcx().delayed_bug("failed to report fulfillment errors"))
256 }
257
258 #[instrument(skip(self), level = "debug")]
259 fn report_fulfillment_error(&self, error: &FulfillmentError<'tcx>) -> ErrorGuaranteed {
260 let mut error = FulfillmentError {
261 obligation: error.obligation.clone(),
262 code: error.code.clone(),
263 root_obligation: error.root_obligation.clone(),
264 };
265 if matches!(
266 error.code,
267 FulfillmentErrorCode::Select(crate::traits::SelectionError::Unimplemented)
268 | FulfillmentErrorCode::Project(_)
269 ) && self.apply_do_not_recommend(&mut error.obligation)
270 {
271 error.code = FulfillmentErrorCode::Select(SelectionError::Unimplemented);
272 }
273
274 match error.code {
275 FulfillmentErrorCode::Select(ref selection_error) => self.report_selection_error(
276 error.obligation.clone(),
277 &error.root_obligation,
278 selection_error,
279 ),
280 FulfillmentErrorCode::Project(ref e) => {
281 self.report_projection_error(&error.obligation, e)
282 }
283 FulfillmentErrorCode::Ambiguity { overflow: None } => {
284 self.maybe_report_ambiguity(&error.obligation)
285 }
286 FulfillmentErrorCode::Ambiguity { overflow: Some(suggest_increasing_limit) } => {
287 self.report_overflow_no_abort(error.obligation.clone(), suggest_increasing_limit)
288 }
289 FulfillmentErrorCode::Subtype(ref expected_found, ref err) => self
290 .report_mismatched_types(
291 &error.obligation.cause,
292 error.obligation.param_env,
293 expected_found.expected,
294 expected_found.found,
295 *err,
296 )
297 .emit(),
298 FulfillmentErrorCode::ConstEquate(ref expected_found, ref err) => {
299 let mut diag = self.report_mismatched_consts(
300 &error.obligation.cause,
301 error.obligation.param_env,
302 expected_found.expected,
303 expected_found.found,
304 *err,
305 );
306 let code = error.obligation.cause.code().peel_derives().peel_match_impls();
307 if let ObligationCauseCode::WhereClause(..)
308 | ObligationCauseCode::WhereClauseInExpr(..) = code
309 {
310 self.note_obligation_cause_code(
311 error.obligation.cause.body_id,
312 &mut diag,
313 error.obligation.predicate,
314 error.obligation.param_env,
315 code,
316 &mut vec![],
317 &mut Default::default(),
318 );
319 }
320 diag.emit()
321 }
322 FulfillmentErrorCode::Cycle(ref cycle) => self.report_overflow_obligation_cycle(cycle),
323 }
324 }
325}
326
327pub(crate) fn to_pretty_impl_header(tcx: TyCtxt<'_>, impl_def_id: DefId) -> Option<String> {
330 use std::fmt::Write;
331
332 let trait_ref = tcx.impl_trait_ref(impl_def_id)?.instantiate_identity();
333 let mut w = "impl".to_owned();
334
335 #[derive(Debug, Default)]
336 struct SizednessFound {
337 sized: bool,
338 meta_sized: bool,
339 }
340
341 let mut types_with_sizedness_bounds = FxIndexMap::<_, SizednessFound>::default();
342
343 let args = ty::GenericArgs::identity_for_item(tcx, impl_def_id);
344
345 let arg_names = args.iter().map(|k| k.to_string()).filter(|k| k != "'_").collect::<Vec<_>>();
346 if !arg_names.is_empty() {
347 w.push('<');
348 w.push_str(&arg_names.join(", "));
349 w.push('>');
350
351 for ty in args.types() {
352 types_with_sizedness_bounds.insert(ty, SizednessFound::default());
354 }
355 }
356
357 write!(
358 w,
359 " {}{} for {}",
360 tcx.impl_polarity(impl_def_id).as_str(),
361 trait_ref.print_only_trait_path(),
362 tcx.type_of(impl_def_id).instantiate_identity()
363 )
364 .unwrap();
365
366 let predicates = tcx.predicates_of(impl_def_id).predicates;
367 let mut pretty_predicates = Vec::with_capacity(predicates.len());
368
369 let sized_trait = tcx.lang_items().sized_trait();
370 let meta_sized_trait = tcx.lang_items().meta_sized_trait();
371
372 for (p, _) in predicates {
373 if let Some(trait_clause) = p.as_trait_clause() {
375 let self_ty = trait_clause.self_ty().skip_binder();
376 let sizedness_of = types_with_sizedness_bounds.entry(self_ty).or_default();
377 if Some(trait_clause.def_id()) == sized_trait {
378 sizedness_of.sized = true;
379 continue;
380 } else if Some(trait_clause.def_id()) == meta_sized_trait {
381 sizedness_of.meta_sized = true;
382 continue;
383 }
384 }
385
386 pretty_predicates.push(p.to_string());
387 }
388
389 for (ty, sizedness) in types_with_sizedness_bounds {
390 if !tcx.features().sized_hierarchy() {
391 if sizedness.sized {
392 } else {
394 pretty_predicates.push(format!("{ty}: ?Sized"));
395 }
396 } else {
397 if sizedness.sized {
398 pretty_predicates.push(format!("{ty}: Sized"));
400 } else if sizedness.meta_sized {
401 pretty_predicates.push(format!("{ty}: MetaSized"));
402 } else {
403 pretty_predicates.push(format!("{ty}: PointeeSized"));
404 }
405 }
406 }
407
408 if !pretty_predicates.is_empty() {
409 write!(w, "\n where {}", pretty_predicates.join(", ")).unwrap();
410 }
411
412 w.push(';');
413 Some(w)
414}
415
416impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
417 pub fn report_extra_impl_obligation(
418 &self,
419 error_span: Span,
420 impl_item_def_id: LocalDefId,
421 trait_item_def_id: DefId,
422 requirement: &dyn fmt::Display,
423 ) -> Diag<'a> {
424 let mut err = struct_span_code_err!(
425 self.dcx(),
426 error_span,
427 E0276,
428 "impl has stricter requirements than trait"
429 );
430
431 if !self.tcx.is_impl_trait_in_trait(trait_item_def_id) {
432 if let Some(span) = self.tcx.hir_span_if_local(trait_item_def_id) {
433 let item_name = self.tcx.item_name(impl_item_def_id.to_def_id());
434 err.span_label(span, format!("definition of `{item_name}` from trait"));
435 }
436 }
437
438 err.span_label(error_span, format!("impl has extra requirement {requirement}"));
439
440 err
441 }
442}
443
444pub fn report_dyn_incompatibility<'tcx>(
445 tcx: TyCtxt<'tcx>,
446 span: Span,
447 hir_id: Option<hir::HirId>,
448 trait_def_id: DefId,
449 violations: &[DynCompatibilityViolation],
450) -> Diag<'tcx> {
451 let trait_str = tcx.def_path_str(trait_def_id);
452 let trait_span = tcx.hir_get_if_local(trait_def_id).and_then(|node| match node {
453 hir::Node::Item(item) => match item.kind {
454 hir::ItemKind::Trait(_, _, _, ident, ..) | hir::ItemKind::TraitAlias(ident, _, _) => {
455 Some(ident.span)
456 }
457 _ => unreachable!(),
458 },
459 _ => None,
460 });
461
462 let mut err = struct_span_code_err!(
463 tcx.dcx(),
464 span,
465 E0038,
466 "the {} `{}` is not dyn compatible",
467 tcx.def_descr(trait_def_id),
468 trait_str
469 );
470 err.span_label(span, format!("`{trait_str}` is not dyn compatible"));
471
472 attempt_dyn_to_impl_suggestion(tcx, hir_id, &mut err);
473
474 let mut reported_violations = FxIndexSet::default();
475 let mut multi_span = vec![];
476 let mut messages = vec![];
477 for violation in violations {
478 if let DynCompatibilityViolation::SizedSelf(sp) = &violation
479 && !sp.is_empty()
480 {
481 reported_violations.insert(DynCompatibilityViolation::SizedSelf(vec![].into()));
484 }
485 if reported_violations.insert(violation.clone()) {
486 let spans = violation.spans();
487 let msg = if trait_span.is_none() || spans.is_empty() {
488 format!("the trait is not dyn compatible because {}", violation.error_msg())
489 } else {
490 format!("...because {}", violation.error_msg())
491 };
492 if spans.is_empty() {
493 err.note(msg);
494 } else {
495 for span in spans {
496 multi_span.push(span);
497 messages.push(msg.clone());
498 }
499 }
500 }
501 }
502 let has_multi_span = !multi_span.is_empty();
503 let mut note_span = MultiSpan::from_spans(multi_span.clone());
504 if let (Some(trait_span), true) = (trait_span, has_multi_span) {
505 note_span.push_span_label(trait_span, "this trait is not dyn compatible...");
506 }
507 for (span, msg) in iter::zip(multi_span, messages) {
508 note_span.push_span_label(span, msg);
509 }
510 err.span_note(
511 note_span,
512 "for a trait to be dyn compatible it needs to allow building a vtable\n\
513 for more information, visit <https://doc.rust-lang.org/reference/items/traits.html#dyn-compatibility>",
514 );
515
516 if trait_span.is_some() {
518 let mut potential_solutions: Vec<_> =
519 reported_violations.into_iter().map(|violation| violation.solution()).collect();
520 potential_solutions.sort();
521 potential_solutions.dedup();
523 for solution in potential_solutions {
524 solution.add_to(&mut err);
525 }
526 }
527
528 attempt_dyn_to_enum_suggestion(tcx, trait_def_id, &*trait_str, &mut err);
529
530 err
531}
532
533fn attempt_dyn_to_enum_suggestion(
536 tcx: TyCtxt<'_>,
537 trait_def_id: DefId,
538 trait_str: &str,
539 err: &mut Diag<'_>,
540) {
541 let impls_of = tcx.trait_impls_of(trait_def_id);
542
543 if !impls_of.blanket_impls().is_empty() {
544 return;
545 }
546
547 let concrete_impls: Option<Vec<Ty<'_>>> = impls_of
548 .non_blanket_impls()
549 .values()
550 .flatten()
551 .map(|impl_id| {
552 let Some(impl_type) = tcx.type_of(*impl_id).no_bound_vars() else { return None };
555
556 match impl_type.kind() {
561 ty::Str | ty::Slice(_) | ty::Dynamic(_, _, ty::DynKind::Dyn) => {
562 return None;
563 }
564 _ => {}
565 }
566 Some(impl_type)
567 })
568 .collect();
569 let Some(concrete_impls) = concrete_impls else { return };
570
571 const MAX_IMPLS_TO_SUGGEST_CONVERTING_TO_ENUM: usize = 9;
572 if concrete_impls.is_empty() || concrete_impls.len() > MAX_IMPLS_TO_SUGGEST_CONVERTING_TO_ENUM {
573 return;
574 }
575
576 let externally_visible = if let Some(def_id) = trait_def_id.as_local() {
577 tcx.resolutions(()).effective_visibilities.is_exported(def_id)
581 } else {
582 false
583 };
584
585 if let [only_impl] = &concrete_impls[..] {
586 let within = if externally_visible { " within this crate" } else { "" };
587 err.help(with_no_trimmed_paths!(format!(
588 "only type `{only_impl}` implements `{trait_str}`{within}; \
589 consider using it directly instead."
590 )));
591 } else {
592 let types = concrete_impls
593 .iter()
594 .map(|t| with_no_trimmed_paths!(format!(" {}", t)))
595 .collect::<Vec<String>>()
596 .join("\n");
597
598 err.help(format!(
599 "the following types implement `{trait_str}`:\n\
600 {types}\n\
601 consider defining an enum where each variant holds one of these types,\n\
602 implementing `{trait_str}` for this new enum and using it instead",
603 ));
604 }
605
606 if externally_visible {
607 err.note(format!(
608 "`{trait_str}` may be implemented in other crates; if you want to support your users \
609 passing their own types here, you can't refer to a specific type",
610 ));
611 }
612}
613
614fn attempt_dyn_to_impl_suggestion(tcx: TyCtxt<'_>, hir_id: Option<hir::HirId>, err: &mut Diag<'_>) {
617 let Some(hir_id) = hir_id else { return };
618 let hir::Node::Ty(ty) = tcx.hir_node(hir_id) else { return };
619 let hir::TyKind::TraitObject([trait_ref, ..], ..) = ty.kind else { return };
620
621 let Some((_id, first_non_type_parent_node)) =
626 tcx.hir_parent_iter(hir_id).find(|(_id, node)| !matches!(node, hir::Node::Ty(_)))
627 else {
628 return;
629 };
630 if first_non_type_parent_node.fn_sig().is_none() {
631 return;
632 }
633
634 err.span_suggestion_verbose(
635 ty.span.until(trait_ref.span),
636 "consider using an opaque type instead",
637 "impl ",
638 Applicability::MaybeIncorrect,
639 );
640}