Skip to content

Instantly share code, notes, and snippets.

@benzipperer
Created October 19, 2024 01:42
Show Gist options
  • Save benzipperer/4ed69994e7e60ac7330b74c9e2de92c4 to your computer and use it in GitHub Desktop.
Save benzipperer/4ed69994e7e60ac7330b74c9e2de92c4 to your computer and use it in GitHub Desktop.
show all the function names in a given set of R scripts using the treesitter package
# show all the function names in a given set of R scripts
function_definitions = function(files) {
purrr:::map(files, function_definitions_script) |>
purrr::list_rbind()
}
function_definitions_script = function(file) {
text = brio::read_lines(file) |>
paste(collapse = "\n")
language <- treesitter.r::language()
parser <- treesitter::parser(language)
tree = treesitter::parser_parse(parser, text)
node = treesitter::tree_root_node(tree)
query_source = '
(
(binary_operator
lhs: (identifier) @name
rhs: (function_definition))
)
'
function_query <- treesitter::query(language, query_source)
captures <- treesitter::query_captures(function_query, node)
purrr::map(captures$node, extract_node_info) |>
purrr::list_rbind() |>
dplyr::mutate(file = file)
}
extract_node_info = function(node) {
tibble::tibble(
name = treesitter::node_text(node),
line = treesitter::node_range(node)$start_point$row + 1
)
}
@JosiahParry
Copy link

Thank you for this! I've adapted it to find just function names based on text instead of a file. I really appreciate it!

find_function_names <- function(text) {
  language <- treesitter.r::language()
  parser <- treesitter::parser(language)
  tree <- treesitter::parser_parse(parser, text)
  node <- treesitter::tree_root_node(tree)
  
  query_source <- "
    (
    (binary_operator
      lhs: (identifier) @name
      rhs: (function_definition))
    )
  "
  function_query <- treesitter::query(language, query_source)
  captures <- treesitter::query_captures(function_query, node)
  
  vapply(captures$node, treesitter::node_text, character(1)) 
}

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