Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make it clear in cursor-related doc that they are scoped to the starting node #567

Open
ubolonton opened this issue Mar 5, 2020 · 5 comments

Comments

@ubolonton
Copy link
Contributor

There seems to be a bug with ts_tree_cursor_goto_parent when the cursor is initialized on a non-root node.

I got it in the Emacs Lisp binding, but can reproduce it with the NodeJS binding (0.16.0):

const Parser = require('tree-sitter');
const Rust = require('tree-sitter-rust');

parser = new Parser();
parser.setLanguage(Rust);

tree = parser.parse("fn foo() {}");

> c0 = tree.rootNode.walk(); c0.gotoFirstChild();
true
>
> c1 = c0.currentNode.walk(); c0.currentNode === c1.currentNode;
true
>
> c0.gotoParent();
true
>
> c1.gotoParent();
false
>
> c0.currentNode.type;
'source_file'
>
> c1.currentNode.type;
'function_item'
>
@maxbrunsfeld
Copy link
Contributor

Yeah, this is actually the expected behavior. The cursor only "walks" within the node that it started from, and it can't go outside of it. This is possible to change, but it would add some complexity. Maybe it's worth it though, because this has confused people before.

@ubolonton
Copy link
Contributor Author

The cursor only "walks" within the node that it started from, and it can't go outside of it.

Oh, it makes sense now. Maybe we can update the doc to clear up the confusion?

My current use case is getting the "path" from the root node to a given node, to restore cursor position after code formatting: emacs-tree-sitter/elisp-tree-sitter#28. Would ts_node_parent be more suitable, at least for now?

@maxbrunsfeld
Copy link
Contributor

maxbrunsfeld commented Mar 6, 2020

I think you could use TreeCursor::goto_first_child_for_byte to walk the cursor to the leaf node at a given byte offset (based on the cursor position) keeping track of the steps along the way.

But ts_node_parent is also fine. There is some caching done in that method to make sure it performs well in the common case of walking repeatedly up the tree.

@ubolonton ubolonton changed the title ts_tree_cursor_goto_parent doesn't work when starting from non-root node Make it clear in cursor-related doc that they are scoped to the starting node Mar 7, 2020
@ubolonton
Copy link
Contributor Author

Thanks!

@Enter-tainer
Copy link

Enter-tainer commented Nov 17, 2021

I've encountered the same issue yesterday. Maybe we should make it clear in the document to end the confusion.

See #1485

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

4 participants