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