1use rustc_ast::TraitObjectSyntax;
2use rustc_data_structures::fx::{FxHashSet, FxIndexMap, FxIndexSet};
3use rustc_errors::codes::*;
4use rustc_errors::{
5 Applicability, Diag, DiagCtxtHandle, Diagnostic, EmissionGuarantee, Level, StashKey,
6 Suggestions, struct_span_code_err,
7};
8use rustc_hir::def::{DefKind, Res};
9use rustc_hir::def_id::DefId;
10use rustc_hir::{self as hir, HirId, LangItem};
11use rustc_lint_defs::builtin::{BARE_TRAIT_OBJECTS, UNUSED_ASSOCIATED_TYPE_BOUNDS};
12use rustc_middle::ty::elaborate::ClauseWithSupertraitSpan;
13use rustc_middle::ty::{
14 self, BottomUpFolder, ExistentialPredicateStableCmpExt as _, Ty, TyCtxt, TypeFoldable,
15 TypeVisitableExt, Upcast,
16};
17use rustc_span::edit_distance::find_best_match_for_name;
18use rustc_span::{ErrorGuaranteed, Span};
19use rustc_trait_selection::error_reporting::traits::report_dyn_incompatibility;
20use rustc_trait_selection::error_reporting::traits::suggestions::NextTypeParamName;
21use rustc_trait_selection::traits;
22use smallvec::{SmallVec, smallvec};
23use tracing::{debug, instrument};
24
25use super::HirTyLowerer;
26use crate::diagnostics::DynTraitAssocItemBindingMentionsSelf;
27use crate::hir_ty_lowering::{
28 GenericArgCountMismatch, ImpliedBoundsContext, OverlappingAsssocItemConstraints,
29 PredicateFilter, RegionInferReason,
30};
31
32impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
33 x;#[instrument(level = "debug", skip_all, ret)]
35 pub(super) fn lower_trait_object_ty(
36 &self,
37 span: Span,
38 hir_id: hir::HirId,
39 hir_bounds: &[hir::PolyTraitRef<'tcx>],
40 lifetime: &hir::Lifetime,
41 syntax: TraitObjectSyntax,
42 ) -> Ty<'tcx> {
43 let tcx = self.tcx();
44 let dummy_self = tcx.types.trait_object_dummy_self;
45
46 match syntax {
47 TraitObjectSyntax::Dyn => {}
48 TraitObjectSyntax::None => {
49 match self.prohibit_or_lint_bare_trait_object_ty(span, hir_id, hir_bounds) {
50 Some(guar) => return Ty::new_error(tcx, guar),
54 None => {}
55 }
56 }
57 }
58
59 let mut user_written_bounds = Vec::new();
60 let mut potential_assoc_items = Vec::new();
61 for poly_trait_ref in hir_bounds.iter() {
62 let result = self.lower_poly_trait_ref(
68 poly_trait_ref,
69 dummy_self,
70 &mut user_written_bounds,
71 PredicateFilter::SelfOnly,
72 OverlappingAsssocItemConstraints::Forbidden,
73 );
74 if let Err(GenericArgCountMismatch { invalid_args, .. }) = result.correct {
75 potential_assoc_items.extend(invalid_args);
76 }
77 }
78
79 self.add_default_traits(
80 &mut user_written_bounds,
81 dummy_self,
82 &hir_bounds
83 .iter()
84 .map(|&trait_ref| hir::GenericBound::Trait(trait_ref))
85 .collect::<Vec<_>>(),
86 ImpliedBoundsContext::AssociatedTypeOrImplTrait,
87 span,
88 );
89
90 let (mut elaborated_trait_bounds, elaborated_projection_bounds) =
91 traits::expand_trait_aliases(tcx, user_written_bounds.iter().copied());
92
93 debug!(?user_written_bounds, ?elaborated_trait_bounds);
95 let meta_sized_did = tcx.require_lang_item(LangItem::MetaSized, span);
96 if user_written_bounds
99 .iter()
100 .all(|(clause, _)| clause.as_trait_clause().map(|p| p.def_id()) != Some(meta_sized_did))
101 {
102 elaborated_trait_bounds.retain(|(pred, _)| pred.def_id() != meta_sized_did);
103 }
104 debug!(?user_written_bounds, ?elaborated_trait_bounds);
105
106 let (regular_traits, mut auto_traits): (Vec<_>, Vec<_>) = elaborated_trait_bounds
107 .into_iter()
108 .partition(|(trait_ref, _)| !tcx.trait_is_auto(trait_ref.def_id()));
109
110 if regular_traits.is_empty() && auto_traits.is_empty() {
112 let guar =
113 self.report_trait_object_with_no_traits(span, user_written_bounds.iter().copied());
114 return Ty::new_error(tcx, guar);
115 }
116 if regular_traits.len() > 1 {
118 let guar = self.report_trait_object_addition_traits(®ular_traits);
119 return Ty::new_error(tcx, guar);
120 }
121 if let Err(guar) = regular_traits.error_reported() {
123 return Ty::new_error(tcx, guar);
124 }
125
126 for (clause, span) in user_written_bounds {
130 if let Some(trait_pred) = clause.as_trait_clause() {
131 let violations = self.dyn_compatibility_violations(trait_pred.def_id());
132 if !violations.is_empty() {
133 let reported = report_dyn_incompatibility(
134 tcx,
135 span,
136 Some(hir_id),
137 trait_pred.def_id(),
138 &violations,
139 )
140 .emit();
141 return Ty::new_error(tcx, reported);
142 }
143 }
144 }
145
146 let mut projection_bounds = FxIndexMap::default();
156 for (proj, proj_span) in elaborated_projection_bounds {
157 let item_def_id = proj.item_def_id();
158
159 let proj = proj.map_bound(|mut proj| {
160 let references_self = proj.term.walk().any(|arg| arg == dummy_self.into());
161 if references_self {
162 let guar = self.dcx().emit_err(DynTraitAssocItemBindingMentionsSelf {
163 span,
164 kind: tcx.def_descr(item_def_id),
165 binding: proj_span,
166 });
167 proj.term = replace_dummy_self_with_error(tcx, proj.term, guar);
168 }
169 proj
170 });
171
172 let key = (
173 item_def_id,
174 tcx.anonymize_bound_vars(
175 proj.map_bound(|proj| proj.projection_term.trait_ref(tcx)),
176 ),
177 );
178 if let Some((old_proj, old_proj_span)) =
179 projection_bounds.insert(key, (proj, proj_span))
180 && tcx.anonymize_bound_vars(proj) != tcx.anonymize_bound_vars(old_proj)
181 {
182 let kind = tcx.def_descr(item_def_id);
183 let name = tcx.item_name(item_def_id);
184 self.dcx()
185 .struct_span_err(span, format!("conflicting {kind} bindings for `{name}`"))
186 .with_span_label(
187 old_proj_span,
188 format!("`{name}` is specified to be `{}` here", old_proj.term()),
189 )
190 .with_span_label(
191 proj_span,
192 format!("`{name}` is specified to be `{}` here", proj.term()),
193 )
194 .emit();
195 }
196 }
197
198 let principal_trait = regular_traits.into_iter().next();
199
200 let mut ordered_associated_items = vec![];
206
207 if let Some((principal_trait, ref spans)) = principal_trait {
208 let principal_trait = principal_trait.map_bound(|trait_pred| {
209 assert_eq!(trait_pred.polarity, ty::PredicatePolarity::Positive);
210 trait_pred.trait_ref
211 });
212
213 for ClauseWithSupertraitSpan { clause, supertrait_span } in traits::elaborate(
214 tcx,
215 [ClauseWithSupertraitSpan::new(
216 ty::TraitRef::identity(tcx, principal_trait.def_id()).upcast(tcx),
217 *spans.last().unwrap(),
218 )],
219 )
220 .filter_only_self()
221 {
222 let clause = clause.instantiate_supertrait(tcx, principal_trait);
223 debug!("observing object predicate `{clause:?}`");
224
225 let bound_predicate = clause.kind();
226 match bound_predicate.skip_binder() {
227 ty::ClauseKind::Trait(pred) => {
228 let trait_ref =
230 tcx.anonymize_bound_vars(bound_predicate.rebind(pred.trait_ref));
231 ordered_associated_items.extend(
232 tcx.associated_items(pred.trait_ref.def_id)
233 .in_definition_order()
234 .filter(|item| item.is_type() || item.is_type_const())
237 .filter(|item| !item.is_impl_trait_in_trait())
239 .map(|item| (item.def_id, trait_ref)),
240 );
241 }
242 ty::ClauseKind::Projection(pred) => {
243 let pred = bound_predicate.rebind(pred);
244 let references_self =
247 pred.skip_binder().term.walk().any(|arg| arg == dummy_self.into());
248
249 if !references_self {
267 let key = (
268 pred.item_def_id(),
269 tcx.anonymize_bound_vars(
270 pred.map_bound(|proj| proj.projection_term.trait_ref(tcx)),
271 ),
272 );
273 if !projection_bounds.contains_key(&key) {
274 projection_bounds.insert(key, (pred, supertrait_span));
275 }
276 }
277
278 self.check_elaborated_projection_mentions_input_lifetimes(
279 pred,
280 *spans.first().unwrap(),
281 supertrait_span,
282 );
283 }
284 _ => (),
285 }
286 }
287 }
288
289 for &(projection_bound, span) in projection_bounds.values() {
291 let def_id = projection_bound.item_def_id();
292 if tcx.generics_require_sized_self(def_id) {
293 tcx.emit_node_span_lint(
297 UNUSED_ASSOCIATED_TYPE_BOUNDS,
298 hir_id,
299 span,
300 crate::diagnostics::UnusedAssociatedTypeBounds { span },
301 );
302 }
303 }
304
305 let mut missing_assoc_items = FxIndexSet::default();
317 let projection_bounds: Vec<_> = ordered_associated_items
318 .into_iter()
319 .filter_map(|key @ (def_id, _)| {
320 if let Some(&assoc) = projection_bounds.get(&key) {
321 return Some(assoc);
322 }
323 if !tcx.generics_require_sized_self(def_id) {
324 missing_assoc_items.insert(key);
325 }
326 None
327 })
328 .collect();
329
330 if let Err(guar) = self.check_for_required_assoc_items(
332 principal_trait.as_ref().map_or(smallvec![], |(_, spans)| spans.clone()),
333 missing_assoc_items,
334 potential_assoc_items,
335 hir_bounds,
336 ) {
337 return Ty::new_error(tcx, guar);
338 }
339
340 let mut duplicates = FxHashSet::default();
345 auto_traits.retain(|(trait_pred, _)| duplicates.insert(trait_pred.def_id()));
346
347 debug!(?principal_trait);
348 debug!(?auto_traits);
349
350 let principal_trait_ref = principal_trait.map(|(trait_pred, spans)| {
352 trait_pred.map_bound(|trait_pred| {
353 let trait_ref = trait_pred.trait_ref;
354 assert_eq!(trait_pred.polarity, ty::PredicatePolarity::Positive);
355 assert_eq!(trait_ref.self_ty(), dummy_self);
356
357 let span = *spans.first().unwrap();
358
359 let mut missing_generic_params = Vec::new();
362 let generics = tcx.generics_of(trait_ref.def_id);
363 let args: Vec<_> = trait_ref
364 .args
365 .iter()
366 .enumerate()
367 .skip(1)
369 .map(|(index, arg)| {
370 if arg.walk().any(|arg| arg == dummy_self.into()) {
371 let param = &generics.own_params[index];
372 missing_generic_params.push((param.name, param.kind.clone()));
373 param.to_error(tcx)
374 } else {
375 arg
376 }
377 })
378 .collect();
379
380 let empty_generic_args = hir_bounds.iter().any(|hir_bound| {
381 hir_bound.trait_ref.path.res == Res::Def(DefKind::Trait, trait_ref.def_id)
382 && hir_bound.span.contains(span)
383 });
384 self.report_missing_generic_params(
385 missing_generic_params,
386 trait_ref.def_id,
387 span,
388 empty_generic_args,
389 );
390
391 ty::ExistentialPredicate::Trait(ty::ExistentialTraitRef::new(
392 tcx,
393 trait_ref.def_id,
394 args,
395 ))
396 })
397 });
398
399 let existential_projections = projection_bounds.into_iter().map(|(bound, _)| {
400 bound.map_bound(|mut b| {
401 assert_eq!(b.projection_term.self_ty(), dummy_self);
402
403 let references_self = b.projection_term.args.iter().skip(1).any(|arg| {
406 if arg.walk().any(|arg| arg == dummy_self.into()) {
407 return true;
408 }
409 false
410 });
411 if references_self {
412 let guar = tcx
413 .dcx()
414 .span_delayed_bug(span, "trait object projection bounds reference `Self`");
415 b.projection_term = replace_dummy_self_with_error(tcx, b.projection_term, guar);
416 }
417
418 ty::ExistentialPredicate::Projection(ty::ExistentialProjection::erase_self_ty(
419 tcx, b,
420 ))
421 })
422 });
423
424 let mut auto_trait_predicates: Vec<_> = auto_traits
425 .into_iter()
426 .map(|(trait_pred, _)| {
427 assert_eq!(trait_pred.polarity(), ty::PredicatePolarity::Positive);
428 assert_eq!(trait_pred.self_ty().skip_binder(), dummy_self);
429
430 ty::Binder::dummy(ty::ExistentialPredicate::AutoTrait(trait_pred.def_id()))
431 })
432 .collect();
433 auto_trait_predicates.dedup();
434
435 let mut predicates = principal_trait_ref
438 .into_iter()
439 .chain(existential_projections)
440 .chain(auto_trait_predicates)
441 .collect::<SmallVec<[_; 8]>>();
442 predicates.sort_by(|a, b| a.skip_binder().stable_cmp(tcx, &b.skip_binder()));
443 let predicates = tcx.mk_poly_existential_predicates(&predicates);
444
445 let region_bound = self.lower_trait_object_lifetime(lifetime, predicates, span);
446
447 Ty::new_dynamic(tcx, predicates, region_bound)
448 }
449
450 fn lower_trait_object_lifetime(
451 &self,
452 lifetime: &hir::Lifetime,
453 predicates: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
454 span: Span,
455 ) -> ty::Region<'tcx> {
456 if let hir::LifetimeKind::ImplicitObjectLifetimeDefault | hir::LifetimeKind::Infer =
459 lifetime.kind
460 && let Some(region) = self.compute_object_lifetime_bound(span, predicates)
461 {
462 return region;
463 }
464
465 let reason = if let hir::LifetimeKind::ImplicitObjectLifetimeDefault = lifetime.kind {
466 RegionInferReason::ObjectLifetimeDefault(span.shrink_to_hi())
467 } else {
468 RegionInferReason::ExplicitObjectLifetime
469 };
470
471 self.lower_lifetime(lifetime, reason)
472 }
473
474 fn check_elaborated_projection_mentions_input_lifetimes(
479 &self,
480 pred: ty::PolyProjectionPredicate<'tcx>,
481 span: Span,
482 supertrait_span: Span,
483 ) {
484 let tcx = self.tcx();
485
486 let late_bound_in_projection_term =
494 tcx.collect_constrained_late_bound_regions(pred.map_bound(|pred| pred.projection_term));
495 let late_bound_in_term =
496 tcx.collect_referenced_late_bound_regions(pred.map_bound(|pred| pred.term));
497 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/hir_ty_lowering/dyn_trait.rs:497",
"rustc_hir_analysis::hir_ty_lowering::dyn_trait",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/hir_ty_lowering/dyn_trait.rs"),
::tracing_core::__macro_support::Option::Some(497u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering::dyn_trait"),
::tracing_core::field::FieldSet::new(&["late_bound_in_projection_term"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&late_bound_in_projection_term)
as &dyn Value))])
});
} else { ; }
};debug!(?late_bound_in_projection_term);
498 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/hir_ty_lowering/dyn_trait.rs:498",
"rustc_hir_analysis::hir_ty_lowering::dyn_trait",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/hir_ty_lowering/dyn_trait.rs"),
::tracing_core::__macro_support::Option::Some(498u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering::dyn_trait"),
::tracing_core::field::FieldSet::new(&["late_bound_in_term"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&late_bound_in_term)
as &dyn Value))])
});
} else { ; }
};debug!(?late_bound_in_term);
499
500 self.validate_late_bound_regions(
505 late_bound_in_projection_term,
506 late_bound_in_term,
507 |br_name| {
508 let item_name = tcx.item_name(pred.item_def_id());
509 {
self.dcx().struct_span_err(span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("binding for associated type `{0}` references {1}, which does not appear in the trait input types",
item_name, br_name))
})).with_code(E0582)
}struct_span_code_err!(
510 self.dcx(),
511 span,
512 E0582,
513 "binding for associated type `{}` references {}, \
514 which does not appear in the trait input types",
515 item_name,
516 br_name
517 )
518 .with_span_label(supertrait_span, "due to this supertrait")
519 },
520 );
521 }
522
523 x;#[instrument(level = "debug", skip(self, span), ret)]
531 fn compute_object_lifetime_bound(
532 &self,
533 span: Span,
534 existential_predicates: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
535 ) -> Option<ty::Region<'tcx>> {
537 let tcx = self.tcx();
538
539 let derived_region_bounds = traits::wf::object_region_bounds(tcx, existential_predicates);
542
543 if derived_region_bounds.is_empty() {
546 return None;
547 }
548
549 if derived_region_bounds.iter().any(|r| r.is_static()) {
552 return Some(tcx.lifetimes.re_static);
553 }
554
555 let r = derived_region_bounds[0];
559 if derived_region_bounds[1..].iter().any(|r1| r != *r1) {
560 self.dcx().emit_err(crate::diagnostics::AmbiguousLifetimeBound { span });
561 }
562 Some(r)
563 }
564
565 fn prohibit_or_lint_bare_trait_object_ty(
570 &self,
571 span: Span,
572 hir_id: hir::HirId,
573 hir_bounds: &[hir::PolyTraitRef<'tcx>],
574 ) -> Option<ErrorGuaranteed> {
575 struct TraitObjectWithoutDyn<'a, 'tcx> {
576 span: Span,
577 hir_id: HirId,
578 sugg: Vec<(Span, String)>,
579 this: &'a dyn HirTyLowerer<'tcx>,
580 }
581
582 impl<'a, 'b, 'tcx> Diagnostic<'a, ()> for TraitObjectWithoutDyn<'b, 'tcx> {
583 fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a, ()> {
584 let Self { span, hir_id, sugg, this } = self;
585 let mut lint =
586 Diag::new(dcx, level, "trait objects without an explicit `dyn` are deprecated");
587 if span.can_be_used_for_suggestions() {
588 lint.multipart_suggestion(
589 "if this is a dyn-compatible trait, use `dyn`",
590 sugg,
591 Applicability::MachineApplicable,
592 );
593 }
594 this.maybe_suggest_blanket_trait_impl(span, hir_id, &mut lint);
595 lint
596 }
597 }
598
599 let tcx = self.tcx();
600 let [poly_trait_ref, ..] = hir_bounds else { return None };
601
602 let in_path = match tcx.parent_hir_node(hir_id) {
603 hir::Node::Ty(hir::Ty {
604 kind: hir::TyKind::Path(hir::QPath::TypeRelative(qself, _)),
605 ..
606 })
607 | hir::Node::Expr(hir::Expr {
608 kind: hir::ExprKind::Path(hir::QPath::TypeRelative(qself, _)),
609 ..
610 })
611 | hir::Node::PatExpr(hir::PatExpr {
612 kind: hir::PatExprKind::Path(hir::QPath::TypeRelative(qself, _)),
613 ..
614 }) if qself.hir_id == hir_id => true,
615 _ => false,
616 };
617 let needs_bracket = in_path
618 && !tcx
619 .sess
620 .source_map()
621 .span_to_prev_source(span)
622 .ok()
623 .is_some_and(|s| s.trim_end().ends_with('<'));
624
625 let is_global = poly_trait_ref.trait_ref.path.is_global();
626
627 let mut sugg = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(span.shrink_to_lo(),
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}dyn {1}",
if needs_bracket { "<" } else { "" },
if is_global { "(" } else { "" }))
}))]))vec![(
628 span.shrink_to_lo(),
629 format!(
630 "{}dyn {}",
631 if needs_bracket { "<" } else { "" },
632 if is_global { "(" } else { "" },
633 ),
634 )];
635
636 if is_global || needs_bracket {
637 sugg.push((
638 span.shrink_to_hi(),
639 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1}",
if is_global { ")" } else { "" },
if needs_bracket { ">" } else { "" }))
})format!(
640 "{}{}",
641 if is_global { ")" } else { "" },
642 if needs_bracket { ">" } else { "" },
643 ),
644 ));
645 }
646
647 if span.edition().at_least_rust_2021() {
648 let mut diag = {
self.dcx().struct_span_err(span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}",
"expected a type, found a trait"))
})).with_code(E0782)
}rustc_errors::struct_span_code_err!(
649 self.dcx(),
650 span,
651 E0782,
652 "{}",
653 "expected a type, found a trait"
654 );
655 if span.can_be_used_for_suggestions()
656 && poly_trait_ref.trait_ref.trait_def_id().is_some()
657 && !self.maybe_suggest_impl_trait(span, hir_id, hir_bounds, &mut diag)
658 && !self.maybe_suggest_dyn_trait(hir_id, span, sugg, &mut diag)
659 {
660 self.maybe_suggest_add_generic_impl_trait(span, hir_id, &mut diag);
661 }
662 self.maybe_suggest_blanket_trait_impl(span, hir_id, &mut diag);
664 self.maybe_suggest_assoc_ty_bound(hir_id, &mut diag);
665 self.maybe_suggest_typoed_method(
666 hir_id,
667 poly_trait_ref.trait_ref.trait_def_id(),
668 &mut diag,
669 );
670 if let Some(mut sugg) =
673 self.dcx().steal_non_err(span, StashKey::AssociatedTypeSuggestion)
674 && let Suggestions::Enabled(ref mut s1) = diag.suggestions
675 && let Suggestions::Enabled(ref mut s2) = sugg.suggestions
676 {
677 s1.append(s2);
678 sugg.cancel();
679 }
680 Some(diag.emit())
681 } else {
682 tcx.emit_node_span_lint(
683 BARE_TRAIT_OBJECTS,
684 hir_id,
685 span,
686 TraitObjectWithoutDyn { span, hir_id, sugg, this: self },
687 );
688 None
689 }
690 }
691
692 fn maybe_suggest_add_generic_impl_trait(
695 &self,
696 span: Span,
697 hir_id: hir::HirId,
698 diag: &mut Diag<'_>,
699 ) -> bool {
700 let tcx = self.tcx();
701
702 let parent_hir_id = tcx.parent_hir_id(hir_id);
703 let parent_item = tcx.hir_get_parent_item(hir_id).def_id;
704
705 let generics = match tcx.hir_node_by_def_id(parent_item) {
706 hir::Node::Item(hir::Item {
707 kind: hir::ItemKind::Struct(_, generics, variant),
708 ..
709 }) => {
710 if !variant.fields().iter().any(|field| field.hir_id == parent_hir_id) {
711 return false;
712 }
713 generics
714 }
715 hir::Node::Item(hir::Item { kind: hir::ItemKind::Enum(_, generics, def), .. }) => {
716 if !def
717 .variants
718 .iter()
719 .flat_map(|variant| variant.data.fields().iter())
720 .any(|field| field.hir_id == parent_hir_id)
721 {
722 return false;
723 }
724 generics
725 }
726 _ => return false,
727 };
728
729 let Ok(rendered_ty) = tcx.sess.source_map().span_to_snippet(span) else {
730 return false;
731 };
732
733 let param = "TUV"
734 .chars()
735 .map(|c| c.to_string())
736 .chain((0..).map(|i| ::alloc::__export::must_use({ ::alloc::fmt::format(format_args!("P{0}", i)) })format!("P{i}")))
737 .find(|s| !generics.params.iter().any(|param| param.name.ident().as_str() == s))
738 .expect("we definitely can find at least one param name to generate");
739 let mut sugg = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(span, param.to_string())]))vec![(span, param.to_string())];
740 if let Some(insertion_span) = generics.span_for_param_suggestion() {
741 sugg.push((insertion_span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(", {1}: {0}", rendered_ty, param))
})format!(", {param}: {}", rendered_ty)));
742 } else {
743 sugg.push((generics.where_clause_span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("<{1}: {0}>", rendered_ty, param))
})format!("<{param}: {}>", rendered_ty)));
744 }
745 diag.multipart_suggestion(
746 "you might be missing a type parameter",
747 sugg,
748 Applicability::MachineApplicable,
749 );
750 true
751 }
752
753 fn maybe_suggest_blanket_trait_impl<G: EmissionGuarantee>(
755 &self,
756 span: Span,
757 hir_id: hir::HirId,
758 diag: &mut Diag<'_, G>,
759 ) {
760 let tcx = self.tcx();
761 let parent_id = tcx.hir_get_parent_item(hir_id).def_id;
762 if let hir::Node::Item(hir::Item {
763 kind: hir::ItemKind::Impl(hir::Impl { self_ty: impl_self_ty, of_trait, generics, .. }),
764 ..
765 }) = tcx.hir_node_by_def_id(parent_id)
766 && hir_id == impl_self_ty.hir_id
767 {
768 let Some(of_trait) = of_trait else {
769 diag.span_suggestion_verbose(
770 impl_self_ty.span.shrink_to_hi(),
771 "you might have intended to implement this trait for a given type",
772 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" for /* Type */"))
})format!(" for /* Type */"),
773 Applicability::HasPlaceholders,
774 );
775 return;
776 };
777 if !of_trait.trait_ref.trait_def_id().is_some_and(|def_id| def_id.is_local()) {
778 return;
779 }
780 let of_trait_span = of_trait.trait_ref.path.span;
781 let Ok(of_trait_name) = tcx.sess.source_map().span_to_snippet(of_trait_span) else {
783 return;
784 };
785
786 let Ok(impl_trait_name) = self.tcx().sess.source_map().span_to_snippet(span) else {
787 return;
788 };
789 let sugg = self.add_generic_param_suggestion(generics, span, &impl_trait_name);
790 diag.multipart_suggestion(
791 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("alternatively use a blanket implementation to implement `{0}` for all types that also implement `{1}`",
of_trait_name, impl_trait_name))
})format!(
792 "alternatively use a blanket implementation to implement `{of_trait_name}` for \
793 all types that also implement `{impl_trait_name}`"
794 ),
795 sugg,
796 Applicability::MaybeIncorrect,
797 );
798 }
799 }
800
801 fn maybe_suggest_dyn_trait(
809 &self,
810 hir_id: hir::HirId,
811 span: Span,
812 sugg: Vec<(Span, String)>,
813 diag: &mut Diag<'_>,
814 ) -> bool {
815 let tcx = self.tcx();
816 if span.in_derive_expansion() {
817 return false;
818 }
819
820 match tcx.parent_hir_node(hir_id) {
823 hir::Node::Ty(_)
829 | hir::Node::Expr(_)
830 | hir::Node::PatExpr(_)
831 | hir::Node::PathSegment(_)
832 | hir::Node::AssocItemConstraint(_)
833 | hir::Node::TraitRef(_)
834 | hir::Node::Item(_)
835 | hir::Node::WherePredicate(_) => {}
836
837 hir::Node::Field(field) => {
838 if let hir::Node::Item(hir::Item {
840 kind: hir::ItemKind::Struct(_, _, variant), ..
841 }) = tcx.parent_hir_node(field.hir_id)
842 && variant
843 .fields()
844 .last()
845 .is_some_and(|tail_field| tail_field.hir_id == field.hir_id)
846 {
847 } else {
849 return false;
850 }
851 }
852 _ => return false,
853 }
854
855 diag.multipart_suggestion(
857 "you can add the `dyn` keyword if you want a trait object",
858 sugg,
859 Applicability::MachineApplicable,
860 );
861 true
862 }
863
864 fn add_generic_param_suggestion(
865 &self,
866 generics: &hir::Generics<'_>,
867 self_ty_span: Span,
868 impl_trait_name: &str,
869 ) -> Vec<(Span, String)> {
870 let param_name = generics.params.next_type_param_name(None);
872
873 let add_generic_sugg = if let Some(span) = generics.span_for_param_suggestion() {
874 (span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(", {0}: {1}", param_name,
impl_trait_name))
})format!(", {param_name}: {impl_trait_name}"))
875 } else {
876 (generics.span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("<{0}: {1}>", param_name,
impl_trait_name))
})format!("<{param_name}: {impl_trait_name}>"))
877 };
878 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(self_ty_span, param_name), add_generic_sugg]))vec![(self_ty_span, param_name), add_generic_sugg]
879 }
880
881 fn maybe_suggest_impl_trait(
883 &self,
884 span: Span,
885 hir_id: hir::HirId,
886 hir_bounds: &[hir::PolyTraitRef<'tcx>],
887 diag: &mut Diag<'_>,
888 ) -> bool {
889 let tcx = self.tcx();
890 let parent_id = tcx.hir_get_parent_item(hir_id).def_id;
891 let (sig, generics) = match tcx.hir_node_by_def_id(parent_id) {
898 hir::Node::Item(hir::Item {
899 kind: hir::ItemKind::Fn { sig, generics, .. }, ..
900 }) => (sig, generics),
901 hir::Node::TraitItem(hir::TraitItem {
902 kind: hir::TraitItemKind::Fn(sig, _),
903 generics,
904 ..
905 }) => (sig, generics),
906 hir::Node::ImplItem(hir::ImplItem {
907 kind: hir::ImplItemKind::Fn(sig, _),
908 generics,
909 ..
910 }) => (sig, generics),
911 _ => return false,
912 };
913 let Ok(trait_name) = tcx.sess.source_map().span_to_snippet(span) else {
914 return false;
915 };
916 let impl_sugg = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(span.shrink_to_lo(), "impl ".to_string())]))vec![(span.shrink_to_lo(), "impl ".to_string())];
917 let is_dyn_compatible = hir_bounds.iter().all(|bound| match bound.trait_ref.path.res {
919 Res::Def(DefKind::Trait, id) => tcx.is_dyn_compatible(id),
920 _ => false,
921 });
922
923 let borrowed = #[allow(non_exhaustive_omitted_patterns)] match tcx.parent_hir_node(hir_id) {
hir::Node::Ty(hir::Ty { kind: hir::TyKind::Ref(..), .. }) => true,
_ => false,
}matches!(
924 tcx.parent_hir_node(hir_id),
925 hir::Node::Ty(hir::Ty { kind: hir::TyKind::Ref(..), .. })
926 );
927
928 if let hir::FnRetTy::Return(ty) = sig.decl.output
930 && ty.peel_refs().hir_id == hir_id
931 {
932 let pre = if !is_dyn_compatible {
933 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` is dyn-incompatible, ",
trait_name))
})format!("`{trait_name}` is dyn-incompatible, ")
934 } else {
935 String::new()
936 };
937 let msg = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}use `impl {1}` to return an opaque type, as long as you return a single underlying type",
pre, trait_name))
})format!(
938 "{pre}use `impl {trait_name}` to return an opaque type, as long as you return a \
939 single underlying type",
940 );
941
942 diag.multipart_suggestion(msg, impl_sugg, Applicability::MachineApplicable);
943
944 if is_dyn_compatible {
946 let suggestion = if borrowed {
950 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(ty.span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("Box<dyn {0}>",
trait_name))
}))]))vec![(ty.span, format!("Box<dyn {trait_name}>"))]
951 } else {
952 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(ty.span.shrink_to_lo(), "Box<dyn ".to_string()),
(ty.span.shrink_to_hi(), ">".to_string())]))vec![
953 (ty.span.shrink_to_lo(), "Box<dyn ".to_string()),
954 (ty.span.shrink_to_hi(), ">".to_string()),
955 ]
956 };
957
958 diag.multipart_suggestion(
959 "alternatively, you can return an owned trait object",
960 suggestion,
961 Applicability::MachineApplicable,
962 );
963 }
964 return true;
965 }
966
967 for ty in sig.decl.inputs {
969 if ty.peel_refs().hir_id != hir_id {
970 continue;
971 }
972 let sugg = self.add_generic_param_suggestion(generics, span, &trait_name);
973 diag.multipart_suggestion(
974 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("use a new generic type parameter, constrained by `{0}`",
trait_name))
})format!("use a new generic type parameter, constrained by `{trait_name}`"),
975 sugg,
976 Applicability::MachineApplicable,
977 );
978 diag.multipart_suggestion(
979 "you can also use an opaque type, but users won't be able to specify the type \
980 parameter when calling the `fn`, having to rely exclusively on type inference",
981 impl_sugg,
982 Applicability::MachineApplicable,
983 );
984 if !is_dyn_compatible {
985 diag.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` is dyn-incompatible, otherwise a trait object could be used",
trait_name))
})format!(
986 "`{trait_name}` is dyn-incompatible, otherwise a trait object could be used"
987 ));
988 } else {
989 let (dyn_str, paren_dyn_str) =
991 if borrowed { ("dyn ", "(dyn ") } else { ("&dyn ", "&(dyn ") };
992
993 let sugg = if let [_, _, ..] = hir_bounds {
994 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(span.shrink_to_lo(), paren_dyn_str.to_string()),
(span.shrink_to_hi(), ")".to_string())]))vec![
996 (span.shrink_to_lo(), paren_dyn_str.to_string()),
997 (span.shrink_to_hi(), ")".to_string()),
998 ]
999 } else {
1000 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(span.shrink_to_lo(), dyn_str.to_string())]))vec![(span.shrink_to_lo(), dyn_str.to_string())]
1001 };
1002 diag.multipart_suggestion(
1003 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("alternatively, use a trait object to accept any type that implements `{0}`, accessing its methods at runtime using dynamic dispatch",
trait_name))
})format!(
1004 "alternatively, use a trait object to accept any type that implements \
1005 `{trait_name}`, accessing its methods at runtime using dynamic dispatch",
1006 ),
1007 sugg,
1008 Applicability::MachineApplicable,
1009 );
1010 }
1011 return true;
1012 }
1013 false
1014 }
1015
1016 fn maybe_suggest_assoc_ty_bound(&self, hir_id: hir::HirId, diag: &mut Diag<'_>) {
1017 let mut parents = self.tcx().hir_parent_iter(hir_id);
1018
1019 if let Some((c_hir_id, hir::Node::AssocItemConstraint(constraint))) = parents.next()
1020 && let Some(obj_ty) = constraint.ty()
1021 && let Some((_, hir::Node::TraitRef(trait_ref))) = parents.next()
1022 {
1023 if let Some((_, hir::Node::Ty(ty))) = parents.next()
1024 && let hir::TyKind::TraitObject(..) = ty.kind
1025 {
1026 return;
1028 }
1029
1030 if trait_ref
1031 .path
1032 .segments
1033 .iter()
1034 .find_map(|seg| {
1035 seg.args.filter(|args| args.constraints.iter().any(|c| c.hir_id == c_hir_id))
1036 })
1037 .is_none_or(|args| args.parenthesized != hir::GenericArgsParentheses::No)
1038 {
1039 return;
1041 }
1042
1043 let lo = if constraint.gen_args.span_ext.is_dummy() {
1044 constraint.ident.span
1045 } else {
1046 constraint.gen_args.span_ext
1047 };
1048 let hi = obj_ty.span;
1049
1050 if !lo.eq_ctxt(hi) {
1051 return;
1052 }
1053
1054 diag.span_suggestion_verbose(
1055 lo.between(hi),
1056 "you might have meant to write a bound here",
1057 ": ",
1058 Applicability::MaybeIncorrect,
1059 );
1060 }
1061 }
1062
1063 fn maybe_suggest_typoed_method(
1064 &self,
1065 hir_id: hir::HirId,
1066 trait_def_id: Option<DefId>,
1067 diag: &mut Diag<'_>,
1068 ) {
1069 let tcx = self.tcx();
1070 let Some(trait_def_id) = trait_def_id else {
1071 return;
1072 };
1073 let hir::Node::Expr(hir::Expr {
1074 kind: hir::ExprKind::Path(hir::QPath::TypeRelative(path_ty, segment)),
1075 ..
1076 }) = tcx.parent_hir_node(hir_id)
1077 else {
1078 return;
1079 };
1080 if path_ty.hir_id != hir_id {
1081 return;
1082 }
1083 let names: Vec<_> = tcx
1084 .associated_items(trait_def_id)
1085 .in_definition_order()
1086 .filter(|assoc| assoc.namespace() == hir::def::Namespace::ValueNS)
1087 .map(|cand| cand.name())
1088 .collect();
1089 if let Some(typo) = find_best_match_for_name(&names, segment.ident.name, None) {
1090 diag.span_suggestion_verbose(
1091 segment.ident.span,
1092 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("you may have misspelled this associated item, causing `{0}` to be interpreted as a type rather than a trait",
tcx.item_name(trait_def_id)))
})format!(
1093 "you may have misspelled this associated item, causing `{}` \
1094 to be interpreted as a type rather than a trait",
1095 tcx.item_name(trait_def_id),
1096 ),
1097 typo,
1098 Applicability::MaybeIncorrect,
1099 );
1100 }
1101 }
1102}
1103
1104fn replace_dummy_self_with_error<'tcx, T: TypeFoldable<TyCtxt<'tcx>>>(
1105 tcx: TyCtxt<'tcx>,
1106 t: T,
1107 guar: ErrorGuaranteed,
1108) -> T {
1109 t.fold_with(&mut BottomUpFolder {
1110 tcx,
1111 ty_op: |ty| {
1112 if ty == tcx.types.trait_object_dummy_self { Ty::new_error(tcx, guar) } else { ty }
1113 },
1114 lt_op: |lt| lt,
1115 ct_op: |ct| ct,
1116 })
1117}