R/function-factory-helpers.R

Defines functions check_fn_wrappable check_reported_reserved check_args_by_row_single check_fn_result check_args_disabled_unnamed check_args_disabled capture_key_args check_key_args_abbreviated absorb_key_args check_variadic_cols check_variadic_arg insert_key_args check_fn_results write_result_cols check_factory_arg_names check_factory_dots resolve_enums eval_enum_defaults is_enum_default name_mapper eval_defaults new_settings formals_settings check_factory_key_args_names check_factory_key_args_values

Documented in absorb_key_args

#' Check that key arguments name columns of `data`
#'
#' Two checks called within `absorb_key_args()`:
#'
#' - `check_factory_key_args_values()` errors if a key argument names a column
#'   that `data` doesn't have.
#' - `check_factory_key_args_names()` errors if a key column is missing from
#'   `data` and no key argument stands in for it.
#'
#' @param data Data frame passed to the mapper.
#' @param key_cols_call Named character vector that maps key argument names to
#'   the columns of `data` that they refer to, such as `c(x = "mean")`.
#' @param key_cols_missing,key_cols_call_names String. Names of the key columns
#'   that are missing from `data`, and of the key arguments the user specified.
#'
#' @return No return value; might throw an error.
#'
#' @noRd
check_factory_key_args_values <- function(data, key_cols_call) {
  offenders <- key_cols_call[!key_cols_call %in% colnames(data)]

  if (length(offenders) == 0L) {
    return(NULL)
  }

  offenders_names <- offenders |>
    names() |>
    glue::as_glue() |>
    wrap_in_backticks()
  offenders <- wrap_in_backticks(offenders)
  name_current_fn <- name_last_export_code()
  if (length(offenders) == 1L) {
    msg_is_colname <- "is not a column name"
  } else {
    msg_is_colname <- "are not column names"
  }

  msg_error <- c(
    "!" = "{offenders} {msg_is_colname} of `data`.",
    "x" = "The {offenders_names[1L]} argument of \\
      {name_current_fn} was specified as {offenders[[1L]]}, \\
      but there is no column in `data` called {offenders[[1L]]}."
  )

  if (length(offenders) > 1L) {
    if (length(offenders) == 2L) {
      msg_arg_s <- "argument"
      msg_a <- "a "
      msg_col <- "column"
    } else {
      msg_arg_s <- "arguments"
      msg_a <- ""
      msg_col <- "columns"
    }
    msg_error <- append(
      msg_error,
      c(
        "x" = "Same with the {offenders_names[-1L]} {msg_arg_s}: \\
          `data` doesn't contain {msg_a}{offenders[-1L]} {msg_col}."
      )
    )
  }

  abort_in_export(msg_error)
}


check_factory_key_args_names <- function(
  key_cols_missing,
  key_cols_call_names
) {
  offenders <- key_cols_missing |>
    call_on(\(x) x[!x %in% key_cols_call_names])

  if (length(offenders) == 0L) {
    return(NULL)
  }

  offenders <- wrap_in_backticks(offenders)

  msg_fn_name <- name_last_export_code()

  if (length(offenders) == 1L) {
    msg_missing <- "Column {offenders} is"
    msg_is_are <- "is"
    msg_needs_to_be <- "It should be a column"
    msg_names <- "the name of the equivalent column"
    msg_column_s <- "Column"
    msg_argument <- "argument"
  } else {
    msg_missing <- "Columns {offenders} are"
    msg_is_are <- "are"
    msg_needs_to_be <- "They should be columns"
    msg_names <- "the names of the equivalent columns"
    msg_it_them <- "them"
    msg_column_s <- "Columns"
    msg_argument <- "arguments"
  }

  abort_in_export(
    "{msg_column_s} {offenders} {msg_is_are} \\
          missing from `data`.",
    "x" = "{msg_needs_to_be} of the input data frame.",
    "i" = "Alternatively, specify the {offenders} \\
          {msg_argument} of {msg_fn_name} as {msg_names}."
  )
}


# The settings of a mapper `fn`, such as `rounding`: its formals after the
# dots, minus those named in `exclude`. `function_map_seq()` and
# `function_map_total_n()` copy them with `fn`'s defaults, so that they show
# up in `formals()`, tab completion, and the help page. A `fn` without dots has
# no settings to copy; it gets them through the dots.
formals_settings <- function(fn, exclude) {
  formals_fn <- formals(fn)
  index_dots <- match("...", names(formals_fn))
  if (is.na(index_dots)) {
    return(list())
  }
  formals_after <- formals_fn[-seq_len(index_dots)]
  formals_after[setdiff(names(formals_after), exclude)]
}


# The settings of a call for the "scrutiny" attribute, as a tibble: `setting`,
# `value` (a list), `default`, and `added_by`, the mapper whose setting it is.
# A sequence or total-n mapper adds its own rows to the basic mapper's. A
# setting missing from `defaults` never counts as a default.
new_settings <- function(values, defaults, added_by) {
  names_values <- names(values)
  if (is.null(names_values)) {
    names_values <- character()
  }
  is_default <- vapply(
    names_values,
    function(name) {
      rlang::has_name(defaults, name) &&
        # Exactly, as `dplyr::bind_rows()` compares them; `all.equal()` took
        # a tolerance of `1e-9` for a default of 0:
        same_value(values[[name]], defaults[[name]])
    },
    logical(1L),
    USE.NAMES = FALSE
  )
  tibble::new_tibble(
    list(
      setting = names_values,
      value = unname(values),
      default = is_default,
      added_by = rep(added_by, length(values))
    ),
    nrow = length(values)
  )
}

# The defaults of `formals`, evaluated once, when a factory creates a mapper.
# A set of strings resolves to its first, as a call does. An argument without
# a default, or with one that can't be evaluated outside of a call, is left
# out:
eval_defaults <- function(formals, env) {
  formals <- formals[!vapply(formals, rlang::is_missing, logical(1L))]
  out <- list()
  for (name in names(formals)) {
    ok <- TRUE
    value <- tryCatch(eval(formals[[name]], env), error = function(e) {
      ok <<- FALSE
    })
    if (!ok) {
      next
    }
    if (is_enum_default(formals[[name]])) {
      value <- value[[1L]]
    }
    out[name] <- list(value)
  }
  out
}

# The name of a mapper, by the convention behind its class: "grim_map" for a
# `.name_test` of "GRIM". `added_by` uses it, since a manufactured function
# does not know the name it was assigned to:
name_mapper <- function(name_test, suffix) {
  sub("^scrutiny_", "", class_name_test(name_test, suffix))
}


# Is a formal's default a set of strings, as in `formula = c("exact",
# "mean_n")`? See `function_map()`.
is_enum_default <- function(default) {
  is.call(default) &&
    identical(default[[1L]], as.name("c")) &&
    length(default) > 2L &&
    all(vapply(as.list(default)[-1L], is.character, logical(1L)))
}


# The whole sets behind the enum defaults among `formals`, as a named list:
eval_enum_defaults <- function(formals, env) {
  is_enum <- vapply(formals, is_enum_default, logical(1L), USE.NAMES = FALSE)
  lapply(formals[is_enum], eval, env)
}


# Resolve the enums among `vals` that were given as their whole default set,
# as a wrapper forwarding its own default does, to the first string, as
# `rlang::arg_match()` would. Everything downstream -- the length check, the
# `*_scalar()` function, the "scrutiny" attribute -- then sees one string.
# `defaults` is from `eval_enum_defaults()`:
resolve_enums <- function(vals, defaults) {
  for (name in intersect(names(vals), names(defaults))) {
    if (identical(vals[[name]], defaults[[name]])) {
      vals[[name]] <- vals[[name]][[1L]]
    }
  }
  vals
}


#' Check that no dots argument is misspelled
#'
#' `check_factory_dots()` is called within mappers made by [`function_map()`],
#' [`function_map_seq()`], and [`function_map_total_n()`]. It errors if an
#' argument passed through the dots is not an argument of `fn`.
#'
#' @param fn Function applied by the mapper.
#' @param fn_name_scalar String (length 1). Name of `fn`.
#' @param ... The dots of the mapper.
#'
#' @return No return value; might throw an error.
#'
#' @noRd
check_factory_dots <- function(fn, fn_name_scalar, ...) {
  dots <- rlang::enexprs(...)
  dots_names <- names(dots)
  offenders <- dots_names[!dots_names %in% names(formals(fn))]

  if (length(offenders) == 0L) {
    return(NULL)
  }

  # `x_meaning` replaced GRIM's `percent`:
  if ("percent" %in% offenders && "x_meaning" %in% names(formals(fn))) {
    stop_percent(name_last_export())
  }

  fn_name_mapper <- name_last_export_code()

  # The dots come right after the key arguments, so an unnamed argument after
  # them lands here with an empty name:
  n_unnamed <- sum(offenders == "")
  if (n_unnamed > 0L) {
    abort_in_export(
      "{n_unnamed} unnamed argument{?s} after the key arguments.",
      "x" = "Every argument after `...` must be named in full.",
      "i" = "The key arguments are the columns to test, such as `x` and `n`."
    )
  }

  # An abbreviation, such as `items` for `items_averaged`, lands here too. `fn`
  # has the arguments a sequence or total-n mapper passes on, such as
  # `rounding`:
  names_full <- union(names(formals(rlang::caller_fn())), names(formals(fn)))
  names_meant <- unique(unlist(lapply(offenders, function(offender) {
    names_full[startsWith(names_full, offender)]
  })))

  offenders <- paste0("`", offenders, "`")

  if (length(offenders) == 1L) {
    msg_arg <- "argument"
    msg_it_they <- "It's not an"
  } else {
    msg_arg <- "arguments"
    msg_it_they <- "They are not"
  }

  abort_in_export(
    "Invalid {msg_arg} {offenders}.",
    "x" = "{msg_it_they} {msg_arg} of {fn_name_mapper} \\
      or `{fn_name_scalar}()`.",
    "i" = if (length(names_meant) > 0L) {
      "Did you mean {wrap_in_backticks(names_meant)}? Arguments after \\
      `...` must be named in full."
    }
  )
}


#' Check that an argument names arguments of `.fn`
#'
#' Several arguments of `function_map()`, such as `.reported` and
#' `.args_by_row`, must name arguments of `.fn`. `check_factory_arg_names()`
#' checks this when the mapper is created, so the error can name the factory
#' argument at fault.
#'
#' @param names String. The values given for `arg_name`.
#' @param formals_fn Pairlist. The formal arguments of `.fn`.
#' @param fn_name String (length 1). Name of `.fn`.
#' @param arg_name String (length 1). Name of the function factory's argument
#'   that `names` was given for, such as `".reported"`.
#'
#' @return No return value; might throw an error.
#'
#' @noRd
check_factory_arg_names <- function(names, formals_fn, fn_name, arg_name) {
  offenders <- names[!names %in% names(formals_fn)]

  if (length(offenders) == 0L) {
    return(NULL)
  }

  offenders <- wrap_in_backticks(offenders)

  if (length(offenders) == 1L) {
    msg_arg <- "argument"
    msg_it_they <- "It was"
  } else {
    msg_arg <- "arguments"
    msg_it_they <- "They were"
  }

  abort_in_export(
    "Function `{fn_name}()` lacks {msg_arg} {offenders}.",
    "i" = "{msg_it_they} given as `{arg_name}` in the \\
    `function_map()` call, where `.fn` was specified as `{fn_name}`."
  )
}


#' Turn a mapper's test results into output columns
#'
#' A `*_scalar()` function returns a single value per row or, as with
#' `show_rec = TRUE`, a list of values per row. `write_result_cols()` handles
#' both.
#'
#' @param results List with one element per row of the mapper's input data
#'   frame, as returned by `purrr::pmap()`.
#' @param col_names String vector with the names of the columns that the
#'   `*_scalar()` function's list of values unpacks into, key result first. It
#'   is the `.col_names` argument of `function_map()`, and may be `NULL`.
#' @param fn_name String (length 1). Name of the `*_scalar()` function, for
#'   messages.
#'
#' @return Named list of columns.
#'
#' @noRd
write_result_cols <- function(results, col_names, fn_name) {
  # With no rows, there is no result to read the output's shape off, so only
  # the key result column is created. `unlist()` below would return `NULL`, and
  # the tibble would count a column that it doesn't have:
  if (length(results) == 0L) {
    out <- list(logical(0L))
    names(out) <- if (is.null(col_names)) "consistency" else col_names[1L]
    return(out)
  }

  lengths_results <- lengths(results)

  # A result without a value, such as `NULL`, would be dropped by `unlist()`,
  # and the other rows' results recycled into its place:
  n_empty <- sum(lengths_results == 0L)

  if (n_empty > 0L) {
    abort_in_export(
      "`{fn_name}()` returned no value for {n_empty} row{?s}.",
      "x" = "It must return a single logical value, or a list starting with \\
      one, for every row."
    )
  }

  if (all(lengths_results == 1L)) {
    check_fn_results(unlist(results, use.names = FALSE), fn_name)
    out <- list(unlist(results, use.names = FALSE))
    names(out) <- if (is.null(col_names)) "consistency" else col_names[1L]
    return(out)
  }

  # Without `.col_names`, there is nothing to unpack into:
  if (is.null(col_names)) {
    offenders <- unique(lengths_results[lengths_results != 1L])
    abort_in_export(
      "`{fn_name}()` returned {offenders[1L]} values for at least one row.",
      "x" = "It must return a single logical value for every row, unless \
      `.col_names` names the values it returns.",
      "i" = "`.col_names` is an argument of `function_map()`, specified \
      when the present function was created."
    )
  }

  offenders <- unique(lengths_results[lengths_results != length(col_names)])

  if (length(offenders) > 0L) {
    abort_in_export(
      "The consistency test function returned {offenders[1L]} value{?s} \\
      for at least one row.",
      "x" = "It must return either a single value or one value per \\
      `.col_names` name, of which there are {length(col_names)}.",
      "i" = "`.col_names` is an argument of `function_map()`, specified \\
      when the present function was created."
    )
  }

  check_fn_results(
    unlist(lapply(results, function(x) x[[1L]]), use.names = FALSE),
    fn_name
  )

  split_result_cols(results, col_names)
}


# `check_fn_result()` saw the first row's result before the mapping. Every
# other row's key result must be logical, too: `unlist()` would otherwise
# coerce the column to character or numeric in silence.
check_fn_results <- function(keys, fn_name) {
  if (!is.logical(keys)) {
    abort_in_export(
      "`{fn_name}()` must return a single logical value, or a list \\
      starting with one, for every row.",
      "x" = "For some rows, it returned {.cls {typeof(keys)}} values."
    )
  }
}


#' Insert key arguments into the factory-made function
#'
#' `insert_key_args()` adds the key arguments, such as `x` and `n`, to the
#' formals of a factory-made function, each with `NULL` as the default. A user
#' whose columns have other names specifies them through these arguments, and
#' `absorb_key_args()` renames the columns at call time.
#'
#' @param fn Factory-made function.
#' @param reported String. Names of the key arguments to be inserted into `fn`.
#' @param insert_after Integer. Index of the formal of `fn` after which the key
#'   arguments are inserted. Default is `1L`.
#' @param variadic String (length 1) or `NULL`, the default. Optionally, the
#'   name of a variadic key argument, which is inserted ahead of the `reported`
#'   ones with no default: it takes a tidyselect expression, and there is no
#'   set of columns that could be guessed at.
#'
#' @return Function `fn` with new arguments, named after `reported`, with
#'   `NULL` as the default for each, led by `variadic` without a default.
#'
#' @noRd
insert_key_args <- function(fn, reported, insert_after = 1L, variadic = NULL) {
  key_args <- rep(list(NULL), times = length(reported))
  names(key_args) <- reported

  if (!is.null(variadic)) {
    # The empty symbol is what a formal without a default has; see `alist()`:
    arg_variadic <- rlang::missing_arg() |>
      list() |>
      rlang::set_names(variadic)
    key_args <- c(arg_variadic, key_args)
  }

  `formals<-`(
    fn,
    value = fn |>
      formals() |>
      append(key_args, after = insert_after)
  )
}


#' Check that a variadic key argument was specified
#'
#' The variadic argument of a factory-made function has no default.
#' `check_variadic_arg()` turns the empty quosure that results from leaving it
#' out into an error that says so.
#'
#' @param quo Quosure captured from the variadic argument.
#' @param name String (length 1). Name of that argument.
#'
#' @return No return value; might throw an error.
#'
#' @noRd
check_variadic_arg <- function(quo, name) {
  if (rlang::quo_is_missing(quo)) {
    fn_name <- name_last_export_code()
    abort_in_export(
      "The `{name}` argument of {fn_name} must be specified.",
      "x" = "It has no default: which columns are tested is up to the data, \\
      and testing all the remaining ones by default would quietly draw in \\
      any column that is not a key column for some other reason.",
      "i" = "Select them using tidyselect syntax, as in \\
      `{name} = c(a, b, c)` or `{name} = starts_with(\"item\")`."
    )
  }
}


#' Check what a variadic key argument selected
#'
#' `tidyselect::eval_select()` guarantees that the selected columns exist, but
#' not that they are usable as variadic key columns. They are not if:
#'
#' - The selection is empty. `purrr::pmap()` would report this as a recycling
#'   failure over a variable the caller has never heard of.
#' - The selection includes a column that already has a role in the test. It
#'   would appear twice in the output.
#'
#' @param index Integer. Column positions, as returned by
#'   `tidyselect::eval_select()`.
#' @param data The mapper's input data frame.
#' @param spoken_for String. Names of the columns that have a role already:
#'   the key columns and any helper columns.
#' @param name String (length 1). Name of the variadic argument.
#'
#' @return No return value; might throw an error.
#'
#' @noRd
check_variadic_cols <- function(index, data, spoken_for, name) {
  fn_name <- name_last_export_code()

  if (length(index) == 0L) {
    abort_in_export(
      "The `{name}` argument of {fn_name} selected no columns.",
      "x" = "There would be no values to test."
    )
  }

  for (col in names(index)) {
    check_not_integer64(data[[index[[col]]]], col)
    check_not_factor(data[[index[[col]]]], col)
  }

  # The selected columns are combined row by row with `c()`, which takes a
  # factor's level codes or a date's day count for numbers next to a numeric
  # column. So they must have a common type:
  tryCatch(
    vctrs::vec_ptype_common(!!!as.list(data[index])),
    error = function(cnd) {
      reason <- conditionMessage(cnd)

      abort_in_export(
        "The columns that `{name}` selects in {fn_name} must have a common \\
        type.",
        "x" = "{reason}"
      )
    }
  )

  offenders <- intersect(colnames(data)[index], spoken_for)

  if (length(offenders) == 0L) {
    return(invisible(NULL))
  }

  name_first <- offenders[1L]
  offenders <- wrap_in_backticks(offenders)

  if (length(offenders) == 1L) {
    msg_that_column <- "That column has"
    msg_subject <- "it"
    msg_object <- "it"
    msg_one <- "one"
  } else {
    msg_that_column <- "Those columns have"
    msg_subject <- "they"
    msg_object <- "them"
    msg_one <- "some"
  }

  abort_in_export(
    "The `{name}` argument of {fn_name} selected {offenders}.",
    "x" = "{msg_that_column} a role in the test already, so {msg_subject} \\
    cannot also be tested as {msg_one} of the `{name}` values.",
    "i" = "Exclude {msg_object} from the selection, as in \\
    `{name} = !{name_first}`."
  )
}

#' Rename key columns according to the key arguments
#'
#' @description `r lifecycle::badge("superseded")`
#'
#'   `absorb_key_args()` is superseded by [`function_map()`], whose mappers
#'   rename key columns themselves.
#'
#'   Call it in a handwritten mapper. If a key argument such as `x` names a
#'   column of `data`, it renames that column to the key argument's name, so
#'   that the rest of the mapper finds it.
#'
#' @param data Data frame passed to the mapper.
#' @param reported String. Names of the key arguments.
#' @param key_cols_call Optionally, a named character vector that maps key
#'   argument names to the columns of `data` that they refer to, such as `c(x =
#'   "mean")`. By default, it is read from the key arguments of the calling
#'   mapper.
#'
#' @export
#'
#' @return `data`, possibly with columns renamed. Reassign the result to
#'   `data`.
#'
#' @examples
#' df <- tibble::tibble(mean = c(5.19, 4.56), n = c(28, 30))
#' absorb_key_args(df, c("x", "n"), key_cols_call = c(x = "mean"))
absorb_key_args <- function(data, reported, key_cols_call = NULL) {
  # The key arguments are read in the mapper's frame, not off its call: the
  # call is `FUN(X[[i]], ...)` if the mapper was reached through `lapply()`,
  # and names a variable rather than its value if called from another function.
  if (is.null(key_cols_call)) {
    fn_caller <- rlang::caller_fn()
    env <- rlang::caller_env()
    # `NULL` at the top level, where `formals()` would warn:
    names_formals <- if (is.null(fn_caller)) {
      character()
    } else {
      names(formals(fn_caller))
    }
    check_key_args_abbreviated(reported, names_formals, rlang::caller_call())
    quos <- list()
    for (name in intersect(reported, names_formals)) {
      quos[[name]] <- eval(rlang::call2(rlang::enquo, rlang::sym(name)), env)
    }
    # A handwritten caller may pass the key arguments on through its dots:
    if (any(names_formals == "...")) {
      quos_dots <- eval(quote(rlang::enquos(...)), env)
      quos <- c(quos, quos_dots[intersect(reported, names(quos_dots))])
    }
    key_cols_call <- capture_key_args(data, quos)
  }

  # A key argument pointing at the column that already has its name is a no-op:
  key_cols_call <- key_cols_call[key_cols_call != names(key_cols_call)]

  # A column by the key argument's own name would be tested instead of the one
  # the argument points to, which is not what the user asked for:
  key_cols_clash <- names(key_cols_call)[
    names(key_cols_call) %in% colnames(data)
  ]
  if (length(key_cols_clash) > 0L) {
    name_arg <- key_cols_clash[[1L]]
    name_col <- key_cols_call[[name_arg]]
    abort_in_export(
      "`{name_arg}` was specified as {.val {name_col}}, but `data` \\
      already has a `{name_arg}` column.",
      "x" = "It is unclear which of the two columns should be tested.",
      "i" = "Rename or remove the `{name_arg}` column first."
    )
  }

  key_cols_missing <- reported |>
    call_on(\(x) x[!x %in% colnames(data)]) |>
    as.character()

  if (length(key_cols_missing) == 0L) {
    return(data)
  }

  names(key_cols_missing) <- key_cols_missing
  key_cols_call <- key_cols_call[names(key_cols_call) %in% key_cols_missing]
  key_cols_call_names <- names(key_cols_call)

  check_factory_key_args_values(data, key_cols_call)
  check_factory_key_args_names(key_cols_missing, key_cols_call_names)

  # One column cannot stand in for two key columns:
  if (anyDuplicated(key_cols_call) > 0L) {
    name_col <- key_cols_call[duplicated(key_cols_call)][1L]
    names_args <- key_cols_call_names[key_cols_call == name_col]
    abort_in_export(
      "{wrap_in_backticks(names_args)} must name different columns.",
      "x" = "They all name `{name_col}`."
    )
  }

  # Rename, then move the key columns to the front:
  index <- match(key_cols_call, colnames(data))
  colnames(data)[index] <- key_cols_call_names
  data |>
    dplyr::relocate(dplyr::all_of(unname(key_cols_missing)))
}


# The key arguments come before the dots, so R matches them partially:
# `percentage_of_map(percent = TRUE)` reads as `percentage = TRUE`, and the
# error would then blame `percentage`, which the user never named.
check_key_args_abbreviated <- function(reported, names_formals, call) {
  names_call <- names(call)
  names_abbreviated <- setdiff(names_call, c("", names_formals, reported))
  for (name in names_abbreviated) {
    name_full <- reported[startsWith(reported, name)]
    if (length(name_full) > 0L) {
      abort_in_export(
        "`{name}` is not an argument of `{name_last_export()}()`.",
        "x" = "R reads it as `{name_full[[1L]]}`, which must be a column name.",
        "i" = "Did you mean another argument? Write its name out in full."
      )
    }
  }
}

# Turn the key arguments, captured as named quosures, into a named character
# vector of column names. A `NULL` argument, i.e., one not specified, is left
# out, and so is a variable or expression that is `NULL`, as from a wrapper
# with a `NULL` default. A bare name is a column name if `data` has such a column, otherwise
# the string that a variable of that name holds. Any other expression must
# evaluate to a single string.
capture_key_args <- function(data, quos) {
  out <- character()
  for (name in names(quos)) {
    quo <- quos[[name]]
    expr <- rlang::quo_get_expr(quo)
    value <- if (rlang::is_symbol(expr)) {
      value_sym <- rlang::as_string(expr)
      value_var <- rlang::env_get(
        rlang::quo_get_env(quo),
        value_sym,
        default = NULL,
        inherit = TRUE
      )
      is_var_null <- is.null(value_var) &&
        rlang::env_has(rlang::quo_get_env(quo), value_sym, inherit = TRUE)
      if (any(value_sym == colnames(data))) {
        value_sym
      } else if (is_var_null || rlang::is_string(value_var)) {
        value_var
      } else {
        value_sym
      }
    } else {
      rlang::eval_tidy(quo)
    }
    if (is.null(value)) {
      next
    }
    if (!rlang::is_string(value)) {
      abort_in_export(
        "The `{name}` argument must be a column name.",
        "x" = "It is {.obj_type_friendly {value}}.",
        "i" = "Specify it as a string, like `{name} = \"my_col\"`, or as a \\
        bare column name."
      )
    }
    out[[name]] <- value
  }
  out
}


#' Check that disabled arguments are not specified
#'
#' `check_args_disabled()` is called within mappers made by [`function_map()`]
#' or [`function_map_seq()`]. It errors if the caller specified an argument
#' that is disabled via `.args_disabled` or fixed via `.args_fixed`.
#'
#' @param args_disabled String. Names of the disabled arguments.
#'
#' @return No return value; might throw an error.
#'
#' @noRd
check_args_disabled <- function(args_disabled) {
  if (is.null(args_disabled)) {
    return(NULL)
  }
  # Disabled arguments arrive through the caller's dots, or they are formals of
  # the caller, as `dispersion` is in a sequence mapper. The names of the dots
  # are read off the dots themselves, not off the call, which through
  # `lapply()` is `FUN(X[[i]], ...)` and names nothing:
  env_caller <- parent.frame()
  names_dots <- if (exists("...", envir = env_caller, inherits = FALSE)) {
    eval(quote(...names()), env_caller)
  }
  names_formals <- names(formals(sys.function(sys.parent())))
  is_given <- vapply(
    args_disabled,
    function(arg) {
      (arg %in% names_dots) ||
        ((arg %in% names_formals) &&
          !eval(call("missing", as.name(arg)), env_caller))
    },
    logical(1L),
    USE.NAMES = FALSE
  )
  offenders <- args_disabled[is_given]
  if (length(offenders) > 0L) {
    fn_name <- name_last_export_code()
    if (length(offenders) > 3L) {
      offenders <- offenders[1:3]
      msg_among_others <- ", among others"
    } else {
      msg_among_others <- ""
    }
    if (length(offenders) > 1L) {
      msg_arg_s <- "Arguments"
      msg_is_are <- "are"
    } else {
      msg_arg_s <- "Argument"
      msg_is_are <- "is"
    }
    offenders <- wrap_in_backticks(offenders)
    abort_in_export(
      "{msg_arg_s} {offenders} {msg_is_are} \\
          disabled in {fn_name}{msg_among_others}."
    )
  }
}


#' Check that the vector of disabled arguments is unnamed
#'
#' `check_args_disabled_unnamed()` is called when a factory creates a mapper.
#' It errors if `.args_disabled` is a named vector rather than just the names of
#' the arguments to disable.
#'
#' @param args_disabled The factory's `.args_disabled` argument, specified by
#'   the factory's user.
#'
#' @return No return value; might throw an error.
#'
#' @noRd
check_args_disabled_unnamed <- function(args_disabled) {
  if (!is.null(names(args_disabled))) {
    name <- deparse(substitute(args_disabled))
    name_names <- wrap_in_backticks(names(args_disabled))
    name_fn <- name_last_export_code()
    if (length(name_names) == 1L) {
      msg_names <- "this name"
    } else {
      msg_names <- "these names"
    }
    abort_in_export(
      "In {name_fn}, the `{name}` argument must be \\
      an unnamed string vector.",
      "x" = "It has {msg_names}: {name_names}."
    )
  }
}


#' Check what a test function returned
#'
#' `check_fn_result()` is called on the result of applying `.fn` to the
#' first row. The key result column is logical, so `.fn` must return a single
#' logical value, or a list that starts with one.
#'
#' @param result What `.fn` returned.
#' @param fn_name String. Name of `.fn`, for the message.
#'
#' @return `result`, invisibly; might throw an error.
#'
#' @noRd
check_fn_result <- function(result, fn_name) {
  key <- if (is.list(result) && length(result) > 0L) result[[1L]] else result
  if (!is.logical(key) || length(key) != 1L) {
    abort_in_export(
      "`{fn_name}()` must return a single logical value, or a list \\
      starting with one.",
      "x" = "It returned {.obj_type_friendly {result}}."
    )
  }
  invisible(result)
}


# An `.args_by_row` argument of a basic mapper other than `digits_*` reaches
# the re-tests of a sequence or total-n mapper through the dots, with one value
# per row of the user's `data`, not of the rows tested. So it must be a single
# value there:
check_args_by_row_single <- function(args_by_row, dots, name_fn, tier) {
  for (name in intersect(names(dots), args_by_row)) {
    if (length(dots[[name]]) > 1L) {
      abort_in_export(
        "`{name}` must be a single value here.",
        "x" = "It has length {length(dots[[name]])}.",
        "i" = "{tier} mappers test other rows than those of `data`, so an \\
        argument can't have one value per row there.",
        "i" = "Basic mappers such as `{name_fn}()` do accept one value per row."
      )
    }
  }
}


# A key column named like something the factory-made function uses itself --
# an argument, a variable in its body, or a column of its output -- would be
# overwritten or misread at call time, so the factory refuses it. `reserved`
# has the names, `factory` the factory's name:
check_reported_reserved <- function(reported, reserved, factory) {
  offenders <- intersect(reported, reserved)
  if (length(offenders) > 0L) {
    abort_in_export(
      "`.reported` has names that `{factory}()` uses internally.",
      "x" = "Rename {wrap_in_backticks(offenders)}.",
      "i" = "Reserved: {wrap_in_backticks(reserved)}."
    )
  }
}


# Whether the seq and total-n tiers can wrap `.fn`. They derive their arguments
# from `.reported`, so not a mapper with a variadic argument. Nor one whose
# result columns they would overwrite or misread with the columns they add
# (`reserved`):
check_fn_wrappable <- function(fn, name_key_result, reserved, factory) {
  arg_variadic <- attr(fn, "scrutiny_arg_variadic", exact = TRUE)
  if (!is.null(arg_variadic)) {
    abort_in_export(
      "`{factory}()` can't wrap a mapper with a variadic argument.",
      "x" = "`.fn` takes a variable number of key columns through \\
      `{arg_variadic}`."
    )
  }
  # Helper and by-row arguments are returned as columns, too:
  cols_result <- c(
    name_key_result,
    attr(fn, "scrutiny_cols_result", exact = TRUE),
    attr(fn, "scrutiny_args_helper", exact = TRUE),
    attr(fn, "scrutiny_args_by_row", exact = TRUE)
  )
  offenders <- intersect(cols_result, reserved)
  if (length(offenders) > 0L) {
    abort_in_export(
      "`.fn` returns columns that `{factory}()` adds itself.",
      "x" = "Rename {wrap_in_backticks(offenders)} where `.fn` was made.",
      "i" = "Reserved: {wrap_in_backticks(reserved)}."
    )
  }
}

Try the scrutiny package in your browser

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

scrutiny documentation built on Nov. 11, 2026, 1:09 a.m.