py-tree-sitter icon indicating copy to clipboard operation
py-tree-sitter copied to clipboard

Cursor tree traversal

Open SasCezar opened this issue 5 years ago • 3 comments

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?

SasCezar avatar Aug 13 '20 06:08 SasCezar

Issue Label Bot is not confident enough to auto-label this issue. See dashboard for more details.

issue-label-bot[bot] avatar Aug 13 '20 06:08 issue-label-bot[bot]

Possibly the following might be of interest: https://github.com/tree-sitter/py-tree-sitter/issues/33#issuecomment-689426763

sogaiu avatar Sep 09 '20 08:09 sogaiu

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.

bencevans avatar Jun 20 '21 13:06 bencevans

Closing as a duplicate of #33 since that one has more info.

ObserverOfTime avatar Feb 26 '24 11:02 ObserverOfTime