Treesitter query vs traversal, what do they cost?

Hi folks, i’m writing a plugin that “move cursor to the ‘import’ section of
the current buffer” based on treesitter.
So i have two choices to find the last ‘import’ node: 1) traversal the AST
tree 2) using queries. And actually i did it in both ways, which can
be found here: View paste NJHA.

Thus I have some doubts on these two approaches:

a. for 1), does each access of node cause a copy from C to lua? or other costs i dont know

b. for 2), treesitter will perform the query agains the whole tree?

  • if so, that’s quite expensive, because the ‘import’ nodes are special which always
    occur in top level.

c. for a more general treesitter use, which part can i cache during the editting? or should i?

  • the parser got from vim.treesitter.get_parser()
  • the trees got from parser:trees()

could anyone clear up my doubts? thanks a lot.

so far, I prefer the 1) because it’s easier to implement also I know how it works; I dont have to learn another query DSL, and look deep into the code to figured out how queries are beeing executed. Actually, I found nowhere to ask questions about this area.

i got a little better understanding about treesitter though the document of treesitter itself.
well, nvim provides no apis for ts_node_edit, so if I want to change the AST I have to change the buffer (nvim_buf_set_{lines,text}) not the tree. (in nvim-treesitter.ts_utils.swap_nodes, it’s lsp.util.apply_text_edits exactlly)
also I drew some inspirations from nvim-treesitter, nvim-treesitter-textobject.

I still dont have a clear understanding on my previous doubts, but seems I got a way to make it, haha.