]> git.lizzy.rs Git - rust.git/blob - src/librustc_metadata/cstore_impl.rs
Rollup merge of #41876 - oli-obk:diagnosing_diagnostics, r=nagisa
[rust.git] / src / librustc_metadata / cstore_impl.rs
1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use cstore;
12 use encoder;
13 use locator;
14 use schema;
15
16 use rustc::dep_graph::DepTrackingMapConfig;
17 use rustc::middle::cstore::{CrateStore, CrateSource, LibSource, DepKind,
18                             ExternCrate, NativeLibrary, LinkMeta,
19                             LinkagePreference, LoadedMacro, EncodedMetadata};
20 use rustc::hir::def;
21 use rustc::middle::lang_items;
22 use rustc::session::Session;
23 use rustc::ty::{self, TyCtxt};
24 use rustc::ty::maps::Providers;
25 use rustc::hir::def_id::{CrateNum, DefId, DefIndex, CRATE_DEF_INDEX, LOCAL_CRATE};
26
27 use rustc::dep_graph::{DepNode, GlobalMetaDataKind};
28 use rustc::hir::map::{DefKey, DefPath, DisambiguatedDefPathData};
29 use rustc::util::nodemap::{NodeSet, DefIdMap};
30 use rustc_back::PanicStrategy;
31
32 use std::any::Any;
33 use std::rc::Rc;
34
35 use syntax::ast;
36 use syntax::attr;
37 use syntax::parse::filemap_to_stream;
38 use syntax::symbol::Symbol;
39 use syntax_pos::{Span, NO_EXPANSION};
40 use rustc::hir::svh::Svh;
41 use rustc_back::target::Target;
42 use rustc::hir;
43
44 macro_rules! provide {
45     (<$lt:tt> $tcx:ident, $def_id:ident, $cdata:ident $($name:ident => $compute:block)*) => {
46         pub fn provide<$lt>(providers: &mut Providers<$lt>) {
47             $(fn $name<'a, $lt:$lt>($tcx: TyCtxt<'a, $lt, $lt>, $def_id: DefId)
48                                     -> <ty::queries::$name<$lt> as
49                                         DepTrackingMapConfig>::Value {
50                 assert!(!$def_id.is_local());
51
52                 $tcx.dep_graph.read(DepNode::MetaData($def_id));
53
54                 let $cdata = $tcx.sess.cstore.crate_data_as_rc_any($def_id.krate);
55                 let $cdata = $cdata.downcast_ref::<cstore::CrateMetadata>()
56                     .expect("CrateStore crated ata is not a CrateMetadata");
57                 $compute
58             })*
59
60             *providers = Providers {
61                 $($name,)*
62                 ..*providers
63             };
64         }
65     }
66 }
67
68 provide! { <'tcx> tcx, def_id, cdata
69     type_of => { cdata.get_type(def_id.index, tcx) }
70     generics_of => { tcx.alloc_generics(cdata.get_generics(def_id.index)) }
71     predicates_of => { cdata.get_predicates(def_id.index, tcx) }
72     super_predicates_of => { cdata.get_super_predicates(def_id.index, tcx) }
73     trait_def => {
74         tcx.alloc_trait_def(cdata.get_trait_def(def_id.index))
75     }
76     adt_def => { cdata.get_adt_def(def_id.index, tcx) }
77     adt_destructor => {
78         let _ = cdata;
79         tcx.calculate_dtor(def_id, &mut |_,_| Ok(()))
80     }
81     variances_of => { Rc::new(cdata.get_item_variances(def_id.index)) }
82     associated_item_def_ids => {
83         let mut result = vec![];
84         cdata.each_child_of_item(def_id.index, |child| result.push(child.def.def_id()));
85         Rc::new(result)
86     }
87     associated_item => { cdata.get_associated_item(def_id.index) }
88     impl_trait_ref => { cdata.get_impl_trait(def_id.index, tcx) }
89     impl_polarity => { cdata.get_impl_polarity(def_id.index) }
90     coerce_unsized_info => {
91         cdata.get_coerce_unsized_info(def_id.index).unwrap_or_else(|| {
92             bug!("coerce_unsized_info: `{:?}` is missing its info", def_id);
93         })
94     }
95     optimized_mir => {
96         let mir = cdata.maybe_get_optimized_mir(tcx, def_id.index).unwrap_or_else(|| {
97             bug!("get_optimized_mir: missing MIR for `{:?}`", def_id)
98         });
99
100         let mir = tcx.alloc_mir(mir);
101
102         mir
103     }
104     mir_const_qualif => { cdata.mir_const_qualif(def_id.index) }
105     typeck_tables_of => { cdata.item_body_tables(def_id.index, tcx) }
106     closure_kind => { cdata.closure_kind(def_id.index) }
107     closure_type => { cdata.closure_ty(def_id.index, tcx) }
108     inherent_impls => { Rc::new(cdata.get_inherent_implementations_for_type(def_id.index)) }
109     is_foreign_item => { cdata.is_foreign_item(def_id.index) }
110     describe_def => { cdata.get_def(def_id.index) }
111     def_span => { cdata.get_span(def_id.index, &tcx.sess) }
112     stability => { cdata.get_stability(def_id.index) }
113     deprecation => { cdata.get_deprecation(def_id.index) }
114     item_attrs => { cdata.get_item_attrs(def_id.index, &tcx.dep_graph) }
115     // FIXME(#38501) We've skipped a `read` on the `HirBody` of
116     // a `fn` when encoding, so the dep-tracking wouldn't work.
117     // This is only used by rustdoc anyway, which shouldn't have
118     // incremental recompilation ever enabled.
119     fn_arg_names => { cdata.get_fn_arg_names(def_id.index) }
120     impl_parent => { cdata.get_parent_impl(def_id.index) }
121     trait_of_item => { cdata.get_trait_of_item(def_id.index) }
122     is_exported_symbol => {
123         let dep_node = cdata.metadata_dep_node(GlobalMetaDataKind::ExportedSymbols);
124         cdata.exported_symbols.get(&tcx.dep_graph, dep_node).contains(&def_id.index)
125     }
126     item_body_nested_bodies => { Rc::new(cdata.item_body_nested_bodies(def_id.index)) }
127     const_is_rvalue_promotable_to_static => {
128         cdata.const_is_rvalue_promotable_to_static(def_id.index)
129     }
130     is_mir_available => { cdata.is_item_mir_available(def_id.index) }
131 }
132
133 impl CrateStore for cstore::CStore {
134     fn crate_data_as_rc_any(&self, krate: CrateNum) -> Rc<Any> {
135         self.get_crate_data(krate)
136     }
137
138     fn visibility(&self, def: DefId) -> ty::Visibility {
139         self.dep_graph.read(DepNode::MetaData(def));
140         self.get_crate_data(def.krate).get_visibility(def.index)
141     }
142
143     fn item_generics_cloned(&self, def: DefId) -> ty::Generics {
144         self.dep_graph.read(DepNode::MetaData(def));
145         self.get_crate_data(def.krate).get_generics(def.index)
146     }
147
148     fn implementations_of_trait(&self, filter: Option<DefId>) -> Vec<DefId>
149     {
150         if let Some(def_id) = filter {
151             self.dep_graph.read(DepNode::MetaData(def_id));
152         }
153         let mut result = vec![];
154         self.iter_crate_data(|_, cdata| {
155             cdata.get_implementations_for_trait(filter, &self.dep_graph, &mut result)
156         });
157         result
158     }
159
160     fn impl_defaultness(&self, def: DefId) -> hir::Defaultness
161     {
162         self.dep_graph.read(DepNode::MetaData(def));
163         self.get_crate_data(def.krate).get_impl_defaultness(def.index)
164     }
165
166     fn associated_item_cloned(&self, def: DefId) -> ty::AssociatedItem
167     {
168         self.dep_graph.read(DepNode::MetaData(def));
169         self.get_crate_data(def.krate).get_associated_item(def.index)
170     }
171
172     fn is_const_fn(&self, did: DefId) -> bool
173     {
174         self.dep_graph.read(DepNode::MetaData(did));
175         self.get_crate_data(did.krate).is_const_fn(did.index)
176     }
177
178     fn is_default_impl(&self, impl_did: DefId) -> bool {
179         self.dep_graph.read(DepNode::MetaData(impl_did));
180         self.get_crate_data(impl_did.krate).is_default_impl(impl_did.index)
181     }
182
183     fn is_statically_included_foreign_item(&self, def_id: DefId) -> bool
184     {
185         self.do_is_statically_included_foreign_item(def_id)
186     }
187
188     fn is_dllimport_foreign_item(&self, def_id: DefId) -> bool {
189         if def_id.krate == LOCAL_CRATE {
190             self.dllimport_foreign_items.borrow().contains(&def_id.index)
191         } else {
192             self.get_crate_data(def_id.krate)
193                 .is_dllimport_foreign_item(def_id.index, &self.dep_graph)
194         }
195     }
196
197     fn dylib_dependency_formats(&self, cnum: CrateNum)
198                                 -> Vec<(CrateNum, LinkagePreference)>
199     {
200         self.get_crate_data(cnum).get_dylib_dependency_formats(&self.dep_graph)
201     }
202
203     fn dep_kind(&self, cnum: CrateNum) -> DepKind
204     {
205         let data = self.get_crate_data(cnum);
206         let dep_node = data.metadata_dep_node(GlobalMetaDataKind::CrateDeps);
207         self.dep_graph.read(dep_node);
208         data.dep_kind.get()
209     }
210
211     fn export_macros(&self, cnum: CrateNum) {
212         let data = self.get_crate_data(cnum);
213         let dep_node = data.metadata_dep_node(GlobalMetaDataKind::CrateDeps);
214
215         self.dep_graph.read(dep_node);
216         if data.dep_kind.get() == DepKind::UnexportedMacrosOnly {
217             data.dep_kind.set(DepKind::MacrosOnly)
218         }
219     }
220
221     fn lang_items(&self, cnum: CrateNum) -> Vec<(DefIndex, usize)>
222     {
223         self.get_crate_data(cnum).get_lang_items(&self.dep_graph)
224     }
225
226     fn missing_lang_items(&self, cnum: CrateNum)
227                           -> Vec<lang_items::LangItem>
228     {
229         self.get_crate_data(cnum).get_missing_lang_items(&self.dep_graph)
230     }
231
232     fn is_staged_api(&self, cnum: CrateNum) -> bool
233     {
234         self.get_crate_data(cnum).is_staged_api(&self.dep_graph)
235     }
236
237     fn is_allocator(&self, cnum: CrateNum) -> bool
238     {
239         self.get_crate_data(cnum).is_allocator(&self.dep_graph)
240     }
241
242     fn is_panic_runtime(&self, cnum: CrateNum) -> bool
243     {
244         self.get_crate_data(cnum).is_panic_runtime(&self.dep_graph)
245     }
246
247     fn is_compiler_builtins(&self, cnum: CrateNum) -> bool {
248         self.get_crate_data(cnum).is_compiler_builtins(&self.dep_graph)
249     }
250
251     fn is_sanitizer_runtime(&self, cnum: CrateNum) -> bool {
252         self.get_crate_data(cnum).is_sanitizer_runtime(&self.dep_graph)
253     }
254
255     fn panic_strategy(&self, cnum: CrateNum) -> PanicStrategy {
256         self.get_crate_data(cnum).panic_strategy(&self.dep_graph)
257     }
258
259     fn crate_name(&self, cnum: CrateNum) -> Symbol
260     {
261         self.get_crate_data(cnum).name
262     }
263
264     fn original_crate_name(&self, cnum: CrateNum) -> Symbol
265     {
266         self.get_crate_data(cnum).name()
267     }
268
269     fn extern_crate(&self, cnum: CrateNum) -> Option<ExternCrate>
270     {
271         self.get_crate_data(cnum).extern_crate.get()
272     }
273
274     fn crate_hash(&self, cnum: CrateNum) -> Svh
275     {
276         self.get_crate_hash(cnum)
277     }
278
279     fn crate_disambiguator(&self, cnum: CrateNum) -> Symbol
280     {
281         self.get_crate_data(cnum).disambiguator()
282     }
283
284     fn plugin_registrar_fn(&self, cnum: CrateNum) -> Option<DefId>
285     {
286         self.get_crate_data(cnum).root.plugin_registrar_fn.map(|index| DefId {
287             krate: cnum,
288             index: index
289         })
290     }
291
292     fn derive_registrar_fn(&self, cnum: CrateNum) -> Option<DefId>
293     {
294         self.get_crate_data(cnum).root.macro_derive_registrar.map(|index| DefId {
295             krate: cnum,
296             index: index
297         })
298     }
299
300     fn native_libraries(&self, cnum: CrateNum) -> Vec<NativeLibrary>
301     {
302         self.get_crate_data(cnum).get_native_libraries(&self.dep_graph)
303     }
304
305     fn exported_symbols(&self, cnum: CrateNum) -> Vec<DefId>
306     {
307         self.get_crate_data(cnum).get_exported_symbols(&self.dep_graph)
308     }
309
310     fn is_no_builtins(&self, cnum: CrateNum) -> bool {
311         self.get_crate_data(cnum).is_no_builtins(&self.dep_graph)
312     }
313
314     fn retrace_path(&self,
315                     cnum: CrateNum,
316                     path: &[DisambiguatedDefPathData])
317                     -> Option<DefId> {
318         let cdata = self.get_crate_data(cnum);
319         cdata.def_path_table
320              .retrace_path(&path)
321              .map(|index| DefId { krate: cnum, index: index })
322     }
323
324     /// Returns the `DefKey` for a given `DefId`. This indicates the
325     /// parent `DefId` as well as some idea of what kind of data the
326     /// `DefId` refers to.
327     fn def_key(&self, def: DefId) -> DefKey {
328         // Note: loading the def-key (or def-path) for a def-id is not
329         // a *read* of its metadata. This is because the def-id is
330         // really just an interned shorthand for a def-path, which is the
331         // canonical name for an item.
332         //
333         // self.dep_graph.read(DepNode::MetaData(def));
334         self.get_crate_data(def.krate).def_key(def.index)
335     }
336
337     fn def_path(&self, def: DefId) -> DefPath {
338         // See `Note` above in `def_key()` for why this read is
339         // commented out:
340         //
341         // self.dep_graph.read(DepNode::MetaData(def));
342         self.get_crate_data(def.krate).def_path(def.index)
343     }
344
345     fn def_path_hash(&self, def: DefId) -> u64 {
346         self.get_crate_data(def.krate).def_path_hash(def.index)
347     }
348
349     fn struct_field_names(&self, def: DefId) -> Vec<ast::Name>
350     {
351         self.dep_graph.read(DepNode::MetaData(def));
352         self.get_crate_data(def.krate).get_struct_field_names(def.index)
353     }
354
355     fn item_children(&self, def_id: DefId) -> Vec<def::Export>
356     {
357         self.dep_graph.read(DepNode::MetaData(def_id));
358         let mut result = vec![];
359         self.get_crate_data(def_id.krate)
360             .each_child_of_item(def_id.index, |child| result.push(child));
361         result
362     }
363
364     fn load_macro(&self, id: DefId, sess: &Session) -> LoadedMacro {
365         let data = self.get_crate_data(id.krate);
366         if let Some(ref proc_macros) = data.proc_macros {
367             return LoadedMacro::ProcMacro(proc_macros[id.index.as_usize() - 1].1.clone());
368         }
369
370         let (name, def) = data.get_macro(id.index);
371         let source_name = format!("<{} macros>", name);
372
373         let filemap = sess.parse_sess.codemap().new_filemap(source_name, def.body);
374         let local_span = Span { lo: filemap.start_pos, hi: filemap.end_pos, ctxt: NO_EXPANSION };
375         let body = filemap_to_stream(&sess.parse_sess, filemap);
376
377         // Mark the attrs as used
378         let attrs = data.get_item_attrs(id.index, &self.dep_graph);
379         for attr in attrs.iter() {
380             attr::mark_used(attr);
381         }
382
383         let name = data.def_key(id.index).disambiguated_data.data
384             .get_opt_name().expect("no name in load_macro");
385         sess.imported_macro_spans.borrow_mut()
386             .insert(local_span, (name.to_string(), data.get_span(id.index, sess)));
387
388         LoadedMacro::MacroDef(ast::Item {
389             ident: ast::Ident::with_empty_ctxt(name),
390             id: ast::DUMMY_NODE_ID,
391             span: local_span,
392             attrs: attrs.iter().cloned().collect(),
393             node: ast::ItemKind::MacroDef(body.into()),
394             vis: ast::Visibility::Inherited,
395         })
396     }
397
398     fn item_body<'a, 'tcx>(&self,
399                            tcx: TyCtxt<'a, 'tcx, 'tcx>,
400                            def_id: DefId)
401                            -> &'tcx hir::Body {
402         if let Some(cached) = tcx.hir.get_inlined_body(def_id) {
403             return cached;
404         }
405
406         self.dep_graph.read(DepNode::MetaData(def_id));
407         debug!("item_body({}): inlining item", tcx.item_path_str(def_id));
408
409         self.get_crate_data(def_id.krate).item_body(tcx, def_id.index)
410     }
411
412     fn crates(&self) -> Vec<CrateNum>
413     {
414         let mut result = vec![];
415         self.iter_crate_data(|cnum, _| result.push(cnum));
416         result
417     }
418
419     fn used_libraries(&self) -> Vec<NativeLibrary>
420     {
421         self.get_used_libraries().borrow().clone()
422     }
423
424     fn used_link_args(&self) -> Vec<String>
425     {
426         self.get_used_link_args().borrow().clone()
427     }
428
429     fn metadata_filename(&self) -> &str
430     {
431         locator::METADATA_FILENAME
432     }
433
434     fn metadata_section_name(&self, target: &Target) -> &str
435     {
436         locator::meta_section_name(target)
437     }
438
439     fn used_crates(&self, prefer: LinkagePreference) -> Vec<(CrateNum, LibSource)>
440     {
441         self.do_get_used_crates(prefer)
442     }
443
444     fn used_crate_source(&self, cnum: CrateNum) -> CrateSource
445     {
446         self.get_crate_data(cnum).source.clone()
447     }
448
449     fn extern_mod_stmt_cnum(&self, emod_id: ast::NodeId) -> Option<CrateNum>
450     {
451         self.do_extern_mod_stmt_cnum(emod_id)
452     }
453
454     fn encode_metadata<'a, 'tcx>(&self,
455                                  tcx: TyCtxt<'a, 'tcx, 'tcx>,
456                                  link_meta: &LinkMeta,
457                                  reachable: &NodeSet)
458                                  -> EncodedMetadata
459     {
460         encoder::encode_metadata(tcx, link_meta, reachable)
461     }
462
463     fn metadata_encoding_version(&self) -> &[u8]
464     {
465         schema::METADATA_HEADER
466     }
467
468     /// Returns a map from a sufficiently visible external item (i.e. an external item that is
469     /// visible from at least one local module) to a sufficiently visible parent (considering
470     /// modules that re-export the external item to be parents).
471     fn visible_parent_map<'a>(&'a self) -> ::std::cell::Ref<'a, DefIdMap<DefId>> {
472         {
473             let visible_parent_map = self.visible_parent_map.borrow();
474             if !visible_parent_map.is_empty() {
475                 return visible_parent_map;
476             }
477         }
478
479         use std::collections::vec_deque::VecDeque;
480         use std::collections::hash_map::Entry;
481
482         let mut visible_parent_map = self.visible_parent_map.borrow_mut();
483
484         for cnum in (1 .. self.next_crate_num().as_usize()).map(CrateNum::new) {
485             let cdata = self.get_crate_data(cnum);
486
487             match cdata.extern_crate.get() {
488                 // Ignore crates without a corresponding local `extern crate` item.
489                 Some(extern_crate) if !extern_crate.direct => continue,
490                 _ => {},
491             }
492
493             let mut bfs_queue = &mut VecDeque::new();
494             let mut add_child = |bfs_queue: &mut VecDeque<_>, child: def::Export, parent: DefId| {
495                 let child = child.def.def_id();
496
497                 if self.visibility(child) != ty::Visibility::Public {
498                     return;
499                 }
500
501                 match visible_parent_map.entry(child) {
502                     Entry::Occupied(mut entry) => {
503                         // If `child` is defined in crate `cnum`, ensure
504                         // that it is mapped to a parent in `cnum`.
505                         if child.krate == cnum && entry.get().krate != cnum {
506                             entry.insert(parent);
507                         }
508                     }
509                     Entry::Vacant(entry) => {
510                         entry.insert(parent);
511                         bfs_queue.push_back(child);
512                     }
513                 }
514             };
515
516             bfs_queue.push_back(DefId {
517                 krate: cnum,
518                 index: CRATE_DEF_INDEX
519             });
520             while let Some(def) = bfs_queue.pop_front() {
521                 for child in self.item_children(def) {
522                     add_child(bfs_queue, child, def);
523                 }
524             }
525         }
526
527         drop(visible_parent_map);
528         self.visible_parent_map.borrow()
529     }
530 }