gdsyntax 0.1.5

GDScript syntax trees and syntax errors, shared by the gdsuite tools
Documentation
//! GDScript syntax trees and syntax errors, shared by the gdsuite tools.
//!
//! The parser is a translation of Godot 4.7's own tokenizer and parser
//! ([`lexer`], [`parser`]), so it accepts and rejects what Godot does, with
//! Godot's error messages. Its tree is lossless: every byte of the file,
//! comments and whitespace included, is in it, so `tree.text()` is always the
//! source. [`ast`] gives typed access to declarations, statements and
//! expressions.
//!
//! ```
//! use gdsyntax::ast::Member;
//!
//! let tree = gdsyntax::parse("extends Node\n\n\nfunc _ready() -> void:\n\tprint(\"hi\")\n");
//! assert!(tree.errors().is_empty());
//! for member in tree.file().members() {
//!     if let Member::Func(func) = member {
//!         assert_eq!(func.name().unwrap().text(), "_ready");
//!     }
//! }
//! ```

pub mod ast;
pub mod kind;
pub mod lexer;
pub mod literal;
pub mod parser;

pub use kind::{GDScript, SyntaxKind};
/// The tree library, re-exported so that its types (`NodeOrToken`,
/// `TextRange`, `WalkEvent`...) are the ones this crate's tree uses.
pub use rowan;

/// A node of a lossless GDScript tree.
pub type SyntaxNode = rowan::SyntaxNode<GDScript>;
/// A token of a lossless GDScript tree.
pub type SyntaxToken = rowan::SyntaxToken<GDScript>;
/// A node or a token.
pub type SyntaxElement = rowan::SyntaxElement<GDScript>;

/// A place in the source. Both fields are 1-based; `column` counts characters.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct Position {
    pub line: usize,
    pub column: usize,
}

/// An error in the source, with Godot's message.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SyntaxError {
    pub start: Position,
    pub end: Position,
    /// Byte offsets of the error.
    pub range: std::ops::Range<usize>,
    pub message: String,
}

/// A parsed GDScript file: its source, its tree and its errors.
pub struct SyntaxTree {
    source: String,
    root: SyntaxNode,
    errors: Vec<parser::ParseError>,
    /// The byte offset where each line starts; the first is 0.
    line_starts: Vec<usize>,
}

/// Parse GDScript source. Parsing never fails: code that is not valid
/// GDScript still ends up in the tree, and [`SyntaxTree::errors`] says what
/// is wrong, in the order Godot reports it.
pub fn parse(source: impl Into<String>) -> SyntaxTree {
    let source = source.into();
    let parse = parser::parse(&source);
    let line_starts = std::iter::once(0)
        .chain(source.match_indices('\n').map(|(index, _)| index + 1))
        .collect();
    SyntaxTree {
        root: SyntaxNode::new_root(parse.green),
        errors: parse.errors,
        source,
        line_starts,
    }
}

/// The message Godot gives for a script that is not valid UTF-8.
pub const INVALID_UTF8_MESSAGE: &str = "Script contains invalid unicode (UTF-8), so it was not loaded. Please ensure that scripts are saved in valid UTF-8 unicode.";

/// Parse a file's bytes. Valid UTF-8 parses as with [`parse`]. Godot does
/// not load a script that is not valid UTF-8; here each invalid sequence is
/// replaced with U+FFFD so the rest can still be parsed, and the first error
/// is Godot's [`INVALID_UTF8_MESSAGE`], at the first invalid byte.
///
/// Offsets and positions always refer to [`SyntaxTree::source`]. After a
/// replacement, offsets past it no longer match the bytes passed in, but
/// lines do: a line break is never replaced.
pub fn parse_bytes(bytes: &[u8]) -> SyntaxTree {
    match std::str::from_utf8(bytes) {
        Ok(source) => parse(source),
        Err(error) => {
            let valid = error.valid_up_to();
            let mut tree = parse(String::from_utf8_lossy(bytes).into_owned());
            let end = valid
                + tree.source[valid..]
                    .chars()
                    .next()
                    .map_or(0, char::len_utf8);
            tree.errors.insert(
                0,
                parser::ParseError {
                    message: INVALID_UTF8_MESSAGE.to_string(),
                    start: valid,
                    end,
                },
            );
            tree
        }
    }
}

impl SyntaxTree {
    pub fn source(&self) -> &str {
        &self.source
    }

    /// The root `SOURCE_FILE` node.
    pub fn root(&self) -> &SyntaxNode {
        &self.root
    }

    /// The root as a typed [`ast::SourceFile`].
    pub fn file(&self) -> ast::SourceFile {
        use ast::AstNode;
        ast::SourceFile::cast(self.root.clone()).expect("the root is always a SOURCE_FILE")
    }

    pub fn has_errors(&self) -> bool {
        !self.errors.is_empty()
    }

    /// The errors, in the order Godot reports them; the first is the one
    /// Godot's editor shows.
    pub fn errors(&self) -> Vec<SyntaxError> {
        self.errors
            .iter()
            .map(|error| SyntaxError {
                start: self.position(error.start),
                end: self.position(error.end),
                range: error.start..error.end,
                message: error.message.clone(),
            })
            .collect()
    }

    /// The position of a byte offset in the source. An offset past the end
    /// is the end of the source, and one inside a multi-byte character is
    /// that character. Finding the line is a binary search, not a scan of
    /// the file.
    pub fn position(&self, byte: usize) -> Position {
        let mut byte = byte.min(self.source.len());
        while !self.source.is_char_boundary(byte) {
            byte -= 1;
        }
        let line = self.line_starts.partition_point(|&start| start <= byte);
        let line_start = self.line_starts[line - 1];
        Position {
            line,
            column: self.source[line_start..byte].chars().count() + 1,
        }
    }

    /// The byte offset of a position: the inverse of [`SyntaxTree::position`].
    /// The column may be one past the line's last character, for the end of
    /// the line. `None` for a position outside the source.
    pub fn offset(&self, position: Position) -> Option<usize> {
        let start = *self.line_starts.get(position.line.checked_sub(1)?)?;
        // The line up to its `\n`; a `\r` before it counts as a character,
        // as in `position`.
        let end = self
            .line_starts
            .get(position.line)
            .map_or(self.source.len(), |next| next - 1);
        let text = &self.source[start..end];
        let column = position.column.checked_sub(1)?;
        if column == text.chars().count() {
            return Some(start + text.len());
        }
        text.char_indices()
            .nth(column)
            .map(|(index, _)| start + index)
    }

    /// How many lines the source has, counted as [`str::lines`] does: a final
    /// line break does not start another line, and an empty source has none.
    pub fn line_count(&self) -> usize {
        let last = self.line_starts.len();
        if self.line_starts[last - 1] == self.source.len() {
            last - 1
        } else {
            last
        }
    }

    /// The byte range of a line (1-based), without its `\n` or `\r\n`.
    pub fn line_range(&self, line: usize) -> Option<std::ops::Range<usize>> {
        if line == 0 || line > self.line_count() {
            return None;
        }
        let start = self.line_starts[line - 1];
        let mut end = self
            .line_starts
            .get(line)
            .map_or(self.source.len(), |next| next - 1);
        if end > start && self.source.as_bytes()[end - 1] == b'\r' && end < self.source.len() {
            end -= 1;
        }
        Some(start..end)
    }

    /// The text of a line (1-based), without its `\n` or `\r\n`.
    pub fn line_text(&self, line: usize) -> Option<&str> {
        self.line_range(line).map(|range| &self.source[range])
    }

    /// Every line with its 1-based number, as [`str::lines`] gives them.
    pub fn lines(&self) -> impl Iterator<Item = (usize, &str)> {
        (1..=self.line_count()).map(|line| (line, self.line_text(line).unwrap_or("")))
    }
}

/// The source as a flat tree of tokens, without parsing: one `SOURCE_FILE`
/// node holding every token, with the tokenizer's errors.
pub fn lossless_tree(source: &str) -> (SyntaxNode, Vec<lexer::LexError>) {
    let lexed = lexer::tokenize(source);
    let mut builder = rowan::GreenNodeBuilder::new();
    builder.start_node(SyntaxKind::SOURCE_FILE.into());
    let mut offset = 0;
    for token in &lexed.tokens {
        let end = offset + token.len as usize;
        builder.token(token.kind.into(), &source[offset..end]);
        offset = end;
    }
    builder.finish_node();
    (SyntaxNode::new_root(builder.finish()), lexed.errors)
}

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

    #[test]
    fn valid_code_has_no_errors() {
        let tree = parse("extends Node\n\n\nfunc _ready() -> void:\n\tprint(\"hi\")\n");
        assert!(!tree.has_errors());
        assert_eq!(tree.root().kind(), SyntaxKind::SOURCE_FILE);
        assert_eq!(tree.root().to_string(), tree.source());
    }

    #[test]
    fn reports_godot_s_first_error_where_it_is() {
        let tree = parse("extends Node\n\nfunc f(:\n\tpass\n");
        let errors = tree.errors();
        assert_eq!(errors[0].message, "Expected parameter name.");
        assert_eq!(errors[0].start.line, 3);
    }

    #[test]
    fn columns_count_characters_not_bytes() {
        let tree = parse("var é = 1\n");
        let byte = tree.source().find('=').unwrap();
        // "var é " is 6 characters but 7 bytes.
        assert_eq!(tree.position(byte), Position { line: 1, column: 7 });
    }

    #[test]
    fn an_offset_inside_a_character_is_that_character() {
        let source = "var a = \"\u{27a1}\"\nvar b\n";
        let tree = parse(source);
        let arrow = source.find('\u{27a1}').unwrap();
        for byte in arrow..arrow + '\u{27a1}'.len_utf8() {
            assert_eq!(
                tree.position(byte),
                Position {
                    line: 1,
                    column: 10
                }
            );
        }
        assert_eq!(tree.position(usize::MAX), Position { line: 3, column: 1 });
    }

    #[test]
    fn bytes_that_are_utf8_parse_as_text() {
        let source = "func f():\n\tpass\n";
        let tree = parse_bytes(source.as_bytes());
        assert!(!tree.has_errors());
        assert_eq!(tree.source(), source);
    }

    #[test]
    fn invalid_utf8_is_godot_s_first_error_and_the_rest_still_parses() {
        let tree = parse_bytes(b"var a = 1\nvar b = \"\xff\"\nfunc test_x():\n\tpass\n");
        let errors = tree.errors();
        assert_eq!(errors.len(), 1);
        assert_eq!(errors[0].message, INVALID_UTF8_MESSAGE);
        assert_eq!(
            errors[0].start,
            Position {
                line: 2,
                column: 10
            }
        );
        assert!(tree.source().contains('\u{fffd}'));
        let names: Vec<String> = tree
            .file()
            .members()
            .filter_map(|member| member.name())
            .map(|name| name.text().to_string())
            .collect();
        assert_eq!(names, ["a", "b", "test_x"]);
    }

    #[test]
    fn comments_are_in_the_tree() {
        let tree = parse("# note\nvar x = 1\n");
        let comment = tree.root().first_token().unwrap();
        assert_eq!(comment.kind(), SyntaxKind::COMMENT);
        assert_eq!(comment.text(), "# note");
    }
}