py-tree-sitter
py-tree-sitter copied to clipboard
Cursor tree traversal
Hi, I'm trying to create a tree traversal using the cursor. The cursor should print the nodes as the recursive method in this other issue (https://github.com/tree-sitter/py-tree-sitter/issues/5). However, the recursive implementation without cursor is very inefficient as it ends up with a huge recursion depth.
This is what I wrote so far, it prints some parts of the tree, but then it stops.
def print_node(code, node):
pos_point = f"[{node.start_point},{node.end_point}]"
pos_byte = f"({node.start_byte},{node.end_byte}"
print(
f"{code[node.start_byte:node.end_byte]:<25}{node.type}"
)
def itraverse(code, cursor):
has_sibling = True
while has_sibling:
has_childs = True
while has_childs:
has_childs = cursor.goto_first_child()
if not has_childs:
print_node(code, cursor.node)
#print_node(code, cursor.node)
has_sibling = cursor.goto_next_sibling()
I think the problem is that the goto_next_sibling() doesn't work as I think (going to the closest sibling of the subtree). Is there a way to traverse the tree without using a stack and memorize the nodes that have been visited?
Issue Label Bot is not confident enough to auto-label this issue. See dashboard for more details.
Possibly the following might be of interest: https://github.com/tree-sitter/py-tree-sitter/issues/33#issuecomment-689426763
If I understand correctly, this is the same as #33. I also used recursion but got stumped by the stack limit, so I have rewritten it to use the TreeCursor. Code found in https://github.com/tree-sitter/py-tree-sitter/issues/33#issuecomment-864557166.
Closing as a duplicate of #33 since that one has more info.