Skip to main content

rustpython_compiler_source/
lib.rs

1pub use ruff_source_file::{LineIndex, OneIndexed as LineNumber, PositionEncoding, SourceLocation};
2use ruff_text_size::TextRange;
3pub use ruff_text_size::TextSize;
4
5#[derive(Clone)]
6pub struct SourceCode<'src> {
7    pub path: &'src str,
8    pub text: &'src str,
9    pub index: LineIndex,
10}
11
12impl<'src> SourceCode<'src> {
13    pub fn new(path: &'src str, text: &'src str) -> Self {
14        let index = LineIndex::from_source_text(text);
15        Self { path, text, index }
16    }
17
18    pub fn line_index(&self, offset: TextSize) -> LineNumber {
19        self.index.line_index(offset)
20    }
21
22    pub fn source_location(&self, offset: TextSize) -> SourceLocation {
23        self.index
24            .source_location(offset, self.text, PositionEncoding::Utf8)
25    }
26
27    pub fn get_range(&'src self, range: TextRange) -> &'src str {
28        &self.text[range.start().to_usize()..range.end().to_usize()]
29    }
30}
31
32pub struct SourceCodeOwned {
33    pub path: String,
34    pub text: String,
35    pub index: LineIndex,
36}
37
38impl SourceCodeOwned {
39    pub fn new(path: String, text: String) -> Self {
40        let index = LineIndex::from_source_text(&text);
41        Self { path, text, index }
42    }
43}