Skip to main content

litcheck_core/diagnostics/
location.rs

1use core::{fmt, ops::Range};
2
3use super::{
4    ByteIndex, FileName,
5    source_file::{ColumnNumber, LineNumber},
6};
7
8/// A [Location] represents file and span information for portability across source managers
9#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
10pub struct Location {
11    /// The path to the source file in which the relevant source code can be found
12    pub uri: FileName,
13    /// The starting byte index (inclusive) of this location
14    pub start: ByteIndex,
15    /// The ending byte index (exclusive) of this location
16    pub end: ByteIndex,
17}
18
19impl Location {
20    /// Creates a new [Location].
21    pub const fn new(uri: FileName, start: ByteIndex, end: ByteIndex) -> Self {
22        Self { uri, start, end }
23    }
24
25    /// Get the name (or path) of the source file
26    pub fn uri(&self) -> &FileName {
27        &self.uri
28    }
29
30    /// Returns the byte range represented by this location
31    pub const fn range(&self) -> Range<ByteIndex> {
32        self.start..self.end
33    }
34}
35
36/// A [FileLineCol] represents traditional file/line/column information for use in rendering.
37#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
38pub struct FileLineCol {
39    /// The path to the source file in which the relevant source code can be found
40    pub uri: FileName,
41    /// The one-indexed number of the line to which this location refers
42    pub line: LineNumber,
43    /// The one-indexed column of the line on which this location starts
44    pub column: ColumnNumber,
45}
46
47impl FileLineCol {
48    /// Creates a new [Location].
49    pub fn new(
50        uri: FileName,
51        line: impl Into<LineNumber>,
52        column: impl Into<ColumnNumber>,
53    ) -> Self {
54        Self {
55            uri,
56            line: line.into(),
57            column: column.into(),
58        }
59    }
60
61    /// Get the name (or path) of the source file
62    pub fn uri(&self) -> &FileName {
63        &self.uri
64    }
65
66    /// Returns the line of the location.
67    pub const fn line(&self) -> LineNumber {
68        self.line
69    }
70
71    /// Moves the column by the given offset.
72    pub fn move_column(&mut self, offset: i32) {
73        self.column += offset;
74    }
75}
76
77impl fmt::Display for FileLineCol {
78    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
79        write!(f, "[{}@{}:{}]", &self.uri, self.line, self.column)
80    }
81}