Skip to content

Commit 80926fc

Browse files
committed
Auto merge of #86368 - michaelwoerister:lexing-ice, r=davidtwco
Disambiguate between SourceFiles from different crates even if they have the same path This PR fixes an ICE that can occur when the compiler encounters a source file that is part of both the local crate and an upstream crate: 1. While importing source files from an upstream crate the compiler creates a `SourceFile` entry for `foo.rs` in the `SourceMap`. Since this is an imported source file its `src` field is `None`. 2. At a later point the parser encounters `foo.rs` again. It tells the `SourceMap` to load the file but because we already have an entry for `foo.rs` the `SourceMap` will return the existing version with `src == None`. 3. The parser proceeds under the assumption that `src.is_some()` and panics when actually trying to use the file's contents. This PR fixes the issue by adding the source file's associated `CrateNum` to the `SourceMap`'s interning key. As a consequence the two instances of the file will each have a separate entry in the `SourceMap`. They just happen to share the same file path. This approach seemed less problematic to me than trying to mutate the `SourceFile` after it had already been created. Another, more involved, approach might be to merge the `src` and the `external_src` field. Fixes #85955
2 parents 3487be1 + c3c4ab5 commit 80926fc

File tree

4 files changed

+89
-15
lines changed

4 files changed

+89
-15
lines changed

compiler/rustc_middle/src/ty/query/on_disk_cache.rs

+33-5
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ pub struct OnDiskCache<'sess> {
5454
cnum_map: OnceCell<UnhashMap<StableCrateId, CrateNum>>,
5555

5656
source_map: &'sess SourceMap,
57-
file_index_to_stable_id: FxHashMap<SourceFileIndex, StableSourceFileId>,
57+
file_index_to_stable_id: FxHashMap<SourceFileIndex, EncodedSourceFileId>,
5858

5959
// Caches that are populated lazily during decoding.
6060
file_index_to_file: Lock<FxHashMap<SourceFileIndex, Lrc<SourceFile>>>,
@@ -111,7 +111,7 @@ pub struct OnDiskCache<'sess> {
111111
// This type is used only for serialization and deserialization.
112112
#[derive(Encodable, Decodable)]
113113
struct Footer {
114-
file_index_to_stable_id: FxHashMap<SourceFileIndex, StableSourceFileId>,
114+
file_index_to_stable_id: FxHashMap<SourceFileIndex, EncodedSourceFileId>,
115115
query_result_index: EncodedQueryResultIndex,
116116
diagnostics_index: EncodedQueryResultIndex,
117117
// The location of all allocations.
@@ -157,6 +157,32 @@ crate struct RawDefId {
157157
pub index: u32,
158158
}
159159

160+
/// An `EncodedSourceFileId` is the same as a `StableSourceFileId` except that
161+
/// the source crate is represented as a [StableCrateId] instead of as a
162+
/// `CrateNum`. This way `EncodedSourceFileId` can be encoded and decoded
163+
/// without any additional context, i.e. with a simple `opaque::Decoder` (which
164+
/// is the only thing available when decoding the cache's [Footer].
165+
#[derive(Encodable, Decodable, Clone, Debug)]
166+
struct EncodedSourceFileId {
167+
file_name_hash: u64,
168+
stable_crate_id: StableCrateId,
169+
}
170+
171+
impl EncodedSourceFileId {
172+
fn translate(&self, cnum_map: &UnhashMap<StableCrateId, CrateNum>) -> StableSourceFileId {
173+
let cnum = cnum_map[&self.stable_crate_id];
174+
StableSourceFileId { file_name_hash: self.file_name_hash, cnum }
175+
}
176+
177+
fn new(tcx: TyCtxt<'_>, file: &SourceFile) -> EncodedSourceFileId {
178+
let source_file_id = StableSourceFileId::new(file);
179+
EncodedSourceFileId {
180+
file_name_hash: source_file_id.file_name_hash,
181+
stable_crate_id: tcx.stable_crate_id(source_file_id.cnum),
182+
}
183+
}
184+
}
185+
160186
impl<'sess> OnDiskCache<'sess> {
161187
/// Creates a new `OnDiskCache` instance from the serialized data in `data`.
162188
pub fn new(sess: &'sess Session, data: Vec<u8>, start_pos: usize) -> Self {
@@ -238,7 +264,8 @@ impl<'sess> OnDiskCache<'sess> {
238264
let index = SourceFileIndex(index as u32);
239265
let file_ptr: *const SourceFile = &**file as *const _;
240266
file_to_file_index.insert(file_ptr, index);
241-
file_index_to_stable_id.insert(index, StableSourceFileId::new(&file));
267+
let source_file_id = EncodedSourceFileId::new(tcx, &file);
268+
file_index_to_stable_id.insert(index, source_file_id);
242269
}
243270

244271
(file_to_file_index, file_index_to_stable_id)
@@ -605,7 +632,7 @@ pub struct CacheDecoder<'a, 'tcx> {
605632
source_map: &'a SourceMap,
606633
cnum_map: &'a UnhashMap<StableCrateId, CrateNum>,
607634
file_index_to_file: &'a Lock<FxHashMap<SourceFileIndex, Lrc<SourceFile>>>,
608-
file_index_to_stable_id: &'a FxHashMap<SourceFileIndex, StableSourceFileId>,
635+
file_index_to_stable_id: &'a FxHashMap<SourceFileIndex, EncodedSourceFileId>,
609636
alloc_decoding_session: AllocDecodingSession<'a>,
610637
syntax_contexts: &'a FxHashMap<u32, AbsoluteBytePos>,
611638
expn_data: &'a FxHashMap<u32, AbsoluteBytePos>,
@@ -618,14 +645,15 @@ impl<'a, 'tcx> CacheDecoder<'a, 'tcx> {
618645
ref file_index_to_file,
619646
ref file_index_to_stable_id,
620647
ref source_map,
648+
ref cnum_map,
621649
..
622650
} = *self;
623651

624652
file_index_to_file
625653
.borrow_mut()
626654
.entry(index)
627655
.or_insert_with(|| {
628-
let stable_id = file_index_to_stable_id[&index];
656+
let stable_id = file_index_to_stable_id[&index].translate(cnum_map);
629657
source_map
630658
.source_file_by_stable_id(stable_id)
631659
.expect("failed to lookup `SourceFile` in new context")

compiler/rustc_span/src/source_map.rs

+31-10
Original file line numberDiff line numberDiff line change
@@ -117,25 +117,42 @@ impl FileLoader for RealFileLoader {
117117
}
118118
}
119119

120-
// This is a `SourceFile` identifier that is used to correlate `SourceFile`s between
121-
// subsequent compilation sessions (which is something we need to do during
122-
// incremental compilation).
120+
/// This is a [SourceFile] identifier that is used to correlate source files between
121+
/// subsequent compilation sessions (which is something we need to do during
122+
/// incremental compilation).
123+
///
124+
/// The [StableSourceFileId] also contains the CrateNum of the crate the source
125+
/// file was originally parsed for. This way we get two separate entries in
126+
/// the [SourceMap] if the same file is part of both the local and an upstream
127+
/// crate. Trying to only have one entry for both cases is problematic because
128+
/// at the point where we discover that there's a local use of the file in
129+
/// addition to the upstream one, we might already have made decisions based on
130+
/// the assumption that it's an upstream file. Treating the two files as
131+
/// different has no real downsides.
123132
#[derive(Copy, Clone, PartialEq, Eq, Hash, Encodable, Decodable, Debug)]
124-
pub struct StableSourceFileId(u128);
133+
pub struct StableSourceFileId {
134+
// A hash of the source file's FileName. This is hash so that it's size
135+
// is more predictable than if we included the actual FileName value.
136+
pub file_name_hash: u64,
137+
138+
// The CrateNum of the crate this source file was originally parsed for.
139+
// We cannot include this information in the hash because at the time
140+
// of hashing we don't have the context to map from the CrateNum's numeric
141+
// value to a StableCrateId.
142+
pub cnum: CrateNum,
143+
}
125144

126145
// FIXME: we need a more globally consistent approach to the problem solved by
127146
// StableSourceFileId, perhaps built atop source_file.name_hash.
128147
impl StableSourceFileId {
129148
pub fn new(source_file: &SourceFile) -> StableSourceFileId {
130-
StableSourceFileId::new_from_name(&source_file.name)
149+
StableSourceFileId::new_from_name(&source_file.name, source_file.cnum)
131150
}
132151

133-
fn new_from_name(name: &FileName) -> StableSourceFileId {
152+
fn new_from_name(name: &FileName, cnum: CrateNum) -> StableSourceFileId {
134153
let mut hasher = StableHasher::new();
135-
136154
name.hash(&mut hasher);
137-
138-
StableSourceFileId(hasher.finish())
155+
StableSourceFileId { file_name_hash: hasher.finish(), cnum }
139156
}
140157
}
141158

@@ -274,7 +291,7 @@ impl SourceMap {
274291
// be empty, so the working directory will be used.
275292
let (filename, _) = self.path_mapping.map_filename_prefix(&filename);
276293

277-
let file_id = StableSourceFileId::new_from_name(&filename);
294+
let file_id = StableSourceFileId::new_from_name(&filename, LOCAL_CRATE);
278295

279296
let lrc_sf = match self.source_file_by_stable_id(file_id) {
280297
Some(lrc_sf) => lrc_sf,
@@ -288,6 +305,10 @@ impl SourceMap {
288305
self.hash_kind,
289306
));
290307

308+
// Let's make sure the file_id we generated above actually matches
309+
// the ID we generate for the SourceFile we just created.
310+
debug_assert_eq!(StableSourceFileId::new(&source_file), file_id);
311+
291312
let mut files = self.files.borrow_mut();
292313

293314
files.source_files.push(source_file.clone());
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
#[inline]
2+
pub fn some_function() -> u32 {
3+
1
4+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
// This test makes sure that the compiler can handle the same source file to be
2+
// part of the local crate *and* an upstream crate. This can happen, for example,
3+
// when there is some auto-generated code that is part of both a library and an
4+
// accompanying integration test.
5+
//
6+
// The test uses include!() to include a source file that is also part of
7+
// an upstream crate.
8+
//
9+
// This is a regression test for https://github.com/rust-lang/rust/issues/85955.
10+
11+
// check-pass
12+
// compile-flags: --crate-type=rlib
13+
// aux-build:same-file-in-two-crates-aux.rs
14+
extern crate same_file_in_two_crates_aux;
15+
16+
pub fn foo() -> u32 {
17+
same_file_in_two_crates_aux::some_function() +
18+
some_function()
19+
}
20+
21+
include!("./auxiliary/same-file-in-two-crates-aux.rs");

0 commit comments

Comments
 (0)