Skip to content

Commit 0987b84

Browse files
committed
rustc_span: refactor byte_pos_to_line_and_col
1 parent 8da2a5a commit 0987b84

File tree

1 file changed

+31
-28
lines changed

1 file changed

+31
-28
lines changed

compiler/rustc_span/src/caching_source_map_view.rs

+31-28
Original file line numberDiff line numberDiff line change
@@ -70,38 +70,16 @@ impl<'sm> CachingSourceMapView<'sm> {
7070
}
7171

7272
// No cache hit ...
73-
let mut oldest = 0;
74-
for index in 1..self.line_cache.len() {
75-
if self.line_cache[index].time_stamp < self.line_cache[oldest].time_stamp {
76-
oldest = index;
77-
}
78-
}
79-
80-
let cache_entry = &mut self.line_cache[oldest];
73+
let oldest = self.oldest_cache_entry_index();
8174

8275
// If the entry doesn't point to the correct file, fix it up
83-
if !file_contains(&cache_entry.file, pos) {
84-
let file_valid;
85-
if self.source_map.files().len() > 0 {
86-
let file_index = self.source_map.lookup_source_file_idx(pos);
87-
let file = &self.source_map.files()[file_index];
88-
89-
if file_contains(&file, pos) {
90-
cache_entry.file = file.clone();
91-
cache_entry.file_index = file_index;
92-
file_valid = true;
93-
} else {
94-
file_valid = false;
95-
}
96-
} else {
97-
file_valid = false;
98-
}
99-
100-
if !file_valid {
101-
return None;
102-
}
76+
if !file_contains(&self.line_cache[oldest].file, pos) {
77+
let (file, file_index) = self.file_for_position(pos)?;
78+
self.line_cache[oldest].file = file;
79+
self.line_cache[oldest].file_index = file_index;
10380
}
10481

82+
let cache_entry = &mut self.line_cache[oldest];
10583
let line_index = cache_entry.file.lookup_line(pos).unwrap();
10684
let line_bounds = cache_entry.file.line_bounds(line_index);
10785

@@ -111,6 +89,31 @@ impl<'sm> CachingSourceMapView<'sm> {
11189

11290
Some((cache_entry.file.clone(), cache_entry.line_number, pos - cache_entry.line.start))
11391
}
92+
93+
fn oldest_cache_entry_index(&self) -> usize {
94+
let mut oldest = 0;
95+
96+
for idx in 1..self.line_cache.len() {
97+
if self.line_cache[idx].time_stamp < self.line_cache[oldest].time_stamp {
98+
oldest = idx;
99+
}
100+
}
101+
102+
oldest
103+
}
104+
105+
fn file_for_position(&self, pos: BytePos) -> Option<(Lrc<SourceFile>, usize)> {
106+
if !self.source_map.files().is_empty() {
107+
let file_idx = self.source_map.lookup_source_file_idx(pos);
108+
let file = &self.source_map.files()[file_idx];
109+
110+
if file_contains(file, pos) {
111+
return Some((file.clone(), file_idx));
112+
}
113+
}
114+
115+
None
116+
}
114117
}
115118

116119
#[inline]

0 commit comments

Comments
 (0)