Skip to content

Commit ce57648

Browse files
committed
Move relative pos calculation to SourceFile
1 parent dbdfa6e commit ce57648

File tree

2 files changed

+19
-16
lines changed

2 files changed

+19
-16
lines changed

src/libsyntax/json.rs

+2-16
Original file line numberDiff line numberDiff line change
@@ -333,24 +333,10 @@ impl DiagnosticSpan {
333333
})
334334
});
335335

336-
let file_np = &start.file.normalized_pos;
337-
let np_start_diff = match file_np.binary_search_by(
338-
|np| np.pos.cmp(&span.lo())) {
339-
Ok(i) => file_np[i].diff,
340-
Err(i) if i == 0 => 0,
341-
Err(i) => file_np[i-1].diff,
342-
};
343-
let np_end_diff = match file_np.binary_search_by(
344-
|np| np.pos.cmp(&span.hi())) {
345-
Ok(i) => file_np[i].diff,
346-
Err(i) if i == 0 => 0,
347-
Err(i) => file_np[i-1].diff,
348-
};
349-
350336
DiagnosticSpan {
351337
file_name: start.file.name.to_string(),
352-
byte_start: span.lo().0 - start.file.start_pos.0 + np_start_diff,
353-
byte_end: span.hi().0 - start.file.start_pos.0 + np_end_diff,
338+
byte_start: start.file.original_relative_byte_pos(span.lo()).0,
339+
byte_end: start.file.original_relative_byte_pos(span.hi()).0,
354340
line_start: start.line,
355341
line_end: end.line,
356342
column_start: start.col.0 + 1,

src/libsyntax_pos/lib.rs

+17
Original file line numberDiff line numberDiff line change
@@ -1239,6 +1239,23 @@ impl SourceFile {
12391239
pub fn contains(&self, byte_pos: BytePos) -> bool {
12401240
byte_pos >= self.start_pos && byte_pos <= self.end_pos
12411241
}
1242+
1243+
/// Calculates the original byte position relative to the start of the file
1244+
/// based on the given byte position.
1245+
pub fn original_relative_byte_pos(&self, pos: BytePos) -> BytePos {
1246+
1247+
// Diff before any records is 0. Otherwise use the previously recorded
1248+
// diff as that applies to the following characters until a new diff
1249+
// is recorded.
1250+
let diff = match self.normalized_pos.binary_search_by(
1251+
|np| np.pos.cmp(&pos)) {
1252+
Ok(i) => self.normalized_pos[i].diff,
1253+
Err(i) if i == 0 => 0,
1254+
Err(i) => self.normalized_pos[i-1].diff,
1255+
};
1256+
1257+
BytePos::from_u32(pos.0 - self.start_pos.0 + diff)
1258+
}
12421259
}
12431260

12441261
/// Normalizes the source code and records the normalizations.

0 commit comments

Comments
 (0)