]> git.lizzy.rs Git - rust.git/blob - src/librustc_interface/queries.rs
Rollup merge of #72551 - alilleybrinker:document-debug-stability, r=KodrAus
[rust.git] / src / librustc_interface / queries.rs
1 use crate::interface::{Compiler, Result};
2 use crate::passes::{self, BoxedResolver, QueryContext};
3
4 use rustc_ast::{self, 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::mem;
22 use std::rc::Rc;
23
24 /// Represent the result of a query.
25 /// This result can be stolen with the `take` method and generated with the `compute` method.
26 pub struct Query<T> {
27     result: RefCell<Option<Result<T>>>,
28 }
29
30 impl<T> Query<T> {
31     fn compute<F: FnOnce() -> Result<T>>(&self, f: F) -> Result<&Query<T>> {
32         let mut result = self.result.borrow_mut();
33         if result.is_none() {
34             *result = Some(f());
35         }
36         result.as_ref().unwrap().as_ref().map(|_| self).map_err(|err| *err)
37     }
38
39     /// Takes ownership of the query result. Further attempts to take or peek the query
40     /// result will panic unless it is generated by calling the `compute` method.
41     pub fn take(&self) -> T {
42         self.result.borrow_mut().take().expect("missing query result").unwrap()
43     }
44
45     /// Borrows the query result using the RefCell. Panics if the result is stolen.
46     pub fn peek(&self) -> Ref<'_, T> {
47         Ref::map(self.result.borrow(), |r| {
48             r.as_ref().unwrap().as_ref().expect("missing query result")
49         })
50     }
51
52     /// Mutably borrows the query result using the RefCell. Panics if the result is stolen.
53     pub fn peek_mut(&self) -> RefMut<'_, T> {
54         RefMut::map(self.result.borrow_mut(), |r| {
55             r.as_mut().unwrap().as_mut().expect("missing query result")
56         })
57     }
58 }
59
60 impl<T> Default for Query<T> {
61     fn default() -> Self {
62         Query { result: RefCell::new(None) }
63     }
64 }
65
66 pub struct Queries<'tcx> {
67     compiler: &'tcx Compiler,
68     gcx: OnceCell<GlobalCtxt<'tcx>>,
69
70     arena: WorkerLocal<Arena<'tcx>>,
71     hir_arena: WorkerLocal<rustc_ast_lowering::Arena<'tcx>>,
72
73     dep_graph_future: Query<Option<DepGraphFuture>>,
74     parse: Query<ast::Crate>,
75     crate_name: Query<String>,
76     register_plugins: Query<(ast::Crate, Lrc<LintStore>)>,
77     expansion: Query<(ast::Crate, Steal<Rc<RefCell<BoxedResolver>>>, Lrc<LintStore>)>,
78     dep_graph: Query<DepGraph>,
79     lower_to_hir: Query<(&'tcx Crate<'tcx>, Steal<ResolverOutputs>)>,
80     prepare_outputs: Query<OutputFilenames>,
81     global_ctxt: Query<QueryContext<'tcx>>,
82     ongoing_codegen: Query<Box<dyn Any>>,
83 }
84
85 impl<'tcx> Queries<'tcx> {
86     pub fn new(compiler: &'tcx Compiler) -> Queries<'tcx> {
87         Queries {
88             compiler,
89             gcx: OnceCell::new(),
90             arena: WorkerLocal::new(|_| Arena::default()),
91             hir_arena: WorkerLocal::new(|_| rustc_ast_lowering::Arena::default()),
92             dep_graph_future: Default::default(),
93             parse: Default::default(),
94             crate_name: Default::default(),
95             register_plugins: Default::default(),
96             expansion: Default::default(),
97             dep_graph: Default::default(),
98             lower_to_hir: Default::default(),
99             prepare_outputs: Default::default(),
100             global_ctxt: Default::default(),
101             ongoing_codegen: Default::default(),
102         }
103     }
104
105     fn session(&self) -> &Lrc<Session> {
106         &self.compiler.sess
107     }
108     fn codegen_backend(&self) -> &Lrc<Box<dyn CodegenBackend>> {
109         &self.compiler.codegen_backend()
110     }
111
112     pub fn dep_graph_future(&self) -> Result<&Query<Option<DepGraphFuture>>> {
113         self.dep_graph_future.compute(|| {
114             Ok(self
115                 .session()
116                 .opts
117                 .build_dep_graph()
118                 .then(|| rustc_incremental::load_dep_graph(self.session())))
119         })
120     }
121
122     pub fn parse(&self) -> Result<&Query<ast::Crate>> {
123         self.parse.compute(|| {
124             passes::parse(self.session(), &self.compiler.input).map_err(|mut parse_error| {
125                 parse_error.emit();
126                 ErrorReported
127             })
128         })
129     }
130
131     pub fn register_plugins(&self) -> Result<&Query<(ast::Crate, Lrc<LintStore>)>> {
132         self.register_plugins.compute(|| {
133             let crate_name = self.crate_name()?.peek().clone();
134             let krate = self.parse()?.take();
135
136             let empty: &(dyn Fn(&Session, &mut LintStore) + Sync + Send) = &|_, _| {};
137             let result = passes::register_plugins(
138                 self.session(),
139                 &*self.codegen_backend().metadata_loader(),
140                 self.compiler.register_lints.as_deref().unwrap_or_else(|| empty),
141                 krate,
142                 &crate_name,
143             );
144
145             // Compute the dependency graph (in the background). We want to do
146             // this as early as possible, to give the DepGraph maximum time to
147             // load before dep_graph() is called, but it also can't happen
148             // until after rustc_incremental::prepare_session_directory() is
149             // called, which happens within passes::register_plugins().
150             self.dep_graph_future().ok();
151
152             result
153         })
154     }
155
156     pub fn crate_name(&self) -> Result<&Query<String>> {
157         self.crate_name.compute(|| {
158             Ok(match self.compiler.crate_name {
159                 Some(ref crate_name) => crate_name.clone(),
160                 None => {
161                     let parse_result = self.parse()?;
162                     let krate = parse_result.peek();
163                     find_crate_name(Some(self.session()), &krate.attrs, &self.compiler.input)
164                 }
165             })
166         })
167     }
168
169     pub fn expansion(
170         &self,
171     ) -> Result<&Query<(ast::Crate, Steal<Rc<RefCell<BoxedResolver>>>, Lrc<LintStore>)>> {
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| attr.check_name(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
398     // This method is different to all the other methods in `Compiler` because
399     // it lacks a `Queries` entry. It's also not currently used. It does serve
400     // as an example of how `Compiler` can be used, with additional steps added
401     // between some passes. And see `rustc_driver::run_compiler` for a more
402     // complex example.
403     pub fn compile(&self) -> Result<()> {
404         let linker = self.enter(|queries| {
405             queries.prepare_outputs()?;
406
407             if self.session().opts.output_types.contains_key(&OutputType::DepInfo)
408                 && self.session().opts.output_types.len() == 1
409             {
410                 return Ok(None);
411             }
412
413             queries.global_ctxt()?;
414
415             // Drop AST after creating GlobalCtxt to free memory.
416             mem::drop(queries.expansion()?.take());
417
418             queries.ongoing_codegen()?;
419
420             let linker = queries.linker()?;
421             Ok(Some(linker))
422         })?;
423
424         if let Some(linker) = linker {
425             linker.link()?
426         }
427
428         Ok(())
429     }
430 }