tree-sitter / py-tree-sitter

Python bindings to the Tree-sitter parsing library
https://tree-sitter.github.io/py-tree-sitter/
MIT License
817 stars 96 forks source link

Retrieve the 'name' from a node #263

Closed learn-more closed 1 month ago

learn-more commented 1 month ago

The function child_by_field_name() needs the field name for a node, but this name is very hard to find.

Example:

    parser = Parser(CPP_LANGUAGE)
    tree = parser.parse(b"void test();")
    root = tree.root_node
    print(f'{str(root)=}')
    node = root.child(0)
    # Node is named, but how to get the name?
    print(f'{node.type=}, {node.is_named=}, {node.id=}, {node.kind_id=}, {str(node)=}')

All these options do not work:

    print(f'{root.field_name_for_child(0)=}')
    print(f'{CPP_LANGUAGE.field_name_for_id(node.id)=}')
    print(f'{CPP_LANGUAGE.field_name_for_id(node.kind_id)=}')

Is there an option I am missing? Would it make sense to add a name field to a node?

ObserverOfTime commented 1 month ago

Node names (node.type) and field names are two different things. field_name_for_id expects the field id.