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