rustc_query_system/query/
job.rs

1use std::hash::Hash;
2use std::io::Write;
3use std::iter;
4use std::num::NonZero;
5use std::sync::Arc;
6
7use parking_lot::{Condvar, Mutex};
8use rustc_data_structures::fx::{FxHashMap, FxHashSet};
9use rustc_errors::{Diag, DiagCtxtHandle};
10use rustc_hir::def::DefKind;
11use rustc_session::Session;
12use rustc_span::{DUMMY_SP, Span};
13
14use crate::dep_graph::DepContext;
15use crate::error::CycleStack;
16use crate::query::plumbing::CycleError;
17use crate::query::{QueryContext, QueryStackFrame};
18
19/// Represents a span and a query key.
20#[derive(#[automatically_derived]
impl ::core::clone::Clone for QueryInfo {
    #[inline]
    fn clone(&self) -> QueryInfo {
        QueryInfo {
            span: ::core::clone::Clone::clone(&self.span),
            query: ::core::clone::Clone::clone(&self.query),
        }
    }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for QueryInfo {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f, "QueryInfo",
            "span", &self.span, "query", &&self.query)
    }
}Debug)]
21pub struct QueryInfo {
22    /// The span corresponding to the reason for which this query was required.
23    pub span: Span,
24    pub query: QueryStackFrame,
25}
26
27pub type QueryMap = FxHashMap<QueryJobId, QueryJobInfo>;
28
29/// A value uniquely identifying an active query job.
30#[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)]
31pub struct QueryJobId(pub NonZero<u64>);
32
33impl QueryJobId {
34    fn query(self, map: &QueryMap) -> QueryStackFrame {
35        map.get(&self).unwrap().query.clone()
36    }
37
38    fn span(self, map: &QueryMap) -> Span {
39        map.get(&self).unwrap().job.span
40    }
41
42    fn parent(self, map: &QueryMap) -> Option<QueryJobId> {
43        map.get(&self).unwrap().job.parent
44    }
45
46    fn latch(self, map: &QueryMap) -> Option<&QueryLatch> {
47        map.get(&self).unwrap().job.latch.as_ref()
48    }
49}
50
51#[derive(#[automatically_derived]
impl ::core::clone::Clone for QueryJobInfo {
    #[inline]
    fn clone(&self) -> QueryJobInfo {
        QueryJobInfo {
            query: ::core::clone::Clone::clone(&self.query),
            job: ::core::clone::Clone::clone(&self.job),
        }
    }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for QueryJobInfo {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f, "QueryJobInfo",
            "query", &self.query, "job", &&self.job)
    }
}Debug)]
52pub struct QueryJobInfo {
53    pub query: QueryStackFrame,
54    pub job: QueryJob,
55}
56
57/// Represents an active query job.
58#[derive(#[automatically_derived]
impl ::core::fmt::Debug for QueryJob {
    #[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)]
59pub struct QueryJob {
60    pub id: QueryJobId,
61
62    /// The span corresponding to the reason for which this query was required.
63    pub span: Span,
64
65    /// The parent query job which created this job and is implicitly waiting on it.
66    pub parent: Option<QueryJobId>,
67
68    /// The latch that is used to wait on this job.
69    latch: Option<QueryLatch>,
70}
71
72impl Clone for QueryJob {
73    fn clone(&self) -> Self {
74        Self { id: self.id, span: self.span, parent: self.parent, latch: self.latch.clone() }
75    }
76}
77
78impl QueryJob {
79    /// Creates a new query job.
80    #[inline]
81    pub fn new(id: QueryJobId, span: Span, parent: Option<QueryJobId>) -> Self {
82        QueryJob { id, span, parent, latch: None }
83    }
84
85    pub(super) fn latch(&mut self) -> QueryLatch {
86        if self.latch.is_none() {
87            self.latch = Some(QueryLatch::new());
88        }
89        self.latch.as_ref().unwrap().clone()
90    }
91
92    /// Signals to waiters that the query is complete.
93    ///
94    /// This does nothing for single threaded rustc,
95    /// as there are no concurrent jobs which could be waiting on us
96    #[inline]
97    pub fn signal_complete(self) {
98        if let Some(latch) = self.latch {
99            latch.set();
100        }
101    }
102}
103
104impl QueryJobId {
105    pub(super) fn find_cycle_in_stack(
106        &self,
107        query_map: QueryMap,
108        current_job: &Option<QueryJobId>,
109        span: Span,
110    ) -> CycleError {
111        // Find the waitee amongst `current_job` parents
112        let mut cycle = Vec::new();
113        let mut current_job = Option::clone(current_job);
114
115        while let Some(job) = current_job {
116            let info = query_map.get(&job).unwrap();
117            cycle.push(QueryInfo { span: info.job.span, query: info.query.clone() });
118
119            if job == *self {
120                cycle.reverse();
121
122                // This is the end of the cycle
123                // The span entry we included was for the usage
124                // of the cycle itself, and not part of the cycle
125                // Replace it with the span which caused the cycle to form
126                cycle[0].span = span;
127                // Find out why the cycle itself was used
128                let usage = info
129                    .job
130                    .parent
131                    .as_ref()
132                    .map(|parent| (info.job.span, parent.query(&query_map)));
133                return CycleError { usage, cycle };
134            }
135
136            current_job = info.job.parent;
137        }
138
139        { ::core::panicking::panic_fmt(format_args!("did not find a cycle")); }panic!("did not find a cycle")
140    }
141
142    #[cold]
143    #[inline(never)]
144    pub fn find_dep_kind_root(&self, query_map: QueryMap) -> (QueryJobInfo, usize) {
145        let mut depth = 1;
146        let info = query_map.get(&self).unwrap();
147        let dep_kind = info.query.dep_kind;
148        let mut current_id = info.job.parent;
149        let mut last_layout = (info.clone(), depth);
150
151        while let Some(id) = current_id {
152            let info = query_map.get(&id).unwrap();
153            if info.query.dep_kind == dep_kind {
154                depth += 1;
155                last_layout = (info.clone(), depth);
156            }
157            current_id = info.job.parent;
158        }
159        last_layout
160    }
161}
162
163#[derive(#[automatically_derived]
impl ::core::fmt::Debug for QueryWaiter {
    #[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)]
164struct QueryWaiter {
165    query: Option<QueryJobId>,
166    condvar: Condvar,
167    span: Span,
168    cycle: Mutex<Option<CycleError>>,
169}
170
171#[derive(#[automatically_derived]
impl ::core::fmt::Debug for QueryLatchInfo {
    #[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)]
172struct QueryLatchInfo {
173    complete: bool,
174    waiters: Vec<Arc<QueryWaiter>>,
175}
176
177#[derive(#[automatically_derived]
impl ::core::fmt::Debug for QueryLatch {
    #[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)]
178pub(super) struct QueryLatch {
179    info: Arc<Mutex<QueryLatchInfo>>,
180}
181
182impl Clone for QueryLatch {
183    fn clone(&self) -> Self {
184        Self { info: Arc::clone(&self.info) }
185    }
186}
187
188impl QueryLatch {
189    fn new() -> Self {
190        QueryLatch {
191            info: Arc::new(Mutex::new(QueryLatchInfo { complete: false, waiters: Vec::new() })),
192        }
193    }
194
195    /// Awaits for the query job to complete.
196    pub(super) fn wait_on(
197        &self,
198        qcx: impl QueryContext,
199        query: Option<QueryJobId>,
200        span: Span,
201    ) -> Result<(), CycleError> {
202        let waiter =
203            Arc::new(QueryWaiter { query, span, cycle: Mutex::new(None), condvar: Condvar::new() });
204        self.wait_on_inner(qcx, &waiter);
205        // FIXME: Get rid of this lock. We have ownership of the QueryWaiter
206        // although another thread may still have a Arc reference so we cannot
207        // use Arc::get_mut
208        let mut cycle = waiter.cycle.lock();
209        match cycle.take() {
210            None => Ok(()),
211            Some(cycle) => Err(cycle),
212        }
213    }
214
215    /// Awaits the caller on this latch by blocking the current thread.
216    fn wait_on_inner(&self, qcx: impl QueryContext, waiter: &Arc<QueryWaiter>) {
217        let mut info = self.info.lock();
218        if !info.complete {
219            // We push the waiter on to the `waiters` list. It can be accessed inside
220            // the `wait` call below, by 1) the `set` method or 2) by deadlock detection.
221            // Both of these will remove it from the `waiters` list before resuming
222            // this thread.
223            info.waiters.push(Arc::clone(waiter));
224
225            // If this detects a deadlock and the deadlock handler wants to resume this thread
226            // we have to be in the `wait` call. This is ensured by the deadlock handler
227            // getting the self.info lock.
228            rustc_thread_pool::mark_blocked();
229            let proxy = qcx.jobserver_proxy();
230            proxy.release_thread();
231            waiter.condvar.wait(&mut info);
232            // Release the lock before we potentially block in `acquire_thread`
233            drop(info);
234            proxy.acquire_thread();
235        }
236    }
237
238    /// Sets the latch and resumes all waiters on it
239    fn set(&self) {
240        let mut info = self.info.lock();
241        if true {
    if !!info.complete {
        ::core::panicking::panic("assertion failed: !info.complete")
    };
};debug_assert!(!info.complete);
242        info.complete = true;
243        let registry = rustc_thread_pool::Registry::current();
244        for waiter in info.waiters.drain(..) {
245            rustc_thread_pool::mark_unblocked(&registry);
246            waiter.condvar.notify_one();
247        }
248    }
249
250    /// Removes a single waiter from the list of waiters.
251    /// This is used to break query cycles.
252    fn extract_waiter(&self, waiter: usize) -> Arc<QueryWaiter> {
253        let mut info = self.info.lock();
254        if true {
    if !!info.complete {
        ::core::panicking::panic("assertion failed: !info.complete")
    };
};debug_assert!(!info.complete);
255        // Remove the waiter from the list of waiters
256        info.waiters.remove(waiter)
257    }
258}
259
260/// A resumable waiter of a query. The usize is the index into waiters in the query's latch
261type Waiter = (QueryJobId, usize);
262
263/// Visits all the non-resumable and resumable waiters of a query.
264/// Only waiters in a query are visited.
265/// `visit` is called for every waiter and is passed a query waiting on `query_ref`
266/// and a span indicating the reason the query waited on `query_ref`.
267/// If `visit` returns Some, this function returns.
268/// For visits of non-resumable waiters it returns the return value of `visit`.
269/// For visits of resumable waiters it returns Some(Some(Waiter)) which has the
270/// required information to resume the waiter.
271/// If all `visit` calls returns None, this function also returns None.
272fn visit_waiters<F>(query_map: &QueryMap, query: QueryJobId, mut visit: F) -> Option<Option<Waiter>>
273where
274    F: FnMut(Span, QueryJobId) -> Option<Option<Waiter>>,
275{
276    // Visit the parent query which is a non-resumable waiter since it's on the same stack
277    if let Some(parent) = query.parent(query_map)
278        && let Some(cycle) = visit(query.span(query_map), parent)
279    {
280        return Some(cycle);
281    }
282
283    // Visit the explicit waiters which use condvars and are resumable
284    if let Some(latch) = query.latch(query_map) {
285        for (i, waiter) in latch.info.lock().waiters.iter().enumerate() {
286            if let Some(waiter_query) = waiter.query {
287                if visit(waiter.span, waiter_query).is_some() {
288                    // Return a value which indicates that this waiter can be resumed
289                    return Some(Some((query, i)));
290                }
291            }
292        }
293    }
294
295    None
296}
297
298/// Look for query cycles by doing a depth first search starting at `query`.
299/// `span` is the reason for the `query` to execute. This is initially DUMMY_SP.
300/// If a cycle is detected, this initial value is replaced with the span causing
301/// the cycle.
302fn cycle_check(
303    query_map: &QueryMap,
304    query: QueryJobId,
305    span: Span,
306    stack: &mut Vec<(Span, QueryJobId)>,
307    visited: &mut FxHashSet<QueryJobId>,
308) -> Option<Option<Waiter>> {
309    if !visited.insert(query) {
310        return if let Some(p) = stack.iter().position(|q| q.1 == query) {
311            // We detected a query cycle, fix up the initial span and return Some
312
313            // Remove previous stack entries
314            stack.drain(0..p);
315            // Replace the span for the first query with the cycle cause
316            stack[0].0 = span;
317            Some(None)
318        } else {
319            None
320        };
321    }
322
323    // Query marked as visited is added it to the stack
324    stack.push((span, query));
325
326    // Visit all the waiters
327    let r = visit_waiters(query_map, query, |span, successor| {
328        cycle_check(query_map, successor, span, stack, visited)
329    });
330
331    // Remove the entry in our stack if we didn't find a cycle
332    if r.is_none() {
333        stack.pop();
334    }
335
336    r
337}
338
339/// Finds out if there's a path to the compiler root (aka. code which isn't in a query)
340/// from `query` without going through any of the queries in `visited`.
341/// This is achieved with a depth first search.
342fn connected_to_root(
343    query_map: &QueryMap,
344    query: QueryJobId,
345    visited: &mut FxHashSet<QueryJobId>,
346) -> bool {
347    // We already visited this or we're deliberately ignoring it
348    if !visited.insert(query) {
349        return false;
350    }
351
352    // This query is connected to the root (it has no query parent), return true
353    if query.parent(query_map).is_none() {
354        return true;
355    }
356
357    visit_waiters(query_map, query, |_, successor| {
358        connected_to_root(query_map, successor, visited).then_some(None)
359    })
360    .is_some()
361}
362
363// Deterministically pick an query from a list
364fn pick_query<'a, T, F>(query_map: &QueryMap, queries: &'a [T], f: F) -> &'a T
365where
366    F: Fn(&T) -> (Span, QueryJobId),
367{
368    // Deterministically pick an entry point
369    // FIXME: Sort this instead
370    queries
371        .iter()
372        .min_by_key(|v| {
373            let (span, query) = f(v);
374            let hash = query.query(query_map).hash;
375            // Prefer entry points which have valid spans for nicer error messages
376            // We add an integer to the tuple ensuring that entry points
377            // with valid spans are picked first
378            let span_cmp = if span == DUMMY_SP { 1 } else { 0 };
379            (span_cmp, hash)
380        })
381        .unwrap()
382}
383
384/// Looks for query cycles starting from the last query in `jobs`.
385/// If a cycle is found, all queries in the cycle is removed from `jobs` and
386/// the function return true.
387/// If a cycle was not found, the starting query is removed from `jobs` and
388/// the function returns false.
389fn remove_cycle(
390    query_map: &QueryMap,
391    jobs: &mut Vec<QueryJobId>,
392    wakelist: &mut Vec<Arc<QueryWaiter>>,
393) -> bool {
394    let mut visited = FxHashSet::default();
395    let mut stack = Vec::new();
396    // Look for a cycle starting with the last query in `jobs`
397    if let Some(waiter) =
398        cycle_check(query_map, jobs.pop().unwrap(), DUMMY_SP, &mut stack, &mut visited)
399    {
400        // The stack is a vector of pairs of spans and queries; reverse it so that
401        // the earlier entries require later entries
402        let (mut spans, queries): (Vec<_>, Vec<_>) = stack.into_iter().rev().unzip();
403
404        // Shift the spans so that queries are matched with the span for their waitee
405        spans.rotate_right(1);
406
407        // Zip them back together
408        let mut stack: Vec<_> = iter::zip(spans, queries).collect();
409
410        // Remove the queries in our cycle from the list of jobs to look at
411        for r in &stack {
412            if let Some(pos) = jobs.iter().position(|j| j == &r.1) {
413                jobs.remove(pos);
414            }
415        }
416
417        // Find the queries in the cycle which are
418        // connected to queries outside the cycle
419        let entry_points = stack
420            .iter()
421            .filter_map(|&(span, query)| {
422                if query.parent(query_map).is_none() {
423                    // This query is connected to the root (it has no query parent)
424                    Some((span, query, None))
425                } else {
426                    let mut waiters = Vec::new();
427                    // Find all the direct waiters who lead to the root
428                    visit_waiters(query_map, query, |span, waiter| {
429                        // Mark all the other queries in the cycle as already visited
430                        let mut visited = FxHashSet::from_iter(stack.iter().map(|q| q.1));
431
432                        if connected_to_root(query_map, waiter, &mut visited) {
433                            waiters.push((span, waiter));
434                        }
435
436                        None
437                    });
438                    if waiters.is_empty() {
439                        None
440                    } else {
441                        // Deterministically pick one of the waiters to show to the user
442                        let waiter = *pick_query(query_map, &waiters, |s| *s);
443                        Some((span, query, Some(waiter)))
444                    }
445                }
446            })
447            .collect::<Vec<(Span, QueryJobId, Option<(Span, QueryJobId)>)>>();
448
449        // Deterministically pick an entry point
450        let (_, entry_point, usage) = pick_query(query_map, &entry_points, |e| (e.0, e.1));
451
452        // Shift the stack so that our entry point is first
453        let entry_point_pos = stack.iter().position(|(_, query)| query == entry_point);
454        if let Some(pos) = entry_point_pos {
455            stack.rotate_left(pos);
456        }
457
458        let usage = usage.as_ref().map(|(span, query)| (*span, query.query(query_map)));
459
460        // Create the cycle error
461        let error = CycleError {
462            usage,
463            cycle: stack
464                .iter()
465                .map(|&(s, ref q)| QueryInfo { span: s, query: q.query(query_map) })
466                .collect(),
467        };
468
469        // We unwrap `waiter` here since there must always be one
470        // edge which is resumable / waited using a query latch
471        let (waitee_query, waiter_idx) = waiter.unwrap();
472
473        // Extract the waiter we want to resume
474        let waiter = waitee_query.latch(query_map).unwrap().extract_waiter(waiter_idx);
475
476        // Set the cycle error so it will be picked up when resumed
477        *waiter.cycle.lock() = Some(error);
478
479        // Put the waiter on the list of things to resume
480        wakelist.push(waiter);
481
482        true
483    } else {
484        false
485    }
486}
487
488/// Detects query cycles by using depth first search over all active query jobs.
489/// If a query cycle is found it will break the cycle by finding an edge which
490/// uses a query latch and then resuming that waiter.
491/// There may be multiple cycles involved in a deadlock, so this searches
492/// all active queries for cycles before finally resuming all the waiters at once.
493pub fn break_query_cycles(query_map: QueryMap, registry: &rustc_thread_pool::Registry) {
494    let mut wakelist = Vec::new();
495    // It is OK per the comments:
496    // - https://github.com/rust-lang/rust/pull/131200#issuecomment-2798854932
497    // - https://github.com/rust-lang/rust/pull/131200#issuecomment-2798866392
498    #[allow(rustc::potential_query_instability)]
499    let mut jobs: Vec<QueryJobId> = query_map.keys().cloned().collect();
500
501    let mut found_cycle = false;
502
503    while jobs.len() > 0 {
504        if remove_cycle(&query_map, &mut jobs, &mut wakelist) {
505            found_cycle = true;
506        }
507    }
508
509    // Check that a cycle was found. It is possible for a deadlock to occur without
510    // a query cycle if a query which can be waited on uses Rayon to do multithreading
511    // internally. Such a query (X) may be executing on 2 threads (A and B) and A may
512    // wait using Rayon on B. Rayon may then switch to executing another query (Y)
513    // which in turn will wait on X causing a deadlock. We have a false dependency from
514    // X to Y due to Rayon waiting and a true dependency from Y to X. The algorithm here
515    // only considers the true dependency and won't detect a cycle.
516    if !found_cycle {
517        {
    ::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!(
518            "deadlock detected as we're unable to find a query cycle to break\n\
519            current query map:\n{:#?}",
520            query_map
521        );
522    }
523
524    // Mark all the thread we're about to wake up as unblocked. This needs to be done before
525    // we wake the threads up as otherwise Rayon could detect a deadlock if a thread we
526    // resumed fell asleep and this thread had yet to mark the remaining threads as unblocked.
527    for _ in 0..wakelist.len() {
528        rustc_thread_pool::mark_unblocked(registry);
529    }
530
531    for waiter in wakelist.into_iter() {
532        waiter.condvar.notify_one();
533    }
534}
535
536#[inline(never)]
537#[cold]
538pub fn report_cycle<'a>(
539    sess: &'a Session,
540    CycleError { usage, cycle: stack }: &CycleError,
541) -> Diag<'a> {
542    if !!stack.is_empty() {
    ::core::panicking::panic("assertion failed: !stack.is_empty()")
};assert!(!stack.is_empty());
543
544    let span = stack[0].query.default_span(stack[1 % stack.len()].span);
545
546    let mut cycle_stack = Vec::new();
547
548    use crate::error::StackCount;
549    let stack_count = if stack.len() == 1 { StackCount::Single } else { StackCount::Multiple };
550
551    for i in 1..stack.len() {
552        let query = &stack[i].query;
553        let span = query.default_span(stack[(i + 1) % stack.len()].span);
554        cycle_stack.push(CycleStack { span, desc: query.description.to_owned() });
555    }
556
557    let mut cycle_usage = None;
558    if let Some((span, ref query)) = *usage {
559        cycle_usage = Some(crate::error::CycleUsage {
560            span: query.default_span(span),
561            usage: query.description.to_string(),
562        });
563    }
564
565    let alias = if stack.iter().all(|entry| #[allow(non_exhaustive_omitted_patterns)] match entry.query.def_kind {
    Some(DefKind::TyAlias) => true,
    _ => false,
}matches!(entry.query.def_kind, Some(DefKind::TyAlias)))
566    {
567        Some(crate::error::Alias::Ty)
568    } else if stack.iter().all(|entry| entry.query.def_kind == Some(DefKind::TraitAlias)) {
569        Some(crate::error::Alias::Trait)
570    } else {
571        None
572    };
573
574    let cycle_diag = crate::error::Cycle {
575        span,
576        cycle_stack,
577        stack_bottom: stack[0].query.description.to_owned(),
578        alias,
579        cycle_usage,
580        stack_count,
581        note_span: (),
582    };
583
584    sess.dcx().create_err(cycle_diag)
585}
586
587pub fn print_query_stack<Qcx: QueryContext>(
588    qcx: Qcx,
589    mut current_query: Option<QueryJobId>,
590    dcx: DiagCtxtHandle<'_>,
591    limit_frames: Option<usize>,
592    mut file: Option<std::fs::File>,
593) -> usize {
594    // Be careful relying on global state here: this code is called from
595    // a panic hook, which means that the global `DiagCtxt` may be in a weird
596    // state if it was responsible for triggering the panic.
597    let mut count_printed = 0;
598    let mut count_total = 0;
599
600    // Make use of a partial query map if we fail to take locks collecting active queries.
601    let query_map = match qcx.collect_active_jobs(false) {
602        Ok(query_map) => query_map,
603        Err(query_map) => query_map,
604    };
605
606    if let Some(ref mut file) = file {
607        let _ = file.write_fmt(format_args!("\n\nquery stack during panic:\n"))writeln!(file, "\n\nquery stack during panic:");
608    }
609    while let Some(query) = current_query {
610        let Some(query_info) = query_map.get(&query) else {
611            break;
612        };
613        if Some(count_printed) < limit_frames || limit_frames.is_none() {
614            // Only print to stderr as many stack frames as `num_frames` when present.
615            // FIXME: needs translation
616            #[allow(rustc::diagnostic_outside_of_impl)]
617            #[allow(rustc::untranslatable_diagnostic)]
618            dcx.struct_failure_note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#{0} [{1:?}] {2}", count_printed,
                query_info.query.dep_kind, query_info.query.description))
    })format!(
619                "#{} [{:?}] {}",
620                count_printed, query_info.query.dep_kind, query_info.query.description
621            ))
622            .with_span(query_info.job.span)
623            .emit();
624            count_printed += 1;
625        }
626
627        if let Some(ref mut file) = file {
628            let _ = file.write_fmt(format_args!("#{0} [{1}] {2}\n", count_total,
        qcx.dep_context().dep_kind_info(query_info.query.dep_kind).name,
        query_info.query.description))writeln!(
629                file,
630                "#{} [{}] {}",
631                count_total,
632                qcx.dep_context().dep_kind_info(query_info.query.dep_kind).name,
633                query_info.query.description
634            );
635        }
636
637        current_query = query_info.job.parent;
638        count_total += 1;
639    }
640
641    if let Some(ref mut file) = file {
642        let _ = file.write_fmt(format_args!("end of query stack\n"))writeln!(file, "end of query stack");
643    }
644    count_total
645}