use std::marker::PhantomData;
use crate::role::{Role, RoleSet};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Span {
pub start_byte: usize,
pub end_byte: usize,
pub line: usize,
pub column: usize,
}
pub trait Node<'t>: Copy + Sized {
fn kind(&self) -> &'t str;
fn roles(&self) -> RoleSet;
fn span(&self) -> Span;
fn child_count(&self) -> usize;
fn child(&self, index: usize) -> Option<Self>;
fn child_by_field(&self, name: &str) -> Option<Self>;
fn text(&self) -> &'t str;
fn has_role(&self, role: Role) -> bool {
self.roles().contains(role)
}
fn children(&self) -> Children<'t, Self> {
Children {
parent: *self,
index: 0,
count: self.child_count(),
marker: PhantomData,
}
}
}
pub struct Children<'t, N: Node<'t>> {
parent: N,
index: usize,
count: usize,
marker: PhantomData<&'t ()>,
}
impl<'t, N: Node<'t>> Iterator for Children<'t, N> {
type Item = N;
fn next(&mut self) -> Option<N> {
while self.index < self.count {
let index = self.index;
self.index += 1;
if let Some(child) = self.parent.child(index) {
return Some(child);
}
}
None
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Visit {
Descend,
Skip,
}
pub fn walk<'t, N: Node<'t>>(node: N, visit: &mut impl FnMut(N) -> Visit) {
if visit(node) == Visit::Descend {
for child in node.children() {
walk(child, visit);
}
}
}
pub struct Unit<'t, N: Node<'t>> {
pub path: &'t str,
pub source: &'t str,
pub root: N,
pub under_test: Option<N>,
}
impl<'t, N: Node<'t>> Unit<'t, N> {
pub fn new(path: &'t str, source: &'t str, root: N) -> Self {
Unit {
path,
source,
root,
under_test: None,
}
}
}