feat(treesitter): upstream node_length() as a node method

Util from the nvim-treesitter project.
This commit is contained in:
Quentin Rasmont
2022-05-01 21:13:47 +02:00
committed by bfredl
parent baba43681e
commit f57341a4b6
2 changed files with 31 additions and 0 deletions

View File

@@ -90,6 +90,7 @@ static struct luaL_Reg node_meta[] = {
{ "prev_named_sibling", node_prev_named_sibling }, { "prev_named_sibling", node_prev_named_sibling },
{ "named_children", node_named_children }, { "named_children", node_named_children },
{ "root", node_root }, { "root", node_root },
{ "byte_length", node_byte_length },
{ NULL, NULL } { NULL, NULL }
}; };
@@ -1111,6 +1112,20 @@ static int node_root(lua_State *L)
return 1; return 1;
} }
static int node_byte_length(lua_State *L)
{
TSNode node;
if (!node_check(L, 1, &node)) {
return 0;
}
uint32_t start_byte = ts_node_start_byte(node);
uint32_t end_byte = ts_node_end_byte(node);
lua_pushnumber(L, end_byte - start_byte);
return 1;
}
/// assumes the match table being on top of the stack /// assumes the match table being on top of the stack
static void set_match(lua_State *L, TSQueryMatch *match, int nodeidx) static void set_match(lua_State *L, TSQueryMatch *match, int nodeidx)
{ {

View File

@@ -92,4 +92,20 @@ describe('treesitter node API', function()
eq(lua_eval('tostring(root)'), lua_eval('tostring(node:root())')) eq(lua_eval('tostring(root)'), lua_eval('tostring(node:root())'))
end) end)
it('can compute the byte length of a node', function()
insert([[
int main() {
int x = 3;
}]])
exec_lua([[
tree = vim.treesitter.get_parser(0, "c"):parse()[1]
root = tree:root()
child = root:child(0):child(0)
]])
eq(28, lua_eval('root:byte_length()'))
eq(3, lua_eval('child:byte_length()'))
end)
end) end)