]> git.lizzy.rs Git - rust.git/blob - src/librustc_interface/queries.rs
Rollup merge of #65507 - polyedre:master, r=nikomatsakis
[rust.git] / src / librustc_interface / queries.rs
1 use crate::interface::{Compiler, Result};
2 use crate::passes::{self, BoxedResolver, ExpansionResult, BoxedGlobalCtxt, PluginInfo};
3
4 use rustc_incremental::DepGraphFuture;
5 use rustc::session::config::{OutputFilenames, OutputType};
6 use rustc::util::common::{time, ErrorReported};
7 use rustc::hir;
8 use rustc::hir::def_id::LOCAL_CRATE;
9 use rustc::ty::steal::Steal;
10 use rustc::dep_graph::DepGraph;
11 use std::cell::{Ref, RefMut, RefCell};
12 use std::rc::Rc;
13 use std::any::Any;
14 use std::mem;
15 use syntax::{self, ast};
16
17 /// Represent the result of a query.
18 /// This result can be stolen with the `take` method and returned with the `give` method.
19 pub struct Query<T> {
20     result: RefCell<Option<Result<T>>>,
21 }
22
23 impl<T> Query<T> {
24     fn compute<F: FnOnce() -> Result<T>>(&self, f: F) -> Result<&Query<T>> {
25         let mut result = self.result.borrow_mut();
26         if result.is_none() {
27             *result = Some(f());
28         }
29         result.as_ref().unwrap().as_ref().map(|_| self).map_err(|err| *err)
30     }
31
32     /// Takes ownership of the query result. Further attempts to take or peek the query
33     /// result will panic unless it is returned by calling the `give` method.
34     pub fn take(&self) -> T {
35         self.result
36             .borrow_mut()
37             .take()
38             .expect("missing query result")
39             .unwrap()
40     }
41
42     /// Returns a stolen query result. Panics if there's already a result.
43     pub fn give(&self, value: T) {
44         let mut result = self.result.borrow_mut();
45         assert!(result.is_none(), "a result already exists");
46         *result = Some(Ok(value));
47     }
48
49     /// Borrows the query result using the RefCell. Panics if the result is stolen.
50     pub fn peek(&self) -> Ref<'_, T> {
51         Ref::map(self.result.borrow(), |r| {
52             r.as_ref().unwrap().as_ref().expect("missing query result")
53         })
54     }
55
56     /// Mutably borrows the query result using the RefCell. Panics if the result is stolen.
57     pub fn peek_mut(&self) -> RefMut<'_, T> {
58         RefMut::map(self.result.borrow_mut(), |r| {
59             r.as_mut().unwrap().as_mut().expect("missing query result")
60         })
61     }
62 }
63
64 impl<T> Default for Query<T> {
65     fn default() -> Self {
66         Query {
67             result: RefCell::new(None),
68         }
69     }
70 }
71
72 #[derive(Default)]
73 pub(crate) struct Queries {
74     dep_graph_future: Query<Option<DepGraphFuture>>,
75     parse: Query<ast::Crate>,
76     crate_name: Query<String>,
77     register_plugins: Query<(ast::Crate, PluginInfo)>,
78     expansion: Query<(ast::Crate, Steal<Rc<RefCell<BoxedResolver>>>)>,
79     dep_graph: Query<DepGraph>,
80     lower_to_hir: Query<(Steal<hir::map::Forest>, ExpansionResult)>,
81     prepare_outputs: Query<OutputFilenames>,
82     global_ctxt: Query<BoxedGlobalCtxt>,
83     ongoing_codegen: Query<Box<dyn Any>>,
84     link: Query<()>,
85 }
86
87 impl Compiler {
88     pub fn dep_graph_future(&self) -> Result<&Query<Option<DepGraphFuture>>> {
89         self.queries.dep_graph_future.compute(|| {
90             Ok(if self.session().opts.build_dep_graph() {
91                 Some(rustc_incremental::load_dep_graph(self.session()))
92             } else {
93                 None
94             })
95         })
96     }
97
98     pub fn parse(&self) -> Result<&Query<ast::Crate>> {
99         self.queries.parse.compute(|| {
100             passes::parse(self.session(), &self.input).map_err(
101                 |mut parse_error| {
102                     parse_error.emit();
103                     ErrorReported
104                 },
105             )
106         })
107     }
108
109     pub fn register_plugins(&self) -> Result<&Query<(ast::Crate, PluginInfo)>> {
110         self.queries.register_plugins.compute(|| {
111             let crate_name = self.crate_name()?.peek().clone();
112             let krate = self.parse()?.take();
113
114             let result = passes::register_plugins(
115                 self.session(),
116                 self.cstore(),
117                 krate,
118                 &crate_name,
119             );
120
121             // Compute the dependency graph (in the background). We want to do
122             // this as early as possible, to give the DepGraph maximum time to
123             // load before dep_graph() is called, but it also can't happen
124             // until after rustc_incremental::prepare_session_directory() is
125             // called, which happens within passes::register_plugins().
126             self.dep_graph_future().ok();
127
128             result
129         })
130     }
131
132     pub fn crate_name(&self) -> Result<&Query<String>> {
133         self.queries.crate_name.compute(|| {
134             Ok(match self.crate_name {
135                 Some(ref crate_name) => crate_name.clone(),
136                 None => {
137                     let parse_result = self.parse()?;
138                     let krate = parse_result.peek();
139                     rustc_codegen_utils::link::find_crate_name(
140                         Some(self.session()),
141                         &krate.attrs,
142                         &self.input
143                     )
144                 }
145             })
146         })
147     }
148
149     pub fn expansion(
150         &self
151     ) -> Result<&Query<(ast::Crate, Steal<Rc<RefCell<BoxedResolver>>>)>> {
152         self.queries.expansion.compute(|| {
153             let crate_name = self.crate_name()?.peek().clone();
154             let (krate, plugin_info) = self.register_plugins()?.take();
155             passes::configure_and_expand(
156                 self.sess.clone(),
157                 self.cstore().clone(),
158                 krate,
159                 &crate_name,
160                 plugin_info,
161             ).map(|(krate, resolver)| (krate, Steal::new(Rc::new(RefCell::new(resolver)))))
162         })
163     }
164
165     pub fn dep_graph(&self) -> Result<&Query<DepGraph>> {
166         self.queries.dep_graph.compute(|| {
167             Ok(match self.dep_graph_future()?.take() {
168                 None => DepGraph::new_disabled(),
169                 Some(future) => {
170                     let (prev_graph, prev_work_products) =
171                         time(self.session(), "blocked while dep-graph loading finishes", || {
172                             future.open().unwrap_or_else(|e| rustc_incremental::LoadResult::Error {
173                                 message: format!("could not decode incremental cache: {:?}", e),
174                             }).open(self.session())
175                         });
176                     DepGraph::new(prev_graph, prev_work_products)
177                 }
178             })
179         })
180     }
181
182     pub fn lower_to_hir(&self) -> Result<&Query<(Steal<hir::map::Forest>, ExpansionResult)>> {
183         self.queries.lower_to_hir.compute(|| {
184             let expansion_result = self.expansion()?;
185             let peeked = expansion_result.peek();
186             let krate = &peeked.0;
187             let resolver = peeked.1.steal();
188             let hir = Steal::new(resolver.borrow_mut().access(|resolver| {
189                 passes::lower_to_hir(
190                     self.session(),
191                     self.cstore(),
192                     resolver,
193                     &*self.dep_graph()?.peek(),
194                     &krate
195                 )
196             })?);
197             Ok((hir, BoxedResolver::to_expansion_result(resolver)))
198         })
199     }
200
201     pub fn prepare_outputs(&self) -> Result<&Query<OutputFilenames>> {
202         self.queries.prepare_outputs.compute(|| {
203             let krate = self.expansion()?;
204             let krate = krate.peek();
205             let crate_name = self.crate_name()?;
206             let crate_name = crate_name.peek();
207             passes::prepare_outputs(self.session(), self, &krate.0, &*crate_name)
208         })
209     }
210
211     pub fn global_ctxt(&self) -> Result<&Query<BoxedGlobalCtxt>> {
212         self.queries.global_ctxt.compute(|| {
213             let crate_name = self.crate_name()?.peek().clone();
214             let outputs = self.prepare_outputs()?.peek().clone();
215             let hir = self.lower_to_hir()?;
216             let hir = hir.peek();
217             let (ref hir_forest, ref expansion) = *hir;
218             Ok(passes::create_global_ctxt(
219                 self,
220                 hir_forest.steal(),
221                 expansion.defs.steal(),
222                 expansion.resolutions.steal(),
223                 outputs,
224                 &crate_name))
225         })
226     }
227
228     pub fn ongoing_codegen(&self) -> Result<&Query<Box<dyn Any>>> {
229         self.queries.ongoing_codegen.compute(|| {
230             let outputs = self.prepare_outputs()?;
231             self.global_ctxt()?.peek_mut().enter(|tcx| {
232                 tcx.analysis(LOCAL_CRATE).ok();
233
234                 // Don't do code generation if there were any errors
235                 self.session().compile_status()?;
236
237                 Ok(passes::start_codegen(
238                     &***self.codegen_backend(),
239                     tcx,
240                     &*outputs.peek()
241                 ))
242             })
243         })
244     }
245
246     pub fn link(&self) -> Result<&Query<()>> {
247         self.queries.link.compute(|| {
248             let sess = self.session();
249
250             let ongoing_codegen = self.ongoing_codegen()?.take();
251
252             self.codegen_backend().join_codegen_and_link(
253                 ongoing_codegen,
254                 sess,
255                 &*self.dep_graph()?.peek(),
256                 &*self.prepare_outputs()?.peek(),
257             ).map_err(|_| ErrorReported)?;
258
259             Ok(())
260         })
261     }
262
263     // This method is different to all the other methods in `Compiler` because
264     // it lacks a `Queries` entry. It's also not currently used. It does serve
265     // as an example of how `Compiler` can be used, with additional steps added
266     // between some passes. And see `rustc_driver::run_compiler` for a more
267     // complex example.
268     pub fn compile(&self) -> Result<()> {
269         self.prepare_outputs()?;
270
271         if self.session().opts.output_types.contains_key(&OutputType::DepInfo)
272             && self.session().opts.output_types.len() == 1
273         {
274             return Ok(())
275         }
276
277         self.global_ctxt()?;
278
279         // Drop AST after creating GlobalCtxt to free memory.
280         mem::drop(self.expansion()?.take());
281
282         self.ongoing_codegen()?;
283
284         // Drop GlobalCtxt after starting codegen to free memory.
285         mem::drop(self.global_ctxt()?.take());
286
287         self.link().map(|_| ())
288     }
289 }