R/def.R

Defines functions autogen_template defs_initial_template defs_path first_config make_defs replace_defs

replace_defs <- function(parseds) {
  first_config()
  defs <- make_defs(parseds)
  file <- readr::read_lines(defs_path())

  autogen_bounds <- which(grepl("------ autogenerated", file))
  autogen_bounds[1] <- autogen_bounds[1] + 1L # account for the line explaning what to do.
  # remove lines between the autogen bounds
  if ((autogen_bounds[1] + 1L) < (autogen_bounds[2] - 1L)) {
    line_numbers <- seq(from = autogen_bounds[1] + 1L, to = autogen_bounds[2] - 1L)
    file <- file[-line_numbers]
  }

  file <- append(file, defs, after = autogen_bounds[1])
  readr::write_lines(file, defs_path())
}

make_defs <- function(parseds) {
  fn_names <- sapply(parseds, function(x) x$name)
  fn_names <- paste0("_", fn_names)

  nm <- tolower(get_package_name())
  defs <- c(
    fn_names,
    paste0(nm, "_last_error"),
    paste0(nm, "_last_error_clear")
  )
  defs <- paste0("  ", defs) # identation
  defs
}


first_config <- function() {

  # no def file exists!
  # dosomething and return
  if (!fs::file_exists(defs_path())) {
    readr::write_file(defs_initial_template(), defs_path())
  }

  # file exists but don't have an 'auto section'
  # add the auto section
  file <- readr::read_lines(defs_path())
  if (!any(grepl("autogenerated", file))) {

    if (!any(grepl("EXPORTS", file))) {
      stop("No EXPORTS section in the def file. Please add one.")
    }

    file <- append(file, autogen_template(), after = which(grepl("EXPORTS", file))[1])
  }

  readr::write_lines(file, defs_path())
}

defs_path <- function() {
  fs::path(pkg_path(), "csrc", "src", paste0(tolower(get_package_name()), ".def"))
}

defs_initial_template <- function() {
  NAME <- get_package_name()
  glue_code(
"
LIBRARY <<NAME>>
EXPORTS

"
  )
}

autogen_template <- function() {
"
  ;------ autogenerated -------------------------
  ; don't modify between the autogenerated lines
  ;------ autogenerated -------------------------
"
}
mlverse/torchexport documentation built on Dec. 7, 2024, 9:03 a.m.