Skip to content

Commit 9413e7f

Browse files
authored
Provide access to line/col lookup on a SourceFile (#949)
1 parent 6a235e3 commit 9413e7f

File tree

1 file changed

+15
-5
lines changed

1 file changed

+15
-5
lines changed

crates/apollo-compiler/src/parser.rs

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -420,13 +420,25 @@ impl SourceFile {
420420
})
421421
}
422422

423-
pub(crate) fn get_line_column(&self, index: usize) -> Option<LineColumn> {
424-
let (_, zero_indexed_line, zero_indexed_column) = self.ariadne().get_byte_line(index)?;
423+
/// Get [`LineColumn`] for the given 0-indexed UTF-8 byte `offset` from the start of the file.
424+
///
425+
/// Returns None if the offset is out of bounds.
426+
pub fn get_line_column(&self, offset: usize) -> Option<LineColumn> {
427+
let (_, zero_indexed_line, zero_indexed_column) = self.ariadne().get_byte_line(offset)?;
425428
Some(LineColumn {
426429
line: zero_indexed_line + 1,
427430
column: zero_indexed_column + 1,
428431
})
429432
}
433+
434+
/// Get starting and ending [`LineColumn`]s for the given `range` 0-indexed UTF-8 byte offsets.
435+
///
436+
/// Returns `None` if either offset is out of bounds.
437+
pub fn get_line_column_range(&self, range: Range<usize>) -> Option<Range<LineColumn>> {
438+
let start = self.get_line_column(range.start)?;
439+
let end = self.get_line_column(range.end)?;
440+
Some(start..end)
441+
}
430442
}
431443

432444
impl std::fmt::Debug for SourceFile {
@@ -598,9 +610,7 @@ impl SourceSpan {
598610
/// inclusive.
599611
pub fn line_column_range(&self, sources: &SourceMap) -> Option<Range<LineColumn>> {
600612
let source = sources.get(&self.file_id)?;
601-
let start = source.get_line_column(self.offset())?;
602-
let end = source.get_line_column(self.end_offset())?;
603-
Some(Range { start, end })
613+
source.get_line_column_range(self.offset()..self.end_offset())
604614
}
605615
}
606616

0 commit comments

Comments
 (0)