R/utils.R

Defines functions drop_null_elements to_yaml add_rulelist_class add_sgnodelist_class check_all_nodes check_is_rulelist_or_node check_is_tree

check_is_tree <- function(x) {
  if (!inherits(x, "SgRoot")) {
    stop("`x` must be an object of class 'SgRoot'.")
  }
}

check_is_rulelist_or_node <- function(x) {
  if (!inherits(x, c("RuleList", "SgNode"))) {
    stop("`x` must be an object of class 'RuleList' or 'SgNode'.")
  }
}

check_all_nodes <- function(x) {
  elems <- unlist(x, recursive = TRUE)
  # faster than going through all elems via vapply() since here we can stop on
  # first non-node instead of using inherits() on all of them
  for (i in elems) {
    if (!inherits(i, "SgNode")) {
      stop("All elements of `x` must be objects of class 'SgNode'.")
    }
  }
}

add_sgnodelist_class <- function(x) {
  class(x) <- c("SgNodeList", class(x))
  x
}

add_rulelist_class <- function(x) {
  class(x) <- c("RuleList", class(x))
  x
}

to_yaml <- function(x) {
  non_null <- rrapply::rrapply(x, condition = Negate(is.null), how = "prune")
  if ("id" %in% names(non_null)) {
    non_null[["id"]] <- NULL
  }
  yaml::as.yaml(non_null, indent.mapping.sequence = TRUE)
}

seq2 <- Vectorize(seq.default, vectorize.args = c("from", "to"))

drop_null_elements <- function(x) {
  Filter(Negate(is.null), x)
}

Try the astgrepr package in your browser

Any scripts or data that you put into this service are public.

astgrepr documentation built on June 8, 2025, 11:05 a.m.