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