1use std::fmt::Debug;
2use std::hash::Hash;
3use std::io::Write;
4use std::iter;
5use std::num::NonZero;
6use std::sync::Arc;
78use parking_lot::{Condvar, Mutex};
9use rustc_data_structures::fx::{FxHashMap, FxHashSet};
10use rustc_errors::{Diag, DiagCtxtHandle};
11use rustc_hir::def::DefKind;
12use rustc_session::Session;
13use rustc_span::{DUMMY_SP, Span};
1415use super::{QueryStackDeferred, QueryStackFrameExtra};
16use crate::dep_graph::DepContext;
17use crate::error::CycleStack;
18use crate::query::plumbing::CycleError;
19use crate::query::{QueryContext, QueryStackFrame};
2021/// Represents a span and a query key.
22#[derive(#[automatically_derived]
impl<I: ::core::clone::Clone> ::core::clone::Clone for QueryInfo<I> {
#[inline]
fn clone(&self) -> QueryInfo<I> {
QueryInfo {
span: ::core::clone::Clone::clone(&self.span),
frame: ::core::clone::Clone::clone(&self.frame),
}
}
}Clone, #[automatically_derived]
impl<I: ::core::fmt::Debug> ::core::fmt::Debug for QueryInfo<I> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f, "QueryInfo",
"span", &self.span, "frame", &&self.frame)
}
}Debug)]
23pub struct QueryInfo<I> {
24/// The span corresponding to the reason for which this query was required.
25pub span: Span,
26pub frame: QueryStackFrame<I>,
27}
2829impl<'tcx> QueryInfo<QueryStackDeferred<'tcx>> {
30pub(crate) fn lift(&self) -> QueryInfo<QueryStackFrameExtra> {
31QueryInfo { span: self.span, frame: self.frame.lift() }
32 }
33}
3435/// Map from query job IDs to job information collected by
36/// [`QueryContext::collect_active_jobs_from_all_queries`].
37pub type QueryMap<'tcx> = FxHashMap<QueryJobId, QueryJobInfo<'tcx>>;
3839/// A value uniquely identifying an active query job.
40#[derive(#[automatically_derived]
impl ::core::marker::Copy for QueryJobId { }Copy, #[automatically_derived]
impl ::core::clone::Clone for QueryJobId {
#[inline]
fn clone(&self) -> QueryJobId {
let _: ::core::clone::AssertParamIsClone<NonZero<u64>>;
*self
}
}Clone, #[automatically_derived]
impl ::core::cmp::Eq for QueryJobId {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_receiver_is_total_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<NonZero<u64>>;
}
}Eq, #[automatically_derived]
impl ::core::cmp::PartialEq for QueryJobId {
#[inline]
fn eq(&self, other: &QueryJobId) -> bool { self.0 == other.0 }
}PartialEq, #[automatically_derived]
impl ::core::hash::Hash for QueryJobId {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&self.0, state)
}
}Hash, #[automatically_derived]
impl ::core::fmt::Debug for QueryJobId {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_tuple_field1_finish(f, "QueryJobId",
&&self.0)
}
}Debug)]
41pub struct QueryJobId(pub NonZero<u64>);
4243impl QueryJobId {
44fn frame<'a, 'tcx>(self, map: &'a QueryMap<'tcx>) -> QueryStackFrame<QueryStackDeferred<'tcx>> {
45map.get(&self).unwrap().frame.clone()
46 }
4748fn span<'a, 'tcx>(self, map: &'a QueryMap<'tcx>) -> Span {
49map.get(&self).unwrap().job.span
50 }
5152fn parent<'a, 'tcx>(self, map: &'a QueryMap<'tcx>) -> Option<QueryJobId> {
53map.get(&self).unwrap().job.parent
54 }
5556fn latch<'a, 'tcx>(self, map: &'a QueryMap<'tcx>) -> Option<&'a QueryLatch<'tcx>> {
57map.get(&self).unwrap().job.latch.as_ref()
58 }
59}
6061#[derive(#[automatically_derived]
impl<'tcx> ::core::clone::Clone for QueryJobInfo<'tcx> {
#[inline]
fn clone(&self) -> QueryJobInfo<'tcx> {
QueryJobInfo {
frame: ::core::clone::Clone::clone(&self.frame),
job: ::core::clone::Clone::clone(&self.job),
}
}
}Clone, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for QueryJobInfo<'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f, "QueryJobInfo",
"frame", &self.frame, "job", &&self.job)
}
}Debug)]
62pub struct QueryJobInfo<'tcx> {
63pub frame: QueryStackFrame<QueryStackDeferred<'tcx>>,
64pub job: QueryJob<'tcx>,
65}
6667/// Represents an active query job.
68#[derive(#[automatically_derived]
impl<'tcx> ::core::fmt::Debug for QueryJob<'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field4_finish(f, "QueryJob",
"id", &self.id, "span", &self.span, "parent", &self.parent,
"latch", &&self.latch)
}
}Debug)]
69pub struct QueryJob<'tcx> {
70pub id: QueryJobId,
7172/// The span corresponding to the reason for which this query was required.
73pub span: Span,
7475/// The parent query job which created this job and is implicitly waiting on it.
76pub parent: Option<QueryJobId>,
7778/// The latch that is used to wait on this job.
79latch: Option<QueryLatch<'tcx>>,
80}
8182impl<'tcx> Clonefor QueryJob<'tcx> {
83fn clone(&self) -> Self {
84Self { id: self.id, span: self.span, parent: self.parent, latch: self.latch.clone() }
85 }
86}
8788impl<'tcx> QueryJob<'tcx> {
89/// Creates a new query job.
90#[inline]
91pub fn new(id: QueryJobId, span: Span, parent: Option<QueryJobId>) -> Self {
92QueryJob { id, span, parent, latch: None }
93 }
9495pub(super) fn latch(&mut self) -> QueryLatch<'tcx> {
96if self.latch.is_none() {
97self.latch = Some(QueryLatch::new());
98 }
99self.latch.as_ref().unwrap().clone()
100 }
101102/// Signals to waiters that the query is complete.
103 ///
104 /// This does nothing for single threaded rustc,
105 /// as there are no concurrent jobs which could be waiting on us
106#[inline]
107pub fn signal_complete(self) {
108if let Some(latch) = self.latch {
109latch.set();
110 }
111 }
112}
113114impl QueryJobId {
115pub(super) fn find_cycle_in_stack<'tcx>(
116&self,
117 query_map: QueryMap<'tcx>,
118 current_job: &Option<QueryJobId>,
119 span: Span,
120 ) -> CycleError<QueryStackDeferred<'tcx>> {
121// Find the waitee amongst `current_job` parents
122let mut cycle = Vec::new();
123let mut current_job = Option::clone(current_job);
124125while let Some(job) = current_job {
126let info = query_map.get(&job).unwrap();
127 cycle.push(QueryInfo { span: info.job.span, frame: info.frame.clone() });
128129if job == *self {
130 cycle.reverse();
131132// This is the end of the cycle
133 // The span entry we included was for the usage
134 // of the cycle itself, and not part of the cycle
135 // Replace it with the span which caused the cycle to form
136cycle[0].span = span;
137// Find out why the cycle itself was used
138let usage = info
139 .job
140 .parent
141 .as_ref()
142 .map(|parent| (info.job.span, parent.frame(&query_map)));
143return CycleError { usage, cycle };
144 }
145146 current_job = info.job.parent;
147 }
148149{ ::core::panicking::panic_fmt(format_args!("did not find a cycle")); }panic!("did not find a cycle")150 }
151152#[cold]
153 #[inline(never)]
154pub fn find_dep_kind_root<'tcx>(
155&self,
156 query_map: QueryMap<'tcx>,
157 ) -> (QueryJobInfo<'tcx>, usize) {
158let mut depth = 1;
159let info = query_map.get(&self).unwrap();
160let dep_kind = info.frame.dep_kind;
161let mut current_id = info.job.parent;
162let mut last_layout = (info.clone(), depth);
163164while let Some(id) = current_id {
165let info = query_map.get(&id).unwrap();
166if info.frame.dep_kind == dep_kind {
167 depth += 1;
168 last_layout = (info.clone(), depth);
169 }
170 current_id = info.job.parent;
171 }
172last_layout173 }
174}
175176#[derive(#[automatically_derived]
impl<'tcx> ::core::fmt::Debug for QueryWaiter<'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field4_finish(f, "QueryWaiter",
"query", &self.query, "condvar", &self.condvar, "span",
&self.span, "cycle", &&self.cycle)
}
}Debug)]
177struct QueryWaiter<'tcx> {
178 query: Option<QueryJobId>,
179 condvar: Condvar,
180 span: Span,
181 cycle: Mutex<Option<CycleError<QueryStackDeferred<'tcx>>>>,
182}
183184#[derive(#[automatically_derived]
impl<'tcx> ::core::fmt::Debug for QueryLatchInfo<'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f,
"QueryLatchInfo", "complete", &self.complete, "waiters",
&&self.waiters)
}
}Debug)]
185struct QueryLatchInfo<'tcx> {
186 complete: bool,
187 waiters: Vec<Arc<QueryWaiter<'tcx>>>,
188}
189190#[derive(#[automatically_derived]
impl<'tcx> ::core::fmt::Debug for QueryLatch<'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field1_finish(f, "QueryLatch",
"info", &&self.info)
}
}Debug)]
191pub(super) struct QueryLatch<'tcx> {
192 info: Arc<Mutex<QueryLatchInfo<'tcx>>>,
193}
194195impl<'tcx> Clonefor QueryLatch<'tcx> {
196fn clone(&self) -> Self {
197Self { info: Arc::clone(&self.info) }
198 }
199}
200201impl<'tcx> QueryLatch<'tcx> {
202fn new() -> Self {
203QueryLatch {
204 info: Arc::new(Mutex::new(QueryLatchInfo { complete: false, waiters: Vec::new() })),
205 }
206 }
207208/// Awaits for the query job to complete.
209pub(super) fn wait_on(
210&self,
211 qcx: impl QueryContext<'tcx>,
212 query: Option<QueryJobId>,
213 span: Span,
214 ) -> Result<(), CycleError<QueryStackDeferred<'tcx>>> {
215let waiter =
216Arc::new(QueryWaiter { query, span, cycle: Mutex::new(None), condvar: Condvar::new() });
217self.wait_on_inner(qcx, &waiter);
218// FIXME: Get rid of this lock. We have ownership of the QueryWaiter
219 // although another thread may still have a Arc reference so we cannot
220 // use Arc::get_mut
221let mut cycle = waiter.cycle.lock();
222match cycle.take() {
223None => Ok(()),
224Some(cycle) => Err(cycle),
225 }
226 }
227228/// Awaits the caller on this latch by blocking the current thread.
229fn wait_on_inner(&self, qcx: impl QueryContext<'tcx>, waiter: &Arc<QueryWaiter<'tcx>>) {
230let mut info = self.info.lock();
231if !info.complete {
232// We push the waiter on to the `waiters` list. It can be accessed inside
233 // the `wait` call below, by 1) the `set` method or 2) by deadlock detection.
234 // Both of these will remove it from the `waiters` list before resuming
235 // this thread.
236info.waiters.push(Arc::clone(waiter));
237238// If this detects a deadlock and the deadlock handler wants to resume this thread
239 // we have to be in the `wait` call. This is ensured by the deadlock handler
240 // getting the self.info lock.
241rustc_thread_pool::mark_blocked();
242let proxy = qcx.jobserver_proxy();
243proxy.release_thread();
244waiter.condvar.wait(&mut info);
245// Release the lock before we potentially block in `acquire_thread`
246drop(info);
247proxy.acquire_thread();
248 }
249 }
250251/// Sets the latch and resumes all waiters on it
252fn set(&self) {
253let mut info = self.info.lock();
254if true {
if !!info.complete {
::core::panicking::panic("assertion failed: !info.complete")
};
};debug_assert!(!info.complete);
255info.complete = true;
256let registry = rustc_thread_pool::Registry::current();
257for waiter in info.waiters.drain(..) {
258 rustc_thread_pool::mark_unblocked(®istry);
259 waiter.condvar.notify_one();
260 }
261 }
262263/// Removes a single waiter from the list of waiters.
264 /// This is used to break query cycles.
265fn extract_waiter(&self, waiter: usize) -> Arc<QueryWaiter<'tcx>> {
266let mut info = self.info.lock();
267if true {
if !!info.complete {
::core::panicking::panic("assertion failed: !info.complete")
};
};debug_assert!(!info.complete);
268// Remove the waiter from the list of waiters
269info.waiters.remove(waiter)
270 }
271}
272273/// A resumable waiter of a query. The usize is the index into waiters in the query's latch
274type Waiter = (QueryJobId, usize);
275276/// Visits all the non-resumable and resumable waiters of a query.
277/// Only waiters in a query are visited.
278/// `visit` is called for every waiter and is passed a query waiting on `query_ref`
279/// and a span indicating the reason the query waited on `query_ref`.
280/// If `visit` returns Some, this function returns.
281/// For visits of non-resumable waiters it returns the return value of `visit`.
282/// For visits of resumable waiters it returns Some(Some(Waiter)) which has the
283/// required information to resume the waiter.
284/// If all `visit` calls returns None, this function also returns None.
285fn visit_waiters<'tcx, F>(
286 query_map: &QueryMap<'tcx>,
287 query: QueryJobId,
288mut visit: F,
289) -> Option<Option<Waiter>>
290where
291F: FnMut(Span, QueryJobId) -> Option<Option<Waiter>>,
292{
293// Visit the parent query which is a non-resumable waiter since it's on the same stack
294if let Some(parent) = query.parent(query_map)
295 && let Some(cycle) = visit(query.span(query_map), parent)
296 {
297return Some(cycle);
298 }
299300// Visit the explicit waiters which use condvars and are resumable
301if let Some(latch) = query.latch(query_map) {
302for (i, waiter) in latch.info.lock().waiters.iter().enumerate() {
303if let Some(waiter_query) = waiter.query {
304if visit(waiter.span, waiter_query).is_some() {
305// Return a value which indicates that this waiter can be resumed
306return Some(Some((query, i)));
307 }
308 }
309 }
310 }
311312None313}
314315/// Look for query cycles by doing a depth first search starting at `query`.
316/// `span` is the reason for the `query` to execute. This is initially DUMMY_SP.
317/// If a cycle is detected, this initial value is replaced with the span causing
318/// the cycle.
319fn cycle_check<'tcx>(
320 query_map: &QueryMap<'tcx>,
321 query: QueryJobId,
322 span: Span,
323 stack: &mut Vec<(Span, QueryJobId)>,
324 visited: &mut FxHashSet<QueryJobId>,
325) -> Option<Option<Waiter>> {
326if !visited.insert(query) {
327return if let Some(p) = stack.iter().position(|q| q.1 == query) {
328// We detected a query cycle, fix up the initial span and return Some
329330 // Remove previous stack entries
331stack.drain(0..p);
332// Replace the span for the first query with the cycle cause
333stack[0].0 = span;
334Some(None)
335 } else {
336None337 };
338 }
339340// Query marked as visited is added it to the stack
341stack.push((span, query));
342343// Visit all the waiters
344let r = visit_waiters(query_map, query, |span, successor| {
345cycle_check(query_map, successor, span, stack, visited)
346 });
347348// Remove the entry in our stack if we didn't find a cycle
349if r.is_none() {
350stack.pop();
351 }
352353r354}
355356/// Finds out if there's a path to the compiler root (aka. code which isn't in a query)
357/// from `query` without going through any of the queries in `visited`.
358/// This is achieved with a depth first search.
359fn connected_to_root<'tcx>(
360 query_map: &QueryMap<'tcx>,
361 query: QueryJobId,
362 visited: &mut FxHashSet<QueryJobId>,
363) -> bool {
364// We already visited this or we're deliberately ignoring it
365if !visited.insert(query) {
366return false;
367 }
368369// This query is connected to the root (it has no query parent), return true
370if query.parent(query_map).is_none() {
371return true;
372 }
373374visit_waiters(query_map, query, |_, successor| {
375connected_to_root(query_map, successor, visited).then_some(None)
376 })
377 .is_some()
378}
379380// Deterministically pick an query from a list
381fn pick_query<'a, 'tcx, T, F>(query_map: &QueryMap<'tcx>, queries: &'a [T], f: F) -> &'a T
382where
383F: Fn(&T) -> (Span, QueryJobId),
384{
385// Deterministically pick an entry point
386 // FIXME: Sort this instead
387queries388 .iter()
389 .min_by_key(|v| {
390let (span, query) = f(v);
391let hash = query.frame(query_map).hash;
392// Prefer entry points which have valid spans for nicer error messages
393 // We add an integer to the tuple ensuring that entry points
394 // with valid spans are picked first
395let span_cmp = if span == DUMMY_SP { 1 } else { 0 };
396 (span_cmp, hash)
397 })
398 .unwrap()
399}
400401/// Looks for query cycles starting from the last query in `jobs`.
402/// If a cycle is found, all queries in the cycle is removed from `jobs` and
403/// the function return true.
404/// If a cycle was not found, the starting query is removed from `jobs` and
405/// the function returns false.
406fn remove_cycle<'tcx>(
407 query_map: &QueryMap<'tcx>,
408 jobs: &mut Vec<QueryJobId>,
409 wakelist: &mut Vec<Arc<QueryWaiter<'tcx>>>,
410) -> bool {
411let mut visited = FxHashSet::default();
412let mut stack = Vec::new();
413// Look for a cycle starting with the last query in `jobs`
414if let Some(waiter) =
415cycle_check(query_map, jobs.pop().unwrap(), DUMMY_SP, &mut stack, &mut visited)
416 {
417// The stack is a vector of pairs of spans and queries; reverse it so that
418 // the earlier entries require later entries
419let (mut spans, queries): (Vec<_>, Vec<_>) = stack.into_iter().rev().unzip();
420421// Shift the spans so that queries are matched with the span for their waitee
422spans.rotate_right(1);
423424// Zip them back together
425let mut stack: Vec<_> = iter::zip(spans, queries).collect();
426427// Remove the queries in our cycle from the list of jobs to look at
428for r in &stack {
429if let Some(pos) = jobs.iter().position(|j| j == &r.1) {
430 jobs.remove(pos);
431 }
432 }
433434// Find the queries in the cycle which are
435 // connected to queries outside the cycle
436let entry_points = stack437 .iter()
438 .filter_map(|&(span, query)| {
439if query.parent(query_map).is_none() {
440// This query is connected to the root (it has no query parent)
441Some((span, query, None))
442 } else {
443let mut waiters = Vec::new();
444// Find all the direct waiters who lead to the root
445visit_waiters(query_map, query, |span, waiter| {
446// Mark all the other queries in the cycle as already visited
447let mut visited = FxHashSet::from_iter(stack.iter().map(|q| q.1));
448449if connected_to_root(query_map, waiter, &mut visited) {
450waiters.push((span, waiter));
451 }
452453None454 });
455if waiters.is_empty() {
456None457 } else {
458// Deterministically pick one of the waiters to show to the user
459let waiter = *pick_query(query_map, &waiters, |s| *s);
460Some((span, query, Some(waiter)))
461 }
462 }
463 })
464 .collect::<Vec<(Span, QueryJobId, Option<(Span, QueryJobId)>)>>();
465466// Deterministically pick an entry point
467let (_, entry_point, usage) = pick_query(query_map, &entry_points, |e| (e.0, e.1));
468469// Shift the stack so that our entry point is first
470let entry_point_pos = stack.iter().position(|(_, query)| query == entry_point);
471if let Some(pos) = entry_point_pos {
472stack.rotate_left(pos);
473 }
474475let usage = usage.as_ref().map(|(span, query)| (*span, query.frame(query_map)));
476477// Create the cycle error
478let error = CycleError {
479usage,
480 cycle: stack481 .iter()
482 .map(|&(s, ref q)| QueryInfo { span: s, frame: q.frame(query_map) })
483 .collect(),
484 };
485486// We unwrap `waiter` here since there must always be one
487 // edge which is resumable / waited using a query latch
488let (waitee_query, waiter_idx) = waiter.unwrap();
489490// Extract the waiter we want to resume
491let waiter = waitee_query.latch(query_map).unwrap().extract_waiter(waiter_idx);
492493// Set the cycle error so it will be picked up when resumed
494*waiter.cycle.lock() = Some(error);
495496// Put the waiter on the list of things to resume
497wakelist.push(waiter);
498499true
500} else {
501false
502}
503}
504505/// Detects query cycles by using depth first search over all active query jobs.
506/// If a query cycle is found it will break the cycle by finding an edge which
507/// uses a query latch and then resuming that waiter.
508/// There may be multiple cycles involved in a deadlock, so this searches
509/// all active queries for cycles before finally resuming all the waiters at once.
510pub fn break_query_cycles<'tcx>(query_map: QueryMap<'tcx>, registry: &rustc_thread_pool::Registry) {
511let mut wakelist = Vec::new();
512// It is OK per the comments:
513 // - https://github.com/rust-lang/rust/pull/131200#issuecomment-2798854932
514 // - https://github.com/rust-lang/rust/pull/131200#issuecomment-2798866392
515#[allow(rustc::potential_query_instability)]
516let mut jobs: Vec<QueryJobId> = query_map.keys().cloned().collect();
517518let mut found_cycle = false;
519520while jobs.len() > 0 {
521if remove_cycle(&query_map, &mut jobs, &mut wakelist) {
522 found_cycle = true;
523 }
524 }
525526// Check that a cycle was found. It is possible for a deadlock to occur without
527 // a query cycle if a query which can be waited on uses Rayon to do multithreading
528 // internally. Such a query (X) may be executing on 2 threads (A and B) and A may
529 // wait using Rayon on B. Rayon may then switch to executing another query (Y)
530 // which in turn will wait on X causing a deadlock. We have a false dependency from
531 // X to Y due to Rayon waiting and a true dependency from Y to X. The algorithm here
532 // only considers the true dependency and won't detect a cycle.
533if !found_cycle {
534{
::core::panicking::panic_fmt(format_args!("deadlock detected as we\'re unable to find a query cycle to break\ncurrent query map:\n{0:#?}",
query_map));
};panic!(
535"deadlock detected as we're unable to find a query cycle to break\n\
536 current query map:\n{:#?}",
537 query_map
538 );
539 }
540541// Mark all the thread we're about to wake up as unblocked. This needs to be done before
542 // we wake the threads up as otherwise Rayon could detect a deadlock if a thread we
543 // resumed fell asleep and this thread had yet to mark the remaining threads as unblocked.
544for _ in 0..wakelist.len() {
545 rustc_thread_pool::mark_unblocked(registry);
546 }
547548for waiter in wakelist.into_iter() {
549 waiter.condvar.notify_one();
550 }
551}
552553#[inline(never)]
554#[cold]
555pub fn report_cycle<'a>(
556 sess: &'a Session,
557CycleError { usage, cycle: stack }: &CycleError,
558) -> Diag<'a> {
559if !!stack.is_empty() {
::core::panicking::panic("assertion failed: !stack.is_empty()")
};assert!(!stack.is_empty());
560561let span = stack[0].frame.info.default_span(stack[1 % stack.len()].span);
562563let mut cycle_stack = Vec::new();
564565use crate::error::StackCount;
566let stack_count = if stack.len() == 1 { StackCount::Single } else { StackCount::Multiple };
567568for i in 1..stack.len() {
569let frame = &stack[i].frame;
570let span = frame.info.default_span(stack[(i + 1) % stack.len()].span);
571 cycle_stack.push(CycleStack { span, desc: frame.info.description.to_owned() });
572 }
573574let mut cycle_usage = None;
575if let Some((span, ref query)) = *usage {
576cycle_usage = Some(crate::error::CycleUsage {
577 span: query.info.default_span(span),
578 usage: query.info.description.to_string(),
579 });
580 }
581582let alias =
583if stack.iter().all(|entry| #[allow(non_exhaustive_omitted_patterns)] match entry.frame.info.def_kind {
Some(DefKind::TyAlias) => true,
_ => false,
}matches!(entry.frame.info.def_kind, Some(DefKind::TyAlias))) {
584Some(crate::error::Alias::Ty)
585 } else if stack.iter().all(|entry| entry.frame.info.def_kind == Some(DefKind::TraitAlias)) {
586Some(crate::error::Alias::Trait)
587 } else {
588None589 };
590591let cycle_diag = crate::error::Cycle {
592span,
593cycle_stack,
594 stack_bottom: stack[0].frame.info.description.to_owned(),
595alias,
596cycle_usage,
597stack_count,
598 note_span: (),
599 };
600601sess.dcx().create_err(cycle_diag)
602}
603604pub fn print_query_stack<'tcx, Qcx: QueryContext<'tcx>>(
605 qcx: Qcx,
606mut current_query: Option<QueryJobId>,
607 dcx: DiagCtxtHandle<'_>,
608 limit_frames: Option<usize>,
609mut file: Option<std::fs::File>,
610) -> usize {
611// Be careful relying on global state here: this code is called from
612 // a panic hook, which means that the global `DiagCtxt` may be in a weird
613 // state if it was responsible for triggering the panic.
614let mut count_printed = 0;
615let mut count_total = 0;
616617// Make use of a partial query map if we fail to take locks collecting active queries.
618let query_map = match qcx.collect_active_jobs_from_all_queries(false) {
619Ok(query_map) => query_map,
620Err(query_map) => query_map,
621 };
622623if let Some(ref mut file) = file {
624let _ = file.write_fmt(format_args!("\n\nquery stack during panic:\n"))writeln!(file, "\n\nquery stack during panic:");
625 }
626while let Some(query) = current_query {
627let Some(query_info) = query_map.get(&query) else {
628break;
629 };
630let query_extra = query_info.frame.info.extract();
631if Some(count_printed) < limit_frames || limit_frames.is_none() {
632// Only print to stderr as many stack frames as `num_frames` when present.
633 dcx.struct_failure_note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("#{0} [{1:?}] {2}", count_printed,
query_info.frame.dep_kind, query_extra.description))
})format!(
634"#{} [{:?}] {}",
635 count_printed, query_info.frame.dep_kind, query_extra.description
636 ))
637 .with_span(query_info.job.span)
638 .emit();
639 count_printed += 1;
640 }
641642if let Some(ref mut file) = file {
643let _ = file.write_fmt(format_args!("#{0} [{1}] {2}\n", count_total,
qcx.dep_context().dep_kind_vtable(query_info.frame.dep_kind).name,
query_extra.description))writeln!(
644 file,
645"#{} [{}] {}",
646 count_total,
647 qcx.dep_context().dep_kind_vtable(query_info.frame.dep_kind).name,
648 query_extra.description
649 );
650 }
651652 current_query = query_info.job.parent;
653 count_total += 1;
654 }
655656if let Some(ref mut file) = file {
657let _ = file.write_fmt(format_args!("end of query stack\n"))writeln!(file, "end of query stack");
658 }
659count_total660}