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

Allow for early termination of the visitor #19

Merged
merged 4 commits into from
Aug 30, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 15 additions & 4 deletions R/visit.R
Original file line number Diff line number Diff line change
@@ -1,29 +1,40 @@
#' Visits the set of nodes and all of their children, invoking the callback for each visited node
#'
#' @param nodes The list or array of nodes to visit
#' @param callback The callback function to invoke for each node
#' @param callback The callback function to invoke for each node. The callback should return FALSE to stop visiting the children of the node, or anything else to continue.
#'
#' @return FALSE if the visitor was stopped by the callback.
#'
#' @export
visit_nodes <- function(nodes, callback) {
if (!is.null(nodes)) {
for (node in nodes) {
visit_node(node, callback)
res <- visit_node(node, callback)
if (isFALSE(res)) {
return(FALSE)
}
}
}
}

#' Visits the given node and all of their children, invoking the callback for each visited node
#'
#' @param node The node to visit
#' @param callback The callback function to invoke for each node
#' @param callback The callback function to invoke for each node. The callback should return FALSE to stop visiting the children of the node, or anything else to continue.
#'
#' @return FALSE if the visitor was stopped by the callback.
#'
#' @export
visit_node <- function(node, callback) {
if (is.null(node)) {
return()
}

callback(node)
res <- callback(node)
# Exit early if the callback returns FALSE
if (isFALSE(res)) {
return(FALSE)
}

# same logic as the builtin visitor (while explicitly specifying if an entry is a single node or a list)
# https://github.com/Code-Inspect/flowr/blob/main/src/r-bridge/lang-4.x/ast/model/processing/visitor.ts#L22
Expand Down
5 changes: 4 additions & 1 deletion man/visit_node.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 4 additions & 1 deletion man/visit_nodes.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.