1 // Copyright 2017 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 use rustc_data_structures::sync::{Lock, Lrc};
15 use ty::maps::plumbing::CycleError;
16 use ty::context::TyCtxt;
17 use errors::Diagnostic;
19 /// Indicates the state of a query for a given key in a query map
20 pub(super) enum QueryResult<'tcx> {
21 /// An already executing query. The query job can be used to await for its completion
22 Started(Lrc<QueryJob<'tcx>>),
24 /// The query panicked. Queries trying to wait on this will raise a fatal error / silently panic
28 /// A span and a query key
29 #[derive(Clone, Debug)]
30 pub struct QueryInfo<'tcx> {
31 /// The span for a reason this query was required
33 pub query: Query<'tcx>,
36 /// A object representing an active query job.
37 pub struct QueryJob<'tcx> {
38 pub info: QueryInfo<'tcx>,
40 /// The parent query job which created this job and is implicitly waiting on it.
41 pub parent: Option<Lrc<QueryJob<'tcx>>>,
43 /// Diagnostic messages which are emitted while the query executes
44 pub diagnostics: Lock<Vec<Diagnostic>>,
47 impl<'tcx> QueryJob<'tcx> {
48 /// Creates a new query job
49 pub fn new(info: QueryInfo<'tcx>, parent: Option<Lrc<QueryJob<'tcx>>>) -> Self {
51 diagnostics: Lock::new(Vec::new()),
57 /// Awaits for the query job to complete.
59 /// For single threaded rustc there's no concurrent jobs running, so if we are waiting for any
60 /// query that means that there is a query cycle, thus this always running a cycle error.
61 pub(super) fn await<'lcx>(
63 tcx: TyCtxt<'_, 'tcx, 'lcx>,
65 ) -> Result<(), CycleError<'tcx>> {
66 // Get the current executing query (waiter) and find the waitee amongst its parents
67 let mut current_job = tls::with_related_context(tcx, |icx| icx.query.clone());
68 let mut cycle = Vec::new();
70 while let Some(job) = current_job {
71 cycle.insert(0, job.info.clone());
73 if &*job as *const _ == self as *const _ {
74 // This is the end of the cycle
75 // The span entry we included was for the usage
76 // of the cycle itself, and not part of the cycle
77 // Replace it with the span which caused the cycle to form
79 // Find out why the cycle itself was used
80 let usage = job.parent.as_ref().map(|parent| {
81 (job.info.span, parent.info.query.clone())
83 return Err(CycleError { usage, cycle });
86 current_job = job.parent.clone();
89 panic!("did not find a cycle")
92 /// Signals to waiters that the query is complete.
94 /// This does nothing for single threaded rustc,
95 /// as there are no concurrent jobs which could be waiting on us
96 pub fn signal_complete(&self) {}