1use std::collections::VecDeque;
2use std::fmt::Write;
3use std::ops::ControlFlow;
4
5use rustc_data_structures::fx::FxHashSet;
6use rustc_errors::codes::*;
7use rustc_errors::{Applicability, MultiSpan, pluralize, struct_span_code_err};
8use rustc_hir as hir;
9use rustc_hir::def::{DefKind, Res};
10use rustc_middle::dep_graph::DepKind;
11use rustc_middle::query::CycleError;
12use rustc_middle::query::plumbing::CyclePlaceholder;
13use rustc_middle::ty::{self, Representability, Ty, TyCtxt};
14use rustc_middle::{bug, span_bug};
15use rustc_span::def_id::LocalDefId;
16use rustc_span::{ErrorGuaranteed, Span};
17
18use crate::job::report_cycle;
19
20pub(crate) trait FromCycleError<'tcx>: Sized {
21 fn from_cycle_error(tcx: TyCtxt<'tcx>, cycle_error: CycleError, guar: ErrorGuaranteed) -> Self;
26}
27
28impl<'tcx, T> FromCycleError<'tcx> for T {
29 default fn from_cycle_error(
30 tcx: TyCtxt<'tcx>,
31 cycle_error: CycleError,
32 _guar: ErrorGuaranteed,
33 ) -> T {
34 let Some(guar) = tcx.sess.dcx().has_errors() else {
35 ::rustc_middle::util::bug::bug_fmt(format_args!("<{0} as FromCycleError>::from_cycle_error called without errors: {1:#?}",
std::any::type_name::<T>(), cycle_error.cycle));bug!(
36 "<{} as FromCycleError>::from_cycle_error called without errors: {:#?}",
37 std::any::type_name::<T>(),
38 cycle_error.cycle,
39 );
40 };
41 guar.raise_fatal();
42 }
43}
44
45impl<'tcx> FromCycleError<'tcx> for Ty<'_> {
46 fn from_cycle_error(tcx: TyCtxt<'tcx>, _: CycleError, guar: ErrorGuaranteed) -> Self {
47 unsafe { std::mem::transmute::<Ty<'tcx>, Ty<'_>>(Ty::new_error(tcx, guar)) }
50 }
51}
52
53impl<'tcx> FromCycleError<'tcx> for Result<ty::EarlyBinder<'_, Ty<'_>>, CyclePlaceholder> {
54 fn from_cycle_error(_tcx: TyCtxt<'tcx>, _: CycleError, guar: ErrorGuaranteed) -> Self {
55 Err(CyclePlaceholder(guar))
56 }
57}
58
59impl<'tcx> FromCycleError<'tcx> for ty::Binder<'_, ty::FnSig<'_>> {
60 fn from_cycle_error(tcx: TyCtxt<'tcx>, cycle_error: CycleError, guar: ErrorGuaranteed) -> Self {
61 let err = Ty::new_error(tcx, guar);
62
63 let arity = if let Some(info) = cycle_error.cycle.get(0)
64 && info.frame.dep_kind == DepKind::fn_sig
65 && let Some(def_id) = info.frame.def_id
66 && let Some(node) = tcx.hir_get_if_local(def_id)
67 && let Some(sig) = node.fn_sig()
68 {
69 sig.decl.inputs.len()
70 } else {
71 tcx.dcx().abort_if_errors();
72 ::core::panicking::panic("internal error: entered unreachable code")unreachable!()
73 };
74
75 let fn_sig = ty::Binder::dummy(tcx.mk_fn_sig(
76 std::iter::repeat_n(err, arity),
77 err,
78 false,
79 rustc_hir::Safety::Safe,
80 rustc_abi::ExternAbi::Rust,
81 ));
82
83 unsafe { std::mem::transmute::<ty::PolyFnSig<'tcx>, ty::Binder<'_, ty::FnSig<'_>>>(fn_sig) }
86 }
87}
88
89impl<'tcx> FromCycleError<'tcx> for Representability {
90 fn from_cycle_error(
91 tcx: TyCtxt<'tcx>,
92 cycle_error: CycleError,
93 _guar: ErrorGuaranteed,
94 ) -> Self {
95 let mut item_and_field_ids = Vec::new();
96 let mut representable_ids = FxHashSet::default();
97 for info in &cycle_error.cycle {
98 if info.frame.dep_kind == DepKind::representability
99 && let Some(field_id) = info.frame.def_id
100 && let Some(field_id) = field_id.as_local()
101 && let Some(DefKind::Field) = info.frame.info.def_kind
102 {
103 let parent_id = tcx.parent(field_id.to_def_id());
104 let item_id = match tcx.def_kind(parent_id) {
105 DefKind::Variant => tcx.parent(parent_id),
106 _ => parent_id,
107 };
108 item_and_field_ids.push((item_id.expect_local(), field_id));
109 }
110 }
111 for info in &cycle_error.cycle {
112 if info.frame.dep_kind == DepKind::representability_adt_ty
113 && let Some(def_id) = info.frame.def_id_for_ty_in_cycle
114 && let Some(def_id) = def_id.as_local()
115 && !item_and_field_ids.iter().any(|&(id, _)| id == def_id)
116 {
117 representable_ids.insert(def_id);
118 }
119 }
120 let guar = recursive_type_error(tcx, item_and_field_ids, &representable_ids);
121 Representability::Infinite(guar)
122 }
123}
124
125impl<'tcx> FromCycleError<'tcx> for ty::EarlyBinder<'_, Ty<'_>> {
126 fn from_cycle_error(tcx: TyCtxt<'tcx>, cycle_error: CycleError, guar: ErrorGuaranteed) -> Self {
127 ty::EarlyBinder::bind(Ty::from_cycle_error(tcx, cycle_error, guar))
128 }
129}
130
131impl<'tcx> FromCycleError<'tcx> for ty::EarlyBinder<'_, ty::Binder<'_, ty::FnSig<'_>>> {
132 fn from_cycle_error(tcx: TyCtxt<'tcx>, cycle_error: CycleError, guar: ErrorGuaranteed) -> Self {
133 ty::EarlyBinder::bind(ty::Binder::from_cycle_error(tcx, cycle_error, guar))
134 }
135}
136
137impl<'tcx> FromCycleError<'tcx> for &[ty::Variance] {
138 fn from_cycle_error(
139 tcx: TyCtxt<'tcx>,
140 cycle_error: CycleError,
141 _guar: ErrorGuaranteed,
142 ) -> Self {
143 search_for_cycle_permutation(
144 &cycle_error.cycle,
145 |cycle| {
146 if let Some(info) = cycle.get(0)
147 && info.frame.dep_kind == DepKind::variances_of
148 && let Some(def_id) = info.frame.def_id
149 {
150 let n = tcx.generics_of(def_id).own_params.len();
151 ControlFlow::Break(::alloc::vec::from_elem(ty::Bivariant, n)vec![ty::Bivariant; n].leak())
152 } else {
153 ControlFlow::Continue(())
154 }
155 },
156 || {
157 ::rustc_middle::util::bug::span_bug_fmt(cycle_error.usage.as_ref().unwrap().0,
format_args!("only `variances_of` returns `&[ty::Variance]`"))span_bug!(
158 cycle_error.usage.as_ref().unwrap().0,
159 "only `variances_of` returns `&[ty::Variance]`"
160 )
161 },
162 )
163 }
164}
165
166fn search_for_cycle_permutation<Q, T>(
168 cycle: &[Q],
169 try_cycle: impl Fn(&mut VecDeque<&Q>) -> ControlFlow<T, ()>,
170 otherwise: impl FnOnce() -> T,
171) -> T {
172 let mut cycle: VecDeque<_> = cycle.iter().collect();
173 for _ in 0..cycle.len() {
174 match try_cycle(&mut cycle) {
175 ControlFlow::Continue(_) => {
176 cycle.rotate_left(1);
177 }
178 ControlFlow::Break(t) => return t,
179 }
180 }
181
182 otherwise()
183}
184
185impl<'tcx, T> FromCycleError<'tcx> for Result<T, &'_ ty::layout::LayoutError<'_>> {
186 fn from_cycle_error(
187 tcx: TyCtxt<'tcx>,
188 cycle_error: CycleError,
189 _guar: ErrorGuaranteed,
190 ) -> Self {
191 let diag = search_for_cycle_permutation(
192 &cycle_error.cycle,
193 |cycle| {
194 if cycle[0].frame.dep_kind == DepKind::layout_of
195 && let Some(def_id) = cycle[0].frame.def_id_for_ty_in_cycle
196 && let Some(def_id) = def_id.as_local()
197 && let def_kind = tcx.def_kind(def_id)
198 && #[allow(non_exhaustive_omitted_patterns)] match def_kind {
DefKind::Closure => true,
_ => false,
}matches!(def_kind, DefKind::Closure)
199 && let Some(coroutine_kind) = tcx.coroutine_kind(def_id)
200 {
201 let span = if coroutine_kind.is_fn_like() {
206 tcx.def_span(tcx.local_parent(def_id))
207 } else {
208 tcx.def_span(def_id)
209 };
210 let mut diag = {
tcx.sess.dcx().struct_span_err(span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("recursion in {0} {1} requires boxing",
tcx.def_kind_descr_article(def_kind, def_id.to_def_id()),
tcx.def_kind_descr(def_kind, def_id.to_def_id())))
})).with_code(E0733)
}struct_span_code_err!(
211 tcx.sess.dcx(),
212 span,
213 E0733,
214 "recursion in {} {} requires boxing",
215 tcx.def_kind_descr_article(def_kind, def_id.to_def_id()),
216 tcx.def_kind_descr(def_kind, def_id.to_def_id()),
217 );
218 for (i, info) in cycle.iter().enumerate() {
219 if info.frame.dep_kind != DepKind::layout_of {
220 continue;
221 }
222 let Some(frame_def_id) = info.frame.def_id_for_ty_in_cycle else {
223 continue;
224 };
225 let Some(frame_coroutine_kind) = tcx.coroutine_kind(frame_def_id) else {
226 continue;
227 };
228 let frame_span =
229 info.frame.info.default_span(cycle[(i + 1) % cycle.len()].span);
230 if frame_span.is_dummy() {
231 continue;
232 }
233 if i == 0 {
234 diag.span_label(frame_span, "recursive call here");
235 } else {
236 let coroutine_span: Span = if frame_coroutine_kind.is_fn_like() {
237 tcx.def_span(tcx.parent(frame_def_id))
238 } else {
239 tcx.def_span(frame_def_id)
240 };
241 let mut multispan = MultiSpan::from_span(coroutine_span);
242 multispan
243 .push_span_label(frame_span, "...leading to this recursive call");
244 diag.span_note(
245 multispan,
246 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("which leads to this {0}",
tcx.def_descr(frame_def_id)))
})format!("which leads to this {}", tcx.def_descr(frame_def_id)),
247 );
248 }
249 }
250 if #[allow(non_exhaustive_omitted_patterns)] match coroutine_kind {
hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Async, _) => true,
_ => false,
}matches!(
253 coroutine_kind,
254 hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Async, _)
255 ) {
256 diag.note("a recursive `async fn` call must introduce indirection such as `Box::pin` to avoid an infinitely sized future");
257 }
258
259 ControlFlow::Break(diag)
260 } else {
261 ControlFlow::Continue(())
262 }
263 },
264 || report_cycle(tcx.sess, &cycle_error),
265 );
266
267 let guar = diag.emit();
268
269 Err(Box::leak(Box::new(ty::layout::LayoutError::Cycle(guar))))
273 }
274}
275
276fn recursive_type_error(
279 tcx: TyCtxt<'_>,
280 mut item_and_field_ids: Vec<(LocalDefId, LocalDefId)>,
281 representable_ids: &FxHashSet<LocalDefId>,
282) -> ErrorGuaranteed {
283 const ITEM_LIMIT: usize = 5;
284
285 let start_index = item_and_field_ids
287 .iter()
288 .enumerate()
289 .min_by_key(|&(_, &(id, _))| tcx.def_span(id))
290 .unwrap()
291 .0;
292 item_and_field_ids.rotate_left(start_index);
293
294 let cycle_len = item_and_field_ids.len();
295 let show_cycle_len = cycle_len.min(ITEM_LIMIT);
296
297 let mut err_span = MultiSpan::from_spans(
298 item_and_field_ids[..show_cycle_len]
299 .iter()
300 .map(|(id, _)| tcx.def_span(id.to_def_id()))
301 .collect(),
302 );
303 let mut suggestion = Vec::with_capacity(show_cycle_len * 2);
304 for i in 0..show_cycle_len {
305 let (_, field_id) = item_and_field_ids[i];
306 let (next_item_id, _) = item_and_field_ids[(i + 1) % cycle_len];
307 let hir::Node::Field(field) = tcx.hir_node_by_def_id(field_id) else {
309 ::rustc_middle::util::bug::bug_fmt(format_args!("expected field"))bug!("expected field")
310 };
311 let mut found = Vec::new();
312 find_item_ty_spans(tcx, field.ty, next_item_id, &mut found, representable_ids);
313
314 if found.is_empty() {
317 found.push(field.ty.span);
318 }
319
320 for span in found {
321 err_span.push_span_label(span, "recursive without indirection");
322 suggestion.push((span.shrink_to_lo(), "Box<".to_string()));
324 suggestion.push((span.shrink_to_hi(), ">".to_string()));
325 }
326 }
327 let items_list = {
328 let mut s = String::new();
329 for (i, &(item_id, _)) in item_and_field_ids.iter().enumerate() {
330 let path = tcx.def_path_str(item_id);
331 (&mut s).write_fmt(format_args!("`{0}`", path))write!(&mut s, "`{path}`").unwrap();
332 if i == (ITEM_LIMIT - 1) && cycle_len > ITEM_LIMIT {
333 (&mut s).write_fmt(format_args!(" and {0} more", cycle_len - 5))write!(&mut s, " and {} more", cycle_len - 5).unwrap();
334 break;
335 }
336 if cycle_len > 1 && i < cycle_len - 2 {
337 s.push_str(", ");
338 } else if cycle_len > 1 && i == cycle_len - 2 {
339 s.push_str(" and ")
340 }
341 }
342 s
343 };
344 {
tcx.dcx().struct_span_err(err_span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("recursive type{0} {1} {2} infinite size",
if cycle_len == 1 { "" } else { "s" }, items_list,
if cycle_len == 1 { "has" } else { "have" }))
})).with_code(E0072)
}struct_span_code_err!(
345 tcx.dcx(),
346 err_span,
347 E0072,
348 "recursive type{} {} {} infinite size",
349 pluralize!(cycle_len),
350 items_list,
351 pluralize!("has", cycle_len),
352 )
353 .with_multipart_suggestion(
354 "insert some indirection (e.g., a `Box`, `Rc`, or `&`) to break the cycle",
355 suggestion,
356 Applicability::HasPlaceholders,
357 )
358 .emit()
359}
360
361fn find_item_ty_spans(
362 tcx: TyCtxt<'_>,
363 ty: &hir::Ty<'_>,
364 needle: LocalDefId,
365 spans: &mut Vec<Span>,
366 seen_representable: &FxHashSet<LocalDefId>,
367) {
368 match ty.kind {
369 hir::TyKind::Path(hir::QPath::Resolved(_, path)) => {
370 if let Res::Def(kind, def_id) = path.res
371 && #[allow(non_exhaustive_omitted_patterns)] match kind {
DefKind::Enum | DefKind::Struct | DefKind::Union => true,
_ => false,
}matches!(kind, DefKind::Enum | DefKind::Struct | DefKind::Union)
372 {
373 let check_params = def_id.as_local().is_none_or(|def_id| {
374 if def_id == needle {
375 spans.push(ty.span);
376 }
377 seen_representable.contains(&def_id)
378 });
379 if check_params && let Some(args) = path.segments.last().unwrap().args {
380 let params_in_repr = tcx.params_in_repr(def_id);
381 for (i, arg) in args.args.iter().enumerate().take(params_in_repr.domain_size())
383 {
384 if let hir::GenericArg::Type(ty) = arg
385 && params_in_repr.contains(i as u32)
386 {
387 find_item_ty_spans(
388 tcx,
389 ty.as_unambig_ty(),
390 needle,
391 spans,
392 seen_representable,
393 );
394 }
395 }
396 }
397 }
398 }
399 hir::TyKind::Array(ty, _) => find_item_ty_spans(tcx, ty, needle, spans, seen_representable),
400 hir::TyKind::Tup(tys) => {
401 tys.iter().for_each(|ty| find_item_ty_spans(tcx, ty, needle, spans, seen_representable))
402 }
403 _ => {}
404 }
405}