pub mod ast;
pub mod kind;
pub mod lexer;
pub mod literal;
pub mod parser;
pub mod project;
pub use kind::{GDScript, SyntaxKind};
pub use rowan;
pub type SyntaxNode = rowan::SyntaxNode<GDScript>;
pub type SyntaxToken = rowan::SyntaxToken<GDScript>;
pub type SyntaxElement = rowan::SyntaxElement<GDScript>;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct Position {
pub line: usize,
pub column: usize,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SyntaxError {
pub start: Position,
pub end: Position,
pub range: std::ops::Range<usize>,
pub message: String,
}
pub struct SyntaxTree {
source: String,
root: SyntaxNode,
errors: Vec<parser::ParseError>,
line_starts: Vec<usize>,
}
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,
}
}
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.";
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
}
pub fn root(&self) -> &SyntaxNode {
&self.root
}
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()
}
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()
}
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,
}
}
pub fn offset(&self, position: Position) -> Option<usize> {
let start = *self.line_starts.get(position.line.checked_sub(1)?)?;
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)
}
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
}
}
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)
}
pub fn line_text(&self, line: usize) -> Option<&str> {
self.line_range(line).map(|range| &self.source[range])
}
pub fn lines(&self) -> impl Iterator<Item = (usize, &str)> {
(1..=self.line_count()).map(|line| (line, self.line_text(line).unwrap_or("")))
}
}
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();
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");
}
}