Skip to content

Commit f764eaf

Browse files
committed
Auto merge of #45476 - Xanewok:fingerprint-disambiguator, r=michaelwoerister
Use 128 bit instead of Symbol for crate disambiguator As discussed on gitter, this changes `crate_disambiguator` from Strings to what they are represented as, a 128 bit number. There's also one bit I think also needs to change, but wasn't 100% sure how: [create_root_def](https://github.com/rust-lang/rust/blob/f338dba29705e144bad8b2a675284538dd514896/src/librustc/hir/map/definitions.rs#L468-L482). Should I change `DefKey::root_parent_stable_hash` to accept `Fingerprint` as crate_disambiguator to quickly combine the hash of `crate_name` with the new 128 bit hash instead of a string for a disambiguator? r? @michaelwoerister EDIT: Are those 3 tests `mir-opt` failing, because the hash is different, because we calculate it a little bit differently (storing directly instead of hashing the hex-string representation)? Should it be updated like in #45319?
2 parents b247805 + 7fa64bc commit f764eaf

File tree

22 files changed

+94
-65
lines changed

22 files changed

+94
-65
lines changed

src/librustc/hir/map/collector.rs

+3-2
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ use super::*;
1212

1313
use dep_graph::{DepGraph, DepKind, DepNodeIndex};
1414
use hir::intravisit::{Visitor, NestedVisitorMap};
15+
use session::CrateDisambiguator;
1516
use std::iter::repeat;
1617
use syntax::ast::{NodeId, CRATE_NODE_ID};
1718
use syntax_pos::Span;
@@ -118,7 +119,7 @@ impl<'a, 'hir> NodeCollector<'a, 'hir> {
118119
}
119120

120121
pub(super) fn finalize_and_compute_crate_hash(self,
121-
crate_disambiguator: &str)
122+
crate_disambiguator: CrateDisambiguator)
122123
-> Vec<MapEntry<'hir>> {
123124
let mut node_hashes: Vec<_> = self
124125
.hir_body_nodes
@@ -133,7 +134,7 @@ impl<'a, 'hir> NodeCollector<'a, 'hir> {
133134

134135
self.dep_graph.with_task(DepNode::new_no_params(DepKind::Krate),
135136
&self.hcx,
136-
(node_hashes, crate_disambiguator),
137+
(node_hashes, crate_disambiguator.to_fingerprint()),
137138
identity_fn);
138139
self.map
139140
}

src/librustc/hir/map/def_collector.rs

+4-1
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010

1111
use hir::map::definitions::*;
1212
use hir::def_id::{CRATE_DEF_INDEX, DefIndex, DefIndexAddressSpace};
13+
use session::CrateDisambiguator;
1314

1415
use syntax::ast::*;
1516
use syntax::ext::hygiene::Mark;
@@ -43,7 +44,9 @@ impl<'a> DefCollector<'a> {
4344
}
4445
}
4546

46-
pub fn collect_root(&mut self, crate_name: &str, crate_disambiguator: &str) {
47+
pub fn collect_root(&mut self,
48+
crate_name: &str,
49+
crate_disambiguator: CrateDisambiguator) {
4750
let root = self.definitions.create_root_def(crate_name,
4851
crate_disambiguator);
4952
assert_eq!(root, CRATE_DEF_INDEX);

src/librustc/hir/map/definitions.rs

+5-2
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ use rustc_data_structures::fx::FxHashMap;
2222
use rustc_data_structures::indexed_vec::IndexVec;
2323
use rustc_data_structures::stable_hasher::StableHasher;
2424
use serialize::{Encodable, Decodable, Encoder, Decoder};
25+
use session::CrateDisambiguator;
2526
use std::fmt::Write;
2627
use std::hash::Hash;
2728
use syntax::ast;
@@ -231,7 +232,9 @@ impl DefKey {
231232
DefPathHash(hasher.finish())
232233
}
233234

234-
fn root_parent_stable_hash(crate_name: &str, crate_disambiguator: &str) -> DefPathHash {
235+
fn root_parent_stable_hash(crate_name: &str,
236+
crate_disambiguator: CrateDisambiguator)
237+
-> DefPathHash {
235238
let mut hasher = StableHasher::new();
236239
// Disambiguate this from a regular DefPath hash,
237240
// see compute_stable_hash() above.
@@ -467,7 +470,7 @@ impl Definitions {
467470
/// Add a definition with a parent definition.
468471
pub fn create_root_def(&mut self,
469472
crate_name: &str,
470-
crate_disambiguator: &str)
473+
crate_disambiguator: CrateDisambiguator)
471474
-> DefIndex {
472475
let key = DefKey {
473476
parent: None,

src/librustc/hir/map/mod.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -1014,8 +1014,8 @@ pub fn map_crate<'hir>(sess: &::session::Session,
10141014
hcx);
10151015
intravisit::walk_crate(&mut collector, &forest.krate);
10161016

1017-
let crate_disambiguator = sess.local_crate_disambiguator().as_str();
1018-
collector.finalize_and_compute_crate_hash(&crate_disambiguator)
1017+
let crate_disambiguator = sess.local_crate_disambiguator();
1018+
collector.finalize_and_compute_crate_hash(crate_disambiguator)
10191019
};
10201020

10211021
if log_enabled!(::log::LogLevel::Debug) {

src/librustc/middle/cstore.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ use hir::map::definitions::{Definitions, DefKey, DefPathTable};
3030
use hir::svh::Svh;
3131
use ich;
3232
use ty::{self, TyCtxt};
33-
use session::Session;
33+
use session::{Session, CrateDisambiguator};
3434
use session::search_paths::PathKind;
3535
use util::nodemap::NodeSet;
3636

@@ -267,7 +267,7 @@ pub trait CrateStore {
267267
fn export_macros_untracked(&self, cnum: CrateNum);
268268
fn dep_kind_untracked(&self, cnum: CrateNum) -> DepKind;
269269
fn crate_name_untracked(&self, cnum: CrateNum) -> Symbol;
270-
fn crate_disambiguator_untracked(&self, cnum: CrateNum) -> Symbol;
270+
fn crate_disambiguator_untracked(&self, cnum: CrateNum) -> CrateDisambiguator;
271271
fn crate_hash_untracked(&self, cnum: CrateNum) -> Svh;
272272
fn struct_field_names_untracked(&self, def: DefId) -> Vec<ast::Name>;
273273
fn item_children_untracked(&self, did: DefId, sess: &Session) -> Vec<def::Export>;
@@ -338,7 +338,7 @@ impl CrateStore for DummyCrateStore {
338338
fn dep_kind_untracked(&self, cnum: CrateNum) -> DepKind { bug!("is_explicitly_linked") }
339339
fn export_macros_untracked(&self, cnum: CrateNum) { bug!("export_macros") }
340340
fn crate_name_untracked(&self, cnum: CrateNum) -> Symbol { bug!("crate_name") }
341-
fn crate_disambiguator_untracked(&self, cnum: CrateNum) -> Symbol {
341+
fn crate_disambiguator_untracked(&self, cnum: CrateNum) -> CrateDisambiguator {
342342
bug!("crate_disambiguator")
343343
}
344344
fn crate_hash_untracked(&self, cnum: CrateNum) -> Svh { bug!("crate_hash") }

src/librustc/session/mod.rs

+33-9
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ pub use self::code_stats::{CodeStats, DataTypeKind, FieldInfo};
1212
pub use self::code_stats::{SizeKind, TypeSizeInfo, VariantInfo};
1313

1414
use hir::def_id::{CrateNum, DefIndex};
15+
use ich::Fingerprint;
1516

1617
use lint;
1718
use middle::allocator::AllocatorKind;
@@ -29,7 +30,6 @@ use syntax::json::JsonEmitter;
2930
use syntax::feature_gate;
3031
use syntax::parse;
3132
use syntax::parse::ParseSess;
32-
use syntax::symbol::Symbol;
3333
use syntax::{ast, codemap};
3434
use syntax::feature_gate::AttributeType;
3535
use syntax_pos::{Span, MultiSpan};
@@ -83,12 +83,12 @@ pub struct Session {
8383
pub plugin_attributes: RefCell<Vec<(String, AttributeType)>>,
8484
pub crate_types: RefCell<Vec<config::CrateType>>,
8585
pub dependency_formats: RefCell<dependency_format::Dependencies>,
86-
/// The crate_disambiguator is constructed out of all the `-C metadata`
86+
/// The crate_disambiguator is constructed out of all the `-C metadata`
8787
/// arguments passed to the compiler. Its value together with the crate-name
8888
/// forms a unique global identifier for the crate. It is used to allow
8989
/// multiple crates with the same name to coexist. See the
9090
/// trans::back::symbol_names module for more information.
91-
pub crate_disambiguator: RefCell<Option<Symbol>>,
91+
pub crate_disambiguator: RefCell<Option<CrateDisambiguator>>,
9292
pub features: RefCell<feature_gate::Features>,
9393

9494
/// The maximum recursion limit for potentially infinitely recursive
@@ -165,9 +165,9 @@ enum DiagnosticBuilderMethod {
165165
}
166166

167167
impl Session {
168-
pub fn local_crate_disambiguator(&self) -> Symbol {
168+
pub fn local_crate_disambiguator(&self) -> CrateDisambiguator {
169169
match *self.crate_disambiguator.borrow() {
170-
Some(sym) => sym,
170+
Some(value) => value,
171171
None => bug!("accessing disambiguator before initialization"),
172172
}
173173
}
@@ -471,14 +471,18 @@ impl Session {
471471

472472
/// Returns the symbol name for the registrar function,
473473
/// given the crate Svh and the function DefIndex.
474-
pub fn generate_plugin_registrar_symbol(&self, disambiguator: Symbol, index: DefIndex)
474+
pub fn generate_plugin_registrar_symbol(&self, disambiguator: CrateDisambiguator,
475+
index: DefIndex)
475476
-> String {
476-
format!("__rustc_plugin_registrar__{}_{}", disambiguator, index.as_usize())
477+
format!("__rustc_plugin_registrar__{}_{}", disambiguator.to_fingerprint().to_hex(),
478+
index.as_usize())
477479
}
478480

479-
pub fn generate_derive_registrar_symbol(&self, disambiguator: Symbol, index: DefIndex)
481+
pub fn generate_derive_registrar_symbol(&self, disambiguator: CrateDisambiguator,
482+
index: DefIndex)
480483
-> String {
481-
format!("__rustc_derive_registrar__{}_{}", disambiguator, index.as_usize())
484+
format!("__rustc_derive_registrar__{}_{}", disambiguator.to_fingerprint().to_hex(),
485+
index.as_usize())
482486
}
483487

484488
pub fn sysroot<'a>(&'a self) -> &'a Path {
@@ -838,6 +842,26 @@ pub fn build_session_(sopts: config::Options,
838842
sess
839843
}
840844

845+
/// Hash value constructed out of all the `-C metadata` arguments passed to the
846+
/// compiler. Together with the crate-name forms a unique global identifier for
847+
/// the crate.
848+
#[derive(Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Clone, Copy, RustcEncodable, RustcDecodable)]
849+
pub struct CrateDisambiguator(Fingerprint);
850+
851+
impl CrateDisambiguator {
852+
pub fn to_fingerprint(self) -> Fingerprint {
853+
self.0
854+
}
855+
}
856+
857+
impl From<Fingerprint> for CrateDisambiguator {
858+
fn from(fingerprint: Fingerprint) -> CrateDisambiguator {
859+
CrateDisambiguator(fingerprint)
860+
}
861+
}
862+
863+
impl_stable_hash_for!(tuple_struct CrateDisambiguator { fingerprint });
864+
841865
/// Holds data on the current incremental compilation session, if there is one.
842866
#[derive(Debug)]
843867
pub enum IncrCompSession {

src/librustc/ty/context.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -1249,7 +1249,7 @@ impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
12491249
crate_name,
12501250
// Don't print the whole crate disambiguator. That's just
12511251
// annoying in debug output.
1252-
&(crate_disambiguator.as_str())[..4],
1252+
&(crate_disambiguator.to_fingerprint().to_hex())[..4],
12531253
self.def_path(def_id).to_string_no_crate())
12541254
}
12551255

src/librustc/ty/maps/mod.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ use middle::lang_items::{LanguageItems, LangItem};
2929
use middle::exported_symbols::SymbolExportLevel;
3030
use middle::trans::{CodegenUnit, Stats};
3131
use mir;
32-
use session::CompileResult;
32+
use session::{CompileResult, CrateDisambiguator};
3333
use session::config::OutputFilenames;
3434
use traits::Vtable;
3535
use traits::specialization_graph;
@@ -285,7 +285,7 @@ define_maps! { <'tcx>
285285
[] fn native_libraries: NativeLibraries(CrateNum) -> Rc<Vec<NativeLibrary>>,
286286
[] fn plugin_registrar_fn: PluginRegistrarFn(CrateNum) -> Option<DefId>,
287287
[] fn derive_registrar_fn: DeriveRegistrarFn(CrateNum) -> Option<DefId>,
288-
[] fn crate_disambiguator: CrateDisambiguator(CrateNum) -> Symbol,
288+
[] fn crate_disambiguator: CrateDisambiguator(CrateNum) -> CrateDisambiguator,
289289
[] fn crate_hash: CrateHash(CrateNum) -> Svh,
290290
[] fn original_crate_name: OriginalCrateName(CrateNum) -> Symbol,
291291

src/librustc/ty/mod.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ use middle::privacy::AccessLevels;
2626
use middle::resolve_lifetime::ObjectLifetimeDefault;
2727
use mir::Mir;
2828
use mir::GeneratorLayout;
29+
use session::CrateDisambiguator;
2930
use traits;
3031
use ty;
3132
use ty::subst::{Subst, Substs};
@@ -2556,7 +2557,7 @@ fn param_env<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
25562557
}
25572558

25582559
fn crate_disambiguator<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
2559-
crate_num: CrateNum) -> Symbol {
2560+
crate_num: CrateNum) -> CrateDisambiguator {
25602561
assert_eq!(crate_num, LOCAL_CRATE);
25612562
tcx.sess.local_crate_disambiguator()
25622563
}

src/librustc_driver/driver.rs

+9-11
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ use rustc::hir::lowering::lower_crate;
1414
use rustc::ich::Fingerprint;
1515
use rustc_data_structures::stable_hasher::StableHasher;
1616
use rustc_mir as mir;
17-
use rustc::session::{Session, CompileResult};
17+
use rustc::session::{Session, CompileResult, CrateDisambiguator};
1818
use rustc::session::CompileIncomplete;
1919
use rustc::session::config::{self, Input, OutputFilenames, OutputType};
2020
use rustc::session::search_paths::PathKind;
@@ -58,7 +58,6 @@ use syntax::{ast, diagnostics, visit};
5858
use syntax::attr;
5959
use syntax::ext::base::ExtCtxt;
6060
use syntax::parse::{self, PResult};
61-
use syntax::symbol::Symbol;
6261
use syntax::util::node_count::NodeCounter;
6362
use syntax;
6463
use syntax_ext;
@@ -633,12 +632,12 @@ pub fn phase_2_configure_and_expand<F>(sess: &Session,
633632

634633
*sess.crate_types.borrow_mut() = collect_crate_types(sess, &krate.attrs);
635634

636-
let disambiguator = Symbol::intern(&compute_crate_disambiguator(sess));
635+
let disambiguator = compute_crate_disambiguator(sess);
637636
*sess.crate_disambiguator.borrow_mut() = Some(disambiguator);
638637
rustc_incremental::prepare_session_directory(
639638
sess,
640639
&crate_name,
641-
&disambiguator.as_str(),
640+
disambiguator,
642641
);
643642

644643
let dep_graph = if sess.opts.build_dep_graph() {
@@ -1312,16 +1311,13 @@ pub fn collect_crate_types(session: &Session, attrs: &[ast::Attribute]) -> Vec<c
13121311
.collect()
13131312
}
13141313

1315-
pub fn compute_crate_disambiguator(session: &Session) -> String {
1314+
pub fn compute_crate_disambiguator(session: &Session) -> CrateDisambiguator {
13161315
use std::hash::Hasher;
13171316

13181317
// The crate_disambiguator is a 128 bit hash. The disambiguator is fed
13191318
// into various other hashes quite a bit (symbol hashes, incr. comp. hashes,
13201319
// debuginfo type IDs, etc), so we don't want it to be too wide. 128 bits
13211320
// should still be safe enough to avoid collisions in practice.
1322-
// FIXME(mw): It seems that the crate_disambiguator is used everywhere as
1323-
// a hex-string instead of raw bytes. We should really use the
1324-
// smaller representation.
13251321
let mut hasher = StableHasher::<Fingerprint>::new();
13261322

13271323
let mut metadata = session.opts.cg.metadata.clone();
@@ -1340,11 +1336,13 @@ pub fn compute_crate_disambiguator(session: &Session) -> String {
13401336
hasher.write(s.as_bytes());
13411337
}
13421338

1343-
// If this is an executable, add a special suffix, so that we don't get
1344-
// symbol conflicts when linking against a library of the same name.
1339+
// Also incorporate crate type, so that we don't get symbol conflicts when
1340+
// linking against a library of the same name, if this is an executable.
13451341
let is_exe = session.crate_types.borrow().contains(&config::CrateTypeExecutable);
1342+
hasher.write(if is_exe { b"exe" } else { b"lib" });
1343+
1344+
CrateDisambiguator::from(hasher.finish())
13461345

1347-
format!("{}{}", hasher.finish().to_hex(), if is_exe { "-exe" } else {""})
13481346
}
13491347

13501348
pub fn build_output_filenames(input: &Input,

src/librustc_incremental/persist/fs.rs

+7-11
Original file line numberDiff line numberDiff line change
@@ -115,7 +115,7 @@
115115
//! implemented.
116116
117117
use rustc::hir::svh::Svh;
118-
use rustc::session::Session;
118+
use rustc::session::{Session, CrateDisambiguator};
119119
use rustc::util::fs as fs_util;
120120
use rustc_data_structures::{flock, base_n};
121121
use rustc_data_structures::fx::{FxHashSet, FxHashMap};
@@ -188,7 +188,7 @@ pub fn in_incr_comp_dir(incr_comp_session_dir: &Path, file_name: &str) -> PathBu
188188
/// The garbage collection will take care of it.
189189
pub fn prepare_session_directory(sess: &Session,
190190
crate_name: &str,
191-
crate_disambiguator: &str) {
191+
crate_disambiguator: CrateDisambiguator) {
192192
if sess.opts.incremental.is_none() {
193193
return
194194
}
@@ -614,21 +614,17 @@ fn string_to_timestamp(s: &str) -> Result<SystemTime, ()> {
614614

615615
fn crate_path(sess: &Session,
616616
crate_name: &str,
617-
crate_disambiguator: &str)
617+
crate_disambiguator: CrateDisambiguator)
618618
-> PathBuf {
619-
use std::hash::{Hasher, Hash};
620-
use std::collections::hash_map::DefaultHasher;
621619

622620
let incr_dir = sess.opts.incremental.as_ref().unwrap().clone();
623621

624-
// The full crate disambiguator is really long. A hash of it should be
622+
// The full crate disambiguator is really long. 64 bits of it should be
625623
// sufficient.
626-
let mut hasher = DefaultHasher::new();
627-
crate_disambiguator.hash(&mut hasher);
624+
let crate_disambiguator = crate_disambiguator.to_fingerprint().to_smaller_hash();
625+
let crate_disambiguator = base_n::encode(crate_disambiguator, INT_ENCODE_BASE);
628626

629-
let crate_name = format!("{}-{}",
630-
crate_name,
631-
base_n::encode(hasher.finish(), INT_ENCODE_BASE));
627+
let crate_name = format!("{}-{}", crate_name, crate_disambiguator);
632628
incr_dir.join(crate_name)
633629
}
634630

src/librustc_metadata/creader.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ use rustc::hir::def_id::{CrateNum, DefIndex, CRATE_DEF_INDEX};
1919
use rustc::hir::svh::Svh;
2020
use rustc::middle::allocator::AllocatorKind;
2121
use rustc::middle::cstore::DepKind;
22-
use rustc::session::Session;
22+
use rustc::session::{Session, CrateDisambiguator};
2323
use rustc::session::config::{Sanitizer, self};
2424
use rustc_back::PanicStrategy;
2525
use rustc::session::search_paths::PathKind;
@@ -626,7 +626,7 @@ impl<'a> CrateLoader<'a> {
626626
pub fn find_plugin_registrar(&mut self,
627627
span: Span,
628628
name: &str)
629-
-> Option<(PathBuf, Symbol, DefIndex)> {
629+
-> Option<(PathBuf, CrateDisambiguator, DefIndex)> {
630630
let ekrate = self.read_extension_crate(span, &ExternCrateInfo {
631631
name: Symbol::intern(name),
632632
ident: Symbol::intern(name),

src/librustc_metadata/cstore.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ use rustc::hir::def_id::{CRATE_DEF_INDEX, CrateNum, DefIndex};
1717
use rustc::hir::map::definitions::DefPathTable;
1818
use rustc::hir::svh::Svh;
1919
use rustc::middle::cstore::{DepKind, ExternCrate, MetadataLoader};
20+
use rustc::session::CrateDisambiguator;
2021
use rustc_back::PanicStrategy;
2122
use rustc_data_structures::indexed_vec::IndexVec;
2223
use rustc::util::nodemap::{FxHashMap, FxHashSet, NodeMap};
@@ -171,7 +172,7 @@ impl CrateMetadata {
171172
pub fn hash(&self) -> Svh {
172173
self.root.hash
173174
}
174-
pub fn disambiguator(&self) -> Symbol {
175+
pub fn disambiguator(&self) -> CrateDisambiguator {
175176
self.root.disambiguator
176177
}
177178

0 commit comments

Comments
 (0)