TreeCursor
is an R6 class that allows you to walk a tree in a more
efficient way than calling node_*()
functions like node_child()
repeatedly.
You can also more elegantly create a cursor with node_walk()
and
tree_walk()
.
Methods
Method goto_parent()
Go to the current node's parent.
Returns TRUE
if a parent was found, and FALSE
if not.
Method goto_next_sibling()
Go to the current node's next sibling.
Returns TRUE
if a sibling was found, and FALSE
if not.
Method goto_previous_sibling()
Go to the current node's previous sibling.
Returns TRUE
if a sibling was found, and FALSE
if not.
Method goto_first_child()
Go to the current node's first child.
Returns TRUE
if a child was found, and FALSE
if not.
Method goto_last_child()
Go to the current node's last child.
Returns TRUE
if a child was found, and FALSE
if not.
Method goto_first_child_for_byte()
Move the cursor to the first child of its current node that extends beyond the given byte offset.
Returns TRUE
if a child was found, and FALSE
if not.
Examples
language <- treesitter.r::language()
parser <- parser(language)
text <- "fn <- function(a, b) { a + b }"
tree <- parser_parse(parser, text)
node <- tree_root_node(tree)
cursor <- TreeCursor$new(node)
cursor$node()
#> <tree_sitter_node>
#>
#> ── Text ──────────────────────────────────────────────────────────────────
#> fn <- function(a, b) { a + b }
#>
#> ── S-Expression ──────────────────────────────────────────────────────────
#> (program [(0, 0), (0, 30)]
#> (binary_operator [(0, 0), (0, 30)]
#> lhs: (identifier [(0, 0), (0, 2)])
#> operator: "<-" [(0, 3), (0, 5)]
#> rhs: (function_definition [(0, 6), (0, 30)]
#> name: "function" [(0, 6), (0, 14)]
#> parameters: (parameters [(0, 14), (0, 20)]
#> open: "(" [(0, 14), (0, 15)]
#> parameter: (parameter [(0, 15), (0, 16)]
#> name: (identifier [(0, 15), (0, 16)])
#> )
#> (comma [(0, 16), (0, 17)])
#> parameter: (parameter [(0, 18), (0, 19)]
#> name: (identifier [(0, 18), (0, 19)])
#> )
#> close: ")" [(0, 19), (0, 20)]
#> )
#> body: (braced_expression [(0, 21), (0, 30)]
#> open: "{" [(0, 21), (0, 22)]
#> body: (binary_operator [(0, 23), (0, 28)]
#> lhs: (identifier [(0, 23), (0, 24)])
#> operator: "+" [(0, 25), (0, 26)]
#> rhs: (identifier [(0, 27), (0, 28)])
#> )
#> close: "}" [(0, 29), (0, 30)]
#> <truncated>
cursor$goto_first_child()
#> [1] TRUE
cursor$goto_first_child()
#> [1] TRUE
cursor$node()
#> <tree_sitter_node>
#>
#> ── Text ──────────────────────────────────────────────────────────────────
#> fn
#>
#> ── S-Expression ──────────────────────────────────────────────────────────
#> (identifier [(0, 0), (0, 2)])
cursor$goto_next_sibling()
#> [1] TRUE
cursor$node()
#> <tree_sitter_node>
#>
#> ── Text ──────────────────────────────────────────────────────────────────
#> <-
#>
#> ── S-Expression ──────────────────────────────────────────────────────────
#> "<-" [(0, 3), (0, 5)]