use std::collections::HashMap;
use tree_sitter::Tree;
pub const NONE: u32 = u32::MAX;
pub const FLAG_NAMED: u32 = 1;
pub const FLAG_ERROR: u32 = 1 << 1;
pub const FLAG_MISSING: u32 = 1 << 2;
pub const FLAG_EXTRA: u32 = 1 << 3;
pub const FLAG_HAS_ERROR: u32 = 1 << 4;
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct FlatTree {
pub kinds: Vec<String>,
pub fields: Vec<String>,
pub kind: Vec<u32>,
pub field: Vec<u32>,
pub flags: Vec<u32>,
pub parent: Vec<u32>,
pub first_child: Vec<u32>,
pub next_sibling: Vec<u32>,
pub prev_sibling: Vec<u32>,
pub start_byte: Vec<u32>,
pub end_byte: Vec<u32>,
pub start_row: Vec<u32>,
pub start_col: Vec<u32>,
pub end_row: Vec<u32>,
pub end_col: Vec<u32>,
pub child_offset: Vec<u32>,
pub child_list: Vec<u32>,
}
impl FlatTree {
pub fn len(&self) -> usize {
self.kind.len()
}
pub fn is_empty(&self) -> bool {
self.kind.is_empty()
}
pub fn kind_name(&self, i: usize) -> &str {
&self.kinds[self.kind[i] as usize]
}
pub fn field_name(&self, i: usize) -> Option<&str> {
match self.field[i] {
0 => None,
f => Some(&self.fields[f as usize]),
}
}
pub fn children(&self, i: usize) -> Vec<usize> {
let mut out = Vec::new();
let mut c = self.first_child[i];
while c != NONE {
out.push(c as usize);
c = self.next_sibling[c as usize];
}
out
}
}
struct Interner {
table: Vec<String>,
index: HashMap<&'static str, u32>,
by_id: Vec<u32>,
}
impl Interner {
fn new(seed: &[&'static str]) -> Self {
let mut interner = Self {
table: Vec::new(),
index: HashMap::new(),
by_id: Vec::new(),
};
for s in seed {
interner.intern(s);
}
interner
}
fn intern(&mut self, s: &'static str) -> u32 {
if let Some(&i) = self.index.get(s) {
return i;
}
let i = self.table.len() as u32;
self.table.push(s.to_string());
self.index.insert(s, i);
i
}
fn intern_id(&mut self, id: u16, name: impl FnOnce() -> &'static str) -> u32 {
let slot = usize::from(id);
if let Some(&i) = self.by_id.get(slot) {
if i != NONE {
return i;
}
} else {
self.by_id.resize(slot + 1, NONE);
}
let i = self.intern(name());
self.by_id[slot] = i;
i
}
}
fn to_u32(v: usize) -> u32 {
u32::try_from(v).unwrap_or(u32::MAX)
}
pub fn flatten(tree: &Tree) -> FlatTree {
let n = tree.root_node().descendant_count();
let column = || Vec::with_capacity(n);
let mut flat = FlatTree {
kind: column(),
field: column(),
flags: column(),
parent: column(),
first_child: column(),
next_sibling: column(),
prev_sibling: column(),
start_byte: column(),
end_byte: column(),
start_row: column(),
start_col: column(),
end_row: column(),
end_col: column(),
..FlatTree::default()
};
let mut kinds = Interner::new(&[]);
let mut fields = Interner::new(&[""]);
let mut cursor = tree.walk();
let mut parents: Vec<u32> = Vec::new();
let mut last_child: Vec<u32> = Vec::new();
loop {
let node = cursor.node();
let row = to_u32(flat.kind.len());
let mut flags = 0;
for (on, bit) in [
(node.is_named(), FLAG_NAMED),
(node.is_error(), FLAG_ERROR),
(node.is_missing(), FLAG_MISSING),
(node.is_extra(), FLAG_EXTRA),
(node.has_error(), FLAG_HAS_ERROR),
] {
if on {
flags |= bit;
}
}
let (start, end) = (node.start_position(), node.end_position());
flat.kind
.push(kinds.intern_id(node.kind_id(), || node.kind()));
flat.field.push(cursor.field_id().map_or(0, |f| {
fields.intern_id(f.get(), || cursor.field_name().unwrap_or(""))
}));
flat.flags.push(flags);
flat.parent.push(parents.last().copied().unwrap_or(NONE));
flat.first_child.push(NONE);
flat.next_sibling.push(NONE);
flat.prev_sibling.push(NONE);
flat.start_byte.push(to_u32(node.start_byte()));
flat.end_byte.push(to_u32(node.end_byte()));
flat.start_row.push(to_u32(start.row));
flat.start_col.push(to_u32(start.column));
flat.end_row.push(to_u32(end.row));
flat.end_col.push(to_u32(end.column));
if let (Some(&parent), Some(last)) = (parents.last(), last_child.last_mut()) {
if *last == NONE {
flat.first_child[parent as usize] = row;
} else {
flat.next_sibling[*last as usize] = row;
flat.prev_sibling[row as usize] = *last;
}
*last = row;
}
if cursor.goto_first_child() {
parents.push(row);
last_child.push(NONE);
continue;
}
loop {
if cursor.goto_next_sibling() {
break;
}
if !cursor.goto_parent() {
flat.kinds = kinds.table;
flat.fields = fields.table;
index_children(&mut flat);
return flat;
}
parents.pop();
last_child.pop();
}
}
}
fn index_children(flat: &mut FlatTree) {
let n = flat.len();
flat.child_offset = Vec::with_capacity(n + 1);
flat.child_list = Vec::with_capacity(n.saturating_sub(1));
for i in 0..n {
flat.child_offset.push(to_u32(flat.child_list.len()));
let mut c = flat.first_child[i];
while c != NONE {
flat.child_list.push(c);
c = flat.next_sibling[c as usize];
}
}
flat.child_offset.push(to_u32(flat.child_list.len()));
}
#[cfg(test)]
mod tests {
use super::*;
use tree_sitter::{Node, Parser};
fn parse(key: &str, src: &str) -> Tree {
let mut parser = Parser::new();
parser
.set_language(&crate::registry::language_for_key(key).unwrap())
.unwrap();
parser.parse(src, None).unwrap()
}
fn assert_mirrors(flat: &FlatTree, node: Node, row: usize, next: &mut usize) {
assert_eq!(row, *next, "rows are pre-order");
*next += 1;
assert_eq!(flat.kind_name(row), node.kind());
assert_eq!(flat.start_byte[row] as usize, node.start_byte());
assert_eq!(flat.end_byte[row] as usize, node.end_byte());
assert_eq!(flat.start_row[row] as usize, node.start_position().row);
assert_eq!(flat.end_col[row] as usize, node.end_position().column);
assert_eq!(flat.flags[row] & FLAG_NAMED != 0, node.is_named());
assert_eq!(flat.flags[row] & FLAG_HAS_ERROR != 0, node.has_error());
let children = flat.children(row);
assert_eq!(children.len(), node.child_count());
let (lo, hi) = (
flat.child_offset[row] as usize,
flat.child_offset[row + 1] as usize,
);
let listed: Vec<usize> = flat.child_list[lo..hi]
.iter()
.map(|&c| c as usize)
.collect();
assert_eq!(listed, children, "child_list agrees with the sibling links");
let mut cursor = node.walk();
for (i, child) in node.children(&mut cursor).enumerate() {
let child_row = children[i];
assert_eq!(flat.parent[child_row] as usize, row);
assert_eq!(
flat.field_name(child_row),
node.field_name_for_child(i as u32)
);
assert_mirrors(flat, child, child_row, next);
}
}
#[test]
#[cfg(feature = "lang-rust")]
fn rust_tree_is_mirrored_exactly() {
let tree = parse(
"rust",
"/// doc\n#[inline]\npub fn add(x: i32) -> i32 { x + 1 }\nimpl Foo { fn new() -> Self { Foo } }\n",
);
let flat = flatten(&tree);
let mut next = 0;
assert_mirrors(&flat, tree.root_node(), 0, &mut next);
assert_eq!(next, flat.len());
assert_eq!(flat.kind_name(0), "source_file");
assert_eq!(flat.parent[0], NONE);
}
#[test]
#[cfg(feature = "lang-python")]
fn python_fields_and_siblings() {
let tree = parse("python", "def f(a, b):\n return g(a)\n");
let flat = flatten(&tree);
let mut next = 0;
assert_mirrors(&flat, tree.root_node(), 0, &mut next);
let def = flat.first_child[0] as usize;
assert_eq!(flat.kind_name(def), "function_definition");
let named: Vec<_> = flat
.children(def)
.into_iter()
.filter_map(|c| flat.field_name(c).map(|f| (f, flat.kind_name(c))))
.collect();
assert!(named.contains(&("name", "identifier")));
assert!(named.contains(&("body", "block")));
for c in flat.children(def) {
let prev = flat.prev_sibling[c];
if prev != NONE {
assert_eq!(flat.next_sibling[prev as usize] as usize, c);
}
}
}
#[test]
#[cfg(feature = "lang-c")]
fn errors_and_missing_nodes_are_flagged() {
let tree = parse("c", "int f( { return 1 }");
let flat = flatten(&tree);
assert!(flat.flags[0] & FLAG_HAS_ERROR != 0);
assert!((0..flat.len()).any(|i| flat.flags[i] & (FLAG_ERROR | FLAG_MISSING) != 0));
}
#[test]
#[cfg(feature = "lang-typescript")]
fn tsx_parses_jsx_without_errors() {
let tree = parse("tsx", "const a = <div>{x}</div>;\n");
let flat = flatten(&tree);
assert_eq!(flat.flags[0] & FLAG_HAS_ERROR, 0);
}
#[test]
#[cfg(feature = "lang-c")]
fn interned_tables_hold_each_name_once() {
let tree = parse(
"c",
"struct s { int a; };\ntypedef struct s s_t;\nint f(s_t *p) { return p->a + g(p); }\n",
);
let flat = flatten(&tree);
for table in [&flat.kinds, &flat.fields] {
let unique: std::collections::HashSet<_> = table.iter().collect();
assert_eq!(unique.len(), table.len(), "duplicate name in {table:?}");
}
assert_mirrors(&flat, tree.root_node(), 0, &mut 0);
}
}