diff --git a/compiler/rustc_span/src/source_map.rs b/compiler/rustc_span/src/source_map.rs index 81730f2f60869..562cf955e99a6 100644 --- a/compiler/rustc_span/src/source_map.rs +++ b/compiler/rustc_span/src/source_map.rs @@ -12,7 +12,7 @@ pub use crate::hygiene::{ExpnData, ExpnKind}; pub use crate::*; -use rustc_data_structures::fx::FxHashMap; +use rustc_data_structures::fx::{FxHashMap, StdEntry}; use rustc_data_structures::stable_hasher::{Hash128, Hash64, StableHasher}; use rustc_data_structures::sync::{IntoDynSyncSend, Lrc, MappedReadGuard, ReadGuard, RwLock}; use std::cmp; @@ -266,20 +266,24 @@ impl SourceMap { mut file: SourceFile, ) -> Result, OffsetOverflowError> { let mut files = self.files.borrow_mut(); + let SourceMapFiles { ref mut source_files, ref mut stable_id_to_source_file } = &mut *files; + let file = match stable_id_to_source_file.entry(file_id) { + StdEntry::Occupied(o) => o.into_mut(), + StdEntry::Vacant(v) => { + file.start_pos = BytePos(if let Some(last_file) = source_files.last() { + // Add one so there is some space between files. This lets us distinguish + // positions in the `SourceMap`, even in the presence of zero-length files. + last_file.end_position().0.checked_add(1).ok_or(OffsetOverflowError)? + } else { + 0 + }); - file.start_pos = BytePos(if let Some(last_file) = files.source_files.last() { - // Add one so there is some space between files. This lets us distinguish - // positions in the `SourceMap`, even in the presence of zero-length files. - last_file.end_position().0.checked_add(1).ok_or(OffsetOverflowError)? - } else { - 0 - }); - - let file = Lrc::new(file); - files.source_files.push(file.clone()); - files.stable_id_to_source_file.insert(file_id, file.clone()); - - Ok(file) + let file = Lrc::new(file); + source_files.push(file.clone()); + v.insert(file) + } + }; + Ok(file.clone()) } /// Creates a new `SourceFile`.