]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_interface/src/queries.rs
Rollup merge of #76238 - denisvasilik:intra-doc-links-core-iterator, r=jyn514
[rust.git] / compiler / rustc_interface / src / queries.rs
1 use crate::interface::{Compiler, Result};
2 use crate::passes::{self, BoxedResolver, QueryContext};
3
4 use rustc_ast as ast;
5 use rustc_codegen_ssa::traits::CodegenBackend;
6 use rustc_data_structures::sync::{Lrc, OnceCell, WorkerLocal};
7 use rustc_errors::ErrorReported;
8 use rustc_hir::def_id::LOCAL_CRATE;
9 use rustc_hir::Crate;
10 use rustc_incremental::DepGraphFuture;
11 use rustc_lint::LintStore;
12 use rustc_middle::arena::Arena;
13 use rustc_middle::dep_graph::DepGraph;
14 use rustc_middle::ty::steal::Steal;
15 use rustc_middle::ty::{GlobalCtxt, ResolverOutputs, TyCtxt};
16 use rustc_session::config::{OutputFilenames, OutputType};
17 use rustc_session::{output::find_crate_name, Session};
18 use rustc_span::symbol::sym;
19 use std::any::Any;
20 use std::cell::{Ref, RefCell, RefMut};
21 use std::rc::Rc;
22
23 /// Represent the result of a query.
24 /// This result can be stolen with the `take` method and generated with the `compute` method.
25 pub struct Query<T> {
26     result: RefCell<Option<Result<T>>>,
27 }
28
29 impl<T> Query<T> {
30     fn compute<F: FnOnce() -> Result<T>>(&self, f: F) -> Result<&Query<T>> {
31         let mut result = self.result.borrow_mut();
32         if result.is_none() {
33             *result = Some(f());
34         }
35         result.as_ref().unwrap().as_ref().map(|_| self).map_err(|err| *err)
36     }
37
38     /// Takes ownership of the query result. Further attempts to take or peek the query
39     /// result will panic unless it is generated by calling the `compute` method.
40     pub fn take(&self) -> T {
41         self.result.borrow_mut().take().expect("missing query result").unwrap()
42     }
43
44     /// Borrows the query result using the RefCell. Panics if the result is stolen.
45     pub fn peek(&self) -> Ref<'_, T> {
46         Ref::map(self.result.borrow(), |r| {
47             r.as_ref().unwrap().as_ref().expect("missing query result")
48         })
49     }
50
51     /// Mutably borrows the query result using the RefCell. Panics if the result is stolen.
52     pub fn peek_mut(&self) -> RefMut<'_, T> {
53         RefMut::map(self.result.borrow_mut(), |r| {
54             r.as_mut().unwrap().as_mut().expect("missing query result")
55         })
56     }
57 }
58
59 impl<T> Default for Query<T> {
60     fn default() -> Self {
61         Query { result: RefCell::new(None) }
62     }
63 }
64
65 pub struct Queries<'tcx> {
66     compiler: &'tcx Compiler,
67     gcx: OnceCell<GlobalCtxt<'tcx>>,
68
69     arena: WorkerLocal<Arena<'tcx>>,
70     hir_arena: WorkerLocal<rustc_ast_lowering::Arena<'tcx>>,
71
72     dep_graph_future: Query<Option<DepGraphFuture>>,
73     parse: Query<ast::Crate>,
74     crate_name: Query<String>,
75     register_plugins: Query<(ast::Crate, Lrc<LintStore>)>,
76     expansion: Query<(ast::Crate, Steal<Rc<RefCell<BoxedResolver>>>, Lrc<LintStore>)>,
77     dep_graph: Query<DepGraph>,
78     lower_to_hir: Query<(&'tcx Crate<'tcx>, Steal<ResolverOutputs>)>,
79     prepare_outputs: Query<OutputFilenames>,
80     global_ctxt: Query<QueryContext<'tcx>>,
81     ongoing_codegen: Query<Box<dyn Any>>,
82 }
83
84 impl<'tcx> Queries<'tcx> {
85     pub fn new(compiler: &'tcx Compiler) -> Queries<'tcx> {
86         Queries {
87             compiler,
88             gcx: OnceCell::new(),
89             arena: WorkerLocal::new(|_| Arena::default()),
90             hir_arena: WorkerLocal::new(|_| rustc_ast_lowering::Arena::default()),
91             dep_graph_future: Default::default(),
92             parse: Default::default(),
93             crate_name: Default::default(),
94             register_plugins: Default::default(),
95             expansion: Default::default(),
96             dep_graph: Default::default(),
97             lower_to_hir: Default::default(),
98             prepare_outputs: Default::default(),
99             global_ctxt: Default::default(),
100             ongoing_codegen: Default::default(),
101         }
102     }
103
104     fn session(&self) -> &Lrc<Session> {
105         &self.compiler.sess
106     }
107     fn codegen_backend(&self) -> &Lrc<Box<dyn CodegenBackend>> {
108         &self.compiler.codegen_backend()
109     }
110
111     pub fn dep_graph_future(&self) -> Result<&Query<Option<DepGraphFuture>>> {
112         self.dep_graph_future.compute(|| {
113             Ok(self
114                 .session()
115                 .opts
116                 .build_dep_graph()
117                 .then(|| rustc_incremental::load_dep_graph(self.session())))
118         })
119     }
120
121     pub fn parse(&self) -> Result<&Query<ast::Crate>> {
122         self.parse.compute(|| {
123             passes::parse(self.session(), &self.compiler.input).map_err(|mut parse_error| {
124                 parse_error.emit();
125                 ErrorReported
126             })
127         })
128     }
129
130     pub fn register_plugins(&self) -> Result<&Query<(ast::Crate, Lrc<LintStore>)>> {
131         self.register_plugins.compute(|| {
132             let crate_name = self.crate_name()?.peek().clone();
133             let krate = self.parse()?.take();
134
135             let empty: &(dyn Fn(&Session, &mut LintStore) + Sync + Send) = &|_, _| {};
136             let result = passes::register_plugins(
137                 self.session(),
138                 &*self.codegen_backend().metadata_loader(),
139                 self.compiler.register_lints.as_deref().unwrap_or_else(|| empty),
140                 krate,
141                 &crate_name,
142             );
143
144             // Compute the dependency graph (in the background). We want to do
145             // this as early as possible, to give the DepGraph maximum time to
146             // load before dep_graph() is called, but it also can't happen
147             // until after rustc_incremental::prepare_session_directory() is
148             // called, which happens within passes::register_plugins().
149             self.dep_graph_future().ok();
150
151             result
152         })
153     }
154
155     pub fn crate_name(&self) -> Result<&Query<String>> {
156         self.crate_name.compute(|| {
157             Ok(match self.compiler.crate_name {
158                 Some(ref crate_name) => crate_name.clone(),
159                 None => {
160                     let parse_result = self.parse()?;
161                     let krate = parse_result.peek();
162                     find_crate_name(self.session(), &krate.attrs, &self.compiler.input)
163                 }
164             })
165         })
166     }
167
168     pub fn expansion(
169         &self,
170     ) -> Result<&Query<(ast::Crate, Steal<Rc<RefCell<BoxedResolver>>>, Lrc<LintStore>)>> {
171         tracing::trace!("expansion");
172         self.expansion.compute(|| {
173             let crate_name = self.crate_name()?.peek().clone();
174             let (krate, lint_store) = self.register_plugins()?.take();
175             let _timer = self.session().timer("configure_and_expand");
176             passes::configure_and_expand(
177                 self.session().clone(),
178                 lint_store.clone(),
179                 self.codegen_backend().metadata_loader(),
180                 krate,
181                 &crate_name,
182             )
183             .map(|(krate, resolver)| {
184                 (krate, Steal::new(Rc::new(RefCell::new(resolver))), lint_store)
185             })
186         })
187     }
188
189     pub fn dep_graph(&self) -> Result<&Query<DepGraph>> {
190         self.dep_graph.compute(|| {
191             Ok(match self.dep_graph_future()?.take() {
192                 None => DepGraph::new_disabled(),
193                 Some(future) => {
194                     let (prev_graph, prev_work_products) =
195                         self.session().time("blocked_on_dep_graph_loading", || {
196                             future
197                                 .open()
198                                 .unwrap_or_else(|e| rustc_incremental::LoadResult::Error {
199                                     message: format!("could not decode incremental cache: {:?}", e),
200                                 })
201                                 .open(self.session())
202                         });
203                     DepGraph::new(prev_graph, prev_work_products)
204                 }
205             })
206         })
207     }
208
209     pub fn lower_to_hir(&'tcx self) -> Result<&Query<(&'tcx Crate<'tcx>, Steal<ResolverOutputs>)>> {
210         self.lower_to_hir.compute(|| {
211             let expansion_result = self.expansion()?;
212             let peeked = expansion_result.peek();
213             let krate = &peeked.0;
214             let resolver = peeked.1.steal();
215             let lint_store = &peeked.2;
216             let hir = resolver.borrow_mut().access(|resolver| {
217                 Ok(passes::lower_to_hir(
218                     self.session(),
219                     lint_store,
220                     resolver,
221                     &*self.dep_graph()?.peek(),
222                     &krate,
223                     &self.hir_arena,
224                 ))
225             })?;
226             let hir = self.hir_arena.alloc(hir);
227             Ok((hir, Steal::new(BoxedResolver::to_resolver_outputs(resolver))))
228         })
229     }
230
231     pub fn prepare_outputs(&self) -> Result<&Query<OutputFilenames>> {
232         self.prepare_outputs.compute(|| {
233             let expansion_result = self.expansion()?;
234             let (krate, boxed_resolver, _) = &*expansion_result.peek();
235             let crate_name = self.crate_name()?;
236             let crate_name = crate_name.peek();
237             passes::prepare_outputs(
238                 self.session(),
239                 self.compiler,
240                 &krate,
241                 &boxed_resolver,
242                 &crate_name,
243             )
244         })
245     }
246
247     pub fn global_ctxt(&'tcx self) -> Result<&Query<QueryContext<'tcx>>> {
248         self.global_ctxt.compute(|| {
249             let crate_name = self.crate_name()?.peek().clone();
250             let outputs = self.prepare_outputs()?.peek().clone();
251             let lint_store = self.expansion()?.peek().2.clone();
252             let hir = self.lower_to_hir()?.peek();
253             let dep_graph = self.dep_graph()?.peek().clone();
254             let (ref krate, ref resolver_outputs) = &*hir;
255             let _timer = self.session().timer("create_global_ctxt");
256             Ok(passes::create_global_ctxt(
257                 self.compiler,
258                 lint_store,
259                 krate,
260                 dep_graph,
261                 resolver_outputs.steal(),
262                 outputs,
263                 &crate_name,
264                 &self.gcx,
265                 &self.arena,
266             ))
267         })
268     }
269
270     pub fn ongoing_codegen(&'tcx self) -> Result<&Query<Box<dyn Any>>> {
271         self.ongoing_codegen.compute(|| {
272             let outputs = self.prepare_outputs()?;
273             self.global_ctxt()?.peek_mut().enter(|tcx| {
274                 tcx.analysis(LOCAL_CRATE).ok();
275
276                 // Don't do code generation if there were any errors
277                 self.session().compile_status()?;
278
279                 // Hook for compile-fail tests.
280                 Self::check_for_rustc_errors_attr(tcx);
281
282                 Ok(passes::start_codegen(&***self.codegen_backend(), tcx, &*outputs.peek()))
283             })
284         })
285     }
286
287     /// Check for the `#[rustc_error]` annotation, which forces an error in codegen. This is used
288     /// to write compile-fail tests that actually test that compilation succeeds without reporting
289     /// an error.
290     fn check_for_rustc_errors_attr(tcx: TyCtxt<'_>) {
291         let def_id = match tcx.entry_fn(LOCAL_CRATE) {
292             Some((def_id, _)) => def_id,
293             _ => return,
294         };
295
296         let attrs = &*tcx.get_attrs(def_id.to_def_id());
297         let attrs = attrs.iter().filter(|attr| tcx.sess.check_name(attr, sym::rustc_error));
298         for attr in attrs {
299             match attr.meta_item_list() {
300                 // Check if there is a `#[rustc_error(delay_span_bug_from_inside_query)]`.
301                 Some(list)
302                     if list.iter().any(|list_item| {
303                         matches!(
304                             list_item.ident().map(|i| i.name),
305                             Some(sym::delay_span_bug_from_inside_query)
306                         )
307                     }) =>
308                 {
309                     tcx.ensure().trigger_delay_span_bug(def_id);
310                 }
311
312                 // Bare `#[rustc_error]`.
313                 None => {
314                     tcx.sess.span_fatal(
315                         tcx.def_span(def_id),
316                         "fatal error triggered by #[rustc_error]",
317                     );
318                 }
319
320                 // Some other attribute.
321                 Some(_) => {
322                     tcx.sess.span_warn(
323                         tcx.def_span(def_id),
324                         "unexpected annotation used with `#[rustc_error(...)]!",
325                     );
326                 }
327             }
328         }
329     }
330
331     pub fn linker(&'tcx self) -> Result<Linker> {
332         let dep_graph = self.dep_graph()?;
333         let prepare_outputs = self.prepare_outputs()?;
334         let ongoing_codegen = self.ongoing_codegen()?;
335
336         let sess = self.session().clone();
337         let codegen_backend = self.codegen_backend().clone();
338
339         Ok(Linker {
340             sess,
341             dep_graph: dep_graph.peek().clone(),
342             prepare_outputs: prepare_outputs.take(),
343             ongoing_codegen: ongoing_codegen.take(),
344             codegen_backend,
345         })
346     }
347 }
348
349 pub struct Linker {
350     sess: Lrc<Session>,
351     dep_graph: DepGraph,
352     prepare_outputs: OutputFilenames,
353     ongoing_codegen: Box<dyn Any>,
354     codegen_backend: Lrc<Box<dyn CodegenBackend>>,
355 }
356
357 impl Linker {
358     pub fn link(self) -> Result<()> {
359         let codegen_results =
360             self.codegen_backend.join_codegen(self.ongoing_codegen, &self.sess, &self.dep_graph)?;
361         let prof = self.sess.prof.clone();
362         let dep_graph = self.dep_graph;
363         prof.generic_activity("drop_dep_graph").run(move || drop(dep_graph));
364
365         if !self
366             .sess
367             .opts
368             .output_types
369             .keys()
370             .any(|&i| i == OutputType::Exe || i == OutputType::Metadata)
371         {
372             return Ok(());
373         }
374         self.codegen_backend.link(&self.sess, codegen_results, &self.prepare_outputs)
375     }
376 }
377
378 impl Compiler {
379     pub fn enter<F, T>(&self, f: F) -> T
380     where
381         F: for<'tcx> FnOnce(&'tcx Queries<'tcx>) -> T,
382     {
383         let mut _timer = None;
384         let queries = Queries::new(&self);
385         let ret = f(&queries);
386
387         if self.session().opts.debugging_opts.query_stats {
388             if let Ok(gcx) = queries.global_ctxt() {
389                 gcx.peek_mut().print_stats();
390             }
391         }
392
393         _timer = Some(self.session().timer("free_global_ctxt"));
394
395         ret
396     }
397 }