1 // The crate store - a central repo for information collected about external
2 // crates and libraries
5 use rustc::hir::def_id::{CrateNum, DefIndex};
6 use rustc::hir::map::definitions::DefPathTable;
7 use rustc::middle::cstore::{DepKind, ExternCrate, MetadataLoader};
8 use rustc::mir::interpret::AllocDecodingState;
9 use rustc_data_structures::indexed_vec::IndexVec;
10 use rustc::util::nodemap::{FxHashMap, NodeMap};
12 use rustc_data_structures::sync::{Lrc, RwLock, Lock};
14 use syntax::ext::base::SyntaxExtension;
15 use syntax::symbol::Symbol;
18 pub use rustc::middle::cstore::{NativeLibrary, NativeLibraryKind, LinkagePreference};
19 pub use rustc::middle::cstore::NativeLibraryKind::*;
20 pub use rustc::middle::cstore::{CrateSource, LibSource, ForeignModule};
22 pub use crate::cstore_impl::{provide, provide_extern};
24 // A map from external crate numbers (as decoded from some crate file) to
25 // local crate numbers (as generated during this session). Each external
26 // crate may refer to types in other external crates, and each has their
28 pub type CrateNumMap = IndexVec<CrateNum, CrateNum>;
30 pub use rustc_data_structures::sync::MetadataRef;
31 use crate::creader::Library;
33 use proc_macro::bridge::client::ProcMacro;
35 pub struct MetadataBlob(pub MetadataRef);
37 /// Holds information about a syntax_pos::SourceFile imported from another crate.
38 /// See `imported_source_files()` for more information.
39 pub struct ImportedSourceFile {
40 /// This SourceFile's byte-offset within the source_map of its original crate
41 pub original_start_pos: syntax_pos::BytePos,
42 /// The end of this SourceFile within the source_map of its original crate
43 pub original_end_pos: syntax_pos::BytePos,
44 /// The imported SourceFile's representation within the local source_map
45 pub translated_source_file: Lrc<syntax_pos::SourceFile>,
48 pub struct CrateMetadata {
49 /// Original name of the crate.
52 /// Name of the crate as imported. I.e., if imported with
53 /// `extern crate foo as bar;` this will be `bar`.
54 pub imported_name: Symbol,
56 /// Information about the extern crate that caused this crate to
57 /// be loaded. If this is `None`, then the crate was injected
58 /// (e.g., by the allocator)
59 pub extern_crate: Lock<Option<ExternCrate>>,
61 pub blob: MetadataBlob,
62 pub cnum_map: CrateNumMap,
64 pub dependencies: Lock<Vec<CrateNum>>,
65 pub source_map_import_info: RwLock<Vec<ImportedSourceFile>>,
67 /// Used for decoding interpret::AllocIds in a cached & thread-safe manner.
68 pub alloc_decoding_state: AllocDecodingState,
70 // NOTE(eddyb) we pass `'static` to a `'tcx` parameter because this
71 // lifetime is only used behind `Lazy`, and therefore acts like an
72 // universal (`for<'tcx>`), that is paired up with whichever `TyCtxt`
73 // is being used to decode those values.
74 pub root: schema::CrateRoot<'static>,
76 /// For each definition in this crate, we encode a key. When the
77 /// crate is loaded, we read all the keys and put them in this
78 /// hashmap, which gives the reverse mapping. This allows us to
79 /// quickly retrace a `DefPath`, which is needed for incremental
80 /// compilation support.
81 pub def_path_table: Lrc<DefPathTable>,
83 pub trait_impls: FxHashMap<(u32, DefIndex), schema::Lazy<[DefIndex]>>,
85 pub dep_kind: Lock<DepKind>,
86 pub source: CrateSource,
88 /// Whether or not this crate should be consider a private dependency
89 /// for purposes of the 'exported_private_dependencies' lint
90 pub private_dep: bool,
92 pub host_lib: Option<Library>,
95 pub raw_proc_macros: Option<&'static [ProcMacro]>,
99 metas: RwLock<IndexVec<CrateNum, Option<Lrc<CrateMetadata>>>>,
100 /// Map from NodeId's of local extern crate statements to crate numbers
101 extern_mod_crate_map: Lock<NodeMap<CrateNum>>,
102 pub metadata_loader: Box<dyn MetadataLoader + Sync>,
105 pub enum LoadedMacro {
107 ProcMacro(SyntaxExtension),
111 pub fn new(metadata_loader: Box<dyn MetadataLoader + Sync>) -> CStore {
113 // We add an empty entry for LOCAL_CRATE (which maps to zero) in
114 // order to make array indices in `metas` match with the
115 // corresponding `CrateNum`. This first entry will always remain
117 metas: RwLock::new(IndexVec::from_elem_n(None, 1)),
118 extern_mod_crate_map: Default::default(),
123 pub(super) fn alloc_new_crate_num(&self) -> CrateNum {
124 let mut metas = self.metas.borrow_mut();
125 let cnum = CrateNum::new(metas.len());
130 pub(super) fn get_crate_data(&self, cnum: CrateNum) -> Lrc<CrateMetadata> {
131 self.metas.borrow()[cnum].clone()
132 .unwrap_or_else(|| panic!("Failed to get crate data for {:?}", cnum))
135 pub(super) fn set_crate_data(&self, cnum: CrateNum, data: Lrc<CrateMetadata>) {
136 let mut metas = self.metas.borrow_mut();
137 assert!(metas[cnum].is_none(), "Overwriting crate metadata entry");
138 metas[cnum] = Some(data);
141 pub(super) fn iter_crate_data<I>(&self, mut i: I)
142 where I: FnMut(CrateNum, &Lrc<CrateMetadata>)
144 for (k, v) in self.metas.borrow().iter_enumerated() {
145 if let &Some(ref v) = v {
151 pub(super) fn crate_dependencies_in_rpo(&self, krate: CrateNum) -> Vec<CrateNum> {
152 let mut ordering = Vec::new();
153 self.push_dependencies_in_postorder(&mut ordering, krate);
158 pub(super) fn push_dependencies_in_postorder(&self,
159 ordering: &mut Vec<CrateNum>,
161 if ordering.contains(&krate) {
165 let data = self.get_crate_data(krate);
166 for &dep in data.dependencies.borrow().iter() {
168 self.push_dependencies_in_postorder(ordering, dep);
172 ordering.push(krate);
175 pub(super) fn do_postorder_cnums_untracked(&self) -> Vec<CrateNum> {
176 let mut ordering = Vec::new();
177 for (num, v) in self.metas.borrow().iter_enumerated() {
178 if let &Some(_) = v {
179 self.push_dependencies_in_postorder(&mut ordering, num);
185 pub(super) fn add_extern_mod_stmt_cnum(&self, emod_id: ast::NodeId, cnum: CrateNum) {
186 self.extern_mod_crate_map.borrow_mut().insert(emod_id, cnum);
189 pub(super) fn do_extern_mod_stmt_cnum(&self, emod_id: ast::NodeId) -> Option<CrateNum> {
190 self.extern_mod_crate_map.borrow().get(&emod_id).cloned()