wgslift-syntax 0.2.0

Preprocessor, lexer and parser for HLSL, the front end of the wgslift translator
Documentation
//! Source files and byte spans into them.

/// Identifies one source file: the main file or a file it included.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct FileId(pub u32);

/// A byte range in one source file.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Span {
    /// The file the range is in.
    pub file: FileId,
    /// Offset of the first byte.
    pub start: u32,
    /// Offset after the last byte.
    pub end: u32,
}

impl Span {
    /// A span from `start` to `end` in `file`.
    pub fn new(file: FileId, start: usize, end: usize) -> Span {
        Span {
            file,
            start: start.min(u32::MAX as usize) as u32,
            end: end.min(u32::MAX as usize) as u32,
        }
    }

    /// The smallest span that covers `self` and `other`. Spans from different files
    /// keep `self`.
    pub fn to(self, other: Span) -> Span {
        if self.file != other.file {
            return self;
        }
        Span {
            file: self.file,
            start: self.start.min(other.start),
            end: self.end.max(other.end),
        }
    }
}

/// One source file: its name and text.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SourceFile {
    /// The name the file was opened with, for diagnostics.
    pub name: String,
    /// The full text.
    pub text: String,
    line_starts: Vec<u32>,
    /// The `#line` directives of the file, in offset order.
    line_marks: Vec<LineMark>,
    /// The `#include` directive that opened the file.
    pub(crate) included_from: Option<Span>,
}

/// From `offset` on, the physical line `physical` is numbered `line` in `name`.
#[derive(Debug, Clone, PartialEq, Eq)]
struct LineMark {
    offset: u32,
    physical: usize,
    line: usize,
    name: Option<String>,
}

impl SourceFile {
    fn new(name: String, text: String) -> SourceFile {
        let line_starts = std::iter::once(0)
            .chain(text.match_indices('\n').map(|(i, _)| (i + 1) as u32))
            .collect();
        SourceFile {
            name,
            text,
            line_starts,
            line_marks: Vec::new(),
            included_from: None,
        }
    }

    /// The 1-based line and column of a byte offset, with the line numbers that
    /// `#line` gives.
    pub fn line_column(&self, offset: u32) -> (usize, usize) {
        let (physical, column) = self.physical_line_column(offset);
        let line = match self.mark(offset) {
            Some(mark) => mark.line + physical - mark.physical,
            None => physical,
        };
        (line, column)
    }

    fn physical_line_column(&self, offset: u32) -> (usize, usize) {
        let line = self
            .line_starts
            .partition_point(|start| *start <= offset)
            .max(1);
        let start = self.line_starts[line - 1] as usize;
        let before = self.text.get(start..offset as usize).unwrap_or("");
        (line, before.chars().count() + 1)
    }

    fn mark(&self, offset: u32) -> Option<&LineMark> {
        let n = self.line_marks.partition_point(|m| m.offset <= offset);
        n.checked_sub(1).map(|n| &self.line_marks[n])
    }

    /// The `#include` directive that opened the file, if one did.
    pub fn included_from(&self) -> Option<Span> {
        self.included_from
    }

    /// The text of the physical line around a byte offset, and the offset where
    /// that line starts.
    pub fn line_text(&self, offset: u32) -> (&str, u32) {
        let line = self.line_starts.partition_point(|s| *s <= offset).max(1);
        let start = self.line_starts[line - 1];
        let rest = self.text.get(start as usize..).unwrap_or("");
        (rest.lines().next().unwrap_or(""), start)
    }

    /// The file name at a byte offset: the last name `#line` gave, or `name`.
    pub(crate) fn name_at(&self, offset: u32) -> &str {
        self.mark(offset)
            .and_then(|m| m.name.as_deref())
            .unwrap_or(&self.name)
    }

    /// Numbers the line at `offset` as `line`, and the lines after it from there.
    /// `None` keeps the file name.
    pub(crate) fn set_line(&mut self, offset: usize, line: usize, name: Option<String>) {
        let offset = offset.min(u32::MAX as usize) as u32;
        let name = name.or_else(|| self.mark(offset).and_then(|m| m.name.clone()));
        let keep = self.line_marks.partition_point(|m| m.offset < offset);
        self.line_marks.truncate(keep);
        self.line_marks.push(LineMark {
            offset,
            physical: self.physical_line_column(offset).0,
            line,
            name,
        });
    }
}

/// All files that took part in one parse.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct SourceFiles {
    files: Vec<SourceFile>,
}

impl SourceFiles {
    /// Adds a file and returns its id.
    pub fn add(&mut self, name: impl Into<String>, text: impl Into<String>) -> FileId {
        self.files.push(SourceFile::new(name.into(), text.into()));
        FileId((self.files.len() - 1) as u32)
    }

    /// The file with this id.
    pub fn get(&self, id: FileId) -> Option<&SourceFile> {
        self.files.get(id.0 as usize)
    }

    pub(crate) fn get_mut(&mut self, id: FileId) -> Option<&mut SourceFile> {
        self.files.get_mut(id.0 as usize)
    }

    /// The text a span covers, or `""` for a span that is out of range.
    pub fn text(&self, span: Span) -> &str {
        self.get(span.file)
            .and_then(|f| f.text.get(span.start as usize..span.end as usize))
            .unwrap_or("")
    }

    /// `name:line:column` for the start of a span.
    pub fn location(&self, span: Span) -> String {
        match self.get(span.file) {
            Some(file) => {
                let (line, column) = file.line_column(span.start);
                format!("{}:{line}:{column}", file.name_at(span.start))
            }
            None => "<unknown>".to_string(),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn line_and_column_are_one_based() {
        let mut files = SourceFiles::default();
        let id = files.add("a.hlsl", "ab\ncd\n\nef");
        let file = files.get(id).unwrap();
        assert_eq!(file.line_column(0), (1, 1));
        assert_eq!(file.line_column(1), (1, 2));
        assert_eq!(file.line_column(3), (2, 1));
        assert_eq!(file.line_column(7), (4, 1));
        assert_eq!(files.location(Span::new(id, 4, 5)), "a.hlsl:2:2");
    }

    #[test]
    fn a_line_mark_renumbers_later_lines_and_keeps_the_name_until_changed() {
        let mut files = SourceFiles::default();
        let id = files.add("a.hlsl", "x\ny\nz\nw\nv");
        let file = files.get_mut(id).unwrap();
        file.set_line(2, 10, None);
        file.set_line(6, 50, Some("b.hlsl".to_string()));
        file.set_line(8, 60, None);
        let file = files.get(id).unwrap();
        assert_eq!(file.line_column(0), (1, 1));
        assert_eq!(file.line_column(2), (10, 1));
        assert_eq!(file.line_column(4), (11, 1));
        assert_eq!(file.line_column(7), (50, 2));
        assert_eq!(files.location(Span::new(id, 4, 5)), "a.hlsl:11:1");
        assert_eq!(files.location(Span::new(id, 6, 7)), "b.hlsl:50:1");
        assert_eq!(files.location(Span::new(id, 8, 9)), "b.hlsl:60:1");
    }

    #[test]
    fn text_of_a_span_and_out_of_range_spans() {
        let mut files = SourceFiles::default();
        let id = files.add("a", "float4 x;");
        assert_eq!(files.text(Span::new(id, 7, 8)), "x");
        assert_eq!(files.text(Span::new(id, 7, 99)), "");
        assert_eq!(files.text(Span::new(FileId(9), 0, 1)), "");
    }

    #[test]
    fn joining_spans_covers_both() {
        let id = FileId(0);
        assert_eq!(
            Span::new(id, 5, 7).to(Span::new(id, 1, 3)),
            Span::new(id, 1, 7)
        );
        assert_eq!(
            Span::new(id, 5, 7).to(Span::new(FileId(1), 1, 3)),
            Span::new(id, 5, 7)
        );
    }
}