rustc_hir_analysis/hir_ty_lowering/
dyn_compatibility.rs1use rustc_data_structures::fx::{FxHashSet, FxIndexMap, FxIndexSet};
2use rustc_errors::codes::*;
3use rustc_errors::struct_span_code_err;
4use rustc_hir as hir;
5use rustc_hir::def::{DefKind, Res};
6use rustc_lint_defs::builtin::UNUSED_ASSOCIATED_TYPE_BOUNDS;
7use rustc_middle::ty::elaborate::ClauseWithSupertraitSpan;
8use rustc_middle::ty::{
9 self, BottomUpFolder, DynKind, ExistentialPredicateStableCmpExt as _, Ty, TyCtxt, TypeFoldable,
10 TypeVisitableExt, Upcast,
11};
12use rustc_span::{ErrorGuaranteed, Span};
13use rustc_trait_selection::error_reporting::traits::report_dyn_incompatibility;
14use rustc_trait_selection::traits;
15use smallvec::{SmallVec, smallvec};
16use tracing::{debug, instrument};
17
18use super::HirTyLowerer;
19use crate::errors::SelfInTypeAlias;
20use crate::hir_ty_lowering::{
21 GenericArgCountMismatch, GenericArgCountResult, PredicateFilter, RegionInferReason,
22};
23
24impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
25 #[instrument(level = "debug", skip_all, ret)]
27 pub(super) fn lower_trait_object_ty(
28 &self,
29 span: Span,
30 hir_id: hir::HirId,
31 hir_bounds: &[hir::PolyTraitRef<'tcx>],
32 lifetime: &hir::Lifetime,
33 representation: DynKind,
34 ) -> Ty<'tcx> {
35 let tcx = self.tcx();
36 let dummy_self = tcx.types.trait_object_dummy_self;
37
38 let mut user_written_bounds = Vec::new();
39 let mut potential_assoc_types = Vec::new();
40 for trait_bound in hir_bounds.iter() {
41 if let hir::BoundPolarity::Maybe(_) = trait_bound.modifiers.polarity {
42 continue;
43 }
44 if let GenericArgCountResult {
45 correct:
46 Err(GenericArgCountMismatch { invalid_args: cur_potential_assoc_types, .. }),
47 ..
48 } = self.lower_poly_trait_ref(
49 &trait_bound.trait_ref,
50 trait_bound.span,
51 hir::BoundConstness::Never,
52 hir::BoundPolarity::Positive,
53 dummy_self,
54 &mut user_written_bounds,
55 PredicateFilter::SelfOnly,
56 ) {
57 potential_assoc_types.extend(cur_potential_assoc_types);
58 }
59 }
60
61 let ast_bounds: Vec<_> =
62 hir_bounds.iter().map(|&trait_ref| hir::GenericBound::Trait(trait_ref)).collect();
63
64 self.add_default_traits(&mut user_written_bounds, dummy_self, &ast_bounds, None, span);
65
66 let (elaborated_trait_bounds, elaborated_projection_bounds) =
67 traits::expand_trait_aliases(tcx, user_written_bounds.iter().copied());
68 let (regular_traits, mut auto_traits): (Vec<_>, Vec<_>) = elaborated_trait_bounds
69 .into_iter()
70 .partition(|(trait_ref, _)| !tcx.trait_is_auto(trait_ref.def_id()));
71
72 if regular_traits.is_empty() && auto_traits.is_empty() {
74 let guar =
75 self.report_trait_object_with_no_traits(span, user_written_bounds.iter().copied());
76 return Ty::new_error(tcx, guar);
77 }
78 if regular_traits.len() > 1 {
80 let guar = self.report_trait_object_addition_traits(®ular_traits);
81 return Ty::new_error(tcx, guar);
82 }
83 if let Err(guar) = regular_traits.error_reported() {
85 return Ty::new_error(tcx, guar);
86 }
87
88 for (clause, span) in user_written_bounds {
92 if let Some(trait_pred) = clause.as_trait_clause() {
93 let violations = self.dyn_compatibility_violations(trait_pred.def_id());
94 if !violations.is_empty() {
95 let reported = report_dyn_incompatibility(
96 tcx,
97 span,
98 Some(hir_id),
99 trait_pred.def_id(),
100 &violations,
101 )
102 .emit();
103 return Ty::new_error(tcx, reported);
104 }
105 }
106 }
107
108 let mut projection_bounds = FxIndexMap::default();
118 for (proj, proj_span) in elaborated_projection_bounds {
119 let proj = proj.map_bound(|mut b| {
120 if let Some(term_ty) = &b.term.as_type() {
121 let references_self = term_ty.walk().any(|arg| arg == dummy_self.into());
122 if references_self {
123 let guar = self.dcx().emit_err(SelfInTypeAlias { span });
126 b.term = replace_dummy_self_with_error(tcx, b.term, guar);
127 }
128 }
129 b
130 });
131
132 let key = (
133 proj.skip_binder().projection_term.def_id,
134 tcx.anonymize_bound_vars(
135 proj.map_bound(|proj| proj.projection_term.trait_ref(tcx)),
136 ),
137 );
138 if let Some((old_proj, old_proj_span)) =
139 projection_bounds.insert(key, (proj, proj_span))
140 && tcx.anonymize_bound_vars(proj) != tcx.anonymize_bound_vars(old_proj)
141 {
142 let item = tcx.item_name(proj.item_def_id());
143 self.dcx()
144 .struct_span_err(
145 span,
146 format!(
147 "conflicting associated type bounds for `{item}` when \
148 expanding trait alias"
149 ),
150 )
151 .with_span_label(
152 old_proj_span,
153 format!("`{item}` is specified to be `{}` here", old_proj.term()),
154 )
155 .with_span_label(
156 proj_span,
157 format!("`{item}` is specified to be `{}` here", proj.term()),
158 )
159 .emit();
160 }
161 }
162
163 let principal_trait = regular_traits.into_iter().next();
164
165 let mut ordered_associated_types = vec![];
172
173 if let Some((principal_trait, ref spans)) = principal_trait {
174 let principal_trait = principal_trait.map_bound(|trait_pred| {
175 assert_eq!(trait_pred.polarity, ty::PredicatePolarity::Positive);
176 trait_pred.trait_ref
177 });
178
179 for ClauseWithSupertraitSpan { clause, supertrait_span } in traits::elaborate(
180 tcx,
181 [ClauseWithSupertraitSpan::new(
182 ty::TraitRef::identity(tcx, principal_trait.def_id()).upcast(tcx),
183 *spans.last().unwrap(),
184 )],
185 )
186 .filter_only_self()
187 {
188 let clause = clause.instantiate_supertrait(tcx, principal_trait);
189 debug!("observing object predicate `{clause:?}`");
190
191 let bound_predicate = clause.kind();
192 match bound_predicate.skip_binder() {
193 ty::ClauseKind::Trait(pred) => {
194 let trait_ref =
196 tcx.anonymize_bound_vars(bound_predicate.rebind(pred.trait_ref));
197 ordered_associated_types.extend(
198 tcx.associated_items(pred.trait_ref.def_id)
199 .in_definition_order()
200 .filter(|item| item.is_type())
202 .filter(|item| !item.is_impl_trait_in_trait())
204 .map(|item| (item.def_id, trait_ref)),
205 );
206 }
207 ty::ClauseKind::Projection(pred) => {
208 let pred = bound_predicate.rebind(pred);
209 let references_self = match pred.skip_binder().term.kind() {
212 ty::TermKind::Ty(ty) => ty.walk().any(|arg| arg == dummy_self.into()),
213 ty::TermKind::Const(_) => false,
215 };
216
217 if !references_self {
235 let key = (
236 pred.skip_binder().projection_term.def_id,
237 tcx.anonymize_bound_vars(
238 pred.map_bound(|proj| proj.projection_term.trait_ref(tcx)),
239 ),
240 );
241 if !projection_bounds.contains_key(&key) {
242 projection_bounds.insert(key, (pred, supertrait_span));
243 }
244 }
245
246 self.check_elaborated_projection_mentions_input_lifetimes(
247 pred,
248 *spans.first().unwrap(),
249 supertrait_span,
250 );
251 }
252 _ => (),
253 }
254 }
255 }
256
257 for &(projection_bound, span) in projection_bounds.values() {
264 let def_id = projection_bound.item_def_id();
265 if tcx.generics_require_sized_self(def_id) {
266 tcx.emit_node_span_lint(
267 UNUSED_ASSOCIATED_TYPE_BOUNDS,
268 hir_id,
269 span,
270 crate::errors::UnusedAssociatedTypeBounds { span },
271 );
272 }
273 }
274
275 let mut missing_assoc_types = FxIndexSet::default();
282 let projection_bounds: Vec<_> = ordered_associated_types
283 .into_iter()
284 .filter_map(|key| {
285 if let Some(assoc) = projection_bounds.get(&key) {
286 Some(*assoc)
287 } else {
288 if !tcx.generics_require_sized_self(key.0) {
293 missing_assoc_types.insert(key);
294 }
295 None
296 }
297 })
298 .collect();
299
300 if let Err(guar) = self.check_for_required_assoc_tys(
301 principal_trait.as_ref().map_or(smallvec![], |(_, spans)| spans.clone()),
302 missing_assoc_types,
303 potential_assoc_types,
304 hir_bounds,
305 ) {
306 return Ty::new_error(tcx, guar);
307 }
308
309 let mut duplicates = FxHashSet::default();
314 auto_traits.retain(|(trait_pred, _)| duplicates.insert(trait_pred.def_id()));
315
316 debug!(?principal_trait);
317 debug!(?auto_traits);
318
319 let principal_trait_ref = principal_trait.map(|(trait_pred, spans)| {
321 trait_pred.map_bound(|trait_pred| {
322 let trait_ref = trait_pred.trait_ref;
323 assert_eq!(trait_pred.polarity, ty::PredicatePolarity::Positive);
324 assert_eq!(trait_ref.self_ty(), dummy_self);
325
326 let span = *spans.first().unwrap();
327
328 let mut missing_type_params = vec![];
331 let generics = tcx.generics_of(trait_ref.def_id);
332 let args: Vec<_> = trait_ref
333 .args
334 .iter()
335 .enumerate()
336 .skip(1)
338 .map(|(index, arg)| {
339 if arg.walk().any(|arg| arg == dummy_self.into()) {
340 let param = &generics.own_params[index];
341 missing_type_params.push(param.name);
342 Ty::new_misc_error(tcx).into()
343 } else {
344 arg
345 }
346 })
347 .collect();
348
349 let empty_generic_args = hir_bounds.iter().any(|hir_bound| {
350 hir_bound.trait_ref.path.res == Res::Def(DefKind::Trait, trait_ref.def_id)
351 && hir_bound.span.contains(span)
352 });
353 self.report_missing_type_params(
354 missing_type_params,
355 trait_ref.def_id,
356 span,
357 empty_generic_args,
358 );
359
360 ty::ExistentialPredicate::Trait(ty::ExistentialTraitRef::new(
361 tcx,
362 trait_ref.def_id,
363 args,
364 ))
365 })
366 });
367
368 let existential_projections = projection_bounds.into_iter().map(|(bound, _)| {
369 bound.map_bound(|mut b| {
370 assert_eq!(b.projection_term.self_ty(), dummy_self);
371
372 let references_self = b.projection_term.args.iter().skip(1).any(|arg| {
375 if arg.walk().any(|arg| arg == dummy_self.into()) {
376 return true;
377 }
378 false
379 });
380 if references_self {
381 let guar = tcx
382 .dcx()
383 .span_delayed_bug(span, "trait object projection bounds reference `Self`");
384 b.projection_term = replace_dummy_self_with_error(tcx, b.projection_term, guar);
385 }
386
387 ty::ExistentialPredicate::Projection(ty::ExistentialProjection::erase_self_ty(
388 tcx, b,
389 ))
390 })
391 });
392
393 let mut auto_trait_predicates: Vec<_> = auto_traits
394 .into_iter()
395 .map(|(trait_pred, _)| {
396 assert_eq!(trait_pred.polarity(), ty::PredicatePolarity::Positive);
397 assert_eq!(trait_pred.self_ty().skip_binder(), dummy_self);
398
399 ty::Binder::dummy(ty::ExistentialPredicate::AutoTrait(trait_pred.def_id()))
400 })
401 .collect();
402 auto_trait_predicates.dedup();
403
404 let mut v = principal_trait_ref
407 .into_iter()
408 .chain(existential_projections)
409 .chain(auto_trait_predicates)
410 .collect::<SmallVec<[_; 8]>>();
411 v.sort_by(|a, b| a.skip_binder().stable_cmp(tcx, &b.skip_binder()));
412 let existential_predicates = tcx.mk_poly_existential_predicates(&v);
413
414 let region_bound = if !lifetime.is_elided() {
416 self.lower_lifetime(lifetime, RegionInferReason::ExplicitObjectLifetime)
417 } else {
418 self.compute_object_lifetime_bound(span, existential_predicates).unwrap_or_else(|| {
419 if tcx.named_bound_var(lifetime.hir_id).is_some() {
421 self.lower_lifetime(lifetime, RegionInferReason::ExplicitObjectLifetime)
422 } else {
423 let reason =
424 if let hir::LifetimeKind::ImplicitObjectLifetimeDefault = lifetime.kind {
425 if let hir::Node::Ty(hir::Ty {
426 kind: hir::TyKind::Ref(parent_lifetime, _),
427 ..
428 }) = tcx.parent_hir_node(hir_id)
429 && tcx.named_bound_var(parent_lifetime.hir_id).is_none()
430 {
431 RegionInferReason::ExplicitObjectLifetime
433 } else {
434 RegionInferReason::ObjectLifetimeDefault
435 }
436 } else {
437 RegionInferReason::ExplicitObjectLifetime
438 };
439 self.re_infer(span, reason)
440 }
441 })
442 };
443 debug!(?region_bound);
444
445 Ty::new_dynamic(tcx, existential_predicates, region_bound, representation)
446 }
447
448 fn check_elaborated_projection_mentions_input_lifetimes(
453 &self,
454 pred: ty::PolyProjectionPredicate<'tcx>,
455 span: Span,
456 supertrait_span: Span,
457 ) {
458 let tcx = self.tcx();
459
460 let late_bound_in_projection_term =
468 tcx.collect_constrained_late_bound_regions(pred.map_bound(|pred| pred.projection_term));
469 let late_bound_in_term =
470 tcx.collect_referenced_late_bound_regions(pred.map_bound(|pred| pred.term));
471 debug!(?late_bound_in_projection_term);
472 debug!(?late_bound_in_term);
473
474 self.validate_late_bound_regions(
480 late_bound_in_projection_term,
481 late_bound_in_term,
482 |br_name| {
483 let item_name = tcx.item_name(pred.item_def_id());
484 struct_span_code_err!(
485 self.dcx(),
486 span,
487 E0582,
488 "binding for associated type `{}` references {}, \
489 which does not appear in the trait input types",
490 item_name,
491 br_name
492 )
493 .with_span_label(supertrait_span, "due to this supertrait")
494 },
495 );
496 }
497}
498
499fn replace_dummy_self_with_error<'tcx, T: TypeFoldable<TyCtxt<'tcx>>>(
500 tcx: TyCtxt<'tcx>,
501 t: T,
502 guar: ErrorGuaranteed,
503) -> T {
504 t.fold_with(&mut BottomUpFolder {
505 tcx,
506 ty_op: |ty| {
507 if ty == tcx.types.trait_object_dummy_self { Ty::new_error(tcx, guar) } else { ty }
508 },
509 lt_op: |lt| lt,
510 ct_op: |ct| ct,
511 })
512}