Skip to main content

wgslift_syntax/
span.rs

1//! Source files and byte spans into them.
2
3/// Identifies one source file: the main file or a file it included.
4#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
5pub struct FileId(pub u32);
6
7/// A byte range in one source file.
8#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
9pub struct Span {
10    /// The file the range is in.
11    pub file: FileId,
12    /// Offset of the first byte.
13    pub start: u32,
14    /// Offset after the last byte.
15    pub end: u32,
16}
17
18impl Span {
19    /// A span from `start` to `end` in `file`.
20    pub fn new(file: FileId, start: usize, end: usize) -> Span {
21        Span {
22            file,
23            start: start.min(u32::MAX as usize) as u32,
24            end: end.min(u32::MAX as usize) as u32,
25        }
26    }
27
28    /// The smallest span that covers `self` and `other`. Spans from different files
29    /// keep `self`.
30    pub fn to(self, other: Span) -> Span {
31        if self.file != other.file {
32            return self;
33        }
34        Span {
35            file: self.file,
36            start: self.start.min(other.start),
37            end: self.end.max(other.end),
38        }
39    }
40}
41
42/// One source file: its name and text.
43#[derive(Debug, Clone, PartialEq, Eq)]
44pub struct SourceFile {
45    /// The name the file was opened with, for diagnostics.
46    pub name: String,
47    /// The full text.
48    pub text: String,
49    line_starts: Vec<u32>,
50    /// The `#line` directives of the file, in offset order.
51    line_marks: Vec<LineMark>,
52    /// The `#include` directive that opened the file.
53    pub(crate) included_from: Option<Span>,
54}
55
56/// From `offset` on, the physical line `physical` is numbered `line` in `name`.
57#[derive(Debug, Clone, PartialEq, Eq)]
58struct LineMark {
59    offset: u32,
60    physical: usize,
61    line: usize,
62    name: Option<String>,
63}
64
65impl SourceFile {
66    fn new(name: String, text: String) -> SourceFile {
67        let line_starts = std::iter::once(0)
68            .chain(text.match_indices('\n').map(|(i, _)| (i + 1) as u32))
69            .collect();
70        SourceFile {
71            name,
72            text,
73            line_starts,
74            line_marks: Vec::new(),
75            included_from: None,
76        }
77    }
78
79    /// The 1-based line and column of a byte offset, with the line numbers that
80    /// `#line` gives.
81    pub fn line_column(&self, offset: u32) -> (usize, usize) {
82        let (physical, column) = self.physical_line_column(offset);
83        let line = match self.mark(offset) {
84            Some(mark) => mark.line + physical - mark.physical,
85            None => physical,
86        };
87        (line, column)
88    }
89
90    fn physical_line_column(&self, offset: u32) -> (usize, usize) {
91        let line = self
92            .line_starts
93            .partition_point(|start| *start <= offset)
94            .max(1);
95        let start = self.line_starts[line - 1] as usize;
96        let before = self.text.get(start..offset as usize).unwrap_or("");
97        (line, before.chars().count() + 1)
98    }
99
100    fn mark(&self, offset: u32) -> Option<&LineMark> {
101        let n = self.line_marks.partition_point(|m| m.offset <= offset);
102        n.checked_sub(1).map(|n| &self.line_marks[n])
103    }
104
105    /// The `#include` directive that opened the file, if one did.
106    pub fn included_from(&self) -> Option<Span> {
107        self.included_from
108    }
109
110    /// The text of the physical line around a byte offset, and the offset where
111    /// that line starts.
112    pub fn line_text(&self, offset: u32) -> (&str, u32) {
113        let line = self.line_starts.partition_point(|s| *s <= offset).max(1);
114        let start = self.line_starts[line - 1];
115        let rest = self.text.get(start as usize..).unwrap_or("");
116        (rest.lines().next().unwrap_or(""), start)
117    }
118
119    /// The file name at a byte offset: the last name `#line` gave, or `name`.
120    pub(crate) fn name_at(&self, offset: u32) -> &str {
121        self.mark(offset)
122            .and_then(|m| m.name.as_deref())
123            .unwrap_or(&self.name)
124    }
125
126    /// Numbers the line at `offset` as `line`, and the lines after it from there.
127    /// `None` keeps the file name.
128    pub(crate) fn set_line(&mut self, offset: usize, line: usize, name: Option<String>) {
129        let offset = offset.min(u32::MAX as usize) as u32;
130        let name = name.or_else(|| self.mark(offset).and_then(|m| m.name.clone()));
131        let keep = self.line_marks.partition_point(|m| m.offset < offset);
132        self.line_marks.truncate(keep);
133        self.line_marks.push(LineMark {
134            offset,
135            physical: self.physical_line_column(offset).0,
136            line,
137            name,
138        });
139    }
140}
141
142/// All files that took part in one parse.
143#[derive(Debug, Clone, Default, PartialEq, Eq)]
144pub struct SourceFiles {
145    files: Vec<SourceFile>,
146}
147
148impl SourceFiles {
149    /// Adds a file and returns its id.
150    pub fn add(&mut self, name: impl Into<String>, text: impl Into<String>) -> FileId {
151        self.files.push(SourceFile::new(name.into(), text.into()));
152        FileId((self.files.len() - 1) as u32)
153    }
154
155    /// The file with this id.
156    pub fn get(&self, id: FileId) -> Option<&SourceFile> {
157        self.files.get(id.0 as usize)
158    }
159
160    pub(crate) fn get_mut(&mut self, id: FileId) -> Option<&mut SourceFile> {
161        self.files.get_mut(id.0 as usize)
162    }
163
164    /// The text a span covers, or `""` for a span that is out of range.
165    pub fn text(&self, span: Span) -> &str {
166        self.get(span.file)
167            .and_then(|f| f.text.get(span.start as usize..span.end as usize))
168            .unwrap_or("")
169    }
170
171    /// `name:line:column` for the start of a span.
172    pub fn location(&self, span: Span) -> String {
173        match self.get(span.file) {
174            Some(file) => {
175                let (line, column) = file.line_column(span.start);
176                format!("{}:{line}:{column}", file.name_at(span.start))
177            }
178            None => "<unknown>".to_string(),
179        }
180    }
181}
182
183#[cfg(test)]
184mod tests {
185    use super::*;
186
187    #[test]
188    fn line_and_column_are_one_based() {
189        let mut files = SourceFiles::default();
190        let id = files.add("a.hlsl", "ab\ncd\n\nef");
191        let file = files.get(id).unwrap();
192        assert_eq!(file.line_column(0), (1, 1));
193        assert_eq!(file.line_column(1), (1, 2));
194        assert_eq!(file.line_column(3), (2, 1));
195        assert_eq!(file.line_column(7), (4, 1));
196        assert_eq!(files.location(Span::new(id, 4, 5)), "a.hlsl:2:2");
197    }
198
199    #[test]
200    fn a_line_mark_renumbers_later_lines_and_keeps_the_name_until_changed() {
201        let mut files = SourceFiles::default();
202        let id = files.add("a.hlsl", "x\ny\nz\nw\nv");
203        let file = files.get_mut(id).unwrap();
204        file.set_line(2, 10, None);
205        file.set_line(6, 50, Some("b.hlsl".to_string()));
206        file.set_line(8, 60, None);
207        let file = files.get(id).unwrap();
208        assert_eq!(file.line_column(0), (1, 1));
209        assert_eq!(file.line_column(2), (10, 1));
210        assert_eq!(file.line_column(4), (11, 1));
211        assert_eq!(file.line_column(7), (50, 2));
212        assert_eq!(files.location(Span::new(id, 4, 5)), "a.hlsl:11:1");
213        assert_eq!(files.location(Span::new(id, 6, 7)), "b.hlsl:50:1");
214        assert_eq!(files.location(Span::new(id, 8, 9)), "b.hlsl:60:1");
215    }
216
217    #[test]
218    fn text_of_a_span_and_out_of_range_spans() {
219        let mut files = SourceFiles::default();
220        let id = files.add("a", "float4 x;");
221        assert_eq!(files.text(Span::new(id, 7, 8)), "x");
222        assert_eq!(files.text(Span::new(id, 7, 99)), "");
223        assert_eq!(files.text(Span::new(FileId(9), 0, 1)), "");
224    }
225
226    #[test]
227    fn joining_spans_covers_both() {
228        let id = FileId(0);
229        assert_eq!(
230            Span::new(id, 5, 7).to(Span::new(id, 1, 3)),
231            Span::new(id, 1, 7)
232        );
233        assert_eq!(
234            Span::new(id, 5, 7).to(Span::new(FileId(1), 1, 3)),
235            Span::new(id, 5, 7)
236        );
237    }
238}