Add an API for getting a node's child index

This commit is contained in:
Max Brunsfeld 2018-01-09 12:33:51 -08:00
parent f653f2b3bb
commit 315dff3285
3 changed files with 32 additions and 0 deletions

View file

@ -92,6 +92,7 @@ TSNode ts_node_child(TSNode, uint32_t);
TSNode ts_node_named_child(TSNode, uint32_t);
uint32_t ts_node_child_count(TSNode);
uint32_t ts_node_named_child_count(TSNode);
uint32_t ts_node_child_index(TSNode);
TSNode ts_node_next_sibling(TSNode);
TSNode ts_node_next_named_sibling(TSNode);
TSNode ts_node_prev_sibling(TSNode);

View file

@ -329,6 +329,25 @@ TSNode ts_node_parent(TSNode self) {
return result;
}
uint32_t ts_node_child_index(TSNode self) {
const Tree *tree = ts_node__tree(self);
uint32_t result = 0;
for (;;) {
const Tree *parent = tree->context.parent;
uint32_t index = tree->context.index;
if (!parent) return UINT32_MAX;
for (uint32_t i = 0; i < index; i++) {
Tree *child = parent->children[i];
result += child->visible ? 1 : child->visible_child_count;
}
if (parent->visible) break;
tree = parent;
}
return result;
}
TSNode ts_node_child(TSNode self, uint32_t child_index) {
return ts_node__child(self, child_index, true);
}

View file

@ -243,6 +243,18 @@ describe("Node", [&]() {
});
});
describe("child_index()", [&]() {
it("returns the index of the node within its parent", [&]() {
AssertThat(ts_node_child_index(ts_node_child(root_node, 0)), Equals(0u));
AssertThat(ts_node_child_index(ts_node_child(root_node, 1)), Equals(1u));
AssertThat(ts_node_child_index(ts_node_child(root_node, 2)), Equals(2u));
AssertThat(ts_node_child_index(ts_node_child(root_node, 3)), Equals(3u));
AssertThat(ts_node_child_index(ts_node_child(root_node, 4)), Equals(4u));
AssertThat(ts_node_child_index(ts_node_child(root_node, 5)), Equals(5u));
AssertThat(ts_node_child_index(ts_node_child(root_node, 6)), Equals(6u));
});
});
describe("symbols()", [&]() {
it("returns an iterator that yields each of the node's symbols", [&]() {
const TSLanguage *language = ts_document_language(document);