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 #[derive(Debug)]
143 struct ErrorDescriptor<'tcx> {
144 goal: Goal<'tcx, ty::Predicate<'tcx>>,
145 index: Option<usize>, }
147
148 let mut error_map: FxIndexMap<_, Vec<_>> = self
149 .reported_trait_errors
150 .borrow()
151 .iter()
152 .map(|(&span, goals)| {
153 (span, goals.0.iter().map(|&goal| ErrorDescriptor { goal, index: None }).collect())
154 })
155 .collect();
156
157 errors.sort_by_key(|e| {
161 let maybe_sizedness_did = match e.obligation.predicate.kind().skip_binder() {
162 ty::PredicateKind::Clause(ty::ClauseKind::Trait(pred)) => Some(pred.def_id()),
163 ty::PredicateKind::Clause(ty::ClauseKind::HostEffect(pred)) => Some(pred.def_id()),
164 _ => None,
165 };
166
167 match e.obligation.predicate.kind().skip_binder() {
168 _ if maybe_sizedness_did == self.tcx.lang_items().sized_trait() => 1,
169 _ if maybe_sizedness_did == self.tcx.lang_items().meta_sized_trait() => 2,
170 _ if maybe_sizedness_did == self.tcx.lang_items().pointee_sized_trait() => 3,
171 ty::PredicateKind::Coerce(_) => 4,
172 ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(_)) => 5,
173 _ => 0,
174 }
175 });
176
177 for (index, error) in errors.iter().enumerate() {
178 let mut span = error.obligation.cause.span;
181 let expn_data = span.ctxt().outer_expn_data();
182 if let ExpnKind::Desugaring(_) = expn_data.kind {
183 span = expn_data.call_site;
184 }
185
186 error_map
187 .entry(span)
188 .or_default()
189 .push(ErrorDescriptor { goal: error.obligation.as_goal(), index: Some(index) });
190 }
191
192 let mut is_suppressed = vec![false; errors.len()];
195 for (_, error_set) in error_map.iter() {
196 for error in error_set {
198 if let Some(index) = error.index {
199 for error2 in error_set {
203 if error2.index.is_some_and(|index2| is_suppressed[index2]) {
204 continue;
208 }
209
210 if self.error_implies(error2.goal, error.goal)
211 && !(error2.index >= error.index
212 && self.error_implies(error.goal, error2.goal))
213 {
214 info!("skipping {:?} (implied by {:?})", error, error2);
215 is_suppressed[index] = true;
216 break;
217 }
218 }
219 }
220 }
221 }
222
223 let mut reported = None;
224
225 for from_expansion in [false, true] {
226 for (error, suppressed) in iter::zip(&errors, &is_suppressed) {
227 if !suppressed && error.obligation.cause.span.from_expansion() == from_expansion {
228 let guar = self.report_fulfillment_error(error);
229 self.infcx.set_tainted_by_errors(guar);
230 reported = Some(guar);
231 let mut span = error.obligation.cause.span;
234 let expn_data = span.ctxt().outer_expn_data();
235 if let ExpnKind::Desugaring(_) = expn_data.kind {
236 span = expn_data.call_site;
237 }
238 self.reported_trait_errors
239 .borrow_mut()
240 .entry(span)
241 .or_insert_with(|| (vec![], guar))
242 .0
243 .push(error.obligation.as_goal());
244 }
245 }
246 }
247
248 reported.unwrap_or_else(|| self.dcx().delayed_bug("failed to report fulfillment errors"))
252 }
253
254 #[instrument(skip(self), level = "debug")]
255 fn report_fulfillment_error(&self, error: &FulfillmentError<'tcx>) -> ErrorGuaranteed {
256 let mut error = FulfillmentError {
257 obligation: error.obligation.clone(),
258 code: error.code.clone(),
259 root_obligation: error.root_obligation.clone(),
260 };
261 if matches!(
262 error.code,
263 FulfillmentErrorCode::Select(crate::traits::SelectionError::Unimplemented)
264 | FulfillmentErrorCode::Project(_)
265 ) && self.apply_do_not_recommend(&mut error.obligation)
266 {
267 error.code = FulfillmentErrorCode::Select(SelectionError::Unimplemented);
268 }
269
270 match error.code {
271 FulfillmentErrorCode::Select(ref selection_error) => self.report_selection_error(
272 error.obligation.clone(),
273 &error.root_obligation,
274 selection_error,
275 ),
276 FulfillmentErrorCode::Project(ref e) => {
277 self.report_projection_error(&error.obligation, e)
278 }
279 FulfillmentErrorCode::Ambiguity { overflow: None } => {
280 self.maybe_report_ambiguity(&error.obligation)
281 }
282 FulfillmentErrorCode::Ambiguity { overflow: Some(suggest_increasing_limit) } => {
283 self.report_overflow_no_abort(error.obligation.clone(), suggest_increasing_limit)
284 }
285 FulfillmentErrorCode::Subtype(ref expected_found, ref err) => self
286 .report_mismatched_types(
287 &error.obligation.cause,
288 error.obligation.param_env,
289 expected_found.expected,
290 expected_found.found,
291 *err,
292 )
293 .emit(),
294 FulfillmentErrorCode::ConstEquate(ref expected_found, ref err) => {
295 let mut diag = self.report_mismatched_consts(
296 &error.obligation.cause,
297 error.obligation.param_env,
298 expected_found.expected,
299 expected_found.found,
300 *err,
301 );
302 let code = error.obligation.cause.code().peel_derives().peel_match_impls();
303 if let ObligationCauseCode::WhereClause(..)
304 | ObligationCauseCode::WhereClauseInExpr(..) = code
305 {
306 self.note_obligation_cause_code(
307 error.obligation.cause.body_id,
308 &mut diag,
309 error.obligation.predicate,
310 error.obligation.param_env,
311 code,
312 &mut vec![],
313 &mut Default::default(),
314 );
315 }
316 diag.emit()
317 }
318 FulfillmentErrorCode::Cycle(ref cycle) => self.report_overflow_obligation_cycle(cycle),
319 }
320 }
321}
322
323pub(crate) fn to_pretty_impl_header(tcx: TyCtxt<'_>, impl_def_id: DefId) -> Option<String> {
326 use std::fmt::Write;
327
328 let trait_ref = tcx.impl_trait_ref(impl_def_id)?.instantiate_identity();
329 let mut w = "impl".to_owned();
330
331 #[derive(Debug, Default)]
332 struct SizednessFound {
333 sized: bool,
334 meta_sized: bool,
335 }
336
337 let mut types_with_sizedness_bounds = FxIndexMap::<_, SizednessFound>::default();
338
339 let args = ty::GenericArgs::identity_for_item(tcx, impl_def_id);
340
341 let arg_names = args.iter().map(|k| k.to_string()).filter(|k| k != "'_").collect::<Vec<_>>();
342 if !arg_names.is_empty() {
343 w.push('<');
344 w.push_str(&arg_names.join(", "));
345 w.push('>');
346
347 for ty in args.types() {
348 types_with_sizedness_bounds.insert(ty, SizednessFound::default());
350 }
351 }
352
353 write!(
354 w,
355 " {}{} for {}",
356 tcx.impl_polarity(impl_def_id).as_str(),
357 trait_ref.print_only_trait_path(),
358 tcx.type_of(impl_def_id).instantiate_identity()
359 )
360 .unwrap();
361
362 let predicates = tcx.predicates_of(impl_def_id).predicates;
363 let mut pretty_predicates = Vec::with_capacity(predicates.len());
364
365 let sized_trait = tcx.lang_items().sized_trait();
366 let meta_sized_trait = tcx.lang_items().meta_sized_trait();
367
368 for (p, _) in predicates {
369 if let Some(trait_clause) = p.as_trait_clause() {
371 let self_ty = trait_clause.self_ty().skip_binder();
372 let sizedness_of = types_with_sizedness_bounds.entry(self_ty).or_default();
373 if Some(trait_clause.def_id()) == sized_trait {
374 sizedness_of.sized = true;
375 continue;
376 } else if Some(trait_clause.def_id()) == meta_sized_trait {
377 sizedness_of.meta_sized = true;
378 continue;
379 }
380 }
381
382 pretty_predicates.push(p.to_string());
383 }
384
385 for (ty, sizedness) in types_with_sizedness_bounds {
386 if !tcx.features().sized_hierarchy() {
387 if sizedness.sized {
388 } else {
390 pretty_predicates.push(format!("{ty}: ?Sized"));
391 }
392 } else {
393 if sizedness.sized {
394 pretty_predicates.push(format!("{ty}: Sized"));
396 } else if sizedness.meta_sized {
397 pretty_predicates.push(format!("{ty}: MetaSized"));
398 } else {
399 pretty_predicates.push(format!("{ty}: PointeeSized"));
400 }
401 }
402 }
403
404 if !pretty_predicates.is_empty() {
405 write!(w, "\n where {}", pretty_predicates.join(", ")).unwrap();
406 }
407
408 w.push(';');
409 Some(w)
410}
411
412impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
413 pub fn report_extra_impl_obligation(
414 &self,
415 error_span: Span,
416 impl_item_def_id: LocalDefId,
417 trait_item_def_id: DefId,
418 requirement: &dyn fmt::Display,
419 ) -> Diag<'a> {
420 let mut err = struct_span_code_err!(
421 self.dcx(),
422 error_span,
423 E0276,
424 "impl has stricter requirements than trait"
425 );
426
427 if !self.tcx.is_impl_trait_in_trait(trait_item_def_id) {
428 if let Some(span) = self.tcx.hir_span_if_local(trait_item_def_id) {
429 let item_name = self.tcx.item_name(impl_item_def_id.to_def_id());
430 err.span_label(span, format!("definition of `{item_name}` from trait"));
431 }
432 }
433
434 err.span_label(error_span, format!("impl has extra requirement {requirement}"));
435
436 err
437 }
438}
439
440pub fn report_dyn_incompatibility<'tcx>(
441 tcx: TyCtxt<'tcx>,
442 span: Span,
443 hir_id: Option<hir::HirId>,
444 trait_def_id: DefId,
445 violations: &[DynCompatibilityViolation],
446) -> Diag<'tcx> {
447 let trait_str = tcx.def_path_str(trait_def_id);
448 let trait_span = tcx.hir_get_if_local(trait_def_id).and_then(|node| match node {
449 hir::Node::Item(item) => match item.kind {
450 hir::ItemKind::Trait(_, _, _, ident, ..) | hir::ItemKind::TraitAlias(ident, _, _) => {
451 Some(ident.span)
452 }
453 _ => unreachable!(),
454 },
455 _ => None,
456 });
457
458 let mut err = struct_span_code_err!(
459 tcx.dcx(),
460 span,
461 E0038,
462 "the {} `{}` is not dyn compatible",
463 tcx.def_descr(trait_def_id),
464 trait_str
465 );
466 err.span_label(span, format!("`{trait_str}` is not dyn compatible"));
467
468 attempt_dyn_to_impl_suggestion(tcx, hir_id, &mut err);
469
470 let mut reported_violations = FxIndexSet::default();
471 let mut multi_span = vec![];
472 let mut messages = vec![];
473 for violation in violations {
474 if let DynCompatibilityViolation::SizedSelf(sp) = &violation
475 && !sp.is_empty()
476 {
477 reported_violations.insert(DynCompatibilityViolation::SizedSelf(vec![].into()));
480 }
481 if reported_violations.insert(violation.clone()) {
482 let spans = violation.spans();
483 let msg = if trait_span.is_none() || spans.is_empty() {
484 format!("the trait is not dyn compatible because {}", violation.error_msg())
485 } else {
486 format!("...because {}", violation.error_msg())
487 };
488 if spans.is_empty() {
489 err.note(msg);
490 } else {
491 for span in spans {
492 multi_span.push(span);
493 messages.push(msg.clone());
494 }
495 }
496 }
497 }
498 let has_multi_span = !multi_span.is_empty();
499 let mut note_span = MultiSpan::from_spans(multi_span.clone());
500 if let (Some(trait_span), true) = (trait_span, has_multi_span) {
501 note_span.push_span_label(trait_span, "this trait is not dyn compatible...");
502 }
503 for (span, msg) in iter::zip(multi_span, messages) {
504 note_span.push_span_label(span, msg);
505 }
506 err.span_note(
507 note_span,
508 "for a trait to be dyn compatible it needs to allow building a vtable\n\
509 for more information, visit <https://doc.rust-lang.org/reference/items/traits.html#dyn-compatibility>",
510 );
511
512 if trait_span.is_some() {
514 let mut potential_solutions: Vec<_> =
515 reported_violations.into_iter().map(|violation| violation.solution()).collect();
516 potential_solutions.sort();
517 potential_solutions.dedup();
519 for solution in potential_solutions {
520 solution.add_to(&mut err);
521 }
522 }
523
524 attempt_dyn_to_enum_suggestion(tcx, trait_def_id, &*trait_str, &mut err);
525
526 err
527}
528
529fn attempt_dyn_to_enum_suggestion(
532 tcx: TyCtxt<'_>,
533 trait_def_id: DefId,
534 trait_str: &str,
535 err: &mut Diag<'_>,
536) {
537 let impls_of = tcx.trait_impls_of(trait_def_id);
538
539 if !impls_of.blanket_impls().is_empty() {
540 return;
541 }
542
543 let concrete_impls: Option<Vec<Ty<'_>>> = impls_of
544 .non_blanket_impls()
545 .values()
546 .flatten()
547 .map(|impl_id| {
548 let Some(impl_type) = tcx.type_of(*impl_id).no_bound_vars() else { return None };
551
552 match impl_type.kind() {
557 ty::Str | ty::Slice(_) | ty::Dynamic(_, _, ty::DynKind::Dyn) => {
558 return None;
559 }
560 _ => {}
561 }
562 Some(impl_type)
563 })
564 .collect();
565 let Some(concrete_impls) = concrete_impls else { return };
566
567 const MAX_IMPLS_TO_SUGGEST_CONVERTING_TO_ENUM: usize = 9;
568 if concrete_impls.is_empty() || concrete_impls.len() > MAX_IMPLS_TO_SUGGEST_CONVERTING_TO_ENUM {
569 return;
570 }
571
572 let externally_visible = if let Some(def_id) = trait_def_id.as_local() {
573 tcx.resolutions(()).effective_visibilities.is_exported(def_id)
577 } else {
578 false
579 };
580
581 if let [only_impl] = &concrete_impls[..] {
582 let within = if externally_visible { " within this crate" } else { "" };
583 err.help(with_no_trimmed_paths!(format!(
584 "only type `{only_impl}` implements `{trait_str}`{within}; \
585 consider using it directly instead."
586 )));
587 } else {
588 let types = concrete_impls
589 .iter()
590 .map(|t| with_no_trimmed_paths!(format!(" {}", t)))
591 .collect::<Vec<String>>()
592 .join("\n");
593
594 err.help(format!(
595 "the following types implement `{trait_str}`:\n\
596 {types}\n\
597 consider defining an enum where each variant holds one of these types,\n\
598 implementing `{trait_str}` for this new enum and using it instead",
599 ));
600 }
601
602 if externally_visible {
603 err.note(format!(
604 "`{trait_str}` may be implemented in other crates; if you want to support your users \
605 passing their own types here, you can't refer to a specific type",
606 ));
607 }
608}
609
610fn attempt_dyn_to_impl_suggestion(tcx: TyCtxt<'_>, hir_id: Option<hir::HirId>, err: &mut Diag<'_>) {
613 let Some(hir_id) = hir_id else { return };
614 let hir::Node::Ty(ty) = tcx.hir_node(hir_id) else { return };
615 let hir::TyKind::TraitObject([trait_ref, ..], ..) = ty.kind else { return };
616
617 let Some((_id, first_non_type_parent_node)) =
622 tcx.hir_parent_iter(hir_id).find(|(_id, node)| !matches!(node, hir::Node::Ty(_)))
623 else {
624 return;
625 };
626 if first_non_type_parent_node.fn_sig().is_none() {
627 return;
628 }
629
630 err.span_suggestion_verbose(
631 ty.span.until(trait_ref.span),
632 "consider using an opaque type instead",
633 "impl ",
634 Applicability::MaybeIncorrect,
635 );
636}