Created
October 19, 2024 01:42
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you for this! I've adapted it to find just function names based on text instead of a file. I really appreciate it!