[fine] Type checking bones

This commit is contained in:
John Doty 2024-01-05 14:59:48 -08:00
parent 5cc9ecc398
commit c0f40aa512
6 changed files with 613 additions and 3 deletions

View file

@ -18,6 +18,10 @@ impl<'a> SyntaxTree<'a> {
}
}
pub fn root(&self) -> Option<TreeRef> {
self.root
}
pub fn add_tree(&mut self, t: Tree<'a>) -> TreeRef {
assert!(t.parent.is_none());
let tr = TreeRef::from_index(self.trees.len());
@ -40,6 +44,14 @@ impl<'a> SyntaxTree<'a> {
None => String::new(),
}
}
pub fn start_position(&self, t: TreeRef) -> Option<usize> {
self[t].start_position(&self)
}
pub fn end_position(&self, t: TreeRef) -> Option<usize> {
self[t].end_position(&self)
}
}
impl<'a> std::ops::Index<TreeRef> for SyntaxTree<'a> {
@ -56,7 +68,7 @@ impl<'a> std::ops::IndexMut<TreeRef> for SyntaxTree<'a> {
}
}
#[derive(Debug)]
#[derive(Debug, Eq, PartialEq)]
pub enum TreeKind {
Error,
File,
@ -86,7 +98,61 @@ pub struct Tree<'a> {
pub children: Vec<Child<'a>>,
}
#[derive(Copy, Clone, Eq, PartialEq)]
impl<'a> Tree<'a> {
pub fn nth_token(&self, index: usize) -> Option<&Token<'a>> {
self.children
.get(index)
.map(|c| match c {
Child::Token(t) => Some(t),
_ => None,
})
.flatten()
}
pub fn nth_tree(&self, index: usize) -> Option<TreeRef> {
self.children
.get(index)
.map(|c| match c {
Child::Tree(t) => Some(*t),
_ => None,
})
.flatten()
}
pub fn start_position(&self, tree: &SyntaxTree<'a>) -> Option<usize> {
for child in &self.children {
let start = match child {
Child::Tree(tr) => tree.start_position(*tr),
Child::Token(tok) => Some(tok.start),
};
if let Some(start) = start {
return Some(start);
}
}
// Fundamentally no tokens in this tree. This seems *broken*.
None
}
pub fn end_position(&self, tree: &SyntaxTree<'a>) -> Option<usize> {
for child in self.children.iter().rev() {
let end = match child {
Child::Tree(tr) => tree.end_position(*tr),
Child::Token(tok) => Some(tok.start + tok.as_str().len()),
};
if let Some(start) = end {
return Some(start);
}
}
// Fundamentally no tokens in this tree. This seems *broken*.
None
}
}
#[derive(Copy, Clone, Eq, PartialEq, Hash)]
pub struct TreeRef(NonZeroU32);
impl TreeRef {