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