Skip to main content

nifty_syntax/
span.rs

1use std::ops::Range;
2
3/// One source file of a program. Files are numbered in the order they are checked, and
4/// the first, `FileId::default()`, is the project's entry file.
5#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
6pub struct FileId(usize);
7
8impl FileId {
9    #[must_use]
10    pub const fn new(index: usize) -> Self {
11        Self(index)
12    }
13
14    #[must_use]
15    pub const fn index(self) -> usize {
16        self.0
17    }
18}
19
20/// A byte range in the text of one source file.
21#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
22pub struct Span {
23    pub file: FileId,
24    pub start: usize,
25    pub end: usize,
26}
27
28impl Span {
29    #[must_use]
30    pub const fn new(file: FileId, start: usize, end: usize) -> Self {
31        Self { file, start, end }
32    }
33
34    /// The span covering `self` through `other`, which is in the same file.
35    #[must_use]
36    pub const fn to(self, other: Self) -> Self {
37        Self::new(self.file, self.start, other.end)
38    }
39
40    #[must_use]
41    pub const fn range(self) -> Range<usize> {
42        self.start..self.end
43    }
44}