Skip to content

Commit 5a84f9b

Browse files
authored
Rollup merge of rust-lang#66496 - petrochenkov:metapriv2, r=eddyb
rustc_metadata: Privatize more things Continuation of rust-lang#66056. The most notable change here is that `CrateMetadata` is moved from `cstore.rs` to `decoder.rs`. Most of uses of `CrateMetadata` fields are in the decoder and uses of `root: CrateRoot` and other fields are so intertwined with each other that it would be hard to move a part of them into `cstore.rs` to privatize `CrateMetadata` fields, so we are going the other way round. `cstore.rs` can probably be dismantled now, but I'll leave this to some other day. Similarly, remaining `CrateMetadata` fields can be privatized by introducing some getter/setter methods, but not today. r? @eddyb
2 parents 647eda1 + febde53 commit 5a84f9b

File tree

6 files changed

+343
-282
lines changed

6 files changed

+343
-282
lines changed

src/librustc_metadata/creader.rs

+51-81
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,17 @@
11
//! Validates all used crates and extern libraries and loads their metadata
22
3-
use crate::cstore::{self, CStore, MetadataBlob};
4-
use crate::locator::{self, CratePaths};
5-
use crate::rmeta::{CrateRoot, CrateDep};
6-
use rustc_data_structures::sync::{Lock, Once, AtomicCell};
3+
use crate::cstore::CStore;
4+
use crate::locator::{CrateLocator, CratePaths};
5+
use crate::rmeta::{CrateMetadata, CrateNumMap, CrateRoot, CrateDep, MetadataBlob};
76

87
use rustc::hir::def_id::CrateNum;
98
use rustc_data_structures::svh::Svh;
10-
use rustc::dep_graph::DepNodeIndex;
119
use rustc::middle::cstore::DepKind;
12-
use rustc::mir::interpret::AllocDecodingState;
1310
use rustc::session::{Session, CrateDisambiguator};
1411
use rustc::session::config::{Sanitizer, self};
1512
use rustc_target::spec::{PanicStrategy, TargetTriple};
1613
use rustc::session::search_paths::PathKind;
1714
use rustc::middle::cstore::{CrateSource, ExternCrate, ExternCrateSource, MetadataLoaderDyn};
18-
use rustc::util::common::record_time;
1915
use rustc::util::nodemap::FxHashSet;
2016
use rustc::hir::map::Definitions;
2117
use rustc::hir::def_id::LOCAL_CRATE;
@@ -50,9 +46,9 @@ pub struct CrateLoader<'a> {
5046

5147
fn dump_crates(cstore: &CStore) {
5248
info!("resolved crates:");
53-
cstore.iter_crate_data(|_, data| {
49+
cstore.iter_crate_data(|cnum, data| {
5450
info!(" name: {}", data.root.name);
55-
info!(" cnum: {}", data.cnum);
51+
info!(" cnum: {}", cnum);
5652
info!(" hash: {}", data.root.hash);
5753
info!(" reqd: {:?}", *data.dep_kind.lock());
5854
let CrateSource { dylib, rlib, rmeta } = data.source.clone();
@@ -68,13 +64,13 @@ enum LoadResult {
6864
}
6965

7066
enum LoadError<'a> {
71-
LocatorError(locator::Context<'a>),
67+
LocatorError(CrateLocator<'a>),
7268
}
7369

7470
impl<'a> LoadError<'a> {
7571
fn report(self) -> ! {
7672
match self {
77-
LoadError::LocatorError(locate_ctxt) => locate_ctxt.report_errs(),
73+
LoadError::LocatorError(locator) => locator.report_errs(),
7874
}
7975
}
8076
}
@@ -145,7 +141,7 @@ impl<'a> CrateLoader<'a> {
145141
let prev_kind = source.dylib.as_ref().or(source.rlib.as_ref())
146142
.or(source.rmeta.as_ref())
147143
.expect("No sources for crate").1;
148-
if ret.is_none() && (prev_kind == kind || prev_kind == PathKind::All) {
144+
if kind.matches(prev_kind) {
149145
ret = Some(cnum);
150146
}
151147
});
@@ -211,71 +207,52 @@ impl<'a> CrateLoader<'a> {
211207
let root = if let Some(root) = root {
212208
root
213209
} else {
214-
crate_paths = CratePaths { name: crate_root.name, source: source.clone() };
210+
crate_paths = CratePaths::new(crate_root.name, source.clone());
215211
&crate_paths
216212
};
217213

218214
let cnum_map = self.resolve_crate_deps(root, &crate_root, &metadata, cnum, span, dep_kind);
219215

220-
let dependencies: Vec<CrateNum> = cnum_map.iter().cloned().collect();
221-
222-
let raw_proc_macros = crate_root.proc_macro_data.map(|_| {
216+
let raw_proc_macros = if crate_root.is_proc_macro_crate() {
223217
let temp_root;
224218
let (dlsym_source, dlsym_root) = match &host_lib {
225219
Some(host_lib) =>
226220
(&host_lib.source, { temp_root = host_lib.metadata.get_root(); &temp_root }),
227221
None => (&source, &crate_root),
228222
};
229223
let dlsym_dylib = dlsym_source.dylib.as_ref().expect("no dylib for a proc-macro crate");
230-
self.dlsym_proc_macros(&dlsym_dylib.0, dlsym_root.disambiguator, span)
231-
});
232-
233-
let interpret_alloc_index: Vec<u32> = crate_root.interpret_alloc_index
234-
.decode(&metadata)
235-
.collect();
236-
let trait_impls = crate_root
237-
.impls
238-
.decode((&metadata, self.sess))
239-
.map(|trait_impls| (trait_impls.trait_id, trait_impls.impls))
240-
.collect();
241-
242-
let def_path_table = record_time(&self.sess.perf_stats.decode_def_path_tables_time, || {
243-
crate_root.def_path_table.decode((&metadata, self.sess))
244-
});
224+
Some(self.dlsym_proc_macros(&dlsym_dylib.0, dlsym_root.disambiguator, span))
225+
} else {
226+
None
227+
};
245228

246-
self.cstore.set_crate_data(cnum, cstore::CrateMetadata {
247-
extern_crate: Lock::new(None),
248-
def_path_table,
249-
trait_impls,
250-
root: crate_root,
251-
host_hash,
252-
blob: metadata,
253-
cnum_map,
229+
self.cstore.set_crate_data(cnum, CrateMetadata::new(
230+
self.sess,
231+
metadata,
232+
crate_root,
233+
raw_proc_macros,
254234
cnum,
255-
dependencies: Lock::new(dependencies),
256-
source_map_import_info: Once::new(),
257-
alloc_decoding_state: AllocDecodingState::new(interpret_alloc_index),
258-
dep_kind: Lock::new(dep_kind),
235+
cnum_map,
236+
dep_kind,
259237
source,
260238
private_dep,
261-
raw_proc_macros,
262-
dep_node_index: AtomicCell::new(DepNodeIndex::INVALID),
263-
});
239+
host_hash,
240+
));
264241

265242
cnum
266243
}
267244

268245
fn load_proc_macro<'b>(
269246
&self,
270-
locate_ctxt: &mut locator::Context<'b>,
247+
locator: &mut CrateLocator<'b>,
271248
path_kind: PathKind,
272249
) -> Option<(LoadResult, Option<Library>)>
273250
where
274251
'a: 'b,
275252
{
276-
// Use a new locator Context so trying to load a proc macro doesn't affect the error
253+
// Use a new crate locator so trying to load a proc macro doesn't affect the error
277254
// message we emit
278-
let mut proc_macro_locator = locate_ctxt.clone();
255+
let mut proc_macro_locator = locator.clone();
279256

280257
// Try to load a proc macro
281258
proc_macro_locator.is_proc_macro = Some(true);
@@ -287,10 +264,10 @@ impl<'a> CrateLoader<'a> {
287264
LoadResult::Previous(cnum) => return Some((LoadResult::Previous(cnum), None)),
288265
LoadResult::Loaded(library) => Some(LoadResult::Loaded(library))
289266
};
290-
locate_ctxt.hash = locate_ctxt.host_hash;
291-
// Use the locate_ctxt when looking for the host proc macro crate, as that is required
267+
locator.hash = locator.host_hash;
268+
// Use the locator when looking for the host proc macro crate, as that is required
292269
// so we want it to affect the error message
293-
(locate_ctxt, result)
270+
(locator, result)
294271
} else {
295272
(&mut proc_macro_locator, None)
296273
};
@@ -350,37 +327,30 @@ impl<'a> CrateLoader<'a> {
350327
(LoadResult::Previous(cnum), None)
351328
} else {
352329
info!("falling back to a load");
353-
let mut locate_ctxt = locator::Context {
354-
sess: self.sess,
355-
span,
356-
crate_name: name,
330+
let mut locator = CrateLocator::new(
331+
self.sess,
332+
self.metadata_loader,
333+
name,
357334
hash,
358335
host_hash,
359336
extra_filename,
360-
filesearch: self.sess.target_filesearch(path_kind),
361-
target: &self.sess.target.target,
362-
triple: self.sess.opts.target_triple.clone(),
337+
false, // is_host
338+
path_kind,
339+
span,
363340
root,
364-
rejected_via_hash: vec![],
365-
rejected_via_triple: vec![],
366-
rejected_via_kind: vec![],
367-
rejected_via_version: vec![],
368-
rejected_via_filename: vec![],
369-
should_match_name: true,
370-
is_proc_macro: Some(false),
371-
metadata_loader: self.metadata_loader,
372-
};
341+
Some(false), // is_proc_macro
342+
);
373343

374-
self.load(&mut locate_ctxt).map(|r| (r, None)).or_else(|| {
344+
self.load(&mut locator).map(|r| (r, None)).or_else(|| {
375345
dep_kind = DepKind::UnexportedMacrosOnly;
376-
self.load_proc_macro(&mut locate_ctxt, path_kind)
377-
}).ok_or_else(move || LoadError::LocatorError(locate_ctxt))?
346+
self.load_proc_macro(&mut locator, path_kind)
347+
}).ok_or_else(move || LoadError::LocatorError(locator))?
378348
};
379349

380350
match result {
381351
(LoadResult::Previous(cnum), None) => {
382352
let data = self.cstore.get_crate_data(cnum);
383-
if data.root.proc_macro_data.is_some() {
353+
if data.root.is_proc_macro_crate() {
384354
dep_kind = DepKind::UnexportedMacrosOnly;
385355
}
386356
data.dep_kind.with_lock(|data_dep_kind| {
@@ -395,8 +365,8 @@ impl<'a> CrateLoader<'a> {
395365
}
396366
}
397367

398-
fn load(&self, locate_ctxt: &mut locator::Context<'_>) -> Option<LoadResult> {
399-
let library = locate_ctxt.maybe_load_library_crate()?;
368+
fn load(&self, locator: &mut CrateLocator<'_>) -> Option<LoadResult> {
369+
let library = locator.maybe_load_library_crate()?;
400370

401371
// In the case that we're loading a crate, but not matching
402372
// against a hash, we could load a crate which has the same hash
@@ -407,11 +377,11 @@ impl<'a> CrateLoader<'a> {
407377
// don't want to match a host crate against an equivalent target one
408378
// already loaded.
409379
let root = library.metadata.get_root();
410-
if locate_ctxt.triple == self.sess.opts.target_triple {
380+
if locator.triple == self.sess.opts.target_triple {
411381
let mut result = LoadResult::Loaded(library);
412382
self.cstore.iter_crate_data(|cnum, data| {
413383
if data.root.name == root.name && root.hash == data.root.hash {
414-
assert!(locate_ctxt.hash.is_none());
384+
assert!(locator.hash.is_none());
415385
info!("load success, going to previous cnum: {}", cnum);
416386
result = LoadResult::Previous(cnum);
417387
}
@@ -471,16 +441,16 @@ impl<'a> CrateLoader<'a> {
471441
krate: CrateNum,
472442
span: Span,
473443
dep_kind: DepKind)
474-
-> cstore::CrateNumMap {
444+
-> CrateNumMap {
475445
debug!("resolving deps of external crate");
476-
if crate_root.proc_macro_data.is_some() {
477-
return cstore::CrateNumMap::new();
446+
if crate_root.is_proc_macro_crate() {
447+
return CrateNumMap::new();
478448
}
479449

480450
// The map from crate numbers in the crate we're resolving to local crate numbers.
481451
// We map 0 and all other holes in the map to our parent crate. The "additional"
482452
// self-dependencies should be harmless.
483-
std::iter::once(krate).chain(crate_root.crate_deps.decode(metadata).map(|dep| {
453+
std::iter::once(krate).chain(crate_root.decode_crate_deps(metadata).map(|dep| {
484454
info!("resolving dep crate {} hash: `{}` extra filename: `{}`", dep.name, dep.hash,
485455
dep.extra_filename);
486456
if dep.kind == DepKind::UnexportedMacrosOnly {
@@ -824,7 +794,7 @@ impl<'a> CrateLoader<'a> {
824794
fn inject_dependency_if(&self,
825795
krate: CrateNum,
826796
what: &str,
827-
needs_dep: &dyn Fn(&cstore::CrateMetadata) -> bool) {
797+
needs_dep: &dyn Fn(&CrateMetadata) -> bool) {
828798
// don't perform this validation if the session has errors, as one of
829799
// those errors may indicate a circular dependency which could cause
830800
// this to stack overflow.

src/librustc_metadata/cstore.rs

+7-93
Original file line numberDiff line numberDiff line change
@@ -1,109 +1,23 @@
11
// The crate store - a central repo for information collected about external
22
// crates and libraries
33

4-
use crate::rmeta;
5-
use rustc::dep_graph::DepNodeIndex;
6-
use rustc::hir::def_id::{CrateNum, DefIndex};
7-
use rustc::hir::map::definitions::DefPathTable;
8-
use rustc::middle::cstore::{CrateSource, DepKind, ExternCrate};
9-
use rustc::mir::interpret::AllocDecodingState;
4+
use crate::rmeta::CrateMetadata;
5+
6+
use rustc_data_structures::sync::Lrc;
107
use rustc_index::vec::IndexVec;
11-
use rustc::util::nodemap::FxHashMap;
12-
use rustc_data_structures::sync::{Lrc, Lock, MetadataRef, Once, AtomicCell};
13-
use rustc_data_structures::svh::Svh;
8+
use rustc::hir::def_id::CrateNum;
149
use syntax::ast;
1510
use syntax::edition::Edition;
16-
use syntax_expand::base::SyntaxExtension;
1711
use syntax::expand::allocator::AllocatorKind;
18-
use syntax_pos;
19-
use proc_macro::bridge::client::ProcMacro;
12+
use syntax_expand::base::SyntaxExtension;
2013

2114
pub use crate::rmeta::{provide, provide_extern};
2215

23-
// A map from external crate numbers (as decoded from some crate file) to
24-
// local crate numbers (as generated during this session). Each external
25-
// crate may refer to types in other external crates, and each has their
26-
// own crate numbers.
27-
crate type CrateNumMap = IndexVec<CrateNum, CrateNum>;
28-
29-
crate struct MetadataBlob(pub MetadataRef);
30-
31-
/// Holds information about a syntax_pos::SourceFile imported from another crate.
32-
/// See `imported_source_files()` for more information.
33-
crate struct ImportedSourceFile {
34-
/// This SourceFile's byte-offset within the source_map of its original crate
35-
pub original_start_pos: syntax_pos::BytePos,
36-
/// The end of this SourceFile within the source_map of its original crate
37-
pub original_end_pos: syntax_pos::BytePos,
38-
/// The imported SourceFile's representation within the local source_map
39-
pub translated_source_file: Lrc<syntax_pos::SourceFile>,
40-
}
41-
42-
crate struct CrateMetadata {
43-
/// The primary crate data - binary metadata blob.
44-
crate blob: MetadataBlob,
45-
46-
// --- Some data pre-decoded from the metadata blob, usually for performance ---
47-
48-
/// Properties of the whole crate.
49-
/// NOTE(eddyb) we pass `'static` to a `'tcx` parameter because this
50-
/// lifetime is only used behind `Lazy`, and therefore acts like an
51-
/// universal (`for<'tcx>`), that is paired up with whichever `TyCtxt`
52-
/// is being used to decode those values.
53-
crate root: rmeta::CrateRoot<'static>,
54-
/// For each definition in this crate, we encode a key. When the
55-
/// crate is loaded, we read all the keys and put them in this
56-
/// hashmap, which gives the reverse mapping. This allows us to
57-
/// quickly retrace a `DefPath`, which is needed for incremental
58-
/// compilation support.
59-
crate def_path_table: DefPathTable,
60-
/// Trait impl data.
61-
/// FIXME: Used only from queries and can use query cache,
62-
/// so pre-decoding can probably be avoided.
63-
crate trait_impls: FxHashMap<(u32, DefIndex), rmeta::Lazy<[DefIndex]>>,
64-
/// Proc macro descriptions for this crate, if it's a proc macro crate.
65-
crate raw_proc_macros: Option<&'static [ProcMacro]>,
66-
/// Source maps for code from the crate.
67-
crate source_map_import_info: Once<Vec<ImportedSourceFile>>,
68-
/// Used for decoding interpret::AllocIds in a cached & thread-safe manner.
69-
crate alloc_decoding_state: AllocDecodingState,
70-
/// The `DepNodeIndex` of the `DepNode` representing this upstream crate.
71-
/// It is initialized on the first access in `get_crate_dep_node_index()`.
72-
/// Do not access the value directly, as it might not have been initialized yet.
73-
/// The field must always be initialized to `DepNodeIndex::INVALID`.
74-
crate dep_node_index: AtomicCell<DepNodeIndex>,
75-
76-
// --- Other significant crate properties ---
77-
78-
/// ID of this crate, from the current compilation session's point of view.
79-
crate cnum: CrateNum,
80-
/// Maps crate IDs as they are were seen from this crate's compilation sessions into
81-
/// IDs as they are seen from the current compilation session.
82-
crate cnum_map: CrateNumMap,
83-
/// Same ID set as `cnum_map` plus maybe some injected crates like panic runtime.
84-
crate dependencies: Lock<Vec<CrateNum>>,
85-
/// How to link (or not link) this crate to the currently compiled crate.
86-
crate dep_kind: Lock<DepKind>,
87-
/// Filesystem location of this crate.
88-
crate source: CrateSource,
89-
/// Whether or not this crate should be consider a private dependency
90-
/// for purposes of the 'exported_private_dependencies' lint
91-
crate private_dep: bool,
92-
/// The hash for the host proc macro. Used to support `-Z dual-proc-macro`.
93-
crate host_hash: Option<Svh>,
94-
95-
// --- Data used only for improving diagnostics ---
96-
97-
/// Information about the `extern crate` item or path that caused this crate to be loaded.
98-
/// If this is `None`, then the crate was injected (e.g., by the allocator).
99-
crate extern_crate: Lock<Option<ExternCrate>>,
100-
}
101-
10216
#[derive(Clone)]
10317
pub struct CStore {
10418
metas: IndexVec<CrateNum, Option<Lrc<CrateMetadata>>>,
105-
pub(crate) injected_panic_runtime: Option<CrateNum>,
106-
pub(crate) allocator_kind: Option<AllocatorKind>,
19+
crate injected_panic_runtime: Option<CrateNum>,
20+
crate allocator_kind: Option<AllocatorKind>,
10721
}
10822

10923
pub enum LoadedMacro {

0 commit comments

Comments
 (0)